@unbrained/pm-cli 2026.11.4 → 2026.11.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/.agents/skills/HARNESS_COMPATIBILITY.md +1 -1
  2. package/.agents/skills/README.md +14 -14
  3. package/.agents/skills/pm-developer/SKILL.md +16 -16
  4. package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +14 -14
  5. package/.agents/skills/pm-developer/references/SCRIPTING_COMPOSITION.md +10 -10
  6. package/.agents/skills/pm-extensions/SKILL.md +13 -13
  7. package/.agents/skills/pm-extensions/references/AUTHORING.md +12 -12
  8. package/.agents/skills/pm-sdk/SKILL.md +27 -27
  9. package/.agents/skills/pm-sdk/references/SURFACE_MAP.md +32 -32
  10. package/.agents/skills/pm-test-audit/references/AUDIT.md +1 -1
  11. package/.agents/skills/pm-user/SKILL.md +35 -35
  12. package/.claude-plugin/marketplace.json +1 -1
  13. package/AGENTS.md +9 -9
  14. package/CHANGELOG.md +9 -0
  15. package/README.md +13 -13
  16. package/dist/cli/register-setup.js +1 -1
  17. package/dist/cli-bundle/bundle-manifest.json +1 -1
  18. package/dist/cli-bundle/chunks/chunk-2RPORE7M.js +31 -0
  19. package/dist/cli-bundle/chunks/{chunk-NPEDFOVQ.js → chunk-335BZ75D.js} +2 -2
  20. package/dist/cli-bundle/chunks/chunk-5GWEY4P6.js +122 -0
  21. package/dist/cli-bundle/chunks/chunk-6VRX2CM7.js +2 -0
  22. package/dist/cli-bundle/chunks/{chunk-7PGNAHNW.js → chunk-7DEKAXVA.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-3OXQGGRD.js → chunk-7ZRCYESH.js} +42 -41
  24. package/dist/cli-bundle/chunks/{chunk-BWAXA6S4.js → chunk-AUEKTX7V.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-SRDO2NJU.js → chunk-D7KYPRK4.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-ODMJ3HIB.js → chunk-DAX3AOFI.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-L4BKTPJ6.js → chunk-F6NDMKZ4.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-T56MB6SF.js → chunk-FRNMQM45.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-5S6RT5LX.js → chunk-HNGLDMSZ.js} +3 -3
  30. package/dist/cli-bundle/chunks/{chunk-QN7VCOUU.js → chunk-HRCMORE7.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-BK2XAQVC.js → chunk-HRFGFIYU.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-CERNIZLB.js → chunk-JI2GDE4I.js} +42 -42
  33. package/dist/cli-bundle/chunks/{chunk-6T2V3UIK.js → chunk-LS3GI3H4.js} +53 -53
  34. package/dist/cli-bundle/chunks/chunk-OH6WQ7VT.js +3 -0
  35. package/dist/cli-bundle/chunks/{chunk-BRIPGUAO.js → chunk-OJDMJT7Y.js} +2 -2
  36. package/dist/cli-bundle/chunks/{chunk-7RCI7AAA.js → chunk-S4LPZ4TN.js} +2 -2
  37. package/dist/cli-bundle/chunks/{chunk-AQ5UHHQS.js → chunk-UEGXWXUZ.js} +2 -2
  38. package/dist/cli-bundle/chunks/{chunk-5BVZ32G7.js → chunk-XLSHFYXZ.js} +2 -2
  39. package/dist/cli-bundle/chunks/{chunk-2GW662DP.js → chunk-YKXATU2G.js} +2 -2
  40. package/dist/cli-bundle/chunks/{item-revision-UAZOBP2Q.js → item-revision-OJJVPQY7.js} +2 -2
  41. package/dist/cli-bundle/chunks/item-transaction-QEPBUCMY.js +2 -0
  42. package/dist/cli-bundle/chunks/{mutation-admission-QZQI2NN5.js → mutation-admission-INMM3HHG.js} +2 -2
  43. package/dist/cli-bundle/chunks/{register-list-query-P3NOKQUA.js → register-list-query-5Y5JKWU5.js} +2 -2
  44. package/dist/cli-bundle/chunks/{register-mutation-A6I5K5N6.js → register-mutation-WC7OSQID.js} +2 -2
  45. package/dist/cli-bundle/chunks/{register-operations-SPKB3TNM.js → register-operations-PO63DBZH.js} +2 -2
  46. package/dist/cli-bundle/chunks/register-setup-RRFOS7IT.js +2 -0
  47. package/dist/cli-bundle/chunks/{stage-L3T725DS.js → stage-E3MMV4TV.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/chunk-5PMJOJCZ.js +44 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-TFYTTDAK.js → chunk-7KK66ISG.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-Y5GOUUYJ.js → chunk-AHWJPZSJ.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-C7UX2ZI3.js → chunk-C6P6HPCX.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-Q4OIRSKL.js → chunk-CPMSL4HS.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/chunk-CZM75DE3.js +2 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-CO2DNPH7.js → chunk-D2TBEBNW.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-E56OXRYH.js +2 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-FXFDVM5O.js → chunk-F62XGAAY.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/chunk-G4QP365K.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/{chunk-J7M52SCZ.js → chunk-G5PJCR7R.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/chunk-GS3JC5UU.js +23 -0
  60. package/dist/cli-bundle/focused-chunks/{chunk-W3CSX6GI.js → chunk-LW64TINU.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-MEJKELWC.js → chunk-M6V7UMWL.js} +3 -3
  62. package/dist/cli-bundle/focused-chunks/{chunk-CXTDEQ3N.js → chunk-MC7IE7D7.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/chunk-MG7C3JUY.js +2 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-QEVJ3Y67.js → chunk-MK4HV4JO.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-A2246ZM7.js → chunk-NQ7GYFOX.js} +54 -54
  66. package/dist/cli-bundle/focused-chunks/chunk-O7EI33NP.js +91 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-FFO7RBLN.js → chunk-RFTJZ5VB.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{chunk-PNPYQDHU.js → chunk-SNOXXRSJ.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/{chunk-JQS7TYQ6.js → chunk-UPJUTP2V.js} +2 -2
  70. package/dist/cli-bundle/focused-chunks/{chunk-SDLIUZEL.js → chunk-VWWTIX5L.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/{chunk-J6FDCAMH.js → chunk-XHOBYCVE.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/{chunk-J3YOATXR.js → chunk-YMGB2O4E.js} +25 -24
  73. package/dist/cli-bundle/focused-chunks/{item-revision-L6GVT42D.js → item-revision-CTDO4H3I.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{item-transaction-GYGP264N.js → item-transaction-AEAYVVHA.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/{mutation-admission-UWTH56OD.js → mutation-admission-4WM7TNHZ.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/{stage-WRSNJ7VI.js → stage-WV7QXR4C.js} +2 -2
  77. package/dist/cli-bundle/main.js +2 -2
  78. package/dist/cli-bundle/sdk-authoring.js +1 -1
  79. package/dist/cli-bundle/sdk-contracts.js +1 -1
  80. package/dist/cli-bundle/sdk-core.js +1 -1
  81. package/dist/cli-bundle/sdk-governance.js +1 -1
  82. package/dist/cli-bundle/sdk-graph.js +1 -1
  83. package/dist/cli-bundle/sdk-merge.js +57 -57
  84. package/dist/cli-bundle/sdk-query.js +1 -1
  85. package/dist/cli-bundle/sdk-runtime.js +1 -1
  86. package/dist/cli-bundle/sdk-testing.js +1 -1
  87. package/dist/cli-bundle/sdk.js +9 -9
  88. package/dist/core/config/positional-value.d.ts +6 -0
  89. package/dist/core/config/positional-value.js +1 -1
  90. package/dist/core/item/literal-mutation-input.d.ts +17 -0
  91. package/dist/core/item/literal-mutation-input.js +1 -1
  92. package/dist/core/item/parent-reference-policy.d.ts +8 -4
  93. package/dist/core/item/parent-reference-policy.js +1 -1
  94. package/dist/core/item/sprint-release-format.d.ts +2 -1
  95. package/dist/core/item/sprint-release-format.js +1 -1
  96. package/dist/core/output/mutation-projection.js +1 -1
  97. package/dist/core/store/item-mutation-precondition.d.ts +3 -1
  98. package/dist/core/store/item-mutation-precondition.js +1 -1
  99. package/dist/core/store/item-store.js +1 -1
  100. package/dist/core/store/settings.d.ts +14 -0
  101. package/dist/core/store/settings.js +5 -4
  102. package/dist/core/telemetry/policy.d.ts +27 -1
  103. package/dist/core/telemetry/policy.js +1 -1
  104. package/dist/core/telemetry/runtime.d.ts +18 -7
  105. package/dist/core/telemetry/runtime.js +4 -4
  106. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +8 -5
  107. package/dist/sdk/cli-contracts.d.ts +1 -1
  108. package/dist/sdk/cli-contracts.js +1 -1
  109. package/dist/sdk/config.d.ts +2 -2
  110. package/dist/sdk/config.js +1 -1
  111. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  112. package/dist/sdk/governance/health.d.ts +2 -2
  113. package/dist/sdk/governance/health.js +2 -2
  114. package/dist/sdk/index.d.ts +4 -2
  115. package/dist/sdk/index.js +1 -1
  116. package/dist/sdk/init.d.ts +4 -4
  117. package/dist/sdk/init.js +8 -8
  118. package/dist/sdk/lifecycle/claim.d.ts +4 -0
  119. package/dist/sdk/lifecycle/claim.js +1 -1
  120. package/dist/sdk/lifecycle/close.d.ts +10 -0
  121. package/dist/sdk/lifecycle/close.js +1 -1
  122. package/dist/sdk/lifecycle/create.d.ts +7 -5
  123. package/dist/sdk/lifecycle/create.js +1 -1
  124. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +628 -4
  125. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  126. package/dist/sdk/lifecycle/update.d.ts +5 -4
  127. package/dist/sdk/lifecycle/update.js +2 -2
  128. package/dist/sdk/public-surface.json +1 -1
  129. package/dist/sdk/runtime/actions.js +1 -1
  130. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  131. package/dist/sdk/runtime-input.js +1 -1
  132. package/dist/sdk/runtime-primitives.d.ts +1 -0
  133. package/dist/sdk/runtime-primitives.js +1 -1
  134. package/dist/sdk/telemetry.d.ts +1 -1
  135. package/dist/sdk/telemetry.js +2 -2
  136. package/docs/AGENT_GUIDE.md +48 -48
  137. package/docs/AGENT_OUTPUT_ENCODINGS.md +20 -20
  138. package/docs/ASSURANCE.md +10 -10
  139. package/docs/BOUNDED_CONTEXT_READS.md +3 -3
  140. package/docs/CLAUDE_CODE_PLUGIN.md +1 -1
  141. package/docs/CLI_GRAMMAR.md +2 -2
  142. package/docs/COMMANDS.md +56 -35
  143. package/docs/COMMAND_NAMESPACES.md +1 -1
  144. package/docs/CONFIGURATION.md +82 -71
  145. package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +2 -2
  146. package/docs/CONTEXT_INTEGRITY_CONTRACTS.md +5 -5
  147. package/docs/CORPUS_SHAPES.md +1 -1
  148. package/docs/DEPENDENCY_KIND_CONTRACT.md +6 -6
  149. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +5 -5
  150. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +3 -3
  151. package/docs/EXTENSION_AUTHOR_CONTRACTS.md +4 -4
  152. package/docs/HISTORY_ATTESTATION.md +1 -1
  153. package/docs/HISTORY_MAINTENANCE.md +1 -1
  154. package/docs/LIFECYCLE_COMMANDS.md +1 -1
  155. package/docs/MCP_2026_07_28.md +16 -16
  156. package/docs/MCP_2026_07_28_CONFORMANCE.md +19 -19
  157. package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +22 -22
  158. package/docs/MCP_SKILLS_AND_APPS.md +1 -1
  159. package/docs/MERGE_SAFETY.md +6 -6
  160. package/docs/MUTATION_INTEGRITY.md +5 -5
  161. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +14 -14
  162. package/docs/PACKED_FIRST_RUN.md +1 -1
  163. package/docs/QUICKSTART.md +10 -10
  164. package/docs/README.md +21 -21
  165. package/docs/READ_OUTPUT_CONTRACTS.md +9 -9
  166. package/docs/RECURRENCE_RECOVERY_CONTRACTS.md +1 -1
  167. package/docs/RELEASING.md +19 -10
  168. package/docs/SCRIPTING.md +10 -10
  169. package/docs/SDK.md +74 -38
  170. package/docs/SDK_ARTIFACT_OUTPUT.md +1 -1
  171. package/docs/SDK_PRIMITIVE_INVENTORY.md +2 -2
  172. package/docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md +7 -7
  173. package/docs/TESTING.md +1 -1
  174. package/docs/WORKFLOW_POLICIES.md +2 -2
  175. package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +8 -8
  176. package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
  177. package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -1
  178. package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -1
  179. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +1 -1
  180. package/docs/performance/cli-transport-overhead.md +7 -7
  181. package/marketplace.json +1 -1
  182. package/package.json +1 -1
  183. package/packages/pm-beads/package.json +1 -1
  184. package/packages/pm-calendar/package.json +1 -1
  185. package/packages/pm-command-kit/README.md +5 -5
  186. package/packages/pm-command-kit/package.json +1 -1
  187. package/packages/pm-digital-twin/GAP_REPORT.md +16 -16
  188. package/packages/pm-digital-twin/package.json +1 -1
  189. package/packages/pm-governance-audit/package.json +1 -1
  190. package/packages/pm-guide-shell/package.json +1 -1
  191. package/packages/pm-kanban/README.md +1 -1
  192. package/packages/pm-kanban/package.json +1 -1
  193. package/packages/pm-lifecycle-hooks/package.json +1 -1
  194. package/packages/pm-linked-test-adapters/package.json +1 -1
  195. package/packages/pm-search-advanced/package.json +1 -1
  196. package/packages/pm-templates/package.json +1 -1
  197. package/packages/pm-todos/package.json +1 -1
  198. package/packages/pm-vcs/GAP_REPORT.md +1 -1
  199. package/packages/pm-vcs/package.json +1 -1
  200. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  201. package/plugins/pm-claude/README.md +6 -6
  202. package/plugins/pm-claude/package.json +1 -1
  203. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  204. package/plugins/pm-codex/package.json +1 -1
  205. package/plugins/pm-codex/plugin.json +1 -1
  206. package/runtime-dependencies.json +1 -1
  207. package/dist/cli-bundle/chunks/chunk-5Z6LWFDL.js +0 -31
  208. package/dist/cli-bundle/chunks/chunk-DSCFJTHB.js +0 -122
  209. package/dist/cli-bundle/chunks/chunk-QQHMNUZT.js +0 -2
  210. package/dist/cli-bundle/chunks/chunk-TX2W6G37.js +0 -3
  211. package/dist/cli-bundle/chunks/item-transaction-N5F4LXYV.js +0 -2
  212. package/dist/cli-bundle/chunks/register-setup-ZZRHJ4IS.js +0 -2
  213. package/dist/cli-bundle/focused-chunks/chunk-5NGNO54M.js +0 -44
  214. package/dist/cli-bundle/focused-chunks/chunk-B6U44WPW.js +0 -2
  215. package/dist/cli-bundle/focused-chunks/chunk-BAW3DGQO.js +0 -91
  216. package/dist/cli-bundle/focused-chunks/chunk-BHNY3KPJ.js +0 -2
  217. package/dist/cli-bundle/focused-chunks/chunk-CBG67HUP.js +0 -23
  218. package/dist/cli-bundle/focused-chunks/chunk-FEPE2CE4.js +0 -2
  219. package/dist/cli-bundle/focused-chunks/chunk-PMKR4MJI.js +0 -2
@@ -1,54 +1,54 @@
1
- import{A as h,C as g,E as mt,F as be,G as ee,H as Ae,I as Id,J as rs,K as pt,L as Td,a as Pe,b as ns,c as vd,e as jr,f as Lr,g as Fr,h as Ed,i as zr,j as Gt,k as kd,m as ve,n as Sd,o as Od,p as Ur,q as Hr,u as Dn,v as Ad,y as S,z as Pn}from"./chunk-O4ZLEN4T.js";import My 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 $y(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 jy(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=qr(o))}return n}function qr(e){let t=$y(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>qr(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return qr(r)}return jy(e)}function R(e){return JSON.stringify(qr(e))}function Cd(e,t,n,r){for(let o=0;o<t.length;o+=1)if(!n.has(o)&&r(e,t[o]))return n.add(o),!0;return!1}function Ly(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function Fy(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function zy(e,t){if(!(e instanceof Set||t instanceof Set))return;if(!(e instanceof Set&&t instanceof Set)||e.size!==t.size)return!1;let n=[...t],r=new Set;for(let o of e)if(!Cd(o,n,r,W))return!1;return!0}function Uy(e,t){if(!(e instanceof Map||t instanceof Map))return;if(!(e instanceof Map&&t instanceof Map)||e.size!==t.size)return!1;let n=[...t.entries()],r=new Set;for(let[o,i]of e.entries())if(!Cd([o,i],n,r,([s,a],[c,d])=>W(s,c)&&W(a,d)))return!1;return!0}function Hy(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>W(n,t[r]))}function qy(e,t){let n=Object.keys(e).sort((o,i)=>o.localeCompare(i)),r=Object.keys(t).sort((o,i)=>o.localeCompare(i));if(n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!==r[o]||!W(e[i],t[i]))return!1}return!0}var Vy=[Ly,Fy,zy,Uy,Hy];function W(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;for(let n of Vy){let r=n(e,t);if(r!==void 0)return r}return qy(e,t)}function Vr(e){return My.createHash("sha256").update(e,"utf8").digest("hex")}function A(e,t){let n={};for(let o of t){let i=e[o];i!==void 0&&(n[o]=i)}let r=Object.keys(e).filter(o=>!t.includes(o)).sort((o,i)=>o.localeCompare(i));for(let o of r){let i=e[o];i!==void 0&&(n[o]=i)}return n}import{createHash as xd}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 By=["policies","policy-put","policy-remove","policy-mode","policy-check","policy-approve","policy-presets"],Rd=256,os=64;function le(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 Me(e,t,n){if(typeof e!="object"||e===null||Array.isArray(e))return le(`${n} must be an object`);let r=e;return Object.keys(r).some(o=>!t.includes(o))?le(`${n} contains an unknown key`):r}function _t(e,t,n=128){return typeof e!="string"||!e.trim()||e.length>n?le(`${t} must be nonempty text of at most ${n} characters`):e.trim()}function Mn(e,t){if(!Array.isArray(e)||e.length===0||e.length>os)return le(`${t} requires 1-${os} terms`);let n=e.map(r=>_t(r,t));return t==="fields"&&n.some(r=>!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$/.test(r)||r.split(".").some(o=>["__proto__","constructor","prototype"].includes(o)))?le("fields must be safe metadata paths of at most eight segments"):[...new Set(n)]}function Wy(e){let t=Me(e,["kind","fields","authors","allowed"],"rule");return t.kind==="transition"?(Me(t,["kind","allowed"],"transition rule"),!Array.isArray(t.allowed)||t.allowed.length>os?le("transition.allowed must be a bounded array"):{kind:"transition",allowed:t.allowed.map(n=>!Array.isArray(n)||n.length!==2?le("transition pairs need two statuses"):[_t(n[0],"from"),_t(n[1],"to")])}):t.kind==="authors"?(Me(t,["kind","authors"],"authors rule"),{kind:"authors",authors:Mn(t.authors,"authors")}):t.kind==="require_fields"?(Me(t,["kind","fields"],"require_fields rule"),{kind:"require_fields",fields:Mn(t.fields,"fields")}):t.kind==="field_writers"||t.kind==="approval"?(Me(t,["kind","fields","authors"],"field rule"),{kind:t.kind,fields:Mn(t.fields,"fields"),authors:Mn(t.authors,"authors")}):le("unknown rule kind")}function Gy(e){let t={},n=Me(e,["types","tags","statuses","operations","parents","dependency"],"subject");for(let r of["types","tags","statuses","operations","parents"])n[r]!==void 0&&(t[r]=Mn(n[r],r));if(n.dependency!==void 0){let r=Me(n.dependency,["kind","id"],"dependency");t.dependency={kind:_t(r.kind,"dependency kind"),...r.id===void 0?{}:{id:_t(r.id,"dependency id")}}}return t}function Ky(e){let t=Me(e,["id","description","subject","effect","rule"],"policy"),n=_t(t.id,"id");return/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(n)?t.effect!==void 0&&(typeof t.effect!="string"||!["advise","warn","refuse"].includes(t.effect))?le("effect must be advise, warn, or refuse"):{id:n,rule:Wy(t.rule),...t.subject===void 0?{}:{subject:Gy(t.subject)},...t.description===void 0?{}:{description:_t(t.description,"description",500)},...t.effect===void 0?{}:{effect:t.effect}}:le("id must be a stable token")}function Yy(e){let t=Me(e,["version","enforcement","policies"],"document");if(t.version!==1)return le("unsupported version");if(t.enforcement!==void 0&&t.enforcement!=="advise"&&t.enforcement!=="refuse")return le("enforcement must be advise or refuse");if(!Array.isArray(t.policies)||t.policies.length>Rd)return le(`policies must contain at most ${Rd} declarations`);let n=t.policies.map(Ky);return new Set(n.map(r=>r.id)).size!==n.length?le("duplicate policy id"):{version:1,enforcement:t.enforcement??"advise",policies:n}}function Br(e,t){let n=e;for(let r of t.split(".")){if(typeof n!="object"||n===null||!Object.hasOwn(n,r))return;n=n[r]}return n}function Xy(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 Nd(e){return xd("sha256").update(R(e)).digest("hex")}function Jy(e,t){let n=e.rule.kind==="approval"?e.rule.fields:[];return xd("sha256").update(R({id:t.id,fields:n.map(r=>[r,Br(t,r)])})).digest("hex")}function Zy(e,t){return Array.isArray(t)&&t.some(n=>typeof n=="object"&&n!==null&&"kind"in n&&n.kind===e.kind&&(e.id===void 0||"id"in n&&n.id===e.id))}function Qy(e,t,n){return!(e.types&&!e.types.some(r=>r.toLowerCase()===String(t.type).toLowerCase())||e.statuses&&!e.statuses.includes(String(t.status))||e.operations&&!e.operations.includes(n)||e.parents&&!e.parents.includes(String(t.parent))||e.tags&&(!Array.isArray(t.tags)||!e.tags.some(r=>t.tags.includes(r)))||e.dependency&&!Zy(e.dependency,t.dependencies))}function eh(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 n=e.subject??{},r=t.after?.status??t.before?.status;return[t.before,t.after].some(o=>o!==null&&Qy(n,{...o,status:r},t.operation))}function th(e,t,n,r){let o=["type","tags","parent","dependencies"].some(i=>!W(t.before?.[i],t.after?.[i]));return t.after&&(t.completeness_only||n||r||o)?e.filter(i=>!Xy(Br(t.after,i))):[]}function nh(e,t,n,r){let o=t.after??t.before,i=Jy(e,o);return t.approvals?.some(s=>s.policy_fingerprint===r&&s.content_fingerprint===i&&s.author!==t.author&&n.includes(s.author))??!1}function rh(e,t,n){let r=e.rule,o=t.before?.status!==t.after?.status,i="fields"in r&&r.fields.some(s=>!W(Br(t.before,s),Br(t.after,s)));switch(r.kind){case"require_fields":{let s=th(r.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||r.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:r.authors.includes(t.author),missing_fields:[],remediation:"Have a declared workflow actor perform this operation."};case"field_writers":return{satisfied:!i||r.authors.includes(t.author),missing_fields:[],remediation:"Have a declared field writer change the protected fields."};case"approval":return{satisfied:!o||nh(e,t,r.authors,n),missing_fields:[],remediation:`Record an independent approval with pm schema policy-approve <item-id> --policy ${e.id} after preparing the reviewed fields.`}}}function Dd(e,t,n){let r=e.policies.filter(o=>eh(o,t)).map(o=>{let i=o.effect??"advise",s=n(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:!r.some(o=>!o.satisfied&&o.effect==="refuse"),decisions:r,warnings:r.filter(o=>!o.satisfied).map(o=>`workflow_policy:${o.effect}:${o.policy_id}:${o.rule}`)}}function PC(e,t){return Dd(e,t,Nd)}function MC(e){let t=Yy(e),n=new Map(t.policies.map(r=>[r,Nd(r)]));return r=>Dd(t,r,o=>n.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]="451b262c-a9b6-5f1c-b397-2686a5fd953a")}catch{}})();var oh=[["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"})),ih=[...["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"})),sh=[["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"})),ah=[...ih,...sh,...["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,n])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:n}))],is=[{alias:"history-attest",canonical:"history attest",canonical_argv:["history","attest"],lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-3z0k"},...oh,...ah,...["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 jC(e){let t;for(let n of is)n.canonical_argv.length<=(t?.canonical_argv.length??0)||n.canonical_argv.every((r,o)=>r===(o===0&&e[o]==="ctx"?"context":e[o]))&&(t=n);return t}function ch(e){let t=e.trim().replace(/\s+/gu," ");return is.find(n=>n.canonical===t.replace(/^ctx /u,"context "))?.alias??t}function $n(e){return ch(e)}var Wr=[...is,...[["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,n])=>({alias:e,canonical:t,canonical_argv:[t,n],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"}))],LC=Object.fromEntries(Wr.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));function FC(e){let t=e.trim().toLowerCase();return Wr.find(n=>n.alias===t)}function zC(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]="3348c61d-a03e-5023-a5dc-fd6149f478c1")}catch{}})();var dh=[...Pe],lh=[...Gt],uh=[...jr],BC=[...Lr],WC=[...Fr],fh=[...zr],Gr=["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"],GC=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],KC=["install","reconcile","report","driver"],mh=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],ph=["upgrade"],_h=["reopen"],Pd={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},Kt=Object.freeze(Gr.flatMap(e=>e in Pd?[]:e==="extension"||e==="package"?[...mh.map(t=>`${e}-${t}`),...e==="package"?ph.map(t=>`package-${t}`):[],e]:e==="item"?_h.map(t=>`item-${t}`):[e])),yh=Object.freeze(Wr.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&Kt.includes(e.alias)).map(e=>e.alias)),YC=Object.freeze(Kt.filter(e=>!yh.includes(e)));function XC(e=Gr,t=Kt,n=Pd){let r=new Set(t),o=new Set(e);return{missing_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]===void 0),waived_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]!==void 0),stale_waivers:Object.keys(n).filter(i=>!o.has(i)||r.has(i)||t.some(s=>s.startsWith(`${i}-`)))}}function JC(e){return Kt.includes(e)}function ZC(e){return dh.includes(e)}function QC(e){return lh.includes(e)}function eR(e){return uh.includes(e)}function tR(e){return fh.includes(e)}var nR=new Set(["update","item-reopen","close","claim","release","start-task","pause-task","close-task","restore","append","update-many","close-many","delete","comments","notes","learnings","files","docs","test","test-all","plan","history-redact","history-repair","history-compact","validate"]);(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]="b181d38e-7120-5d34-98d9-fd9b4619b9d9")}catch{}})();var hh=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],Md=hh,Yt=["draft","open","in_progress","blocked","closed","canceled"],Kr=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Xt=["string","number","boolean","string_array","array","object"],Yr=["create","update","update_many","list","search","calendar","context"],Xr=["allow","warn","reject"],oR=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],iR=["project","global"],sR=["low","medium","high","critical"],Jr=["low","medium","high","critical"],Zr=["low","medium","high"];var $d=["minimal","default","strict","custom"],aR=["none","warn","strict"],cR=["progressive","strict"],dR=["off","warn","strict"],lR=["off","warn","strict"],jd=["off","warn","strict"];var Qr=["daily","weekly","monthly","yearly"],jn=["mon","tue","wed","thu","fri","sat","sun"];function ss(e){return jn.indexOf(e)}var uR=["draft","research","review","approved","executing","paused","completed","superseded"],Ld=["pending","in_progress","completed","blocked","skipped","superseded"],fR=["codex","claude-code","cursor","generic"],mR=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],pR=["brief","standard","deep","full"],_R=["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 Eh 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 qe(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function gh(e){let t=e.key.trim();if(t.length===0)return null;let n=qe(e.aliases),r=e.description?.trim();return{key:t,values:qe(e.values),required:e.required===!0?!0:void 0,aliases:n.length>0?n:void 0,description:r&&r.length>0?r:void 0}}var bh=e=>e,zd=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function wh(e,t){let n=t(e.command);if(n===null)return null;let r=e.option.trim();return r.length===0?null:{command:n,option:r,required:e.required,visible:e.visible,enabled:e.enabled}}function vh(e,t){let n=new Map;for(let r of e??[]){let o=wh(r,t);o&&n.set(`${o.command}:${o.option.toLowerCase()}`,o)}return[...n.values()].sort((r,o)=>r.command===o.command?r.option.localeCompare(o.option):r.command.localeCompare(o.command))}function Fd(e,t){return t?qe(e):void 0}function as(e){let t=e?.trim();return t&&t.length>0?t:void 0}function cs(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 eo(e,t={}){let n=t.resolvePolicyCommand??bh,r=e.name.trim();if(r.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=qe(e.aliases),d=(e.options??[]).map(u=>gh(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),l=vh(e.command_option_policies,n);return{name:r,description:as(e.description),default_status:as(e.default_status),...e.execution_role===void 0?{}:{execution_role:cs(e.execution_role)},folder:as(e.folder),aliases:c.length>0?c:void 0,required_create_fields:Fd(e.required_create_fields,o),required_create_repeatables:Fd(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 kh=Object.freeze({decision:"human",milestone:"gate"}),Sh=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],Oh=["dep","comment","note","learning","file","test","doc"],Hd=["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"],Ah=["title","description","type","status","priority","tags","body",...Hd,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],Ih=["title","description","body","status","closeReason","priority","type","tags",...Hd,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],qd={"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"},Th={...qd},Ch={...qd},Vd=[["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"]],Bd=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function Wd(e){return Object.fromEntries(e)}var Rh=Wd([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...Vd,["author","--author"],["message","--message"],["dep","--dep"],...Bd]),xh=Wd([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...Vd,...Bd,["author","--author"],["message","--message"],["force","--force"]]);function Nh(e){return e.trim().replace(/^--+/,"").toLowerCase()}function Dh(e){return e==="create"?Ah:Ih}function Ph(e){return e==="create"?Th:Ch}function Gd(e,t){let n=Nh(t);return n.length===0?void 0:Ph(e)[n]||Dh(e).find(r=>r.toLowerCase()===n)}function SR(e,t){return(e==="create"?Rh:xh)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function ls(e){let t=$h(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function Mh(e){let t=e.trim(),n=t.replaceAll("\\","/").replace(/^\/+/,""),r=Eh.posix.normalize(n);if(t.includes("\0")||/^[A-Za-z]:/.test(r)||r==="."||r===".."||r.startsWith("../"))throw new Error(`Item type folder "${e}" must stay inside the pm tracker root.`);return r}function $h(e){let t=e.trim().toLowerCase(),n="",r=!1;for(let o of t){let i=o.charCodeAt(0),s=i>=97&&i<=122,a=i>=48&&i<=57;if(s||a){r&&n.length>0&&(n+="-"),n+=o,r=!1;continue}n.length>0&&(r=!0)}return n}function jh(e){return eo(e,{resolvePolicyCommand:zd})}function Ln(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function Lh(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:Ln(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Ln(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function Fh(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 n=t.command.trim().toLowerCase();return n!=="create"&&n!=="update"?null:{command:n,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 zh(e){if(Array.isArray(e.options))return e.options.map(t=>Lh(t)).filter(t=>t!==null)}function Uh(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>Fh(t)).filter(t=>t!==null)}function Hh(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,n=typeof t.name=="string"?t.name:"";if(n.trim().length===0)return null;let r=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:n,description:o,default_status:i,execution_role:cs(t.execution_role),folder:r,aliases:Ln(t,"aliases"),required_create_fields:Ln(t,"required_create_fields"),required_create_repeatables:Ln(t,"required_create_repeatables"),options:zh(t),command_option_policies:Uh(t)}}function qh(e,t){return e.required_create_fields?qe(e.required_create_fields):t?.required_create_fields??[]}function Vh(e,t){return e.required_create_repeatables?qe(e.required_create_repeatables):t?.required_create_repeatables??[]}function Bh(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function Wh(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Gh(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=Mh(e.folder??t?.folder??ls(n)),s={name:n,execution_role:e.execution_role,folder:i,aliases:qe([...t?.aliases??[],...e.aliases??[]]),required_create_fields:qh(e,t),required_create_repeatables:Vh(e,t),options:Bh(e,t),command_option_policies:Wh(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function Ud(e,t){for(let n of e){let r=jh(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,Gh({...r,execution_role:r.execution_role??i?.execution_role},i))}}function Kh(e){if(!e)return[];let t=[];for(let n of e.item_types??[]){let r=n.types;if(Array.isArray(r))for(let o of r){let i=Hh(o);i&&t.push(i)}}return t}function OR(e,t=null){let n=new Map;for(let c of Md)n.set(c.toLowerCase(),{name:c,execution_role:kh[c.toLowerCase()]??"agent",folder:Dn[c],aliases:[],required_create_fields:[...Sh],required_create_repeatables:[...Oh],options:[],command_option_policies:[]});Ud(e.item_types?.definitions??[],n),Ud(Kh(t),n);let r=[...n.values()].sort((c,d)=>c.name.localeCompare(d.name)),o={},i={},s={};for(let c of r){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(r.map(c=>c.folder))].sort((c,d)=>c.localeCompare(d));return{types:r.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}function Yh(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function Xh(e,t){let n=Yh(e,t);if(n)return t.by_type[n]}function Jh(e,t,n,r){for(let o of r){let i=Gd(n,o);if(i){e.required.add(i);continue}e.errors.push(`Unsupported base required option "${o}" for command "${n}" on type "${t.name}"`)}}function ds(e,t,n){if(n){e.add(t);return}e.delete(t)}function Zh(e,t,n,r){let o=Gd(n,r.option);if(!o){e.errors.push(`Unsupported command_option_policies option "${r.option}" for command "${n}" on type "${t.name}"`);return}r.required!==void 0&&ds(e.required,o,r.required),r.visible!==void 0&&ds(e.hidden,o,!r.visible),r.enabled!==void 0&&ds(e.disabled,o,!r.enabled)}function Qh(e,t,n){for(let r of t.command_option_policies)r.command===n&&Zh(e,t,n,r)}function eg(e,t,n){for(let r of e.required)e.disabled.has(r)&&e.errors.push(`Option "${r}" cannot be both required and disabled for command "${n}" on type "${t.name}"`)}function AR(e,t,n){let r=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:r};return Jh(a,e,t,n),Qh(a,e,t),eg(a,e,t),{required:[...o],hidden:[...i].sort((c,d)=>c.localeCompare(d)),disabled:[...s].sort((c,d)=>c.localeCompare(d)),errors:r}}function tg(e){let t=new Map;for(let n of e.options){t.set(n.key.toLowerCase(),n);for(let r of n.aliases??[])t.set(r.toLowerCase(),n)}return t}function ng(e,t,n){let r=e.values;if(r.length===0)return t;let o=new Map(r.map(i=>[i.toLowerCase(),i])).get(t.toLowerCase());if(!o){n.push(`Invalid value "${t}" for type option "${e.key}". Allowed: ${r.join(", ")}`);return}return o}function IR(e,t,n){let r=Xh(e,n);if(!r)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=tg(r),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 _=r.options.map(y=>y.key).join(", ");o.push(r.options.length>0?`Unknown type option "${l}" for type "${r.name}". Allowed: ${_}`:`Type "${r.name}" does not define any configurable type options`);continue}let m=ng(f,u,o);m!==void 0&&(s[f.key]=m)}for(let c of r.options)c.required&&!(c.key in s)&&o.push(`Missing required type option "${c.key}" for type "${r.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 rg,readdirSync as og,realpathSync as Kd,statSync as Yd}from"node:fs";import ig from"node:os";import C 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 sg={json_markdown:".md",toon:".toon"},ag={".md":"json_markdown",".toon":"toon"},cg=new Set([".git","coverage","dist","node_modules"]),$R=[".md",".toon"];function Fn(e){try{return Yd(e),!0}catch{return!1}}function dg(e){let t=C.resolve(e),n=[];for(;C.dirname(t)!==t;)try{return C.join(Kd(t),...n)}catch(r){if(!be(r))throw r;n.unshift(C.basename(t)),t=C.dirname(t)}return C.join(Kd(t),...n)}function lg(e){try{return Yd(e),!0}catch(t){if(be(t))return!1;throw t}}function Xd(e){try{let t=JSON.parse(rg(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function ug(e){let t=dg(e);for(;;){let n=C.join(t,Ur),r=C.join(n,Hr);if(Fn(r))return n;let o=C.join(t,Hr);if(Fn(o)&&Xd(o))return t;if(lg(C.join(t,".git")))return n;let i=C.dirname(t);if(i===t)return;t=i}}function us(e){return ug(e)??C.resolve(e,Ur)}function jR(e,t){let n=t?C.resolve(t):void 0;try{return og(C.resolve(e),{withFileTypes:!0}).filter(r=>r.isDirectory()&&!cg.has(r.name)).map(r=>C.join(C.resolve(e),r.name)).filter(r=>r!==n).filter(r=>Fn(Ie(r))).filter(r=>Xd(Ie(r))).sort((r,o)=>r.localeCompare(o))[0]}catch{return}}function Jd(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=C.resolve(e,r);if(!Fn(Ie(o))){let i=C.join(o,Ur);if(Fn(Ie(i)))return i}return o}return us(e)}function Zd(e){let t=C.resolve(e),n=C.dirname(t);return C.basename(t)==="pm"&&C.basename(n)===".agents"?C.dirname(n):t}function Qd(e){let t=process.env.PM_GLOBAL_PATH?.trim(),n=t&&t.length>0?t:C.join(ig.homedir(),".pm-cli");return C.resolve(e,n)}function Ie(e){return C.join(e,Hr)}function fg(e,t,n=Dn){let r=n[t]??ls(t);return C.join(e,r)}function LR(e,t,n,r="toon",o=Dn){return C.join(fg(e,t,o),`${n}${sg[r]}`)}function FR(e){let t=e.replaceAll("\\","/"),n=C.posix.extname(t).toLowerCase();return ag[n]??null}function zR(e,t){if(!/^(?!\.{1,2}$)[^/\\:\0]+$/.test(t))throw new g("Invalid history item id: expected a single filename.",h.USAGE);return C.join(e,"history",`${t}.jsonl`)}function fs(e,t){return C.join(e,"locks",`${t}.lock`)}function ms(e){return C.join(e,"runtime")}function to(e){return C.join(ms(e),"test-runs")}function mg(e){return C.join(to(e),"runs")}function UR(e,t){return C.join(mg(e),`${t}.json`)}function pg(e){return C.join(to(e),"stdout")}function _g(e){return C.join(to(e),"stderr")}function HR(e,t){return C.join(pg(e),`${t}.log`)}function qR(e,t){return C.join(_g(e),`${t}.log`)}function yg(e){return C.join(to(e),"results")}function VR(e,t){return C.join(yg(e),`${t}.json`)}(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 el=e=>{let t='"',n=0;for(let r of e){if(r==="\\"){n+=1;continue}t+="\\".repeat(r==='"'?n*2+1:n),t+=r,n=0}return`${t}${"\\".repeat(n*2)}"`},tl=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?el(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,Jt=(e,t=process.platform)=>{let n=e.map(r=>tl(r,t)).join(" ");return n.length>0?`pm ${n}`:"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]="9bb3b2ed-c289-5b96-99ce-9df6e202c464")}catch{}})();var nl=new Set(["--pm-path","--path","--author","--expect-hash","--output-include","--output-limit","--output-budget","--output-format","--format","--output-session","--output-cursor"]),hg=new Set(["--no-extensions","--no-pager","--json","--quiet","--lean","--token-accounting","--output-row-contract","--all"]);function gg(e){let t=e.indexOf("=");return t>0&&nl.has(e.slice(0,t))}function bg(e,t){return typeof t!="string"?!1:e==="--path"||e==="--pm-path"||!t.startsWith("-")}function no(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")return;if(nl.has(n)){t+=bg(n,e[t+1])?1:0;continue}if(!(gg(n)||hg.has(n)||n==="--profile"||n==="--id-only"||n==="--explain")&&!n.startsWith("-"))return t}}function GR(e){let t=no(e);return t===void 0?void 0:e[t].trim().toLowerCase()}import wg from"node:path";import rl 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 zn(e,t){let n=rl.relative(e,t);return n.length===0?!0:!n.startsWith("..")&&!rl.isAbsolute(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]="08181915-ead8-51bc-a078-9d97b9048f37")}catch{}})();var ps=new WeakMap;function nx(e){ps.set(e,e.path)}function vg(e){if(!process.env.PM_PATH?.trim())return;let t=Jd(e);return zn(Zd(t),e)&&t===us(e)?void 0:wg.relative(e,t)||"."}function rx(e,t=process.cwd()){let n=(ps.has(e)?ps.get(e):e.path)||vg(t),r=n?["--pm-path",n]:[];return e.noExtensions&&r.push("--no-extensions"),r}var Eg=new Set(["--literal","--regex","--replacement"]);function kg(e){let t=no(e);if(t===void 0)return!1;if(e[t]==="history-redact")return!0;if(e[t]!=="history")return!1;let n=e.slice(t+1),r=no(n);return r!==void 0&&n[r]==="redact"}function ox(e){if(!kg(e))return[...e];let t=[],n=!1;for(let r of e){if(n){t.push("[redacted]"),n=!1;continue}n=!1;let o=r.indexOf("="),i=o>=0?r.slice(0,o):r;if(!Eg.has(i)){t.push(r);continue}if(o>=0){t.push(`${i}=[redacted]`);continue}t.push(i),n=!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]="32b0a81e-6a21-528a-8cf8-3e764f382044")}catch{}})();var Sg=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"},{flag:"--expect-hash",value_name:"revision"}]),_s=new Set(Sg.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 ol=/^(--[a-z0-9][a-z0-9_-]*)(?:[ =](<[^<>]+>|\[[^[\]]+\]))?$/;function ys(e){if(typeof e!="string")return null;let t=ol.exec(e.trim());if(!t)return null;let n=t[2];return{name:t[1],valueName:n?n.slice(1,-1):null,optional:n?.startsWith("[")??!1}}function cx(e){let t=ys(e);return t?t.name:typeof e=="string"&&e.trim()||null}function Og(e){if(typeof e!="string")return null;let t=e.trim(),n=t.split(/[ =]/,1)[0];return _s.has(n)?"host_owned_flag_collision":ol.test(t)?null:"malformed_long_flag"}function il(e,t){let n=[e,t].find(i=>typeof i=="string"&&_s.has(i.trim().split(/[ =]/,1)[0]));if(typeof n=="string")return{token:n.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof e!="string")return null;let r=e.trim(),o=Og(r);return o===null?null:{token:r,failure:o}}function sl(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]="a797572f-fbc6-5e62-a9b5-5a0bd6ef22b4")}catch{}})();function Ag(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function lx(e){return Ag(e)??void 0}function ux(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 fx(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function cl(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function ro(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 mx(e){let t=ro(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function px(e,t,n){let r=ro(e);return r===null||r<t||r>n?null:r}function _x(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function Ve(e){return typeof e!="object"||e===null?null:e}function al(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function dl(e){let t=al(e);if(!t)return null;if(typeof t.activate=="function")return t;let n=al(t.default);return typeof n?.activate=="function"?n:null}function yx(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]="92573990-a040-526d-a0b1-b91d2ef401f1")}catch{}})();function oo(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import Ig from"node:crypto";import{AsyncLocalStorage as Tg}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 hs=new Tg,ll=1024;function Cg(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 Rg(e){let t={...Cg(e),clockReads:0,tokenReads:0};return n=>hs.run(t,n)}async function vx(e,t){return Rg(e)(t)}function ul(){let e=hs.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 Ex(e){let t=hs.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>ll)throw new Error(`Reproducible token length must be an integer between 0 and ${ll}`);let n="";for(;n.length<e;){let r=Ig.createHash("sha256").update(`${t.seed}\0${t.tokenReads}`).digest();t.tokenReads+=1;for(let o of r)if(n+=(o%36).toString(36),n.length===e)break}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]="0bf155fc-c690-5318-ba1e-275f1787858b")}catch{}})();var xg=/^([+-]?)(\d+)([hdwm])$/i,Ng=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,Dg=/^(\d{4})(\d{2})(\d{2})$/,Pg=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Mg=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,$g=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,jg=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function Te(){return ul()??new Date().toISOString()}function $e(e){return Number.isFinite(Date.parse(e))}function Un(e){let t=jg.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,n,r,o,i,s,a,c,d]=t,[l,u,f,m,_,y]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=ws(l,u-1)&&m<=23&&_<=59&&y<=59&&(c===void 0||Number(c)<=23)&&(d===void 0||Number(d)<=59)}function Zt(e){let t=/\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/iu.exec(e)?.[1];return Un(e)&&(t===void 0||/^\d{0,3}0*$/u.test(t))}var Lg=1e4,io=new Map;function fl(e){let t=io.get(e);if(t!==void 0)return t;let n=Date.parse(e);return io.size>=Lg&&oo(io),io.set(e,n),n}function re(e,t){let n=fl(e),r=fl(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function Tx(e,t){return!(t.deadlineBefore&&(!e.deadline||re(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||re(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&re(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&re(e.updated_at,t.updatedBefore)>0||t.createdAfter&&re(e.created_at,t.createdAfter)<0||t.createdBefore&&re(e.created_at,t.createdBefore)>0)}function gs(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function bs(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 Fg(e,t,n){n&&n!==t&&(e.includes(n)||e.push(n))}function zg(e){let t=[],n=d=>Fg(t,e,d),r=Dg.exec(e);if(r){let[,d,l,u]=r;n(`${d}-${l}-${u}`)}let o=Pg.exec(e);if(o){let[,d,l,u,f,m,_,y,w]=o,v=_?`:${_}`:"";n(`${d}-${l}-${u}T${f}:${m}${v}${gs(y)}${bs(w)}`)}let i=Mg.exec(e);if(i){let[,d,l,u,f,m,_]=i,y=f?`:${f}`:"";n(`${d}T${l}:${u}${y}${gs(m)}${bs(_)}`)}let s=$g.exec(e);if(s){let[,d,l,u,f,m,_]=s,y=f?`:${f}`:"";n(`${d}T${l}:${u}${y}${gs(m)}${bs(_)}`)}let a=10,c=e.slice(0,a);if(Hg(c)){let d=a;for(;d<e.length&&qg(e[d]);)d+=1;d<e.length&&n(`${c}T${e.slice(d)}`)}return t}function Ug(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let n of zg(e)){let r=Date.parse(n);if(Number.isFinite(r))return r}return Number.NaN}function Hg(e){if(e.length!==10)return!1;for(let t=0;t<e.length;t+=1){let n=e[t];if(t===4||t===7){if(n!=="-")return!1;continue}let r=n.charCodeAt(0);if(r<48||r>57)return!1}return!0}function qg(e){return e?e===" "||e===" "||e===`
2
- `||e==="\r"||e==="\f"||e==="\v":!1}function ws(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var Vg=["January","February","March","April","May","June","July","August","September","October","November","December"],Bg=/^(\d{4})-(\d{2})-(\d{2})/,Wg=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function Gg(e,t,n){let r=Bg.exec(t)??Wg.exec(t);if(!r)return;let o=Number.parseInt(r[1],10),i=Number.parseInt(r[2],10),s=Number.parseInt(r[3],10),a=n?.trim()||"deadline";if(i<1||i>12)throw new g(`Invalid ${a} value "${e}". Month "${r[2]}" is out of range \u2014 use a month between 01 and 12.`,h.USAGE,{field:a,value:e});let c=ws(o,i-1);if(s<1||s>c)throw new g(`Invalid ${a} value "${e}". ${Vg[i-1]} ${o} has ${c} days, so day "${r[3]}" does not exist. Use a real YYYY-MM-DD calendar date.`,h.USAGE,{field:a,value:e})}function Kg(e,t){let n=new Date(e.getTime()),r=n.getUTCDate(),o=n.getUTCMonth()+t,i=n.getUTCFullYear()+Math.floor(o/12),s=(o%12+12)%12,a=Math.min(r,ws(i,s));return n.setUTCFullYear(i,s,a),n}function Cx(e,t=new Date,n="deadline"){let r=e.trim();if(r.toLowerCase()==="now")return t.toISOString();let o=xg.exec(r);if(o){let s=o[1]==="-"?-1:1,a=Number.parseInt(o[2],10)*s,c=o[3].toLowerCase();if(c==="m")return Kg(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()}Gg(e,r,n);let i=Ug(r);if(!Number.isFinite(i)){let s=n.trim().length>0?n.trim():"deadline",a=Ng.test(r)?"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()}(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 ml=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function so(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.hasOwn(ml,t)?ml[t]:null}function Yg(e,t,n){return!!(e.value_name?.trim()||t||n||e.required===!0||e.list===!0||e.repeatable===!0)}function Xg(e){return(e.value_type?.trim()||e.type?.trim())?.toLowerCase()}function Nx(e){let t=Xg(e),n=so(t),r=ys(e.long),o=e.value_name?.trim()||null,i=!(n==="boolean"&&t!=="bool")&&Yg(e,r?.valueName,t),s=r?.valueName?r.optional:t==="bool";return{value_type:n,value_arity:i?s?"optional":"required":"none",value_name:i?o??r?.valueName??"value":null}}function pl(e){let t=[],n=r=>{if(Array.isArray(r)){for(let o of r)n(o);return}if(typeof r=="string"){for(let o of r.split(",")){let i=o.trim();i.length>0&&t.push(i)}return}r!=null&&t.push(r)};return n(e),t}function _l(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 Dx(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]="628615ea-5be3-5753-a6c5-3eba8400a8da")}catch{}})();function ao(e,t,n){if(e===t)return 0;if(Math.abs(e.length-t.length)>n)return null;let r=t.length+1,o=new Array(r),i=new Array(r),s=new Array(r);for(let c=0;c<r;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>n)return null;for(let l=0;l<r;l+=1)o[l]=i[l],i[l]=s[l]}let a=i[t.length];return a<=n?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]="2ea7934f-4751-5245-a5ba-492681aa3794")}catch{}})();var vs=[{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 uo(e){return e.trim().toLowerCase().replaceAll("-","_")}function Jg(e){if(e===void 0)return;let t=uo(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function ks(e,t=new Set){if(e===null||typeof e!="object"||t.has(e))return e;if(t.add(e),Array.isArray(e)){for(let n of e)ks(n,t);return Object.freeze(e)}for(let n of Object.values(e))ks(n,t);return Object.freeze(e)}function Zg(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 Qg(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 eb(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 tb(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=uo(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 nb(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 rb(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(n=>typeof n!="string")))throw new TypeError(`Invalid relationship aliases for ${t}`)}function ob(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var Ss=class{#e=new Map;#n=new Map;constructor(t=vs){for(let n of t)this.register(n)}register(t){let n=tb(t);if(nb(t,n),rb(t,n),Zg(t,n),Qg(t,n),eb(t,n),this.#e.has(n)||this.#n.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=Jg(t.inverse),o=[...new Set((t.aliases??[]).map(uo))].sort();for(let s of o){if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid relationship alias: ${s}`);if(s===n||this.#e.has(s)||this.#n.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:n,traversal:ob(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?ks(structuredClone(t.payloadSchema)):void 0});this.#e.set(n,i);for(let s of o)this.#n.set(s,n);return this}resolve(t){if(typeof t!="string")return;let n=uo(t);return this.#e.get(this.#n.get(n)??n)}require(t){let n=this.resolve(t);if(!n)throw new TypeError(`Unknown relationship kind: ${t}`);return n}list(){return Object.freeze([...this.#e.values()].sort((t,n)=>t.kind.localeCompare(n.kind)))}};function Os(){return new Ss}var yt=Os();function Fx(e){return yt.require(e).kind}function zx(e){return yt.resolve(e)?.kind}function Ux(e,t=yt){return t.resolve(e)?.ordering===!0}function ib(e,t,n,r=yt){let o=Hn(e),i=Hn(t);if(!o||!i)throw new TypeError("Relationship endpoint must not be empty");let s=r.require(n);if(o===i&&!s.allowSelf)throw new TypeError(`Self relationship is not allowed for ${s.kind}`);return s}function co(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function sb(e,t,n){let r=typeof e.source=="string"?e.source.trim():"",o=typeof e.target=="string"?e.target.trim():"";if(!t.has(r)||!t.has(o))throw new TypeError(`Relationship endpoint not found: ${r} -> ${o}`);let i=ib(r,o,e.kind,n),s=Object.freeze({...e,source:r,target:o,kind:i.kind}),a=i.direction==="undirected"?[r,o].sort().join("\0"):`${r}\0${o}`;return{edge:s,identity:`${i.kind}\0${a}`}}function lo(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function Hn(e){return typeof e=="string"?e.trim():""}function Es(e,t){let n=Hn(e);return n&&t.has(n)?n:void 0}function ab(e,t,n){let r=[t],o=t;for(;o!==e;)o=n.get(o),r.push(o);return r.reverse()}var yl=class e{#e;#n;#o;#r;#s=new Map;#a=new Map;constructor(t,n,r=yt){this.#e=r,this.#n=new Set([...t].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)),this.#o=Object.freeze([...this.#n].sort());let o=new Map;for(let i of n){let{edge:s,identity:a}=sb(i,this.#n,r);o.set(a,s)}this.#r=Object.freeze([...o.values()].sort(co));for(let i of this.#r)lo(this.#s,i.source,i),lo(this.#a,i.target,i),r.require(i.kind).direction==="undirected"&&(lo(this.#s,i.target,i),lo(this.#a,i.source,i))}static fromItems(t,n=yt){let r=new Set(t.map(i=>Hn(i.id)).filter(Boolean)),o=[];for(let i of t){let s=Hn(i.id);if(!s)continue;let a=Es(i.parent,r);a&&o.push({source:s,target:a,kind:"parent"});let c=Es(i.blocked_by,r);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let d of i.dependencies??[]){let l=Es(d.id,r);l&&n.resolve(d.kind)&&o.push({source:s,target:l,kind:d.kind,createdAt:d.created_at,author:d.author})}}return new e(r,o,n)}edges(){return this.#r}incidentEdges(t){this.#i(t);let n=this.#s.get(t)??[],r=this.#a.get(t)??[];if(n.length===0)return Object.freeze([...r]);if(r.length===0)return Object.freeze([...n]);let o=[],i=0,s=0;for(;i<n.length||s<r.length;){let a=n[i],c=r[s],d=a===void 0?c:c===void 0||co(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.#n.has(t)}registry(){return this.#e}#i(t){if(!this.#n.has(t))throw new TypeError(`Relationship node not found: ${t}`)}#c(t,n){if(!n)return!0;let r=this.#e.require(t.kind);return n.has(t.kind)||r.inverse!==void 0&&n.has(r.inverse)}#t(t,n,r){let o=[...n==="incoming"?[]:this.#s.get(t)??[],...n==="outgoing"?[]:this.#a.get(t)??[]];return[...new Set(o)].filter(i=>this.#c(i,r)).map(i=>({id:i.source===t?i.target:i.source,edge:i})).sort((i,s)=>i.id.localeCompare(s.id)||co(i.edge,s.edge))}adjacency(t,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(c=>this.#e.require(c).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.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,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(a=>this.#e.require(a).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.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,n={}){this.#i(t);let r=n.kinds?new Set(n.kinds.map(m=>this.#e.require(m).kind)):void 0,o=n.direction??"outgoing",i=n.limit??Number.POSITIVE_INFINITY,s=n.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){n.signal?.throwIfAborted();let _=d[m];l+=1;let y=this.#t(_.id,o,r);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,n,r={}){if(this.#i(t),this.#i(n),t===n)return{value:[t],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}};let o=r.kinds?new Set(r.kinds.map(m=>this.#e.require(m).kind)):void 0,i=r.direction??"outgoing",s=r.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){r.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===n)return{value:ab(t,n,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,n={}){let r=this.closure(t,n),o=[t,...r.value].sort(),i=new Set(o),s=n.kinds?new Set(n.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(co)},meta:r.meta}}};function Hx(e,t,n=yt){return{source:e,target:t.id,kind:n.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 cb="__pm_suppress_host_output",As="@unbrained/pm-cli:suppress-host-output:v1";function hl(e){return e===void 0?{__pm_suppress_host_output:As}:{__pm_suppress_host_output:As,result:e}}function fo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[cb]===As}import Qt from"node:fs";import je from"node:path";import{fileURLToPath as db}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 lb="@unbrained/pm-cli";function ub(e){try{return JSON.parse(Qt.readFileSync(e,"utf8")).name===lb}catch{return!1}}function fb(e){let t=Qt.existsSync(e)&&Qt.statSync(e).isDirectory()?je.resolve(e):je.dirname(je.resolve(e));for(;;){let n=je.join(t,"package.json");if(Qt.existsSync(n)&&ub(n))return t;let r=je.dirname(t);if(r===t)return;t=r}}function mo(e,t=[]){let n=db(e);return fb(n)||je.resolve(je.dirname(n),...t)}function Kx(e,t=[]){try{let n=je.join(mo(e,t),"package.json");if(!Qt.existsSync(n))return;let r=JSON.parse(Qt.readFileSync(n,"utf8"));return typeof r.version=="string"&&r.version.trim().length>0?r.version:void 0}catch{return}}function Yx(e=process.env,t="PM_CLI_PACKAGE_ROOT",n,r=[]){let o=e[t];return typeof o=="string"&&o.trim().length>0?je.resolve(o.trim()):n?mo(n,r):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]="53865a81-4c96-51e2-a378-ae0e2781a50f")}catch{}})();var po={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},_o=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),ht=["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 z(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function mb(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function pe(e){return e?D(e):{}}function _e(e){return e?D(e):mb()}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 pb=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),_b=["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 yb(e,t){for(let n of _b){let r=e[n];if(r===void 0)continue;if(!Array.isArray(r)||r.some(i=>typeof i!="string"))return!1;let o=r.map(i=>pb.has(n)?z(i):i.trim()).filter(i=>i.length>0);t[n]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function hb(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n;if(r.format!=="json"&&r.format!=="toon"||!Array.isArray(r.commands)||r.commands.some(o=>typeof o!="string")||typeof r.result_discriminator!="boolean")return null;t.push({format:r.format,commands:[...new Set(r.commands.map(o=>z(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:r.result_discriminator})}return t.sort((n,r)=>n.format.localeCompare(r.format))}function gb(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n.commands;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))return null;t.push({commands:[...new Set(r.map(o=>z(o)))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i))})}return t}function yo(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 n={schema_version:1};if(!yb(t,n))return null;let r=t.preflight_overrides;if(r!==void 0&&(!Number.isInteger(r)||r<0))return null;typeof r=="number"&&(n.preflight_overrides=r);let o=t.renderer_ownership;if(o!==void 0){let s=hb(o);if(s===null)return null;n.renderer_ownership=s}let i=t.preflight_ownership;if(i!==void 0){let s=gb(i);if(s===null)return null;n.preflight_ownership=s}return n}function eN(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]="7359c10a-4c56-57ea-8254-fc26b19e5c84")}catch{}})();function qn(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Be(e){return Pe.includes(e)}function gl(e){let t=e.trim().toLowerCase();return Be(t)?t:null}function bl(e){return e.filter(t=>!Be(t))}function Is(e){let t=e.trim().toLowerCase();return t.length===0?null:vd[t]??null}function wl(e){let t=qn([...e].map(i=>i.toLowerCase())),n=[],r=[];for(let i of t){let s=Is(i);if(s){n.push(s),r.push({alias:i,target:s});continue}n.push(i)}let o=[...new Map(r.map(i=>[`${i.alias}>${i.target}`,i])).values()].sort((i,s)=>i.alias.localeCompare(s.alias));return{capabilities:qn(n),legacy_aliases:o}}function bb(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Is(t);if(n)return n;let r=Math.max(1,Math.floor(t.length*.34)),o=null,i=Number.POSITIVE_INFINITY;for(let s of Pe){let a=ao(t,s,r);a!==null&&a<i&&(i=a,o=s)}return o}function vl(e,t,n){let r=Pe.join(","),o=bb(n)??"none";return`extension_capability_unknown:${e}:${t}:${n}:allowed=${r}:suggested=${o}`}function El(e,t,n){let r=n.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${r}`}function wb(e){let t=/^extension_capability_unknown:(global|project):([^:]+):([^:]+):allowed=([^:]+):suggested=([^:]+)$/.exec(e.trim());if(!t)return null;let[,n,r,o,i,s]=t,a=n,c=i.split(",").map(u=>u.trim()).filter(u=>u.length>0),d=Is(o),l=(s==="none"?void 0:s)??d??void 0;return{layer:a,name:r,capability:o,allowed_capabilities:c,capability_contract_version:ns,suggested_capability:l,suggestion_source:l?d===l?"legacy_alias":"nearest_match":void 0,legacy_alias_target:d??void 0}}function vb(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,n,r,o]=t,i=n,s=[...Pe],a=[];for(let c of o.split(",")){let[d,l]=c.split(">"),u=d?.trim(),f=l?.trim().toLowerCase();!u||!f||!Be(f)||a.push({layer:i,name:r,capability:u,allowed_capabilities:s,capability_contract_version:ns,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 Vn(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function Ts(){return{overrides:[],handlers:[]}}function Cs(){return{overrides:[]}}function Rs(){return{overrides:[]}}function xs(){return{overrides:[]}}function Ns(){return{overrides:[]}}function Ds(){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 Eb=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 kb(e){return{unknownKeys:Object.keys(e).filter(t=>!Eb.has(t)).sort((t,n)=>t>n?1:-1),missingVersionBounds:e.pm_min_version===void 0&&e.pm_max_version===void 0}}function Sb(e){let t=kb(e),n=t.unknownKeys.map(r=>({code:"manifest_unknown_key",path:r,...r==="compatibility"?{suggested_key:"pm_min_version"}:{},message:r==="compatibility"?'Manifest key "compatibility" is ignored; declare the canonical pm_min_version and optional pm_max_version fields instead.':`Manifest key "${r}" is not part of the extension manifest contract and will be ignored.`}));return t.missingVersionBounds&&n.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:n.length===0,findings:n}}function kl(e,t,n){return Sb(n).findings.map(r=>r.code==="manifest_unknown_key"?`extension_manifest_unknown_key:${e}:${t.name}:key=${r.path}${r.suggested_key?`:suggested=${r.suggested_key}`:""}`:`extension_manifest_no_version_bounds:${e}:${t.name}:suggested=pm_min_version`)}import{constants as We}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 Sl=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"}]]),Ob=/^[a-z][a-z0-9_]{0,63}$/u,Ab=new Map([[We.errno.EACCES,"EACCES"],[We.errno.EDQUOT,"EDQUOT"],[We.errno.EMFILE,"EMFILE"],[We.errno.ENFILE,"ENFILE"],[We.errno.ENOMEM,"ENOMEM"],[We.errno.ENOSPC,"ENOSPC"],[We.errno.EPERM,"EPERM"],[We.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),Ib={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function Tb(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&Sl.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:Ab.get(Math.abs(t.errno))??null}function Cb(e,t,n={}){let r=Tb(e);if(r===null)return null;if(!Ob.test(t))throw new g("Host environment operation labels must be bounded identifiers.",h.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=Sl.get(r);return new g(`Host filesystem operation ${t} ${o.summary}.`,h.GENERIC_FAILURE,{code:n.codes?.[o.category]??Ib[o.category].code,reason:r,required:o.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[o.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function Ol(e,t,n={}){try{return await t()}catch(r){throw Cb(r,e,n)??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]="4a7b042c-7fb8-57a5-8f94-de44f82d7589")}catch{}})();function Rb(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Ee(e,t){let n=e.slice(0,t),r=n.charCodeAt(n.length-1),o=e.charCodeAt(n.length);return r>=55296&&r<=56319&&o>=56320&&o<=57343?n.slice(0,-1):n}function uN(e){return Rb(e).split(/[^a-z0-9]+/).filter(t=>t.length>0)}function fN(e,t){if(e.length===0&&t.length===0)return 1;if(e.length===0||t.length===0)return 0;let n=new Set(e),r=new Set(t),o=0;for(let s of n)r.has(s)&&(o+=1);let i=new Set([...n,...r]).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]="f49bad80-c246-59b3-950d-7143585fbdb5")}catch{}})();var xb=5e3;async function Bn(e,t,n){let r=[];for(let o of e)try{await o.run(D(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}async function Nb(e,t){return Bn(e.beforeCommand,"beforeCommand",t)}function Db(e,t,n){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 r=e,o=typeof r.code=="string"?r.code.trim():"",i=typeof r.remediation=="string"?r.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 r.message=="string"?r.message.trim():"";throw new g(s||`Extension mutation guard ${t.name} denied ${n}.`,h.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function Ps(e,t){for(let n of e.beforeMutation??[]){let r,o;try{let i=Promise.resolve().then(()=>n.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(()=>{}),r=await Promise.race([i,new Promise((s,a)=>{o=setTimeout(()=>{a(new g(`Extension mutation guard ${n.name} timed out before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},xb),o.unref?.()})])}catch(i){throw i instanceof g?i:new g(`Extension mutation guard ${n.name} failed before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(o)}Db(r,n,t.operation)}}async function Pb(e,t){return Bn(e.afterCommand,"afterCommand",t)}async function Ms(e,t){return Bn(e.onWrite,"onWrite",t)}async function $s(e,t){return Bn(e.onRead,"onRead",t)}async function js(e,t){return Bn(e.onIndex,"onIndex",t)}function Mb(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 n=t.replace(/\s+/gu," ").trim();if(n.length===0)return"";let r=300;return n.length>r?`${Ee(n,r-1)}\u2026`:n}function ho(e,t){if(typeof e!="object"||e===null||typeof e[t]!="string")return;let n=String(e[t]).replace(/\s+/gu," ").trim();return n.length>0?Ee(n,300):void 0}function $b(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 n=z(t.command);if(n.length===0)return{handled:!1,result:null,warnings:[]};let r=[...e.handlers].reverse().find(o=>o.command===n);if(!r)return{handled:!1,result:null,warnings:[]};try{let o=await r.run({command:n,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",$b(o)],["errorCode",ho(o,"code")],["remediation",ho(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 Object.defineProperty({handled:!1,result:null,warnings:[`extension_command_handler_failed:${r.layer}:${r.name}:${r.command}`],errorMessage:Mb(o),...Object.fromEntries([["errorCode",ho(o,"code")],["remediation",ho(o,"remediation")]].filter(s=>s[1]!==void 0))},"cause",{value:o,configurable:!0})}}async function Fs(e,t){let n=z(t.command);if(n.length===0)return{overridden:!1,context:{command:n,args:D(t.args),options:pe(t.options),global:_e(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 r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,context:{command:n,args:D(t.args),options:pe(t.options),global:_e(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(r.run({command:n,args:D(t.args),options:pe(t.options),global:_e(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?pe(o.options):pe(t.options),a=o.global?_e(o.global):_e(t.global);return{overridden:!0,context:{command:n,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:n,args:D(t.args),options:pe(t.options),global:_e(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:${r.layer}:${r.name}:${r.command}`]}}}async function zs(e,t){let n={command:z(t.command),args:D(t.args),options:pe(t.options),global:_e(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},r=D(t.decision),o=[...e.overrides].reverse().find(i=>!i.commands?.length||i.commands.includes(n.command));if(!o)return{overridden:!1,context:n,decision:r,warnings:[]};try{let i=await Promise.resolve(o.run({command:n.command,args:D(n.args),options:pe(n.options),global:_e(n.global),pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel,decision:D(r)}))??{},s={command:n.command,args:Array.isArray(i.args)?D(i.args):n.args,options:i.options?pe(i.options):n.options,global:i.global?_e(i.global):n.global,pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel},a={enforce_item_format_gate:typeof i.enforce_item_format_gate=="boolean"?i.enforce_item_format_gate:r.enforce_item_format_gate,run_preflight_item_format_sync:typeof i.run_preflight_item_format_sync=="boolean"?i.run_preflight_item_format_sync:r.run_preflight_item_format_sync,run_extension_migrations:typeof i.run_extension_migrations=="boolean"?i.run_extension_migrations:r.run_extension_migrations,enforce_mandatory_migration_gate:typeof i.enforce_mandatory_migration_gate=="boolean"?i.enforce_mandatory_migration_gate:r.enforce_mandatory_migration_gate};return{overridden:!0,context:s,decision:a,warnings:[]}}catch{return{overridden:!1,context:n,decision:r,warnings:[`extension_preflight_override_failed:${o.layer}:${o.name}`]}}}function Al(e){return{handled:!1,result:e.payload,warnings:[]}}function Il(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function Tl(e){return{service:e.service,command:e.command?z(e.command):void 0,args:e.args?D(e.args):void 0,options:e.options?pe(e.options):void 0,global:e.global?_e(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 jb(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 Cl(e,t){return jb(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 Rl(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&W(e,n.payload)}function xl(e,t,n){if(t.handled){if(e.passThrough===!0){n.push(`extension_service_pass_through_contract_violated:${e.layer}:${e.name}:${e.service}`);return}return{handled:!0,result:t.result,warnings:n}}}function Us(e,t){let n=Il(e,t.service);if(n.length===0)return Al(t);let r=[];for(let o of n)try{let i=Tl(t),s=o.run(i);if(s instanceof Promise){r.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(Rl(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=xl(o,Cl(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}async function Hs(e,t){let n=Il(e,t.service);if(n.length===0)return Al(t);let r=[];for(let o of n)try{let i=Tl(t),s=await Promise.resolve(o.run(i));if(Rl(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=xl(o,Cl(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}function qs(e,t){let n=z(t.command);if(n.length===0)return{overridden:!1,result:t.result,warnings:[]};let r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,result:t.result,warnings:[]};try{let o=pe(t.options),i=_e(t.global),s=r.run({command:n,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:${r.layer}:${r.name}:${r.command}`]}:{overridden:!0,result:s,warnings:[]}}catch{return{overridden:!1,result:t.result,warnings:[`extension_command_override_failed:${r.layer}:${r.name}:${r.command}`]}}}function Lb(e,t,n){if((e.commands?.length??0)>0&&!e.commands?.includes(t))return!1;if(e.resultDiscriminator===void 0)return!0;try{return e.resultDiscriminator(D(n))}catch{return!1}}function Vs(e,t){let n=typeof t.command=="string"?z(t.command):"",r=[...e.overrides].reverse().find(o=>o.format===t.format&&Lb(o,n,t.result));if(!r)return{overridden:!1,rendered:null,warnings:[]};try{let o=Array.isArray(t.args)?D(t.args):[],i=pe(t.options),s=_e(t.global),a=typeof t.pm_root=="string"?t.pm_root:"",c=r.run({format:t.format,command:n,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:${r.layer}:${r.name}:${r.format}`]}:{overridden:!0,rendered:c,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${r.layer}:${r.name}:${r.format}`]}}}import Et from"node:fs/promises";import vt from"node:path";import{pathToFileURL as ww}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]="559b05dc-0290-5a7c-97b9-ef1e5e8670ba")}catch{}})();function Nl(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(([n,r])=>[n,r.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[n,r]of Object.entries(t.registrations))e.registrations[n].length=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]="17ae377d-20c2-5e45-825a-48a79c6c7601")}catch{}})();function K(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return t}function te(e,t){if(t!==void 0&&typeof t!="boolean")throw new TypeError(`${e} must be a boolean when provided`)}function B(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 Dl(e,t){if(t===void 0)return;let n=r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean";if(Array.isArray(t)){for(let[r,o]of t.entries())if(!n(o))throw new TypeError(`${e}[${r}] must be a string, number, or boolean`);return}if(!n(t))throw new TypeError(`${e} must be a string, number, or boolean, or an array of these when provided`)}function gt(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[n,r]of t.entries())if(typeof r!="string"||r.trim().length===0)throw new TypeError(`${e}[${n}] must be a non-empty string`)}}function Wn(e,t){if(gt(e,t),!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){let i=o.trim();i.length===0||r.has(i)||(r.add(i),n.push(i))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34536eba-0f92-5599-a807-5b39b000e733")}catch{}})();var Bs=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 Fb=new Set(Bs);function zb(e){if(e!==void 0&&!Fb.has(String(e)))throw new Error(`registerCommand definition.family must be one of: ${Bs.join(", ")}`)}function Pl(e){B("registerCommand definition.action",e.action),B("registerCommand definition.family",e.family),B("registerCommand definition.description",e.description),B("registerCommand definition.intent",e.intent),B("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");zb(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 Ml(e,t="",n=""){if(e===void 0)return;if(en(t)||en(n))throw new TypeError("Native pm commands and actions cannot declare read_output");let r=K("registerCommand definition.read_output",e);if(Object.keys(r).some(s=>s!=="row_keys")||!Array.isArray(r.row_keys))throw new TypeError("registerCommand definition.read_output requires only row_keys: string[]");let o=Array.from(r.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 en(e){let t=e.trim().toLowerCase().replace(/\s+/gu,"-");return Kt.includes(t)||ht.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 Ub(e){let t=K("registerExporter options.output",e),n=new Set(["channel","receipt","media_type"]);for(let r of Object.keys(t))if(!n.has(r))throw new TypeError(`registerExporter options.output contains unsupported field ${r}`);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 B("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 $l(e,t,n){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 r=Ub(t.output);return!n&&r.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."),r}function Ws(e,t,n){return{registration:t,action:n,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 jl(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 we(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 Hb(e){let t=e.trim().toLowerCase();if(t.length===0)return"";let n=t.split(/[.:/]/).map(r=>r.replace(/[\s_-]+/g,"")).filter(r=>r.length>0);return n.length===0?"":n.length===1?n[0]:`${n[0]}.${n.slice(1).join("")}`}function tn(e){return new Set((e??[]).map(t=>Hb(t)).filter(t=>t.length>0))}function Ll(e){let t=we(e);return jr.includes(t)?t:"off"}function Fl(e){let t=we(e);return Lr.includes(t)?t:"off"}function Gn(e){let t=we(e);return Fr.includes(t)?t:"none"}function Gs(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Ed.includes(t)?t:void 0}function zl(e){if(typeof e=="string"){let t=Gs(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:Gs(e.global)??"block",project:Gs(e.project)??"block"}:{global:"block",project:"block"}}function qb(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function j(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function Vb(e){let t=we(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?Gn(e.sandbox_profile):void 0,allowedCapabilities:P(e.allowed_capabilities),blockedCapabilities:P(e.blocked_capabilities),allowedSurfaces:tn(e.allowed_surfaces),blockedSurfaces:tn(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 Ul(e){let t=new Map;for(let n of e??[]){let r=Vb(n);r&&t.set(r.name,r.normalized)}return t}function Bb(e){let t=[],n=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of j([...e.allowedCapabilities,...e.blockedCapabilities]))Be(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of n)for(let i of j([...o.allowedCapabilities,...o.blockedCapabilities]))Be(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let r=new Set(zr);for(let o of j([...e.allowedSurfaces,...e.blockedSurfaces]))r.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of n)for(let i of j([...o.allowedSurfaces,...o.blockedSurfaces]))r.has(i)||t.push(`extension_policy_unknown_surface:${o.name}:${i}`);return[...new Set(t)].sort((o,i)=>o.localeCompare(i))}function Hl(e){let t=e.extensions?.policy??{},n=P(t.allowed_capabilities),r=P(t.blocked_capabilities),o=tn(t.allowed_surfaces),i=tn(t.blocked_surfaces),s=Ul(t.extension_overrides);return{mode:Ll(t.mode),trustMode:Fl(t.trust_mode),pmMaxVersionExceededMode:zl(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:P(t.trusted_extensions),defaultSandboxProfile:Gn(t.default_sandbox_profile),allowedExtensions:P(t.allowed_extensions),blockedExtensions:P(t.blocked_extensions),allowedCapabilities:n,blockedCapabilities:r,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:Bb({allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function ql(e){let t=[...e.overridesByName.values()].sort((n,r)=>n.name.localeCompare(r.name)).map(n=>({name:n.name,...n.disabled?{disabled:!0}:{},...n.requireTrusted?{require_trusted:!0}:{},...n.requireProvenance?{require_provenance:!0}:{},...n.sandboxProfile?{sandbox_profile:n.sandboxProfile}:{},...n.allowedCapabilities.size>0?{allowed_capabilities:j(n.allowedCapabilities)}:{},...n.blockedCapabilities.size>0?{blocked_capabilities:j(n.blockedCapabilities)}:{},...n.allowedSurfaces.size>0?{allowed_surfaces:j(n.allowedSurfaces)}:{},...n.blockedSurfaces.size>0?{blocked_surfaces:j(n.blockedSurfaces)}:{},...n.allowedCommands.size>0?{allowed_commands:j(n.allowedCommands)}:{},...n.blockedCommands.size>0?{blocked_commands:j(n.blockedCommands)}:{},...n.allowedActions.size>0?{allowed_actions:j(n.allowedActions)}:{},...n.blockedActions.size>0?{blocked_actions:j(n.blockedActions)}:{},...n.allowedServices.size>0?{allowed_services:j(n.allowedServices)}:{},...n.blockedServices.size>0?{blocked_services:j(n.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:qb(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:j(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:j(e.allowedExtensions),blocked_extensions:j(e.blockedExtensions),allowed_capabilities:j(e.allowedCapabilities),blocked_capabilities:j(e.blockedCapabilities),allowed_surfaces:j(e.allowedSurfaces),blocked_surfaces:j(e.blockedSurfaces),allowed_commands:j(e.allowedCommands),blocked_commands:j(e.blockedCommands),allowed_actions:j(e.allowedActions),blocked_actions:j(e.blockedActions),allowed_services:j(e.allowedServices),blocked_services:j(e.blockedServices),extension_overrides:t}}function Vl(e){let t=Ul(e.extension_overrides);return{mode:Ll(e.mode),trustMode:Fl(e.trust_mode),pmMaxVersionExceededMode:zl(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:P(e.trusted_extensions),defaultSandboxProfile:Gn(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:tn(e.allowed_surfaces),blockedSurfaces:tn(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 Ge(e,t){return e.overridesByName.get(we(t))??null}function nn(e,t,n,r,o){return t.has(n)?o:e.size>0&&!e.has(n)?r:null}function Bl(e,t,n){let r=n.trim().toLowerCase(),o=Ge(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return nn(i,s,r,"capability_not_allowlisted","capability_blocked")}function Wb(e,t,n){let r=Ge(e,t.name),o=r&&r.allowedSurfaces.size>0?r.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...r?r.blockedSurfaces:[]]);return nn(o,i,n,"surface_not_allowlisted","surface_blocked")}function Gb(e,t,n){let r=z(n);if(r.length===0)return null;let o=Ge(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return nn(i,s,r,"command_not_allowlisted","command_blocked")}function Kb(e,t,n){let r=we(n).replace(/\s+/g,"-");if(r.length===0)return null;let o=Ge(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return nn(i,s,r,"action_not_allowlisted","action_blocked")}function Yb(e,t,n){let r=we(n);if(r.length===0)return null;let o=Ge(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return nn(i,s,r,"service_not_allowlisted","service_blocked")}function Xb(e,t){let n=we(t.name);return Ge(e,t.name)?.disabled===!0?"extension_override_disabled":nn(e.allowedExtensions,e.blockedExtensions,n,"extension_not_allowlisted","extension_blocked")}function Jb(e,t){if(e.trustMode==="off")return null;let n=Ge(e,t.name),r=we(t.name),o=t.trusted===!0,i=t.provenanceVerified===!0;return e.trustedExtensions.size>0&&!e.trustedExtensions.has(r)?"extension_not_trusted":(n?.requireTrusted===!0||e.trustMode==="warn"||e.trustMode==="enforce")&&!o?"extension_untrusted":(e.requireProvenance||n?.requireProvenance===!0)&&!i?"provenance_missing_or_unverified":null}function Zb(e,t){if(e.mode==="off")return null;let n=Ge(e,t.name)?.sandboxProfile??t.sandboxProfile??e.defaultSandboxProfile;if(n==="none")return null;let r=t.permissions;if(!r)return"sandbox_permissions_missing";let o=i=>r[i]===!0;return n==="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 go(e,t,n,r,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}:${n.layer}:${n.name}:reason=${r}${s}`}function Wl(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let n=[],r=Xb(e,t);r&&n.push({reason:r,scope:"extension",mode:e.mode});let o=Jb(e,t);o&&n.push({reason:o,scope:"trust",mode:e.trustMode});let i=Zb(e,t);i&&n.push({reason:i,scope:"extension",mode:e.mode});let s=n.find(c=>c.mode==="enforce");if(s)return{allowed:!1,warning:go("blocked",s.scope,t,s.reason)};let a=n.find(c=>c.mode==="warn");return a?{allowed:!0,warning:go("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function Gl(e,t,n){if(e.mode==="off")return{allowed:!0,warning:null};let r=Bl(e,t,n);return r?{allowed:e.mode==="warn",warning:go(e.mode==="warn"?"violation":"blocked","capability",t,r,{capability:n.trim().toLowerCase()})}:{allowed:!0,warning:null}}function Qb(e,t,n,r,o){let i=typeof r=="string"?Bl(e,t,r):null,s=Wb(e,t,n),a=o.command?Gb(e,t,o.command):null,c=o.action?Kb(e,t,o.action):null,d=o.service?Yb(e,t,o.service):null;return i??s??a??c??d}function ew(e,t,n,r){let o={method:we(e).replace(/\s+/g,"_"),surface:t};return n&&(o.capability=n),r.command&&(o.command=z(r.command)),r.action&&(o.action=we(r.action).replace(/\s+/g,"-")),r.service&&(o.service=we(r.service)),o}function Kl(e,t,n,r,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=Qb(e,t,n,o,s);if(!a)return{allowed:!0,warning:null};let c=go(e.mode==="warn"?"violation":"blocked","registration",t,a,ew(r,n,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 Xl=100;function Yl(e,t){let n=e[t];if(n!=null)return typeof n!="string"||n.trim().length===0?null:n.trim()}function tw(e){if(e==null)return;let t=Ve(e);if(!t)return null;let n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i))){if(r.trim().length===0)return null;let o=t[r];if(typeof o!="string"||o.trim().length===0)return null;n[r.trim()]=o.trim()}return Object.keys(n).length>0?n:void 0}function Ks(e,t){let n=e[t];return typeof n!="string"||n.trim().length===0?null:n.trim()}function Jl(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function bt(e){if(e!=null)return typeof e!="boolean"?null:e}function nw(e){let t=Jl(e.priority);return t===void 0?Xl:t}function rw(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let n=Gn(t);return n!==t.trim().toLowerCase()?null:n}function Ys(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function ow(e){if(e==null)return;let t=Ve(e);if(!t)return null;let n=Ys(t.source),r=Ys(t.signature),o=Ys(t.attestation),i=t.verified===void 0||t.verified===null?void 0:typeof t.verified=="boolean"?t.verified:null;return i===null?null:{...n?{source:n}:{},...r?{signature:r}:{},...o?{attestation:o}:{},...typeof i=="boolean"?{verified:i}:{}}}function iw(e){if(e==null)return;let t=Ve(e);if(!t)return null;let n=bt(t.fs_read),r=bt(t.fs_write),o=bt(t.network),i=bt(t.env_read),s=bt(t.env_write),a=bt(t.process_spawn);return[n,r,o,i,s,a].includes(null)?null:{...typeof n=="boolean"?{fs_read:n}:{},...typeof r=="boolean"?{fs_write:r}:{},...typeof o=="boolean"?{network:o}:{},...typeof i=="boolean"?{env_read:i}:{},...typeof s=="boolean"?{env_write:s}:{},...typeof a=="boolean"?{process_spawn:a}:{}}}function sw(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(n=>typeof n!="string"))return null;let t=wl(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function aw(e){if(e==null)return;let t=Ve(e);if(!t)return null;let n=t.commands;if(n==null)return;if(!Array.isArray(n)||n.some(o=>typeof o!="string"))return null;let r=[...new Set(n.map(o=>z(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return r.length>0?{commands:r}:void 0}function cw(e){let t=Jl(e.manifest_version);if(t===null)return null;let n=Yl(e,"pm_min_version");if(n===null)return null;let r=Yl(e,"pm_max_version");if(r===null)return null;let o=tw(e.engines);if(o===null)return null;let i=bt(e.trusted);if(i===null)return null;let s=rw(e);if(s===null)return null;let a=ow(e.provenance);if(a===null)return null;let c=iw(e.permissions);if(c===null)return null;let d=sw(e.capabilities);if(d===null)return null;let l=aw(e.activation);if(l===null)return null;let u=yo(e.contributions);return u===null?null:{manifest_version:t,pm_min_version:n,pm_max_version:r,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 Xs(e){if(typeof e!="object"||e===null)return null;let t=e,n=Ks(t,"name");if(n===null)return null;let r=Ks(t,"version");if(r===null)return null;let o=Ks(t,"entry");if(o===null)return null;let i=nw(t);if(i===null)return null;let s=cw(t);return s===null?null:{name:n,version:r,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 dw from"node:fs/promises";import Kn 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 Zl(e,t){let n=Kn.dirname(t.manifest_path),r=Kn.relative(n,t.entry_path);if(r.startsWith("..")||Kn.isAbsolute(r))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=Kn.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await Ol("extension_module_graph_snapshot",()=>dw.cp(n,o,{recursive:!0,force:!0})),Kn.join(o,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]="bf5c3834-b388-507e-a13c-3beb5d096abb")}catch{}})();function Ql(e){let t=typeof e=="function"?e:e.run;if(typeof t!="function")throw new TypeError("registerPreflight override requires a function handler");let n=[...new Set((typeof e=="function"?[]:e.commands??[]).map(r=>{if(typeof r!="string"||r.trim().length===0)throw new TypeError("registerPreflight ownership.commands must contain non-empty command paths");return z(r)}))];return{run:t,...n.length>0?{commands:n}:{}}}function eu(e){let t=[];for(let n=1;n<e.overrides.length;n+=1){let r=e.overrides[n];for(let o of e.overrides.slice(0,n))r.commands?.length&&o.commands?.length&&!o.commands.some(i=>r.commands.includes(i))||t.push(`extension_preflight_override_collision:${r.layer}:${r.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 bo=Xt;function tu(e){let t=e.trim().toLowerCase();return bo.includes(t)?t:null}function nu(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Math.max(1,Math.floor(t.length*.34));for(let r of bo)if(ao(t,r,n)!==null)return r;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 ru(e){return e==="toon"||e==="json"}function ou(e){return Gt.includes(e)}function wt(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}var iu=Symbol("extension_registration_trace");function Le(e,t){let n=new TypeError(e);return Object.defineProperty(n,iu,{value:t,enumerable:!1,configurable:!1,writable:!1}),n}function su(e){return e instanceof Error?e[iu]:void 0}function Yn(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>Yn(t));if(typeof e=="function")return"[Function]";if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=Yn(t[r]);return n}return e}function Xn(e){if(Array.isArray(e))return e.map(t=>Xn(t));if(typeof e=="object"&&e!==null){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=Xn(t[r]);return n}return e}function rn(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Yn(t)}function Jn(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Xn(t)}function Zn(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(n=>rn(e,n))}function oe(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function Qn(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function Js(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Zs(e,t){return z(`${e} ${t}`)}function er(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}var lw=new Set(["low","medium","high"]),uw=new Set(["number","string_set"]),fw=new Set(["string","number","boolean"]);function au(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function mw(e,t,n){let r=`registerAssuranceMeasurementProvider provider.keys.${t}`,o=K(r,n);if(!uw.has(String(o.value_type)))throw new TypeError(`${r}.value_type must be number or string_set`);if(B(`${r}.description`,o.description),o.parameters===void 0)return;let i=K(`${r}.parameters`,o.parameters);for(let[s,a]of Object.entries(i)){let c=`${r}.parameters.${s}`;au(`${c}.name`,s);let d=K(c,a);if(!fw.has(String(d.type)))throw new TypeError(`${c}.type must be string, number, or boolean`);te(`${c}.required`,d.required),B(`${c}.description`,d.description)}if(Object.keys(i).length>50)throw new TypeError(`assurance provider ${e} key ${t} exceeds 50 parameters`)}function cu(e){let t=K("registerAssuranceMeasurementProvider provider",e),n=au("registerAssuranceMeasurementProvider provider.id",t.id);if(!/^[a-z0-9][a-z0-9-]*$/u.test(n))throw new TypeError("registerAssuranceMeasurementProvider provider.id must be a stable lowercase id");if(!lw.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 r=K("registerAssuranceMeasurementProvider provider.keys",t.keys);if(Object.keys(r).length===0)throw new TypeError("registerAssuranceMeasurementProvider provider.keys requires at least one key");for(let[o,i]of Object.entries(r)){if(!/^[a-z0-9][a-z0-9-]*$/u.test(o))throw new TypeError(`registerAssuranceMeasurementProvider provider key ${o} must be a stable lowercase id`);mw(n,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 pw=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","value_validation","visible"]);function wo(e,t){return Zn(e,t).map(n=>(n.repeatable===!0&&(n.list=!0),n))}function _w(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Qs(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 n=_w(t);if(n.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return n}function ea(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[r,o]of e.entries()){let i=K(`registerCommand definition.arguments[${r}]`,o),s=oe(`registerCommand definition.arguments[${r}].name`,i.name);if(te(`registerCommand definition.arguments[${r}].required`,i.required),te(`registerCommand definition.arguments[${r}].variadic`,i.variadic),B(`registerCommand definition.arguments[${r}].description`,i.description),s.includes(" "))throw new TypeError(`registerCommand definition.arguments[${r}].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 n=t.map((r,o)=>r.variadic?o:-1).filter(r=>r>=0);if(n.length>1)throw new TypeError("registerCommand definition.arguments supports at most one variadic argument");if(n.length===1&&n[0]!==t.length-1)throw new TypeError("registerCommand definition.arguments variadic argument must be the final argument");return t}function vo(e){if(!Array.isArray(e))throw new TypeError("registerFlags flags requires an array of object definitions");for(let[t,n]of e.entries()){let r=K(`registerFlags flags[${t}]`,n),o=Object.keys(r).filter(c=>!pw.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=r.long,s=r.short;if(i===void 0&&s===void 0)throw new TypeError(`registerFlags flags[${t}] requires at least one of long or short`);B(`registerFlags flags[${t}].long`,i),B(`registerFlags flags[${t}].short`,s);let a=il(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${sl(a.token,a.failure)}`);if(B(`registerFlags flags[${t}].value_name`,r.value_name),B(`registerFlags flags[${t}].description`,r.description),te(`registerFlags flags[${t}].required`,r.required),te(`registerFlags flags[${t}].enabled`,r.enabled),te(`registerFlags flags[${t}].visible`,r.visible),te(`registerFlags flags[${t}].list`,r.list),te(`registerFlags flags[${t}].repeatable`,r.repeatable),r.list!==void 0&&r.repeatable!==void 0&&r.list!==r.repeatable)throw new TypeError(`registerFlags flags[${t}].list and repeatable must match when both are provided`);if(Dl(`registerFlags flags[${t}].default`,r.default),Array.isArray(r.default)&&r.list!==!0&&r.repeatable!==!0)throw new TypeError(`registerFlags flags[${t}].default cannot be an array unless list is true.`);du(`registerFlags flags[${t}]`,r),yw(`registerFlags flags[${t}]`,r)}}function yw(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 n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0),r=n===void 0?null:so(n);if(r!=="number"&&r!=="boolean")throw new TypeError(`${e}.value_validation "strict" requires value_type "number" or "boolean" (string values are never malformed).`)}function du(e,t){let n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0);if(n===void 0)return;let r=so(n);if(r===null)throw new TypeError(`${e} value_type "${n}" 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?pl(t.default):[t.default];for(let[i,s]of o.entries())if(!_l(s,r)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${r}.`)}}function lu(e){if(!Array.isArray(e))throw new TypeError("registerItemFields fields requires an array of object definitions");for(let[t,n]of e.entries()){let r=K(`registerItemFields fields[${t}]`,n);oe(`registerItemFields fields[${t}].name`,r.name);let o=oe(`registerItemFields fields[${t}].type`,r.type);if(tu(o)===null){let i=nu(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${bo.join(", ")}).${s}`)}te(`registerItemFields fields[${t}].optional`,r.optional)}}function hw(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].command_option_policies`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=K(i,o);oe(`${i}.command`,s.command),oe(`${i}.option`,s.option),te(`${i}.enabled`,s.enabled),te(`${i}.required`,s.required),te(`${i}.visible`,s.visible)}}function gw(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].options`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=K(i,o);oe(`${i}.key`,s.key),gt(`${i}.values`,s.values),te(`${i}.required`,s.required),gt(`${i}.aliases`,s.aliases)}}function uu(e){if(!Array.isArray(e))throw new TypeError("registerItemTypes types requires an array of object definitions");for(let[t,n]of e.entries()){let r=`registerItemTypes types[${t}]`,o=K(r,n);oe(`${r}.name`,o.name),B(`${r}.folder`,o.folder),gt(`${r}.aliases`,o.aliases),gt(`${r}.required_create_fields`,o.required_create_fields),gt(`${r}.required_create_repeatables`,o.required_create_repeatables),hw(t,o.command_option_policies),gw(t,o.options)}}function fu(e){let t=K("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(te("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 mu=["types","statuses","fields","workflows","config","templates","packages"],bw={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[n,r]of t.allowed_transitions.entries())if(!Array.isArray(r))throw new TypeError(`${e}.allowed_transitions[${n}] 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 pu(e){let t=K("registerProfile profile",e);if(oe("registerProfile profile.name",t.name),oe("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 n of mu){let r=t[n];if(r!==void 0){if(!Array.isArray(r))throw new TypeError(`registerProfile profile.${n} must be an array when provided`);for(let[o,i]of r.entries()){if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`registerProfile profile.${n}[${o}] must be an object`);bw[n]?.(`registerProfile profile.${n}[${o}]`,i)}}}}function _u(e){e.summary===void 0&&(e.summary="");for(let t of mu)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 yu(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 hu(e){return typeof e=="string"?e:String(e)}function tr(e){let t=e.trim().replace(/^>=\s*/,"").replace(/^v/i,"").split(/[+-]/,1)[0];return/^\d+(?:[.-]\d+)*$/.test(t)?t.split(/[.-]/).map(n=>Number(n)):null}function ta(e,t){let n=tr(e),r=tr(t);if(!n||!r)return null;let o=Math.max(n.length,r.length);for(let i=0;i<o;i+=1){let s=n[i]??0,a=r[i]??0;if(s>a)return 1;if(s<a)return-1}return 0}function gu(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let n=hu(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(!tr(n))return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(t===null)return{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:null};let r=ta(t,n);return r===null?{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:t}:r<0?{kind:"pm_min_version",status:"unmet",allowed:!1,required:n,current:t}:{kind:"pm_min_version",status:"ok",allowed:!0,required:n,current:t}}function bu(e,t,n){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let r=hu(e);if(typeof e!="string"||r.trim().length===0)return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(/^[<>=~^]/.test(r.trim())||!tr(r))return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(t===null)return{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:null};let o=ta(t,r);return o===null?{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:t}:o>0?n==="warn"?{kind:"pm_max_version",status:"exceeded_warn",allowed:!0,required:r,current:t}:{kind:"pm_max_version",status:"exceeded",allowed:!1,required:r,current:t}:{kind:"pm_max_version",status:"ok",allowed:!0,required:r,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]="3abe36f7-3c97-58d2-a56d-b4e0ea958461")}catch{}})();var wu=null,vw=Object.freeze(kd()),vu=0;function Ew(e=Date.now()){return vu+=1,`${vu}-${e}`}function kw(e,t,n){return n.has(e)?!1:t.size===0?!0:t.has(e)}async function Sw(e,t){let[n,r]=await Promise.all([Et.realpath(e),Et.realpath(t)]);return zn(n,r)}function Ow(e,t=process.cwd()){return{global:vt.join(Qd(t),"extensions"),project:vt.join(e,"extensions")}}async function Aw(e){try{return(await Et.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}catch{return[]}}function Iw(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 Eu(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function Tw(e){let t=new Map;try{let n=JSON.parse(await Et.readFile(vt.join(e,".managed-extensions.json"),"utf8")),r=Ve(n)?.entries;if(!Array.isArray(r))return t;for(let o of r){if(typeof o!="object"||o===null)continue;let i=o,s=Eu(i.source?.package),a=[i.source?.input,i.source?.name,s].map(l=>Eu(l)).filter(l=>l!==void 0),c=yo(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 ku(e){return[...e].sort((t,n)=>{if(t.manifest.priority!==n.manifest.priority)return t.manifest.priority-n.manifest.priority;let r=t.manifest.name.localeCompare(n.manifest.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function Cw(e,t){let n=[...ku(e),...ku(t)],r=[];for(let o of n){let i=r.findIndex(s=>s.manifest.name===o.manifest.name);i>=0&&r.splice(i,1),r.push(o)}return r}async function Su(e,t,n,r,o){let i=[],s=[],a=[],c=await Aw(t),d=await Tw(t);for(let l of c){let u=await Nw(e,t,l,n,r,d,o);i.push(u.diagnostic),s.push(...u.warnings),u.candidate&&a.push(u.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function Rw(){return{diagnostics:[],warnings:[],candidates:[]}}function Ou(e,t,n,r){return{diagnostic:{layer:e,directory:t,manifest_path:n,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[r],candidate:null}}function xw(e,t,n,r,o,i,s,a){let c=kl(e,t,n);Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&c.push(El(e,t.name,t.legacy_capability_aliases));for(let d of bl(t.capabilities))c.push(vl(e,t.name,d));return r?o||c.push(`extension_entry_missing:${e}:${t.name}`):c.push(`extension_entry_outside_extension:${e}:${t.name}`),i.warning&&c.push(a?i.warning:i.warning.replace("extension_pm_","extension_disabled_pm_")),s.warning&&c.push(a?s.warning:s.warning.replace("extension_pm_","extension_disabled_pm_")),c}async function Nw(e,t,n,r,o,i,s){let a=vt.join(t,n),c=vt.join(a,"manifest.json");if(!await mt(c))return Ou(e,n,c,`extension_manifest_missing:${e}:${n}`);let d,l;try{let de=JSON.parse(await Et.readFile(c,"utf8"));l=Ve(de),d=Xs(de)}catch{l=null,d=null}if(!d||!l)return Ou(e,n,c,`extension_manifest_invalid:${e}:${n}`);let u=vt.resolve(a,d.entry),f=zn(a,u),m=f?await mt(u):!1,_=f&&m?await Sw(a,u):f,y=kw(d.name,r,o),w=await Mw(e,d),v=await $w(e,d,s),T=xw(e,d,l,_,m,w,v,y),H=_&&m&&w.allowed&&v.allowed,X=i.get(`directory:${n}`)??i.get(`name:${d.name}`);return{diagnostic:{layer:e,directory:n,manifest_path:c,name:d.name,version:d.version,entry:d.entry,priority:d.priority,entry_path:u,enabled:y,status:H?"ok":"warn"},warnings:T,candidate:jl({layer:e,directory:n,manifestPath:c,entryPath:u,manifest:d,sourceIdentity:X,extensionReady:H,enabledForLoad:y})}}async function Dw(e){let t=Ow(e.pmRoot,e.cwd??process.cwd()),n=qn(e.settings.extensions.enabled),r=qn(e.settings.extensions.disabled),o=Hl(e.settings),i=ql(o);if(e.noExtensions)return{disabled_by_flag:!0,roots:t,configured_enabled:n,configured_disabled:r,discovered:[],effective:[],warnings:[...o.warnings],policy:i};let s=new Set(n),a=new Set(r),c=e.ignoreGlobalExtensions===!0?Rw():await Su("global",t.global,s,a,o.pmMaxVersionExceededMode.global),d=await Su("project",t.project,s,a,o.pmMaxVersionExceededMode.project),l=[...o.warnings],u=Cw(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=Wl(o,_);if(y.warning&&l.push(y.warning),!!y.allowed){for(let w of m.manifest.capabilities){let v=Gl(o,_,w);v.warning&&l.push(v.warning)}f.push(Iw(m))}}return{disabled_by_flag:!1,roots:t,configured_enabled:n,configured_disabled:r,discovered:[...c.diagnostics,...d.diagnostics],effective:f,warnings:[...new Set([...c.warnings,...d.warnings,...l])],policy:i}}function Eo(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function Pw(){try{let e=mo(import.meta.url,["../../.."]),t=await Et.readFile(vt.join(e,"package.json"),"utf8"),n=JSON.parse(t);return typeof n.version=="string"&&n.version.trim().length>0?n.version.trim():null}catch{return null}}function Tu(){return wu??=Pw(),wu}function Cu(e,t,n){let r=n.current??"unknown";if(n.kind==="pm_min_version")switch(n.status){case"invalid":return`extension_pm_min_version_invalid:${e}:${t.name}:required=${n.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${e}:${t.name}:required=${n.required}:current=${r}`;case"unmet":return`extension_pm_min_version_unmet:${e}:${t.name}:required=${n.required}:current=${r}`;default:return}switch(n.status){case"invalid":return`extension_pm_max_version_invalid:${e}:${t.name}:allowed=${n.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded":return`extension_pm_max_version_exceeded:${e}:${t.name}:allowed=${n.required}:current=${r}`;default:return}}async function Mw(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let n=gu(t.pm_min_version,await Tu()),r=Cu(e,t,n);return r?{allowed:n.allowed,warning:r}:{allowed:n.allowed}}async function $w(e,t,n){if(t.pm_max_version===void 0)return{allowed:!0};let r=bu(t.pm_max_version,await Tu(),n),o=Cu(e,t,r);return o?{allowed:r.allowed,warning:o}:{allowed:r.allowed}}async function Au(e){try{let t=await Et.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function jw(e,t){let n=e.entry_path;t.module_graph_snapshot_root&&(n=await Zl(t.module_graph_snapshot_root,e));let r=new URL(ww(n).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return r.href;let[o,i]=await Promise.all([Au(e.entry_path),Au(e.manifest_path)]),s=t.reload_token??Ew();return r.searchParams.set("pm_ext_reload",s),r.searchParams.set("pm_ext_entry",o),r.searchParams.set("pm_ext_manifest",i),r.href}async function BD(e){let t=await Dw(e),n=[],r=[],o=[...t.warnings];if(t.disabled_by_flag)return{...t,warnings:o,loaded:n,failed:r};let i=typeof e.extensionFilter=="function"?t.effective.filter(e.extensionFilter):t.effective;for(let s of i)try{let a=await import(await jw(s,e));n.push({...s,module:a})}catch(a){o.push(`extension_load_failed:${s.layer}:${s.name}`),r.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:Eo(a)})}return{...t,warnings:o,loaded:n,failed:r}}var Iu=5e3,Lw=2147483647;function Fw(e){let t={activate:e.activate.bind(e)};if(typeof e.deactivate=="function"){let n=e.deactivate;t.deactivate=n.bind(e)}return t}function Ru(e){let t=dl(e);return t?Fw(t):null}async function WD(e,t,n={}){let r=zw(n?.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=Ru(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 Uw(u,r),{ok:!0}}catch(f){return{ok:!1,layer:l.layer,name:l.name,error:Eo(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 zw(e){return typeof e!="number"||e<0?Iu:e===0||e===1/0?0:Number.isFinite(e)?Math.min(Lw,Math.max(1,Math.floor(e))):Iu}async function Uw(e,t){if(t===0){await e();return}let n;try{let r=Promise.resolve().then(()=>e());r.catch(()=>{}),await Promise.race([r,new Promise((o,i)=>{n=setTimeout(()=>{i(new Error(`extension deactivate timed out after ${t}ms`))},t),n.unref?.()})])}finally{clearTimeout(n)}}function Hw(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let n of e.capabilities){let r=n.trim().toLowerCase();Be(r)&&t.add(r)}return t}function q(e,t,n){let r=Hw(e);if(r!==null&&!r.has(t))throw Le(`${n} requires capability '${t}' in extension manifest capabilities`,{method:n,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 ${n} registration call.`})}function qw(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>Pe.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function Vw(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 na=class{extension;hooks;#e;#n;#o;#r;#s;#a;#i;#c;#t;#d;#l;#u;constructor(t,n,r,o,i,s,a,c,d,l,u){this.#e=t,this.extension=qw(t),this.#n=Vw(t),this.#o=n,this.#r=r,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,n,r,o){let i=Kl(this.#u,this.#n,t,n,r,o);return i.warning&&this.#d.push(i.warning),i.allowed}registerCommandTrace(t,n,r,o,i){return{method:"registerCommand",registration_index:t==="override"?this.#r.overrides.length:this.#r.handlers.length,command:n,expected_schema:r,received:Yn(o),hint:i}}registerCommandOverride(t,n){let r=z(t);if(r.length===0)throw Le("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 n!="function"){let o=this.registerCommandTrace("override",r,'registerCommand("<command>", (context) => unknown)',n,"Provide a function as the second registerCommand argument.");throw Le(`registerCommand requires an override function when command name is provided (command="${r}", registration_index=${o.registration_index})`,o)}this.allowRegistration("commands.override","registerCommand","commands",{command:r})&&this.#r.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}resolveCommandDefinitionRunHandler(t,n){let r=typeof t.run=="function"?t.run:void 0,o=typeof t.handler=="function"?t.handler:void 0;return!r&&o&&this.#d.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${n}`),r??o}registerCommandDefinition(t){if(typeof t!="object"||t===null)throw Le("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 Le("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 n=z(t.name);if(n.length===0)throw Le("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 r=this.resolveCommandDefinitionRunHandler(t,n);if(typeof r!="function"){let o=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; }",r,"Define command definition.run as a function.");throw Le(`registerCommand requires a command definition run handler (command="${n}", registration_index=${o.registration_index})`,o)}try{Pl(t);let o=Qs(n,t.action),i=Ml(t.read_output,n,o);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:n,action:o}))return;let s=t.description?.trim(),a=t.intent?.trim(),c=Wn("registerCommand definition.examples",t.examples),d=Wn("registerCommand definition.failure_hints",t.failure_hints),l=ea(t.arguments);t.flags!==void 0&&(q(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(vo(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:wo("registerCommand definition.flags",t.flags)})));let u={source_version:this.#e.version,read_output:i,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,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=Eo(o),s=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=Le(`registerCommand definition metadata invalid (command="${n}", registration_index=${s.registration_index}): ${i}`,s);this.#d.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${n}`),this.#l.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}registerCommand(t,n){if(q(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,n);return}this.registerCommandDefinition(t)}registerParser(t,n){if(q(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let r=z(oe("registerParser command",t));Qn("registerParser override",n),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerPreflight(t){if(q(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;let n=Ql(t);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...n})}registerService(t,n,r={}){q(this.#e,"services","registerService");let o=String(t).trim().toLowerCase();if(!ou(o))throw new TypeError(`registerService service must be one of: ${Gt.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:o})&&(Qn("registerService override",n),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:o,run:n,...yu(r)?{passThrough:!0}:{}}))}registerRenderer(t,n,r={}){if(q(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof n!="function")throw new TypeError("registerRenderer requires a renderer function");let o=String(t).trim().toLowerCase();if(!ru(o))throw new Error(`registerRenderer format must be toon|json, received: ${String(t)}`);if(r.resultDiscriminator!==void 0&&typeof r.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");let i=[...new Set((r.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return z(s)}))];this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,format:o,run:n,commands:i,...r.resultDiscriminator?{resultDiscriminator:r.resultDiscriminator}:{}})}registerFlags(t,n){if(q(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let r=z(oe("registerFlags targetCommand",t));vo(n);let o=wo("registerFlags flags",n);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:r,flags:o})}registerItemFields(t){if(q(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;lu(t);let n=Zn("registerItemFields fields",t);if(n.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:n})}registerItemTypes(t){if(q(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;uu(t);let n=Zn("registerItemTypes types",t);if(n.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:n})}registerRelationshipKinds(t){if(q(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 n=Os();for(let o of this.#t.relationship_kinds)for(let i of o.definitions)n.register(i);let r=t.map(o=>(n.register(o),n.require(o.kind)));this.#t.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:r})}registerMigration(t){if(q(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;fu(t);let n=Jn("registerMigration definition",t);this.#t.migrations.push(er({layer:this.#e.layer,name:this.#e.name,definition:rn("registerMigration definition",t)},n))}registerProfile(t){if(q(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let n=Xn(t);pu(n),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:_u(n)})}registerImportExportCommandFlags(t,n,r){r.flags!==void 0&&(q(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(vo(r.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:wo(`${t} options.flags`,r.flags)})))}applyImportExportCommandMetadata(t,n,r){if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))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={...r,description:r?.description??o,arguments:r?.arguments??i},a=$l(t,s,r?.description!==void 0);B(`${t} options.action`,s.action),B(`${t} options.description`,s.description),B(`${t} options.intent`,s.intent);let c=Qs(n,s.action),d=Wn(`${t} options.examples`,s.examples),l=Wn(`${t} options.failure_hints`,s.failure_hints),u=ea(s.arguments);this.registerImportExportCommandFlags(t,n,s);let f={source_version:this.#e.version,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,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,n,r){if(q(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=Js(oe("registerImporter name",t));Qn("registerImporter importer",n);let i=Zs(o,"import");this.applyImportExportCommandMetadata("registerImporter",i,r),this.#t.importers.push({layer:this.#e.layer,name:this.#e.name,importer:o}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>n(Ws(s,o,"import"))})}registerExporter(t,n,r){if(q(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=Js(oe("registerExporter name",t));Qn("registerExporter exporter",n);let i=Zs(o,"export"),s=this.applyImportExportCommandMetadata("registerExporter",i,r);this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o,...s===void 0?{}:{output:s}}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async a=>{let c=await n(Ws(a,o,"export"));return s?.receipt==="suppress"&&!fo(c)?hl(c):c}})}registerSearchProvider(t){if(q(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let n=Jn("registerSearchProvider provider",t);this.#t.search_providers.push(er({layer:this.#e.layer,name:this.#e.name,definition:rn("registerSearchProvider provider",t)},n))}registerVectorStoreAdapter(t){if(q(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let n=Jn("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(er({layer:this.#e.layer,name:this.#e.name,definition:rn("registerVectorStoreAdapter adapter",t)},n))}registerAssuranceMeasurementProvider(t){if(q(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(cu(t),t.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");let n=Jn("registerAssuranceMeasurementProvider provider",t);this.#t.assurance_providers.push(er({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:rn("registerAssuranceMeasurementProvider provider",t)},n))}registerBeforeCommand(t){q(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(wt("beforeCommand",t),this.#o.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerBeforeMutation(t){q(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(wt("beforeMutation",t),this.#o.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerAfterCommand(t){q(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(wt("afterCommand",t),this.#o.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnWrite(t){q(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(wt("onWrite",t),this.#o.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnRead(t){q(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(wt("onRead",t),this.#o.onRead.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnIndex(t){q(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(wt("onIndex",t),this.#o.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:t}))}};function Bw(e,t,n,r,o,i,s,a,c,d,l){return new na(e,t,n,r,o,i,s,a,c,d,l)}function Ww(e){let t=e.commands.length,n=e.flags.reduce((s,a)=>s+a.flags.length,0),r=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:n,item_fields:r,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 Gw(e){let t=[],n=(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}`)}};n(e.handlers,"extension_command_handler_collision"),n(e.overrides,"extension_command_override_collision");let r=new Set(e.handlers.map(i=>i.command)),o=[...new Set(e.overrides.map(i=>i.command))].filter(i=>r.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 Kw(e){let t=new Map;for(let r of e.overrides){let o=t.get(r.format)??[];o.push(r),t.set(r.format,o)}let n=[];for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r);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))||n.push(`extension_renderer_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return n}function Yw(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.command)??[];o.push(r),n.set(r.command,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);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:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}var Xw=new Set(["output_format"]);function Jw(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.service)??[];o.push(r),n.set(r.service,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1||Xw.has(r))continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_service_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}async function GD(e){let t=Vl(e.policy??vw),n=Vn(),r=Ts(),o=Cs(),i=Rs(),s=xs(),a=Ns(),c=Ds(),d=[],l=[];for(let m of e.loaded){let _=Ru(m.module);if(!_)continue;let y=d.length,w=Nl({hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await _.activate(Bw(m,n,r,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 T=su(v);d.push({layer:m.layer,name:m.name,entry_path:m.entry_path,error:Eo(v),trace:T})}}let u=[...Gw(r),...Yw(o),...eu(i),...Jw(s),...Kw(a)],f=[...new Set([...l,...u])];return{hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:d,warnings:f,hook_counts:{before_command:n.beforeCommand.length,before_mutation:n.beforeMutation.length,after_command:n.afterCommand.length,on_write:n.onWrite.length,on_read:n.onRead.length,on_index:n.onIndex.length},command_override_count:r.overrides.length,command_handler_count:r.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:Ww(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 JD(e){return{...e,hooks:Vn(),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 QD(){let e=Promise.resolve(),t=new Set;return{async read(n){let r=e,o,i=new Promise(s=>{o=s});t.add(i),await r;try{return await n()}finally{t.delete(i),o()}},write(n){let r=Promise.all([e,...t]).then(()=>n());return e=r.then(()=>{},()=>{}),r}}}function Zw(){let e=Promise.resolve(),t=0,n=[],r=()=>{if(t!==0)return;let o=n.splice(0);for(let i of o)i()};return{enqueue(o){t++;let i=e.then(()=>o());return e=i.then(()=>{},()=>{}).finally(()=>{t--,r()}),i},idle(){return t===0?Promise.resolve():new Promise(o=>n.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 Qw={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"]},xu=":";function Nu(e,t){return`${e}${xu}${ra(t)}`}function ev(e){return e.slice(e.indexOf(xu)+1)}function ra(e){return e.trim().toLowerCase()}function tv(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=gl(n);r!==null&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function Du(e){let t=new Map,n=(l,u)=>{for(let f of l){let m=Nu(f.layer,f.name),_=t.get(m);_===void 0&&(_=new Set,t.set(m,_)),_.add(u)}},{registrations:r,commands:o,parsers:i,preflight:s,services:a,renderers:c,hooks:d}=e;return n(r.commands,"commands"),n(o.overrides,"commands"),n(o.handlers,"commands"),n(r.flags,"schema"),n(r.item_fields,"schema"),n(r.item_types,"schema"),n(r.relationship_kinds??[],"schema"),n(r.migrations,"schema"),n(r.profiles,"schema"),n(r.importers,"importers"),n(r.exporters,"importers"),n(r.search_providers,"search"),n(r.vector_store_adapters,"search"),n(i.overrides,"parser"),n(s.overrides,"preflight"),n(a.overrides,"services"),n(r.assurance_providers??[],"services"),n(c.overrides,"renderers"),n(d.beforeCommand,"hooks"),n(d.beforeMutation,"hooks"),n(d.afterCommand,"hooks"),n(d.onWrite,"hooks"),n(d.onRead,"hooks"),n(d.onIndex,"hooks"),t}function nv(e,t={}){let n=Du(e),r=new Set;t.extensionName!==void 0&&r.add(ra(t.extensionName));for(let i of t.extensionNames??[])r.add(ra(i));let o=new Set;for(let[i,s]of n)if(!(r.size>0&&!r.has(ev(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function rv(e,t){let n=Du(t),r=[];for(let o of e){let i=tv(o.capabilities);if(i.length===0)continue;let s=n.get(Nu(o.layer,o.name))??new Set,a=[...s].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>!s.has(d));r.push({layer:o.layer,name:o.name,declared:i,used:a,unused:c})}return r}import{existsSync as ov}from"node:fs";import{AsyncLocalStorage as iv}from"node:async_hooks";import Fe 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 ze=null,on=null,nr=null,rr=null,sn=null,or=null,ir=null,Ke=null,So,ko=[],Mu=new iv;function M(){return Mu.getStore()}function aP(e){return Mu.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var sv=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function Pu(e){let t=Fe.resolve(e);for(;;){if(ov(Fe.join(t,".git")))return t;let n=Fe.dirname(t);if(n===t)return;t=n}}function Oo(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),n=Pu(t)??Fe.resolve(t),r=Pu(n);if(!e)return{source_workspace_root:n,...r?{repo_root:r}:{}};let o=Fe.relative(n,Fe.resolve(e)),i=o.length>0&&!o.startsWith(`..${Fe.sep}`)&&o!==".."&&!Fe.isAbsolute(o);return{source_workspace_root:n,...r?{repo_root:r}:{},...i?{pm_root_rel:o.split(Fe.sep).join("/")}:{}}}function cP(e){let t=M();if(t){t.hooks=e;return}ze=e}function dP(e){let t=M();if(t){t.commands=e;return}on=e}function lP(e){let t=M();if(t){t.parsers=e;return}nr=e}function uP(e){let t=M();if(t){t.preflight=e;return}rr=e}function fP(e){let t=M();if(t){t.services=e;return}sn=e}function mP(e){let t=M();if(t){t.renderers=e;return}or=e}function pP(e){let t=M();if(t){t.registrations=e;return}ir=e}function $u(){let e=M();return e?e.registrations:ir}function _P(){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}ze=null,on=null,nr=null,rr=null,sn=null,or=null,ir=null,Ke=null,So=null}function yP(e){let t=e?{...e,...Oo(e.pm_root)}:null,n=M();if(n){n.commandContext=t;return}Ke=t}function ju(){let e=M(),t=e?e.commandContext:Ke;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function hP(e){let t=M()??{commandContext:Ke,hooks:ze,commands:on,parsers:nr,preflight:rr,services:sn,renderers:or,registrations:ir};return t.commandContext?.command!==e||[t.hooks,t.preflight,t.services,t.renderers].some(n=>Object.values(n??{}).some(r=>r.length>0))||[t.commands,t.parsers].some(n=>Object.values(n??{}).some(r=>r.some(o=>o.command===e)))?!1:!Object.entries(t.registrations??{}).some(([n,r])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(n)&&r.length>0)}function Ao(e){let t=M();if(t){t.commandResult=e;return}So=e}function gP(){let e=M();return e?e.commandResult:So}function bP(e){if(!e)return;let t=M();t?t.affectedItems.push(e):ko.push(e)}function wP(e,t){if(!e||!e.id)return{};let n={id:e.id,type:e.type,status:e.status};if(!Array.isArray(t))return n;let r=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"||sv.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}function vP(){let e=M(),t=e?.affectedItems??ko;if(t.length===0)return;let n=t;return e?e.affectedItems=[]:ko=[],n}function EP(){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}ze=null,on=null,nr=null,rr=null,sn=null,or=null,ir=null,Ke=null,So=void 0,ko=[]}async function Io(e){let t=M(),n=t?t.hooks:ze;return n?Ms(n,e):[]}async function kP(e){let t=M(),n=t?t.hooks:ze;n&&await Ps(n,e)}async function an(e){let t=M(),n=t?t.hooks:ze;return n?$s(n,e):[]}function SP(){let e=M();return((e?e.hooks:ze)?.onRead?.length??0)>0}async function OP(e){let t=M(),n=t?t.hooks:ze;return n?js(n,e):[]}function Lu(e){let t=M(),n=t?t.commands:on,r=t?t.commandContext:Ke;return!n||!r?{overridden:!1,result:e,warnings:[]}:qs(n,{command:r.command,args:[...r.args],options:r.options?{...r.options}:{},global:r.global?{...r.global}:void 0,pm_root:r.pm_root,source_workspace_root:r.source_workspace_root,repo_root:r.repo_root,pm_root_rel:r.pm_root_rel,result:e})}async function AP(e){let t=M(),n=t?t.commands:on;return n?Ls(n,{...e,...Oo(e.pm_root)}):{handled:!1,result:null,warnings:[]}}async function IP(e){let t=M(),n=t?t.parsers:nr;return n?Fs(n,{...e,...Oo(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 TP(e){let t=M(),n=t?t.preflight:rr;return n?zs(n,{...e,...Oo(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 Fu(e,t){let n=M(),r=n?n.renderers:or,o=n?n.commandContext:Ke;return r?Vs(r,{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 zu(e,t){let n=M(),r=n?n.commandContext:Ke;return{service:e,command:r?.command,args:r?[...r.args]:[],options:r?.options?{...r.options}:{},global:r?.global?{...r.global}:void 0,pm_root:r?.pm_root,source_workspace_root:r?.source_workspace_root,repo_root:r?.repo_root,pm_root_rel:r?.pm_root_rel,payload:t}}async function cn(e,t){let n=M(),r=n?n.services:sn;return r?Hs(r,zu(e,t)):{handled:!1,result:t,warnings:[]}}function oa(e,t){let n=M(),r=n?n.services:sn;return r?Us(r,zu(e,t)):{handled:!1,result:t,warnings:[]}}import{createHash as av}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 MP=["sha256","sha512"],cv="sha256",Uu="sha256";function kt(e){if(e===void 0)return cv;if(e==="sha256"||e==="sha512")return e;throw new TypeError(`unsupported_history_hash_algorithm:${String(e)}`)}function Ye(e,t){return av(kt(t)).update(e,"utf8").digest("hex")}(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 Hu(e){let t=[],n=e[0]?.op==="history_compact_baseline",r=n?1:void 0,o=!1;for(let[i,s]of e.entries())s.op==="delete"&&(o=!0),s.op==="create"&&(r!==void 0&&t.push({prior_genesis_index:r,repeated_create_index:i+1,sequence:o?"delete_then_create":n?"checkpoint_then_create":"multiple_creates"}),r??=i+1,o=!1);return t}import Vu from"node:path";import{link as dv,mkdir as lv,mkdtemp as uv,rm as fv,writeFile as mv}from"node:fs/promises";import ia 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 qu(e,t){let n=ia.dirname(e);await lv(n,{recursive:!0});let r=await uv(ia.join(n,".pm-seed-")),o=ia.join(r,"value");try{await mv(o,t,"utf8");try{return await dv(o,e),!0}catch(i){if(i.code==="EEXIST")return!1;throw i}}finally{await fv(r,{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 pv=2e3,To=new Map;function Xe(e){if(typeof e!="string")return"";let t=To.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return To.size>=pv&&oo(To),To.set(e,n),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]="6e07b1b6-1757-54dd-8833-9d3f984ccf79")}catch{}})();var ie=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),Gu=Od,aa=Sd,_v=["create","update"],yv=new Set(Kr),hv=new Set(Xt),gv=new Set(Yr),bv=new Set(Xr),wv=new Set(["string","number","boolean","array","object"]),vv=16;function Ku(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ev=[e=>e.type===void 0||typeof e.type=="string"&&wv.has(e.type),e=>!Object.hasOwn(e,"const")||Ro(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Ro(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||Ku(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Ro(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 n=Array.isArray(e)?e.every(r=>Ro(r,t)):Object.values(e).every(r=>Ro(r,t));return t.delete(e),n}function Co(e,t=0,n=new Set){if(!Ku(e)||t>vv||n.has(e))return;n.add(e);let r=e,o=r.type,i=r.enum,s=r.one_of,a=r.properties,c=r.items,d=r.required,l=r.min_length,u=r.min_items,f=r.format,m=r.additional_properties;if(!Ev.every(v=>v(r))){n.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([v,T])=>[v,Co(T,t+1,n)])),y=c===void 0?void 0:Co(c,t+1,n),w=s===void 0?void 0:s.map(v=>Co(v,t+1,n));if([...Object.values(_??{}),...c===void 0?[]:[y],...w??[]].some(v=>v===void 0)){n.delete(e);return}return n.delete(e),Object.fromEntries(Object.entries({type:o,const:Object.hasOwn(r,"const")?r.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 ar(e){let t=Array.isArray(e)?e:[];return[...new Set(t.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r))}function ye(e){if(typeof e!="string"||e.length===0)return;let t=Xe(e);return t.length>0?t:void 0}function kv(e){return e.startsWith("--")?e.slice(2):e}function Bu(e){return typeof e=="string"?kv(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function Yu(e){return e.replaceAll("_","-")}function Sv(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[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function sa(e,t){let n=ye(e.id);if(!n)return null;let r=[...new Set(ar(e.aliases).map(Xe).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=ar(e.roles).filter(a=>yv.has(a)),i=e.description?.trim(),s=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:n,aliases:r,roles:o,description:i&&i.length>0?i:void 0,order:s}}function Ov(e){return{draft_status:ye(e?.draft_status),open_status:ye(e?.open_status),in_progress_status:ye(e?.in_progress_status),blocked_status:ye(e?.blocked_status),close_status:ye(e?.close_status),canceled_status:ye(e?.canceled_status)}}function Xu(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=Xe(t[0]),r=Xe(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function Av(e){let t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;let n={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(let r of e.allowed_transitions)Xu(n,r);return{typeKey:t.toLowerCase(),record:n}}function Iv(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=Av(r);if(o===null)continue;let i=t.get(o.typeKey)??o.record;i.denyAll||=o.record.denyAll;for(let s of o.record.pairs)Xu(i,s);t.set(o.typeKey,i)}let n=[];for(let r of t.values())(r.pairs.length>0||r.denyAll)&&n.push({type:r.type,allowed_transitions:r.pairs});return n.sort((r,o)=>r.type.localeCompare(o.type)),n.length>0?n:void 0}function Ju(e){let t=Xe(e.key??"");if(!t)return null;let n=Xe(e.metadata_key??e.front_matter_key??t),r=Bu(e.cli_flag??Yu(t));if(!r)return null;let o=ar(e.cli_aliases).map(u=>Bu(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=hv.has(i)?i:"string",a=(()=>{let u=ar(e.commands).filter(f=>gv.has(f));return u.length>0?u:[..._v]})(),c=e.description?.trim(),d=ar(e.required_types),l=e.value_schema===void 0?void 0:Co(e.value_schema);return e.value_schema!==void 0&&l===void 0?null:{key:t,metadata_key:n,cli_flag:r,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 Tv(e){let t=new Map;for(let[r,o]of e.entries()){let i=sa(o,r);i&&t.set(i.id,i)}let n=Wu([...t.values()]);return n.length>0?n:Wu(aa.map((r,o)=>sa(r,o)).filter(r=>r!==null))}function Wu(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function Cv(e){let t=new Map;for(let n of e??[]){let r=Ju(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function Rv(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 xv(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==Yu(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 Nv(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return bv.has(t)?t:"allow"}function Ce(e){let t={...ie,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:aa,r=Tv(n),o=Cv(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(Rv),fields:o.map(xv),workflow:{...Gu,...Ov(e?.workflow)},type_workflows:Iv(e?.type_workflows),unknown_field_policy:Nv(e?.unknown_field_policy)}}function Dv(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function Pv(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 n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function Mv(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 $v(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 jv(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 Lv(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 ue(e,t,n){let r=t?.trim()||n;return Vu.isAbsolute(r)?r:Vu.join(e,r)}function YP(e,t){return ue(e,t.files.types,ie.types)}async function XP(e,t){let n=Ce(t),r=[{path:ue(e,n.files.types,ie.types),seed:{definitions:[]}},{path:ue(e,n.files.statuses,ie.statuses),seed:{statuses:aa}},{path:ue(e,n.files.fields,ie.fields),seed:{fields:[]}},{path:ue(e,n.files.workflows,ie.workflows),seed:{workflow:Gu}}],o=[];for(let i of r)await mt(i.path)||await qu(i.path,`${JSON.stringify(i.seed,null,2)}
3
- `)&&o.push(i.path);return{created_paths:o}}async function Zu(e,t){let n=Ce(t),r=[],o=ue(e,n.files.types,ie.types),i=ue(e,n.files.statuses,ie.statuses),s=ue(e,n.files.fields,ie.fields),a=ue(e,n.files.workflows,ie.workflows),c,d,l,u,f,m=async(T,H)=>{let X=await Ae(T);if(X!==null)return Dv(X,H,r)},_=await m(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=Pv(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let y=await m(i,"runtime_schema_statuses_invalid_json");y!==void 0&&(d=Mv(y),d===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let w=await m(s,"runtime_schema_fields_invalid_json");w!==void 0&&(l=$v(w),l===void 0&&r.push("runtime_schema_fields_invalid_shape"));let v=await m(a,"runtime_schema_workflows_invalid_json");return v!==void 0&&(u=jv(v),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=Lv(v)),{schema:Ce({...n,statuses:[...n.statuses,...d??[]],fields:[...n.fields,...l??[]],workflow:{...n.workflow,...u},type_workflows:[...n.type_workflows??[],...f??[]]}),type_definitions_from_file:c,warnings:r,created_paths:[]}}function sr(e,t,n,r=!1){let o=n.map(s=>ye(s)).filter(s=>typeof s=="string").find(s=>e.some(a=>a.id===s));if(r&&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 Fv(e){let t=new Map,n=new Map;for(let r of e){n.set(r.id,r),t.set(r.id,r.id),t.set(r.id.replaceAll("_","-"),r.id),t.set(r.id.replaceAll("_"," "),r.id);for(let o of r.aliases)t.set(o,r.id),t.set(o.replaceAll("_","-"),r.id),t.set(o.replaceAll("_"," "),r.id)}return{aliasToId:t,byId:n}}function zv(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let n of e){let r=new Set(n.roles);(r.has("terminal")||r.has("terminal_done")||r.has("terminal_canceled"))&&t.terminalStatuses.add(n.id),r.has("terminal_done")&&t.terminalDoneStatuses.add(n.id),r.has("terminal_canceled")&&t.terminalCanceledStatuses.add(n.id),r.has("active")&&t.activeStatuses.add(n.id),r.has("blocked")&&t.blockedStatuses.add(n.id),r.has("draft")&&t.draftStatuses.add(n.id)}return t}function Qu(e){let t=Ce(e),n=t.statuses.map((v,T)=>sa(v,T)).filter(v=>v!==null),{aliasToId:r,byId:o}=Fv(n),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:d,terminalStatuses:l}=zv(n),u=t.workflow,f=ye(u.open_status)??sr(n,"default_open",["open","in_progress",Yt[0]]),m=ye(u.in_progress_status)??sr(n,"active",["in_progress","in-progress",f],!0),_=ye(u.blocked_status)??sr(n,"blocked",["blocked"]),y=ye(u.close_status)??sr(n,"default_close",["closed","done","complete"]),w=ye(u.canceled_status)??sr(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,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 ca(e,t){let n=Xe(e);if(n)return t.alias_to_id.get(n)}function ef(e){let t=Ce(e),n=new Map,r=t.fields.map(c=>Ju(c)).filter(c=>c!==null);for(let c of r)n.set(c.key,c);let o=[...n.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 tf(e){return Sv(e.key)}function JP(e,t){let n=ca(e,t);return n?t.terminal_statuses.has(n):!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]="6635e694-c788-5805-adb8-ed93cc931946")}catch{}})();var Uv=16;function xo(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[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function o1(e,t,n=new Set,r){if(sf(e,t,r))return;let o=af(e,t,n,r),i=No(e);return[xo(e.cli_flag),...i].find(s=>!o.has(s)&&of(s,i,o))}function of(e,t,n){for(let r of t){if(r===e)break;if(n.has(r))return!1}return!0}function sf(e,t,n){return t.definitions.some(r=>r!==e&&r.metadata_key===e.metadata_key&&(n===void 0||r.commands.includes(n)))}function af(e,t,n,r){return new Set([...n,...t.definitions.filter(o=>o!==e&&(r===void 0||o.commands.includes(r))).flatMap(o=>No(o))])}function cf(e){return e.replace(/^-+/u,"").startsWith("no-")}function Hv(e){return e.startsWith("-")?e:`--${e}`}function i1(e,t,n,r){if(sf(e,t,r))return;let o=af(e,t,n.options,r),i=No(e);return[e.cli_flag,...e.cli_aliases].find(s=>{let a=df(s);return cf(s)||n.flags.has(Hv(s))||o.has(a)?!1:of(a,i,o)})}function df(e){return e.replace(/^-+/u,"").replace(/^no-/u,"").split("-").reduce((t,n)=>`${t}${n.charAt(0).toUpperCase()}${n.slice(1)}`)}function No(e){return[...new Set([tf(e),xo(e.key),xo(e.cli_flag),...e.cli_aliases.map(t=>xo(t)),...[e.cli_flag,...e.cli_aliases].filter(t=>!cf(t)).map(t=>df(t))])]}function lf(e,t){for(let n of No(t)){if(!Object.hasOwn(e,n))continue;let r=e[n];if(r!==void 0)return r}}function uf(e){return Array.isArray(e)?e.flatMap(t=>uf(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 nf(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 n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1}throw new g(`${t} must be one of true|false|1|0|yes|no`,h.USAGE)}function rf(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;let n=typeof e=="string"?e.trim():String(e),r=Number(n);if(!Number.isFinite(r))throw new g(`${t} must be a number`,h.USAGE);return r}function qv(e,t,n){let r=typeof e=="string"?(()=>{try{return JSON.parse(e)}catch{return}})():e;if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r;throw new g(`${t} must be valid JSON ${n}`,h.USAGE)}function Vv(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 Bv(e,t,n){if(t.const!==void 0&&R(e)!==R(t.const))return`${n} must equal ${R(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>R(r)===R(e)))return`${n} must be one of ${t.enum.map(r=>R(r)).join("|")}`;if(!Vv(e,t.type))return`${n} must match configured type ${String(t.type)}`;if(typeof e=="string"){if(t.min_length!==void 0&&e.length<t.min_length)return`${n} must contain at least ${t.min_length} characters`;if(t.format==="date-time"&&!Un(e))return`${n} must be an RFC 3339 date-time`}}function Wv(e,t,n,r){if(Array.isArray(e)){if(t.min_items!==void 0&&e.length<t.min_items)return`${n} must contain at least ${t.min_items} items`;if(t.items)for(let[o,i]of e.entries()){let s=Do(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function Gv(e,t,n,r){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`${n}.${i} is required`;for(let[i,s]of Object.entries(o)){let a=t.properties?.[i];if(!a){if(t.additional_properties===!1)return`${n}.${i} is not allowed`;continue}let c=Do(s,a,`${n}.${i}`,r+1);if(c)return c}}function Do(e,t,n,r=0){if(r>Uv)return`${n} value schema exceeds maximum depth`;let o=Bv(e,t,n);if(o)return o;let i=Wv(e,t,n,r);if(i)return i;let s=Gv(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(Do(e,c,n,r+1)===void 0&&(a+=1,a>1))break;return a===1?void 0:`${n} must match exactly one configured schema variant`}function St(e,t,n){if(!e.value_schema||t===void 0)return t;let r=Do(t,e.value_schema,n);if(r)throw new g(r,h.USAGE);return t}function Kv(e,t,n,r){let o=r==="option"&&Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return St(e,qv(o,n,e.type),n)}function cr(e,t,n,r="option"){let o=n??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object")return Kv(e,t,o,r);if(e.repeatable||e.type==="string_array"){let s=uf(t);return e.type==="number"?St(e,s.map(a=>rf(a,o)),o):e.type==="boolean"?St(e,s.map(a=>nf(a,o)),o):St(e,s,o)}let i=Array.isArray(t)?t[t.length-1]:t;if(i!==void 0)return e.type==="number"?St(e,rf(i,o),o):e.type==="boolean"?St(e,nf(i,o),o):St(e,typeof i=="string"?i:String(i),o)}function Yv(e,t){return!e.required&&!e.required_on_create?!1:e.required_types.length===0?!0:t?e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function s1(e,t,n){let r={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=lf(e,i);if(s===void 0){Yv(i,n)&&o.push(`--${i.cli_flag}`);continue}r[i.metadata_key]=cr(i,s)}return{values:r,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function a1(e,t,n=["update"]){let r={},o=(n??["update"]).flatMap(s=>t.command_to_fields.get(s)??[]),i=new Set;for(let s of o){let a=lf(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),r[s.metadata_key]=cr(s,a)))}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]="c35d4830-d7d1-5ee4-99bc-ab52cc3e4e09")}catch{}})();var da=1,la=2;function d1(e){return Math.max(ua(e),e.tests?.some(t=>t.updated_by!==void 0||t.updated_at!==void 0)?2:1)}function ua(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:1}function ff(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=1))return e}function Xv(e,t=2,n=t){return e<n?"outdated":e>t?"ahead":"current"}function l1(e,t=2,n=t){let r=[],o=[];for(let i of e){let s=Xv(i.version,t,n);s==="outdated"?r.push(i.ref):s==="ahead"&&o.push(i.ref)}return{outdated:r.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 Jv={"in-progress":"in_progress",cancelled:"canceled"};function Po(e,t){if(t){let o=ca(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=Jv[n]??n;if(Yt.includes(r))return r}function Zv(e,t){return Po(e,t)??e}function p1(e,t){return t.terminal_statuses.has(Zv(e,t))}import{encode as nE}from"@toon-format/toon";import{isDeepStrictEqual as mf}from"node:util";import{decode as Qv}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 fa(e){return{value:Qv(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 eE=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function tE(e){if(e.length===0)return[];let t=e.split(/\r?\n/),n=[];for(let r=0;r<t.length;r+=1){let o=t[r]??"",i=o.match(eE);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Mo(e){return tE(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 ya=new Set(["schema","tracker","auto","none"]),gf=new Set(["source","isolated","snapshot"]),rE=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),oE=new Set(["passed","failed","stopped","canceled"]),iE=new Set(Ld);function un(e){return e.replaceAll("\\","/")}function bf(e){for(let t of e)if(t!==0)return t;return 0}function jo(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var wf=["id","title","description","created_at","updated_at"],sE=new Set(ve);function vf(e){if(e?.schema)return{statusRegistry:Qu(e.schema),fieldRegistry:ef(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function aE(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function Je(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 ur(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 Ef(e,t){if(!t||typeof e!="object"||e===null)return;let n=ua(e);if(!(n<=la))throw new g(`Stored item uses format version ${n}; this runtime supports up to ${la}. Upgrade pm before reading or changing this item.`,h.CONFLICT,{code:"item_format_version_unsupported",format_version:n,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 kf(e){let t=new Set(sE);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function O(e,t){e||Je(t)}function fr(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&Je(t),e}function ma(e,t){let n=e[t];O(typeof n=="string",`${t} must be a string`),O($e(n),`${t} must be a valid ISO timestamp`)}function pf(e,t,n){let r=e[t];r!==void 0&&O(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function ha(e,t,n){let r=e[t];r!==void 0&&(O(typeof r=="string",`${n} must be a string`),O($e(r),`${n} must be a valid ISO timestamp`))}function cE(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 n=t.trim().toLowerCase();O(jn.includes(n),`event.recurrence.by_weekday entries must be one of: ${jn.join(", ")}`)}}}function dE(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 lE(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($e(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function uE(e){let t=fr(e,"event.recurrence must be an object");O(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();O(Qr.includes(n),`event.recurrence.freq must be one of: ${Qr.join(", ")}`),pf(t,"interval","event.recurrence.interval"),pf(t,"count","event.recurrence.count"),ha(t,"until","event.recurrence.until"),cE(t.by_weekday),dE(t.by_month_day),lE(t.exdates)}function fE(e){for(let r of wf)O(typeof e[r]=="string",`${r} 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 n=e.pm_format_version;return n!==void 0&&O(typeof n=="number"&&Number.isInteger(n)&&n>=da,`pm_format_version must be an integer >= ${da}`),t}function mE(e,t){let n=e.status;O(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=Po(n,r),i=r?r.definitions.map(s=>s.id):[...Yt];O(o!==void 0,`status must be one of: ${i.join(", ")}`)}function pE(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 n=e.tags;O(Array.isArray(n),"tags must be an array");for(let r of n)O(typeof r=="string","tags entries must be strings")}function _E(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 n=t.trim().toLowerCase(),r=n==="med"||Zr.includes(n);O(r,`confidence string value must be one of: ${[...Zr,"med"].join(", ")}`);return}O(!1,"confidence must be a number or string")}}function yE(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&Je("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||Jr.includes(n);O(r,`severity value must be one of: ${[...Jr,"med"].join(", ")}`)}function hE(e){e.regression!==void 0&&typeof e.regression!="boolean"&&Je("regression must be a boolean")}function gE(e){let t=e.reminders;if(t!==void 0){O(Array.isArray(t),"reminders must be an array");for(let n of t){let r=fr(n,"reminders entries must be objects");O(typeof r.at=="string","reminder.at must be a string"),O($e(r.at),"reminder.at must be a valid ISO timestamp"),O(typeof r.text=="string","reminder.text must be a string"),O(r.text.trim().length>0,"reminder.text must not be empty")}}}function bE(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 wE(e){e.recurrence!==void 0&&(uE(e.recurrence),e.recurrence.until!==void 0&&O(re(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function vE(e){let t=fr(e,"events entries must be objects");O(typeof t.start_at=="string","event.start_at must be a string"),O($e(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($e(t.end_at),"event.end_at must be a valid ISO timestamp"),O(re(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),bE(t),t.all_day!==void 0&&O(typeof t.all_day=="boolean","event.all_day must be a boolean"),wE(t)}function EE(e){let t=e.events;if(t!==void 0){O(Array.isArray(t),"events must be an array");for(let n of t)vE(n)}}function kE(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&O(typeof n=="string",`${t} must be a string`)}}function SE(e){let t=e.type_options;if(t===void 0)return;let n=fr(t,"type_options must be an object");for(let[r,o]of Object.entries(n))O(r.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 OE(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){aE(r,t)&&Je(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=cr(r,o,`metadata field "${r.metadata_key}"`,"metadata")}catch(i){Je(String(i?.message).replace(/^Invalid\s+/u,""))}}}function AE(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=kf(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?Je(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function ga(e,t){let n=fr(e,"item metadata must be an object"),r=fE(n);mE(n,t),pE(n),_E(n),yE(n),hE(n),ma(n,"created_at"),ma(n,"updated_at"),n.deadline!==void 0&&ma(n,"deadline"),gE(n),EE(n),ha(n,"closed_at","closed_at"),ha(n,"completed_at","completed_at"),kE(n),SE(n),OE(n,r,t),AE(n,t)}function IE(e){if(!(!e||e.length===0))return[...e].map((t,n)=>(O(t.created_at===void 0||typeof t.created_at=="string"&&Un(t.created_at),`dependencies.${n}.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,n)=>{let r=re(t.created_at??"",n.created_at??"");if(r!==0)return r;let o=t.id.localeCompare(n.id);if(o!==0)return o;let i=t.kind.localeCompare(n.kind);return i!==0?i:(t.source_kind??"").localeCompare(n.source_kind??"")})}function pa(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=re(t.created_at,n.created_at);if(r!==0)return r;let o=t.text.localeCompare(n.text);return o!==0?o:t.author.localeCompare(n.author)})}function TE(e){if(!e||e.length===0)return;let t=[...e].map(n=>({at:n.at,text:n.text.trim()})).filter(n=>n.text.length>0).sort((n,r)=>{let o=re(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function CE(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!Qr.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>jn.includes(s)))).sort((s,a)=>ss(s)-ss(a)),r=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=>$e(s)))).sort((s,a)=>re(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:n.length>0?n:void 0,by_month_day:r.length>0?r: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 RE(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(xE).sort(NE)}function xE(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:CE(e.recurrence)};return jo(t),t}function NE(e,t){return bf([re(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 DE(e){if(!(!e||e.length===0))return e.map(t=>({path:un(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function PE(e){if(!e||e.length===0)return;let t=e.map(LE).filter(n=>n.run_id.length>0&&n.started_at.length>0&&n.finished_at.length>0&&n.recorded_at.length>0).sort((n,r)=>bf([re(n.recorded_at,r.recorded_at),n.run_id.localeCompare(r.run_id),n.kind.localeCompare(r.kind)]));return t.length>0?t:void 0}function dn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function ME(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function _a(e){return typeof e=="string"?e:""}function $E(e){if(!Array.isArray(e))return;let t=e.filter(r=>r!==null&&typeof r=="object"&&typeof r.name=="string"&&r.name.trim().length>0&&typeof r.value=="number"&&Number.isFinite(r.value)&&typeof r.recorded_at=="string"&&r.recorded_at.trim().length>0).map(r=>({name:r.name.trim(),value:r.value,unit:typeof r.unit=="string"&&r.unit.trim()||void 0,threshold:typeof r.threshold=="number"&&Number.isFinite(r.threshold)?r.threshold:void 0,recorded_at:r.recorded_at.trim()})),n=[...new Map(t.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,32);return n.length>0?n:void 0}function $o(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function jE(e){if(!Array.isArray(e))return;let t=e.filter(n=>n&&typeof n.command=="string"&&n.command.trim().length>0).slice(0,32).map(n=>({command:n.command.trim(),requested_pm_context_mode:$o(n.requested_pm_context_mode,ya),pm_context_mode:$o(n.pm_context_mode,ya),workspace_context_mode:$o(n.workspace_context_mode,gf),trust_reason:$o(n.trust_reason,rE)}));return t.length>0?t:void 0}function LE(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=oE.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:_a(e.started_at),finished_at:_a(e.finished_at),recorded_at:_a(e.recorded_at),attempt:ME(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:dn(e.passed)??0,failed:dn(e.failed)??0,skipped:dn(e.skipped)??0,items:dn(e.items),linked_tests:dn(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:$E(e.measurements),executions:jE(e.executions)};return jo(o),o}function FE(e){if(!(!Array.isArray(e)||e.length===0))return e.map(VE)}function dr(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}function Ea(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ka(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function _f(e){if(!Ea(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!ka(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function zE(e){if(!Ea(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!ka(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function UE(e){let t=e?.trim().toLowerCase();if(!(!t||!ya.has(t)))return t}function HE(e){let t=e?.trim().toLowerCase();if(!(!t||!gf.has(t)))return t}function qE(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Ea(e))return{provenance_invalid:!0};let n=E(e.author),r=E(e.created_at),o=e.source_kind;return!n||!r||!$e(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:E(e.source_ref)}}}function VE(e){let t={command:e.command?.trim()||void 0,path:e.path?un(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:UE(e.pm_context_mode),workspace_context_mode:HE(e.workspace_context_mode),...qE(e.provenance,e.provenance_invalid),updated_by:E(e.updated_by),updated_at:E(e.updated_at),env_set:_f(e.env_set),env_clear:dr(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:dr(e.assert_stdout_contains),assert_stdout_regex:dr(e.assert_stdout_regex),assert_stderr_contains:dr(e.assert_stderr_contains),assert_stderr_regex:dr(e.assert_stderr_regex),assert_stdout_min_lines:dn(e.assert_stdout_min_lines),assert_json_field_equals:_f(e.assert_json_field_equals),assert_json_field_gte:zE(e.assert_json_field_gte),note:e.note?.trim()||void 0};return jo(t),t}function BE(e){if(!(!e||e.length===0))return[...e].map(t=>({path:un(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.path.localeCompare(n.path);return o!==0?o:(t.note??"").localeCompare(n.note??"")})}function E(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function WE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.id),i=E(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=E(r.note);a&&(s.note=a),r.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function GE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.path);if(!o)continue;let i={path:un(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=E(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function KE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.command),i=E(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=un(i));let a=E(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function YE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.path);if(!o)continue;let i={path:un(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=E(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function XE(e){if(e===null||typeof e!="object")return;let t=e,n=E(t.id),r=E(t.title),o=E(t.status),i=o&&iE.has(o)?o:void 0,s=ro(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",c=typeof t.updated_at=="string"?t.updated_at:"";if(!n||!r||!i||!Number.isFinite(s)||!a||!c)return;let d={id:n,order:s,title:r,status:i,created_at:a,updated_at:c};return JE(d,t),d}function JE(e,t){let n=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(let[i,s]of n){let a=E(t[s]);a&&(e[i]=a)}let r=typeof t.completed_at=="string"?t.completed_at:void 0;r&&r.length>0&&(e.completed_at=r);let o=[["linked_items","linked_items",WE],["files","files",GE],["tests","tests",KE],["docs","docs",YE]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function ZE(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=XE(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function QE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=E(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=E(r.rationale);c&&(a.rationale=c);let d=E(r.evidence);d&&(a.evidence=d);let l=E(r.step_id);l&&(a.step_id=l),t.push(a)}return t.length>0?t:void 0}function e0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=E(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=E(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function t0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.text);if(!o)continue;let i={text:o},s=E(r.command);s&&(i.command=s);let a=E(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function n0(e){if(!e)return;let t=Object.entries(e).map(([n,r])=>[n.trim(),r.trim()]).filter(([n,r])=>n.length>0&&r.length>0).sort((n,r)=>n[0].localeCompare(r[0]));if(t.length!==0)return Object.fromEntries(t)}function ln(e){let t=0;for(;t<e.length&&e[t]===`
4
- `;)t+=1;return e.slice(t).trimEnd()}function r0(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Zr.includes(t))return t}function o0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Jr.includes(t))return t}function lr(e){return e||void 0}function i0(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))ka(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function s0(e,t){if(!t?.fieldRegistry)return;let n=e;for(let r of t.fieldRegistry.definitions){let o=n[r.metadata_key];o!==void 0&&(n[r.metadata_key]=cr(r,o,`metadata field "${r.metadata_key}"`,"metadata"))}}function a0(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=kf(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length>0&&t.unknownFieldPolicy==="reject"&&Je(`unknown schema fields are not allowed: ${r.join(", ")}`),r.length>0&&t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`)}function Lo(e,t={}){let n=vf(t),r=Po(e.status,n?.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:ff(e.pm_format_version),source_type:E(e.source_type),type_options:n0(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:IE(e.dependencies),comments:pa(e.comments),notes:pa(e.notes),learnings:pa(e.learnings),files:DE(e.files),tests:FE(e.tests),test_runs:PE(e.test_runs),docs:BE(e.docs),deadline:lr(e.deadline),reminders:TE(e.reminders),events:RE(e.events),closed_at:lr(e.closed_at),completed_at:lr(e.completed_at),assignee:E(e.assignee),claim_principal:E(e.claim_principal),source_owner:E(e.source_owner),author:lr(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:r0(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:o0(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:lr(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:ZE(e.plan_steps),plan_decisions:QE(e.plan_decisions),plan_discoveries:e0(e.plan_discoveries),plan_validation:t0(e.plan_validation)};return i0(i,e),s0(i,n),a0(i,n),jo(i),i}function Sf(e){return A(e,ve)}function c0(e){let t=0,n=!1,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(n){if(r){r=!1;continue}if(i==="\\"){r=!0;continue}i==='"'&&(n=!1);continue}if(i==='"'){n=!0;continue}if(i==="{"){t+=1;continue}if(i==="}"&&(t-=1,t===0))return o}return-1}function d0(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=c0(e);if(t<0)return{frontMatter:"",body:e};let n=e.slice(0,t+1),r=e.slice(t+1).replace(/^\r?\n+/,"");return{frontMatter:n,body:r}}function l0(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!n)return{content:t,stripped:!1};let r=n[0].length;for(;r<t.length;){let o=t.indexOf(`
5
- `,r),i=o===-1?t.length:o,s=t.slice(r,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};r=a}return{content:t,stripped:!1}}function ba(e,t){return Lo(e,{...t,onWarning:void 0})}function u0(e,t,n={}){let r=l0(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=d0(r.content);o||(e.trimStart().startsWith("{")&&ur("json_markdown","JSON front matter is not valid JSON"),ur("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{ur("json_markdown","JSON front matter is not valid JSON")}return Ef(s,n.requireSupportedFormat),ga(s,t),{metadata:ba(s,n),body:ln(i)}}function f0(e,t,n={}){let r;try{r=fa(e).value}catch{ur("toon","TOON item document is not valid TOON")}O(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(Ef(Object.prototype.hasOwnProperty.call(o,"front_matter")?o.front_matter:o,n.requireSupportedFormat),!wf.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&ur("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return ga(o.front_matter,t),O(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:ba(o.front_matter,n),body:ln(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"),ga(s,t),{metadata:ba(s,n),body:ln(typeof i=="string"?i:"")}}function m0(e,t={}){let n=Lo(e.metadata,t),r=Sf(n),o=ln(e.body??"");va(JSON.parse(JSON.stringify(r))),va({body:o});let i=JSON.stringify(r,null,2);return o?`${i}
1
+ import{A as h,C as g,E as mt,F as be,G as ee,H as Ae,I as Td,J as rs,K as pt,L as Cd,a as Pe,b as ns,c as Ed,e as jr,f as Lr,g as Fr,h as kd,i as zr,j as Gt,k as Sd,m as ve,n as Od,o as Ad,p as Ur,q as Hr,u as Dn,v as Id,y as S,z as Pn}from"./chunk-O4ZLEN4T.js";import My 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 $y(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 jy(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=qr(o))}return n}function qr(e){let t=$y(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>qr(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return qr(r)}return jy(e)}function R(e){return JSON.stringify(qr(e))}function Rd(e,t,n,r){for(let o=0;o<t.length;o+=1)if(!n.has(o)&&r(e,t[o]))return n.add(o),!0;return!1}function Ly(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function Fy(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function zy(e,t){if(!(e instanceof Set||t instanceof Set))return;if(!(e instanceof Set&&t instanceof Set)||e.size!==t.size)return!1;let n=[...t],r=new Set;for(let o of e)if(!Rd(o,n,r,W))return!1;return!0}function Uy(e,t){if(!(e instanceof Map||t instanceof Map))return;if(!(e instanceof Map&&t instanceof Map)||e.size!==t.size)return!1;let n=[...t.entries()],r=new Set;for(let[o,i]of e.entries())if(!Rd([o,i],n,r,([s,a],[c,d])=>W(s,c)&&W(a,d)))return!1;return!0}function Hy(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>W(n,t[r]))}function qy(e,t){let n=Object.keys(e).sort((o,i)=>o.localeCompare(i)),r=Object.keys(t).sort((o,i)=>o.localeCompare(i));if(n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!==r[o]||!W(e[i],t[i]))return!1}return!0}var Vy=[Ly,Fy,zy,Uy,Hy];function W(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;for(let n of Vy){let r=n(e,t);if(r!==void 0)return r}return qy(e,t)}function Vr(e){return My.createHash("sha256").update(e,"utf8").digest("hex")}function A(e,t){let n={};for(let o of t){let i=e[o];i!==void 0&&(n[o]=i)}let r=Object.keys(e).filter(o=>!t.includes(o)).sort((o,i)=>o.localeCompare(i));for(let o of r){let i=e[o];i!==void 0&&(n[o]=i)}return n}import{createHash as Nd}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 By=["policies","policy-put","policy-remove","policy-mode","policy-check","policy-approve","policy-presets"],xd=256,os=64;function le(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 Me(e,t,n){if(typeof e!="object"||e===null||Array.isArray(e))return le(`${n} must be an object`);let r=e;return Object.keys(r).some(o=>!t.includes(o))?le(`${n} contains an unknown key`):r}function _t(e,t,n=128){return typeof e!="string"||!e.trim()||e.length>n?le(`${t} must be nonempty text of at most ${n} characters`):e.trim()}function Mn(e,t){if(!Array.isArray(e)||e.length===0||e.length>os)return le(`${t} requires 1-${os} terms`);let n=e.map(r=>_t(r,t));return t==="fields"&&n.some(r=>!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$/.test(r)||r.split(".").some(o=>["__proto__","constructor","prototype"].includes(o)))?le("fields must be safe metadata paths of at most eight segments"):[...new Set(n)]}function Wy(e){let t=Me(e,["kind","fields","authors","allowed"],"rule");return t.kind==="transition"?(Me(t,["kind","allowed"],"transition rule"),!Array.isArray(t.allowed)||t.allowed.length>os?le("transition.allowed must be a bounded array"):{kind:"transition",allowed:t.allowed.map(n=>!Array.isArray(n)||n.length!==2?le("transition pairs need two statuses"):[_t(n[0],"from"),_t(n[1],"to")])}):t.kind==="authors"?(Me(t,["kind","authors"],"authors rule"),{kind:"authors",authors:Mn(t.authors,"authors")}):t.kind==="require_fields"?(Me(t,["kind","fields"],"require_fields rule"),{kind:"require_fields",fields:Mn(t.fields,"fields")}):t.kind==="field_writers"||t.kind==="approval"?(Me(t,["kind","fields","authors"],"field rule"),{kind:t.kind,fields:Mn(t.fields,"fields"),authors:Mn(t.authors,"authors")}):le("unknown rule kind")}function Gy(e){let t={},n=Me(e,["types","tags","statuses","operations","parents","dependency"],"subject");for(let r of["types","tags","statuses","operations","parents"])n[r]!==void 0&&(t[r]=Mn(n[r],r));if(n.dependency!==void 0){let r=Me(n.dependency,["kind","id"],"dependency");t.dependency={kind:_t(r.kind,"dependency kind"),...r.id===void 0?{}:{id:_t(r.id,"dependency id")}}}return t}function Ky(e){let t=Me(e,["id","description","subject","effect","rule"],"policy"),n=_t(t.id,"id");return/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(n)?t.effect!==void 0&&(typeof t.effect!="string"||!["advise","warn","refuse"].includes(t.effect))?le("effect must be advise, warn, or refuse"):{id:n,rule:Wy(t.rule),...t.subject===void 0?{}:{subject:Gy(t.subject)},...t.description===void 0?{}:{description:_t(t.description,"description",500)},...t.effect===void 0?{}:{effect:t.effect}}:le("id must be a stable token")}function Yy(e){let t=Me(e,["version","enforcement","policies"],"document");if(t.version!==1)return le("unsupported version");if(t.enforcement!==void 0&&t.enforcement!=="advise"&&t.enforcement!=="refuse")return le("enforcement must be advise or refuse");if(!Array.isArray(t.policies)||t.policies.length>xd)return le(`policies must contain at most ${xd} declarations`);let n=t.policies.map(Ky);return new Set(n.map(r=>r.id)).size!==n.length?le("duplicate policy id"):{version:1,enforcement:t.enforcement??"advise",policies:n}}function Br(e,t){let n=e;for(let r of t.split(".")){if(typeof n!="object"||n===null||!Object.hasOwn(n,r))return;n=n[r]}return n}function Xy(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 Dd(e){return Nd("sha256").update(R(e)).digest("hex")}function Jy(e,t){let n=e.rule.kind==="approval"?e.rule.fields:[];return Nd("sha256").update(R({id:t.id,fields:n.map(r=>[r,Br(t,r)])})).digest("hex")}function Zy(e,t){return Array.isArray(t)&&t.some(n=>typeof n=="object"&&n!==null&&"kind"in n&&n.kind===e.kind&&(e.id===void 0||"id"in n&&n.id===e.id))}function Qy(e,t,n){return!(e.types&&!e.types.some(r=>r.toLowerCase()===String(t.type).toLowerCase())||e.statuses&&!e.statuses.includes(String(t.status))||e.operations&&!e.operations.includes(n)||e.parents&&!e.parents.includes(String(t.parent))||e.tags&&(!Array.isArray(t.tags)||!e.tags.some(r=>t.tags.includes(r)))||e.dependency&&!Zy(e.dependency,t.dependencies))}function eh(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 n=e.subject??{},r=t.after?.status??t.before?.status;return[t.before,t.after].some(o=>o!==null&&Qy(n,{...o,status:r},t.operation))}function th(e,t,n,r){let o=["type","tags","parent","dependencies"].some(i=>!W(t.before?.[i],t.after?.[i]));return t.after&&(t.completeness_only||n||r||o)?e.filter(i=>!Xy(Br(t.after,i))):[]}function nh(e,t,n,r){let o=t.after??t.before,i=Jy(e,o);return t.approvals?.some(s=>s.policy_fingerprint===r&&s.content_fingerprint===i&&s.author!==t.author&&n.includes(s.author))??!1}function rh(e,t,n){let r=e.rule,o=t.before?.status!==t.after?.status,i="fields"in r&&r.fields.some(s=>!W(Br(t.before,s),Br(t.after,s)));switch(r.kind){case"require_fields":{let s=th(r.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||r.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:r.authors.includes(t.author),missing_fields:[],remediation:"Have a declared workflow actor perform this operation."};case"field_writers":return{satisfied:!i||r.authors.includes(t.author),missing_fields:[],remediation:"Have a declared field writer change the protected fields."};case"approval":return{satisfied:!o||nh(e,t,r.authors,n),missing_fields:[],remediation:`Record an independent approval with pm schema policy-approve <item-id> --policy ${e.id} after preparing the reviewed fields.`}}}function Pd(e,t,n){let r=e.policies.filter(o=>eh(o,t)).map(o=>{let i=o.effect??"advise",s=n(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:!r.some(o=>!o.satisfied&&o.effect==="refuse"),decisions:r,warnings:r.filter(o=>!o.satisfied).map(o=>`workflow_policy:${o.effect}:${o.policy_id}:${o.rule}`)}}function MC(e,t){return Pd(e,t,Dd)}function $C(e){let t=Yy(e),n=new Map(t.policies.map(r=>[r,Dd(r)]));return r=>Pd(t,r,o=>n.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]="451b262c-a9b6-5f1c-b397-2686a5fd953a")}catch{}})();var oh=[["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"})),ih=[...["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"})),sh=[["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"})),ah=[...ih,...sh,...["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,n])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:n}))],is=[{alias:"history-attest",canonical:"history attest",canonical_argv:["history","attest"],lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-3z0k"},...oh,...ah,...["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 LC(e){let t;for(let n of is)n.canonical_argv.length<=(t?.canonical_argv.length??0)||n.canonical_argv.every((r,o)=>r===(o===0&&e[o]==="ctx"?"context":e[o]))&&(t=n);return t}function ch(e){let t=e.trim().replace(/\s+/gu," ");return is.find(n=>n.canonical===t.replace(/^ctx /u,"context "))?.alias??t}function $n(e){return ch(e)}var Wr=[...is,...[["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,n])=>({alias:e,canonical:t,canonical_argv:[t,n],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"}))],FC=Object.fromEntries(Wr.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));function zC(e){let t=e.trim().toLowerCase();return Wr.find(n=>n.alias===t)}function UC(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]="3348c61d-a03e-5023-a5dc-fd6149f478c1")}catch{}})();var dh=[...Pe],lh=[...Gt],uh=[...jr],WC=[...Lr],GC=[...Fr],fh=[...zr],Gr=["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"],KC=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],YC=["install","reconcile","report","driver"],mh=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],ph=["upgrade"],_h=["reopen"],Md={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},Kt=Object.freeze(Gr.flatMap(e=>e in Md?[]:e==="extension"||e==="package"?[...mh.map(t=>`${e}-${t}`),...e==="package"?ph.map(t=>`package-${t}`):[],e]:e==="item"?_h.map(t=>`item-${t}`):[e])),yh=Object.freeze(Wr.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&Kt.includes(e.alias)).map(e=>e.alias)),XC=Object.freeze(Kt.filter(e=>!yh.includes(e)));function JC(e=Gr,t=Kt,n=Md){let r=new Set(t),o=new Set(e);return{missing_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]===void 0),waived_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]!==void 0),stale_waivers:Object.keys(n).filter(i=>!o.has(i)||r.has(i)||t.some(s=>s.startsWith(`${i}-`)))}}function ZC(e){return Kt.includes(e)}function QC(e){return dh.includes(e)}function eR(e){return lh.includes(e)}function tR(e){return uh.includes(e)}function nR(e){return fh.includes(e)}var rR=new Set(["update","item-reopen","close","claim","release","start-task","pause-task","close-task","restore","append","update-many","close-many","delete","comments","notes","learnings","files","docs","test","test-all","plan","history-redact","history-repair","history-compact","validate"]);(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]="b181d38e-7120-5d34-98d9-fd9b4619b9d9")}catch{}})();var hh=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],$d=hh,Yt=["draft","open","in_progress","blocked","closed","canceled"],Kr=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Xt=["string","number","boolean","string_array","array","object"],Yr=["create","update","update_many","list","search","calendar","context"],Xr=["allow","warn","reject"],iR=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],sR=["project","global"],aR=["low","medium","high","critical"],Jr=["low","medium","high","critical"],Zr=["low","medium","high"];var jd=["minimal","default","strict","custom"],cR=["none","warn","strict"],dR=["progressive","strict"],lR=["off","warn","strict"],uR=["off","warn","strict"],Ld=["off","warn","strict"];var Qr=["daily","weekly","monthly","yearly"],jn=["mon","tue","wed","thu","fri","sat","sun"];function ss(e){return jn.indexOf(e)}var fR=["draft","research","review","approved","executing","paused","completed","superseded"],Fd=["pending","in_progress","completed","blocked","skipped","superseded"],mR=["codex","claude-code","cursor","generic"],pR=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],_R=["brief","standard","deep","full"],yR=["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 Eh 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 qe(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function gh(e){let t=e.key.trim();if(t.length===0)return null;let n=qe(e.aliases),r=e.description?.trim();return{key:t,values:qe(e.values),required:e.required===!0?!0:void 0,aliases:n.length>0?n:void 0,description:r&&r.length>0?r:void 0}}var bh=e=>e,Ud=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function wh(e,t){let n=t(e.command);if(n===null)return null;let r=e.option.trim();return r.length===0?null:{command:n,option:r,required:e.required,visible:e.visible,enabled:e.enabled}}function vh(e,t){let n=new Map;for(let r of e??[]){let o=wh(r,t);o&&n.set(`${o.command}:${o.option.toLowerCase()}`,o)}return[...n.values()].sort((r,o)=>r.command===o.command?r.option.localeCompare(o.option):r.command.localeCompare(o.command))}function zd(e,t){return t?qe(e):void 0}function as(e){let t=e?.trim();return t&&t.length>0?t:void 0}function cs(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 eo(e,t={}){let n=t.resolvePolicyCommand??bh,r=e.name.trim();if(r.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=qe(e.aliases),d=(e.options??[]).map(u=>gh(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),l=vh(e.command_option_policies,n);return{name:r,description:as(e.description),default_status:as(e.default_status),...e.execution_role===void 0?{}:{execution_role:cs(e.execution_role)},folder:as(e.folder),aliases:c.length>0?c:void 0,required_create_fields:zd(e.required_create_fields,o),required_create_repeatables:zd(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 kh=Object.freeze({decision:"human",milestone:"gate"}),Sh=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],Oh=["dep","comment","note","learning","file","test","doc"],qd=["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"],Ah=["title","description","type","status","priority","tags","body",...qd,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],Ih=["title","description","body","status","closeReason","priority","type","tags",...qd,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],Vd={"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"},Th={...Vd},Ch={...Vd},Bd=[["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"]],Wd=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function Gd(e){return Object.fromEntries(e)}var Rh=Gd([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...Bd,["author","--author"],["message","--message"],["dep","--dep"],...Wd]),xh=Gd([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...Bd,...Wd,["author","--author"],["message","--message"],["force","--force"]]);function Nh(e){return e.trim().replace(/^--+/,"").toLowerCase()}function Dh(e){return e==="create"?Ah:Ih}function Ph(e){return e==="create"?Th:Ch}function Kd(e,t){let n=Nh(t);return n.length===0?void 0:Ph(e)[n]||Dh(e).find(r=>r.toLowerCase()===n)}function OR(e,t){return(e==="create"?Rh:xh)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function ls(e){let t=$h(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function Mh(e){let t=e.trim(),n=t.replaceAll("\\","/").replace(/^\/+/,""),r=Eh.posix.normalize(n);if(t.includes("\0")||/^[A-Za-z]:/.test(r)||r==="."||r===".."||r.startsWith("../"))throw new Error(`Item type folder "${e}" must stay inside the pm tracker root.`);return r}function $h(e){let t=e.trim().toLowerCase(),n="",r=!1;for(let o of t){let i=o.charCodeAt(0),s=i>=97&&i<=122,a=i>=48&&i<=57;if(s||a){r&&n.length>0&&(n+="-"),n+=o,r=!1;continue}n.length>0&&(r=!0)}return n}function jh(e){return eo(e,{resolvePolicyCommand:Ud})}function Ln(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function Lh(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:Ln(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Ln(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function Fh(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 n=t.command.trim().toLowerCase();return n!=="create"&&n!=="update"?null:{command:n,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 zh(e){if(Array.isArray(e.options))return e.options.map(t=>Lh(t)).filter(t=>t!==null)}function Uh(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>Fh(t)).filter(t=>t!==null)}function Hh(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,n=typeof t.name=="string"?t.name:"";if(n.trim().length===0)return null;let r=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:n,description:o,default_status:i,execution_role:cs(t.execution_role),folder:r,aliases:Ln(t,"aliases"),required_create_fields:Ln(t,"required_create_fields"),required_create_repeatables:Ln(t,"required_create_repeatables"),options:zh(t),command_option_policies:Uh(t)}}function qh(e,t){return e.required_create_fields?qe(e.required_create_fields):t?.required_create_fields??[]}function Vh(e,t){return e.required_create_repeatables?qe(e.required_create_repeatables):t?.required_create_repeatables??[]}function Bh(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function Wh(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Gh(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=Mh(e.folder??t?.folder??ls(n)),s={name:n,execution_role:e.execution_role,folder:i,aliases:qe([...t?.aliases??[],...e.aliases??[]]),required_create_fields:qh(e,t),required_create_repeatables:Vh(e,t),options:Bh(e,t),command_option_policies:Wh(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function Hd(e,t){for(let n of e){let r=jh(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,Gh({...r,execution_role:r.execution_role??i?.execution_role},i))}}function Kh(e){if(!e)return[];let t=[];for(let n of e.item_types??[]){let r=n.types;if(Array.isArray(r))for(let o of r){let i=Hh(o);i&&t.push(i)}}return t}function AR(e,t=null){let n=new Map;for(let c of $d)n.set(c.toLowerCase(),{name:c,execution_role:kh[c.toLowerCase()]??"agent",folder:Dn[c],aliases:[],required_create_fields:[...Sh],required_create_repeatables:[...Oh],options:[],command_option_policies:[]});Hd(e.item_types?.definitions??[],n),Hd(Kh(t),n);let r=[...n.values()].sort((c,d)=>c.name.localeCompare(d.name)),o={},i={},s={};for(let c of r){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(r.map(c=>c.folder))].sort((c,d)=>c.localeCompare(d));return{types:r.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}function Yh(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function Xh(e,t){let n=Yh(e,t);if(n)return t.by_type[n]}function Jh(e,t,n,r){for(let o of r){let i=Kd(n,o);if(i){e.required.add(i);continue}e.errors.push(`Unsupported base required option "${o}" for command "${n}" on type "${t.name}"`)}}function ds(e,t,n){if(n){e.add(t);return}e.delete(t)}function Zh(e,t,n,r){let o=Kd(n,r.option);if(!o){e.errors.push(`Unsupported command_option_policies option "${r.option}" for command "${n}" on type "${t.name}"`);return}r.required!==void 0&&ds(e.required,o,r.required),r.visible!==void 0&&ds(e.hidden,o,!r.visible),r.enabled!==void 0&&ds(e.disabled,o,!r.enabled)}function Qh(e,t,n){for(let r of t.command_option_policies)r.command===n&&Zh(e,t,n,r)}function eg(e,t,n){for(let r of e.required)e.disabled.has(r)&&e.errors.push(`Option "${r}" cannot be both required and disabled for command "${n}" on type "${t.name}"`)}function IR(e,t,n){let r=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:r};return Jh(a,e,t,n),Qh(a,e,t),eg(a,e,t),{required:[...o],hidden:[...i].sort((c,d)=>c.localeCompare(d)),disabled:[...s].sort((c,d)=>c.localeCompare(d)),errors:r}}function tg(e){let t=new Map;for(let n of e.options){t.set(n.key.toLowerCase(),n);for(let r of n.aliases??[])t.set(r.toLowerCase(),n)}return t}function ng(e,t,n){let r=e.values;if(r.length===0)return t;let o=new Map(r.map(i=>[i.toLowerCase(),i])).get(t.toLowerCase());if(!o){n.push(`Invalid value "${t}" for type option "${e.key}". Allowed: ${r.join(", ")}`);return}return o}function TR(e,t,n){let r=Xh(e,n);if(!r)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=tg(r),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 _=r.options.map(y=>y.key).join(", ");o.push(r.options.length>0?`Unknown type option "${l}" for type "${r.name}". Allowed: ${_}`:`Type "${r.name}" does not define any configurable type options`);continue}let m=ng(f,u,o);m!==void 0&&(s[f.key]=m)}for(let c of r.options)c.required&&!(c.key in s)&&o.push(`Missing required type option "${c.key}" for type "${r.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 rg,readdirSync as og,realpathSync as Yd,statSync as Xd}from"node:fs";import ig from"node:os";import C 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 sg={json_markdown:".md",toon:".toon"},ag={".md":"json_markdown",".toon":"toon"},cg=new Set([".git","coverage","dist","node_modules"]),jR=[".md",".toon"];function Fn(e){try{return Xd(e),!0}catch{return!1}}function dg(e){let t=C.resolve(e),n=[];for(;C.dirname(t)!==t;)try{return C.join(Yd(t),...n)}catch(r){if(!be(r))throw r;n.unshift(C.basename(t)),t=C.dirname(t)}return C.join(Yd(t),...n)}function lg(e){try{return Xd(e),!0}catch(t){if(be(t))return!1;throw t}}function Jd(e){try{let t=JSON.parse(rg(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function ug(e){let t=dg(e);for(;;){let n=C.join(t,Ur),r=C.join(n,Hr);if(Fn(r))return n;let o=C.join(t,Hr);if(Fn(o)&&Jd(o))return t;if(lg(C.join(t,".git")))return n;let i=C.dirname(t);if(i===t)return;t=i}}function us(e){return ug(e)??C.resolve(e,Ur)}function LR(e,t){let n=t?C.resolve(t):void 0;try{return og(C.resolve(e),{withFileTypes:!0}).filter(r=>r.isDirectory()&&!cg.has(r.name)).map(r=>C.join(C.resolve(e),r.name)).filter(r=>r!==n).filter(r=>Fn(Ie(r))).filter(r=>Jd(Ie(r))).sort((r,o)=>r.localeCompare(o))[0]}catch{return}}function Zd(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=C.resolve(e,r);if(!Fn(Ie(o))){let i=C.join(o,Ur);if(Fn(Ie(i)))return i}return o}return us(e)}function Qd(e){let t=C.resolve(e),n=C.dirname(t);return C.basename(t)==="pm"&&C.basename(n)===".agents"?C.dirname(n):t}function el(e){let t=process.env.PM_GLOBAL_PATH?.trim(),n=t&&t.length>0?t:C.join(ig.homedir(),".pm-cli");return C.resolve(e,n)}function Ie(e){return C.join(e,Hr)}function fg(e,t,n=Dn){let r=n[t]??ls(t);return C.join(e,r)}function FR(e,t,n,r="toon",o=Dn){return C.join(fg(e,t,o),`${n}${sg[r]}`)}function zR(e){let t=e.replaceAll("\\","/"),n=C.posix.extname(t).toLowerCase();return ag[n]??null}function UR(e,t){if(!/^(?!\.{1,2}$)[^/\\:\0]+$/.test(t))throw new g("Invalid history item id: expected a single filename.",h.USAGE);return C.join(e,"history",`${t}.jsonl`)}function fs(e,t){return C.join(e,"locks",`${t}.lock`)}function ms(e){return C.join(e,"runtime")}function to(e){return C.join(ms(e),"test-runs")}function mg(e){return C.join(to(e),"runs")}function HR(e,t){return C.join(mg(e),`${t}.json`)}function pg(e){return C.join(to(e),"stdout")}function _g(e){return C.join(to(e),"stderr")}function qR(e,t){return C.join(pg(e),`${t}.log`)}function VR(e,t){return C.join(_g(e),`${t}.log`)}function yg(e){return C.join(to(e),"results")}function BR(e,t){return C.join(yg(e),`${t}.json`)}(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 tl=e=>{let t='"',n=0;for(let r of e){if(r==="\\"){n+=1;continue}t+="\\".repeat(r==='"'?n*2+1:n),t+=r,n=0}return`${t}${"\\".repeat(n*2)}"`},nl=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?tl(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,Jt=(e,t=process.platform)=>{let n=e.map(r=>nl(r,t)).join(" ");return n.length>0?`pm ${n}`:"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]="9bb3b2ed-c289-5b96-99ce-9df6e202c464")}catch{}})();var rl=new Set(["--pm-path","--path","--author","--expect-hash","--output-include","--output-limit","--output-budget","--output-format","--format","--output-session","--output-cursor"]),hg=new Set(["--no-extensions","--no-pager","--json","--quiet","--lean","--token-accounting","--output-row-contract","--all"]);function gg(e){let t=e.indexOf("=");return t>0&&rl.has(e.slice(0,t))}function bg(e,t){return typeof t!="string"?!1:e==="--path"||e==="--pm-path"||!t.startsWith("-")}function no(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")return;if(rl.has(n)){t+=bg(n,e[t+1])?1:0;continue}if(!(gg(n)||hg.has(n)||n==="--profile"||n==="--id-only"||n==="--explain")&&!n.startsWith("-"))return t}}function KR(e){let t=no(e);return t===void 0?void 0:e[t].trim().toLowerCase()}import wg from"node:path";import ol 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 zn(e,t){let n=ol.relative(e,t);return n.length===0?!0:!n.startsWith("..")&&!ol.isAbsolute(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]="08181915-ead8-51bc-a078-9d97b9048f37")}catch{}})();var ps=new WeakMap;function rx(e){ps.set(e,e.path)}function vg(e){if(!process.env.PM_PATH?.trim())return;let t=Zd(e);return zn(Qd(t),e)&&t===us(e)?void 0:wg.relative(e,t)||"."}function ox(e,t=process.cwd()){let n=(ps.has(e)?ps.get(e):e.path)||vg(t),r=n?["--pm-path",n]:[];return e.noExtensions&&r.push("--no-extensions"),r}var Eg=new Set(["--literal","--regex","--replacement"]);function kg(e){let t=no(e);if(t===void 0)return!1;if(e[t]==="history-redact")return!0;if(e[t]!=="history")return!1;let n=e.slice(t+1),r=no(n);return r!==void 0&&n[r]==="redact"}function ix(e){if(!kg(e))return[...e];let t=[],n=!1;for(let r of e){if(n){t.push("[redacted]"),n=!1;continue}n=!1;let o=r.indexOf("="),i=o>=0?r.slice(0,o):r;if(!Eg.has(i)){t.push(r);continue}if(o>=0){t.push(`${i}=[redacted]`);continue}t.push(i),n=!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]="32b0a81e-6a21-528a-8cf8-3e764f382044")}catch{}})();var Sg=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"},{flag:"--expect-hash",value_name:"revision"}]),_s=new Set(Sg.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 il=/^(--[a-z0-9][a-z0-9_-]*)(?:[ =](<[^<>]+>|\[[^[\]]+\]))?$/;function ys(e){if(typeof e!="string")return null;let t=il.exec(e.trim());if(!t)return null;let n=t[2];return{name:t[1],valueName:n?n.slice(1,-1):null,optional:n?.startsWith("[")??!1}}function dx(e){let t=ys(e);return t?t.name:typeof e=="string"&&e.trim()||null}function Og(e){if(typeof e!="string")return null;let t=e.trim(),n=t.split(/[ =]/,1)[0];return _s.has(n)?"host_owned_flag_collision":il.test(t)?null:"malformed_long_flag"}function sl(e,t){let n=[e,t].find(i=>typeof i=="string"&&_s.has(i.trim().split(/[ =]/,1)[0]));if(typeof n=="string")return{token:n.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof e!="string")return null;let r=e.trim(),o=Og(r);return o===null?null:{token:r,failure:o}}function al(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]="a797572f-fbc6-5e62-a9b5-5a0bd6ef22b4")}catch{}})();function Ag(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ux(e){return Ag(e)??void 0}function fx(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 mx(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function dl(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function ro(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 px(e){let t=ro(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function _x(e,t,n){let r=ro(e);return r===null||r<t||r>n?null:r}function yx(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function Ve(e){return typeof e!="object"||e===null?null:e}function cl(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function ll(e){let t=cl(e);if(!t)return null;if(typeof t.activate=="function")return t;let n=cl(t.default);return typeof n?.activate=="function"?n:null}function hx(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]="92573990-a040-526d-a0b1-b91d2ef401f1")}catch{}})();function oo(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import Ig from"node:crypto";import{AsyncLocalStorage as Tg}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 hs=new Tg,ul=1024;function Cg(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 Rg(e){let t={...Cg(e),clockReads:0,tokenReads:0};return n=>hs.run(t,n)}async function Ex(e,t){return Rg(e)(t)}function fl(){let e=hs.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 kx(e){let t=hs.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>ul)throw new Error(`Reproducible token length must be an integer between 0 and ${ul}`);let n="";for(;n.length<e;){let r=Ig.createHash("sha256").update(`${t.seed}\0${t.tokenReads}`).digest();t.tokenReads+=1;for(let o of r)if(n+=(o%36).toString(36),n.length===e)break}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]="0bf155fc-c690-5318-ba1e-275f1787858b")}catch{}})();var xg=/^([+-]?)(\d+)([hdwm])$/i,Ng=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,Dg=/^(\d{4})(\d{2})(\d{2})$/,Pg=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Mg=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,$g=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,jg=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function Te(){return fl()??new Date().toISOString()}function $e(e){return Number.isFinite(Date.parse(e))}function Un(e){let t=jg.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,n,r,o,i,s,a,c,d]=t,[l,u,f,m,_,y]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=ws(l,u-1)&&m<=23&&_<=59&&y<=59&&(c===void 0||Number(c)<=23)&&(d===void 0||Number(d)<=59)}function Zt(e){let t=/\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/iu.exec(e)?.[1];return Un(e)&&(t===void 0||/^\d{0,3}0*$/u.test(t))}var Lg=1e4,io=new Map;function ml(e){let t=io.get(e);if(t!==void 0)return t;let n=Date.parse(e);return io.size>=Lg&&oo(io),io.set(e,n),n}function re(e,t){let n=ml(e),r=ml(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function Cx(e,t){return!(t.deadlineBefore&&(!e.deadline||re(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||re(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&re(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&re(e.updated_at,t.updatedBefore)>0||t.createdAfter&&re(e.created_at,t.createdAfter)<0||t.createdBefore&&re(e.created_at,t.createdBefore)>0)}function gs(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function bs(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 Fg(e,t,n){n&&n!==t&&(e.includes(n)||e.push(n))}function zg(e){let t=[],n=d=>Fg(t,e,d),r=Dg.exec(e);if(r){let[,d,l,u]=r;n(`${d}-${l}-${u}`)}let o=Pg.exec(e);if(o){let[,d,l,u,f,m,_,y,w]=o,v=_?`:${_}`:"";n(`${d}-${l}-${u}T${f}:${m}${v}${gs(y)}${bs(w)}`)}let i=Mg.exec(e);if(i){let[,d,l,u,f,m,_]=i,y=f?`:${f}`:"";n(`${d}T${l}:${u}${y}${gs(m)}${bs(_)}`)}let s=$g.exec(e);if(s){let[,d,l,u,f,m,_]=s,y=f?`:${f}`:"";n(`${d}T${l}:${u}${y}${gs(m)}${bs(_)}`)}let a=10,c=e.slice(0,a);if(Hg(c)){let d=a;for(;d<e.length&&qg(e[d]);)d+=1;d<e.length&&n(`${c}T${e.slice(d)}`)}return t}function Ug(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let n of zg(e)){let r=Date.parse(n);if(Number.isFinite(r))return r}return Number.NaN}function Hg(e){if(e.length!==10)return!1;for(let t=0;t<e.length;t+=1){let n=e[t];if(t===4||t===7){if(n!=="-")return!1;continue}let r=n.charCodeAt(0);if(r<48||r>57)return!1}return!0}function qg(e){return e?e===" "||e===" "||e===`
2
+ `||e==="\r"||e==="\f"||e==="\v":!1}function ws(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var Vg=["January","February","March","April","May","June","July","August","September","October","November","December"],Bg=/^(\d{4})-(\d{2})-(\d{2})/,Wg=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function Gg(e,t,n){let r=Bg.exec(t)??Wg.exec(t);if(!r)return;let o=Number.parseInt(r[1],10),i=Number.parseInt(r[2],10),s=Number.parseInt(r[3],10),a=n?.trim()||"deadline";if(i<1||i>12)throw new g(`Invalid ${a} value "${e}". Month "${r[2]}" is out of range \u2014 use a month between 01 and 12.`,h.USAGE,{field:a,value:e});let c=ws(o,i-1);if(s<1||s>c)throw new g(`Invalid ${a} value "${e}". ${Vg[i-1]} ${o} has ${c} days, so day "${r[3]}" does not exist. Use a real YYYY-MM-DD calendar date.`,h.USAGE,{field:a,value:e})}function Kg(e,t){let n=new Date(e.getTime()),r=n.getUTCDate(),o=n.getUTCMonth()+t,i=n.getUTCFullYear()+Math.floor(o/12),s=(o%12+12)%12,a=Math.min(r,ws(i,s));return n.setUTCFullYear(i,s,a),n}function Rx(e,t=new Date,n="deadline"){let r=e.trim();if(r.toLowerCase()==="now")return t.toISOString();let o=xg.exec(r);if(o){let s=o[1]==="-"?-1:1,a=Number.parseInt(o[2],10)*s,c=o[3].toLowerCase();if(c==="m")return Kg(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()}Gg(e,r,n);let i=Ug(r);if(!Number.isFinite(i)){let s=n.trim().length>0?n.trim():"deadline",a=Ng.test(r)?"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()}(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 pl=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function so(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.hasOwn(pl,t)?pl[t]:null}function Yg(e,t,n){return!!(e.value_name?.trim()||t||n||e.required===!0||e.list===!0||e.repeatable===!0)}function Xg(e){return(e.value_type?.trim()||e.type?.trim())?.toLowerCase()}function Dx(e){let t=Xg(e),n=so(t),r=ys(e.long),o=e.value_name?.trim()||null,i=!(n==="boolean"&&t!=="bool")&&Yg(e,r?.valueName,t),s=r?.valueName?r.optional:t==="bool";return{value_type:n,value_arity:i?s?"optional":"required":"none",value_name:i?o??r?.valueName??"value":null}}function _l(e){let t=[],n=r=>{if(Array.isArray(r)){for(let o of r)n(o);return}if(typeof r=="string"){for(let o of r.split(",")){let i=o.trim();i.length>0&&t.push(i)}return}r!=null&&t.push(r)};return n(e),t}function yl(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 Px(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]="628615ea-5be3-5753-a6c5-3eba8400a8da")}catch{}})();function ao(e,t,n){if(e===t)return 0;if(Math.abs(e.length-t.length)>n)return null;let r=t.length+1,o=new Array(r),i=new Array(r),s=new Array(r);for(let c=0;c<r;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>n)return null;for(let l=0;l<r;l+=1)o[l]=i[l],i[l]=s[l]}let a=i[t.length];return a<=n?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]="2ea7934f-4751-5245-a5ba-492681aa3794")}catch{}})();var vs=[{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 uo(e){return e.trim().toLowerCase().replaceAll("-","_")}function Jg(e){if(e===void 0)return;let t=uo(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function ks(e,t=new Set){if(e===null||typeof e!="object"||t.has(e))return e;if(t.add(e),Array.isArray(e)){for(let n of e)ks(n,t);return Object.freeze(e)}for(let n of Object.values(e))ks(n,t);return Object.freeze(e)}function Zg(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 Qg(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 eb(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 tb(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=uo(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 nb(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 rb(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(n=>typeof n!="string")))throw new TypeError(`Invalid relationship aliases for ${t}`)}function ob(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var Ss=class{#e=new Map;#n=new Map;constructor(t=vs){for(let n of t)this.register(n)}register(t){let n=tb(t);if(nb(t,n),rb(t,n),Zg(t,n),Qg(t,n),eb(t,n),this.#e.has(n)||this.#n.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=Jg(t.inverse),o=[...new Set((t.aliases??[]).map(uo))].sort();for(let s of o){if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid relationship alias: ${s}`);if(s===n||this.#e.has(s)||this.#n.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:n,traversal:ob(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?ks(structuredClone(t.payloadSchema)):void 0});this.#e.set(n,i);for(let s of o)this.#n.set(s,n);return this}resolve(t){if(typeof t!="string")return;let n=uo(t);return this.#e.get(this.#n.get(n)??n)}require(t){let n=this.resolve(t);if(!n)throw new TypeError(`Unknown relationship kind: ${t}`);return n}list(){return Object.freeze([...this.#e.values()].sort((t,n)=>t.kind.localeCompare(n.kind)))}};function Os(){return new Ss}var yt=Os();function zx(e){return yt.require(e).kind}function Ux(e){return yt.resolve(e)?.kind}function Hx(e,t=yt){return t.resolve(e)?.ordering===!0}function ib(e,t,n,r=yt){let o=Hn(e),i=Hn(t);if(!o||!i)throw new TypeError("Relationship endpoint must not be empty");let s=r.require(n);if(o===i&&!s.allowSelf)throw new TypeError(`Self relationship is not allowed for ${s.kind}`);return s}function co(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function sb(e,t,n){let r=typeof e.source=="string"?e.source.trim():"",o=typeof e.target=="string"?e.target.trim():"";if(!t.has(r)||!t.has(o))throw new TypeError(`Relationship endpoint not found: ${r} -> ${o}`);let i=ib(r,o,e.kind,n),s=Object.freeze({...e,source:r,target:o,kind:i.kind}),a=i.direction==="undirected"?[r,o].sort().join("\0"):`${r}\0${o}`;return{edge:s,identity:`${i.kind}\0${a}`}}function lo(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function Hn(e){return typeof e=="string"?e.trim():""}function Es(e,t){let n=Hn(e);return n&&t.has(n)?n:void 0}function ab(e,t,n){let r=[t],o=t;for(;o!==e;)o=n.get(o),r.push(o);return r.reverse()}var hl=class e{#e;#n;#o;#r;#s=new Map;#a=new Map;constructor(t,n,r=yt){this.#e=r,this.#n=new Set([...t].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)),this.#o=Object.freeze([...this.#n].sort());let o=new Map;for(let i of n){let{edge:s,identity:a}=sb(i,this.#n,r);o.set(a,s)}this.#r=Object.freeze([...o.values()].sort(co));for(let i of this.#r)lo(this.#s,i.source,i),lo(this.#a,i.target,i),r.require(i.kind).direction==="undirected"&&(lo(this.#s,i.target,i),lo(this.#a,i.source,i))}static fromItems(t,n=yt){let r=new Set(t.map(i=>Hn(i.id)).filter(Boolean)),o=[];for(let i of t){let s=Hn(i.id);if(!s)continue;let a=Es(i.parent,r);a&&o.push({source:s,target:a,kind:"parent"});let c=Es(i.blocked_by,r);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let d of i.dependencies??[]){let l=Es(d.id,r);l&&n.resolve(d.kind)&&o.push({source:s,target:l,kind:d.kind,createdAt:d.created_at,author:d.author})}}return new e(r,o,n)}edges(){return this.#r}incidentEdges(t){this.#i(t);let n=this.#s.get(t)??[],r=this.#a.get(t)??[];if(n.length===0)return Object.freeze([...r]);if(r.length===0)return Object.freeze([...n]);let o=[],i=0,s=0;for(;i<n.length||s<r.length;){let a=n[i],c=r[s],d=a===void 0?c:c===void 0||co(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.#n.has(t)}registry(){return this.#e}#i(t){if(!this.#n.has(t))throw new TypeError(`Relationship node not found: ${t}`)}#c(t,n){if(!n)return!0;let r=this.#e.require(t.kind);return n.has(t.kind)||r.inverse!==void 0&&n.has(r.inverse)}#t(t,n,r){let o=[...n==="incoming"?[]:this.#s.get(t)??[],...n==="outgoing"?[]:this.#a.get(t)??[]];return[...new Set(o)].filter(i=>this.#c(i,r)).map(i=>({id:i.source===t?i.target:i.source,edge:i})).sort((i,s)=>i.id.localeCompare(s.id)||co(i.edge,s.edge))}adjacency(t,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(c=>this.#e.require(c).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.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,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(a=>this.#e.require(a).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.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,n={}){this.#i(t);let r=n.kinds?new Set(n.kinds.map(m=>this.#e.require(m).kind)):void 0,o=n.direction??"outgoing",i=n.limit??Number.POSITIVE_INFINITY,s=n.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){n.signal?.throwIfAborted();let _=d[m];l+=1;let y=this.#t(_.id,o,r);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,n,r={}){if(this.#i(t),this.#i(n),t===n)return{value:[t],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}};let o=r.kinds?new Set(r.kinds.map(m=>this.#e.require(m).kind)):void 0,i=r.direction??"outgoing",s=r.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){r.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===n)return{value:ab(t,n,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,n={}){let r=this.closure(t,n),o=[t,...r.value].sort(),i=new Set(o),s=n.kinds?new Set(n.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(co)},meta:r.meta}}};function qx(e,t,n=yt){return{source:e,target:t.id,kind:n.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 cb="__pm_suppress_host_output",As="@unbrained/pm-cli:suppress-host-output:v1";function gl(e){return e===void 0?{__pm_suppress_host_output:As}:{__pm_suppress_host_output:As,result:e}}function fo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[cb]===As}import Qt from"node:fs";import je from"node:path";import{fileURLToPath as db}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 lb="@unbrained/pm-cli";function ub(e){try{return JSON.parse(Qt.readFileSync(e,"utf8")).name===lb}catch{return!1}}function fb(e){let t=Qt.existsSync(e)&&Qt.statSync(e).isDirectory()?je.resolve(e):je.dirname(je.resolve(e));for(;;){let n=je.join(t,"package.json");if(Qt.existsSync(n)&&ub(n))return t;let r=je.dirname(t);if(r===t)return;t=r}}function mo(e,t=[]){let n=db(e);return fb(n)||je.resolve(je.dirname(n),...t)}function Yx(e,t=[]){try{let n=je.join(mo(e,t),"package.json");if(!Qt.existsSync(n))return;let r=JSON.parse(Qt.readFileSync(n,"utf8"));return typeof r.version=="string"&&r.version.trim().length>0?r.version:void 0}catch{return}}function Xx(e=process.env,t="PM_CLI_PACKAGE_ROOT",n,r=[]){let o=e[t];return typeof o=="string"&&o.trim().length>0?je.resolve(o.trim()):n?mo(n,r):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]="53865a81-4c96-51e2-a378-ae0e2781a50f")}catch{}})();var po={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},_o=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),ht=["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 z(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function mb(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function pe(e){return e?D(e):{}}function _e(e){return e?D(e):mb()}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 pb=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),_b=["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 yb(e,t){for(let n of _b){let r=e[n];if(r===void 0)continue;if(!Array.isArray(r)||r.some(i=>typeof i!="string"))return!1;let o=r.map(i=>pb.has(n)?z(i):i.trim()).filter(i=>i.length>0);t[n]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function hb(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n;if(r.format!=="json"&&r.format!=="toon"||!Array.isArray(r.commands)||r.commands.some(o=>typeof o!="string")||typeof r.result_discriminator!="boolean")return null;t.push({format:r.format,commands:[...new Set(r.commands.map(o=>z(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:r.result_discriminator})}return t.sort((n,r)=>n.format.localeCompare(r.format))}function gb(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n.commands;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))return null;t.push({commands:[...new Set(r.map(o=>z(o)))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i))})}return t}function yo(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 n={schema_version:1};if(!yb(t,n))return null;let r=t.preflight_overrides;if(r!==void 0&&(!Number.isInteger(r)||r<0))return null;typeof r=="number"&&(n.preflight_overrides=r);let o=t.renderer_ownership;if(o!==void 0){let s=hb(o);if(s===null)return null;n.renderer_ownership=s}let i=t.preflight_ownership;if(i!==void 0){let s=gb(i);if(s===null)return null;n.preflight_ownership=s}return n}function tN(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]="7359c10a-4c56-57ea-8254-fc26b19e5c84")}catch{}})();function qn(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Be(e){return Pe.includes(e)}function bl(e){let t=e.trim().toLowerCase();return Be(t)?t:null}function wl(e){return e.filter(t=>!Be(t))}function Is(e){let t=e.trim().toLowerCase();return t.length===0?null:Ed[t]??null}function vl(e){let t=qn([...e].map(i=>i.toLowerCase())),n=[],r=[];for(let i of t){let s=Is(i);if(s){n.push(s),r.push({alias:i,target:s});continue}n.push(i)}let o=[...new Map(r.map(i=>[`${i.alias}>${i.target}`,i])).values()].sort((i,s)=>i.alias.localeCompare(s.alias));return{capabilities:qn(n),legacy_aliases:o}}function bb(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Is(t);if(n)return n;let r=Math.max(1,Math.floor(t.length*.34)),o=null,i=Number.POSITIVE_INFINITY;for(let s of Pe){let a=ao(t,s,r);a!==null&&a<i&&(i=a,o=s)}return o}function El(e,t,n){let r=Pe.join(","),o=bb(n)??"none";return`extension_capability_unknown:${e}:${t}:${n}:allowed=${r}:suggested=${o}`}function kl(e,t,n){let r=n.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${r}`}function wb(e){let t=/^extension_capability_unknown:(global|project):([^:]+):([^:]+):allowed=([^:]+):suggested=([^:]+)$/.exec(e.trim());if(!t)return null;let[,n,r,o,i,s]=t,a=n,c=i.split(",").map(u=>u.trim()).filter(u=>u.length>0),d=Is(o),l=(s==="none"?void 0:s)??d??void 0;return{layer:a,name:r,capability:o,allowed_capabilities:c,capability_contract_version:ns,suggested_capability:l,suggestion_source:l?d===l?"legacy_alias":"nearest_match":void 0,legacy_alias_target:d??void 0}}function vb(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,n,r,o]=t,i=n,s=[...Pe],a=[];for(let c of o.split(",")){let[d,l]=c.split(">"),u=d?.trim(),f=l?.trim().toLowerCase();!u||!f||!Be(f)||a.push({layer:i,name:r,capability:u,allowed_capabilities:s,capability_contract_version:ns,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 Vn(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function Ts(){return{overrides:[],handlers:[]}}function Cs(){return{overrides:[]}}function Rs(){return{overrides:[]}}function xs(){return{overrides:[]}}function Ns(){return{overrides:[]}}function Ds(){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 Eb=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 kb(e){return{unknownKeys:Object.keys(e).filter(t=>!Eb.has(t)).sort((t,n)=>t>n?1:-1),missingVersionBounds:e.pm_min_version===void 0&&e.pm_max_version===void 0}}function Sb(e){let t=kb(e),n=t.unknownKeys.map(r=>({code:"manifest_unknown_key",path:r,...r==="compatibility"?{suggested_key:"pm_min_version"}:{},message:r==="compatibility"?'Manifest key "compatibility" is ignored; declare the canonical pm_min_version and optional pm_max_version fields instead.':`Manifest key "${r}" is not part of the extension manifest contract and will be ignored.`}));return t.missingVersionBounds&&n.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:n.length===0,findings:n}}function Sl(e,t,n){return Sb(n).findings.map(r=>r.code==="manifest_unknown_key"?`extension_manifest_unknown_key:${e}:${t.name}:key=${r.path}${r.suggested_key?`:suggested=${r.suggested_key}`:""}`:`extension_manifest_no_version_bounds:${e}:${t.name}:suggested=pm_min_version`)}import{constants as We}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 Ol=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"}]]),Ob=/^[a-z][a-z0-9_]{0,63}$/u,Ab=new Map([[We.errno.EACCES,"EACCES"],[We.errno.EDQUOT,"EDQUOT"],[We.errno.EMFILE,"EMFILE"],[We.errno.ENFILE,"ENFILE"],[We.errno.ENOMEM,"ENOMEM"],[We.errno.ENOSPC,"ENOSPC"],[We.errno.EPERM,"EPERM"],[We.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),Ib={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function Tb(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&Ol.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:Ab.get(Math.abs(t.errno))??null}function Cb(e,t,n={}){let r=Tb(e);if(r===null)return null;if(!Ob.test(t))throw new g("Host environment operation labels must be bounded identifiers.",h.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=Ol.get(r);return new g(`Host filesystem operation ${t} ${o.summary}.`,h.GENERIC_FAILURE,{code:n.codes?.[o.category]??Ib[o.category].code,reason:r,required:o.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[o.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function Al(e,t,n={}){try{return await t()}catch(r){throw Cb(r,e,n)??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]="4a7b042c-7fb8-57a5-8f94-de44f82d7589")}catch{}})();function Rb(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Ee(e,t){let n=e.slice(0,t),r=n.charCodeAt(n.length-1),o=e.charCodeAt(n.length);return r>=55296&&r<=56319&&o>=56320&&o<=57343?n.slice(0,-1):n}function fN(e){return Rb(e).split(/[^a-z0-9]+/).filter(t=>t.length>0)}function mN(e,t){if(e.length===0&&t.length===0)return 1;if(e.length===0||t.length===0)return 0;let n=new Set(e),r=new Set(t),o=0;for(let s of n)r.has(s)&&(o+=1);let i=new Set([...n,...r]).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]="f49bad80-c246-59b3-950d-7143585fbdb5")}catch{}})();var xb=5e3;async function Bn(e,t,n){let r=[];for(let o of e)try{await o.run(D(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}async function Nb(e,t){return Bn(e.beforeCommand,"beforeCommand",t)}function Db(e,t,n){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 r=e,o=typeof r.code=="string"?r.code.trim():"",i=typeof r.remediation=="string"?r.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 r.message=="string"?r.message.trim():"";throw new g(s||`Extension mutation guard ${t.name} denied ${n}.`,h.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function Ps(e,t){for(let n of e.beforeMutation??[]){let r,o;try{let i=Promise.resolve().then(()=>n.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(()=>{}),r=await Promise.race([i,new Promise((s,a)=>{o=setTimeout(()=>{a(new g(`Extension mutation guard ${n.name} timed out before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},xb),o.unref?.()})])}catch(i){throw i instanceof g?i:new g(`Extension mutation guard ${n.name} failed before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(o)}Db(r,n,t.operation)}}async function Pb(e,t){return Bn(e.afterCommand,"afterCommand",t)}async function Ms(e,t){return Bn(e.onWrite,"onWrite",t)}async function $s(e,t){return Bn(e.onRead,"onRead",t)}async function js(e,t){return Bn(e.onIndex,"onIndex",t)}function Mb(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 n=t.replace(/\s+/gu," ").trim();if(n.length===0)return"";let r=300;return n.length>r?`${Ee(n,r-1)}\u2026`:n}function ho(e,t){if(typeof e!="object"||e===null||typeof e[t]!="string")return;let n=String(e[t]).replace(/\s+/gu," ").trim();return n.length>0?Ee(n,300):void 0}function $b(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 n=z(t.command);if(n.length===0)return{handled:!1,result:null,warnings:[]};let r=[...e.handlers].reverse().find(o=>o.command===n);if(!r)return{handled:!1,result:null,warnings:[]};try{let o=await r.run({command:n,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",$b(o)],["errorCode",ho(o,"code")],["remediation",ho(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 Object.defineProperty({handled:!1,result:null,warnings:[`extension_command_handler_failed:${r.layer}:${r.name}:${r.command}`],errorMessage:Mb(o),...Object.fromEntries([["errorCode",ho(o,"code")],["remediation",ho(o,"remediation")]].filter(s=>s[1]!==void 0))},"cause",{value:o,configurable:!0})}}async function Fs(e,t){let n=z(t.command);if(n.length===0)return{overridden:!1,context:{command:n,args:D(t.args),options:pe(t.options),global:_e(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 r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,context:{command:n,args:D(t.args),options:pe(t.options),global:_e(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(r.run({command:n,args:D(t.args),options:pe(t.options),global:_e(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?pe(o.options):pe(t.options),a=o.global?_e(o.global):_e(t.global);return{overridden:!0,context:{command:n,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:n,args:D(t.args),options:pe(t.options),global:_e(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:${r.layer}:${r.name}:${r.command}`]}}}async function zs(e,t){let n={command:z(t.command),args:D(t.args),options:pe(t.options),global:_e(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},r=D(t.decision),o=[...e.overrides].reverse().find(i=>!i.commands?.length||i.commands.includes(n.command));if(!o)return{overridden:!1,context:n,decision:r,warnings:[]};try{let i=await Promise.resolve(o.run({command:n.command,args:D(n.args),options:pe(n.options),global:_e(n.global),pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel,decision:D(r)}))??{},s={command:n.command,args:Array.isArray(i.args)?D(i.args):n.args,options:i.options?pe(i.options):n.options,global:i.global?_e(i.global):n.global,pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel},a={enforce_item_format_gate:typeof i.enforce_item_format_gate=="boolean"?i.enforce_item_format_gate:r.enforce_item_format_gate,run_preflight_item_format_sync:typeof i.run_preflight_item_format_sync=="boolean"?i.run_preflight_item_format_sync:r.run_preflight_item_format_sync,run_extension_migrations:typeof i.run_extension_migrations=="boolean"?i.run_extension_migrations:r.run_extension_migrations,enforce_mandatory_migration_gate:typeof i.enforce_mandatory_migration_gate=="boolean"?i.enforce_mandatory_migration_gate:r.enforce_mandatory_migration_gate};return{overridden:!0,context:s,decision:a,warnings:[]}}catch{return{overridden:!1,context:n,decision:r,warnings:[`extension_preflight_override_failed:${o.layer}:${o.name}`]}}}function Il(e){return{handled:!1,result:e.payload,warnings:[]}}function Tl(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function Cl(e){return{service:e.service,command:e.command?z(e.command):void 0,args:e.args?D(e.args):void 0,options:e.options?pe(e.options):void 0,global:e.global?_e(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 jb(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 Rl(e,t){return jb(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 xl(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&W(e,n.payload)}function Nl(e,t,n){if(t.handled){if(e.passThrough===!0){n.push(`extension_service_pass_through_contract_violated:${e.layer}:${e.name}:${e.service}`);return}return{handled:!0,result:t.result,warnings:n}}}function Us(e,t){let n=Tl(e,t.service);if(n.length===0)return Il(t);let r=[];for(let o of n)try{let i=Cl(t),s=o.run(i);if(s instanceof Promise){r.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(xl(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Nl(o,Rl(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}async function Hs(e,t){let n=Tl(e,t.service);if(n.length===0)return Il(t);let r=[];for(let o of n)try{let i=Cl(t),s=await Promise.resolve(o.run(i));if(xl(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Nl(o,Rl(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}function qs(e,t){let n=z(t.command);if(n.length===0)return{overridden:!1,result:t.result,warnings:[]};let r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,result:t.result,warnings:[]};try{let o=pe(t.options),i=_e(t.global),s=r.run({command:n,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:${r.layer}:${r.name}:${r.command}`]}:{overridden:!0,result:s,warnings:[]}}catch{return{overridden:!1,result:t.result,warnings:[`extension_command_override_failed:${r.layer}:${r.name}:${r.command}`]}}}function Lb(e,t,n){if((e.commands?.length??0)>0&&!e.commands?.includes(t))return!1;if(e.resultDiscriminator===void 0)return!0;try{return e.resultDiscriminator(D(n))}catch{return!1}}function Vs(e,t){let n=typeof t.command=="string"?z(t.command):"",r=[...e.overrides].reverse().find(o=>o.format===t.format&&Lb(o,n,t.result));if(!r)return{overridden:!1,rendered:null,warnings:[]};try{let o=Array.isArray(t.args)?D(t.args):[],i=pe(t.options),s=_e(t.global),a=typeof t.pm_root=="string"?t.pm_root:"",c=r.run({format:t.format,command:n,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:${r.layer}:${r.name}:${r.format}`]}:{overridden:!0,rendered:c,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${r.layer}:${r.name}:${r.format}`]}}}import Et from"node:fs/promises";import vt from"node:path";import{pathToFileURL as ww}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]="559b05dc-0290-5a7c-97b9-ef1e5e8670ba")}catch{}})();function Dl(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(([n,r])=>[n,r.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[n,r]of Object.entries(t.registrations))e.registrations[n].length=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]="17ae377d-20c2-5e45-825a-48a79c6c7601")}catch{}})();function K(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return t}function te(e,t){if(t!==void 0&&typeof t!="boolean")throw new TypeError(`${e} must be a boolean when provided`)}function B(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 Pl(e,t){if(t===void 0)return;let n=r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean";if(Array.isArray(t)){for(let[r,o]of t.entries())if(!n(o))throw new TypeError(`${e}[${r}] must be a string, number, or boolean`);return}if(!n(t))throw new TypeError(`${e} must be a string, number, or boolean, or an array of these when provided`)}function gt(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[n,r]of t.entries())if(typeof r!="string"||r.trim().length===0)throw new TypeError(`${e}[${n}] must be a non-empty string`)}}function Wn(e,t){if(gt(e,t),!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){let i=o.trim();i.length===0||r.has(i)||(r.add(i),n.push(i))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34536eba-0f92-5599-a807-5b39b000e733")}catch{}})();var Bs=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 Fb=new Set(Bs);function zb(e){if(e!==void 0&&!Fb.has(String(e)))throw new Error(`registerCommand definition.family must be one of: ${Bs.join(", ")}`)}function Ml(e){B("registerCommand definition.action",e.action),B("registerCommand definition.family",e.family),B("registerCommand definition.description",e.description),B("registerCommand definition.intent",e.intent),B("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");zb(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 $l(e,t="",n=""){if(e===void 0)return;if(en(t)||en(n))throw new TypeError("Native pm commands and actions cannot declare read_output");let r=K("registerCommand definition.read_output",e);if(Object.keys(r).some(s=>s!=="row_keys")||!Array.isArray(r.row_keys))throw new TypeError("registerCommand definition.read_output requires only row_keys: string[]");let o=Array.from(r.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 en(e){let t=e.trim().toLowerCase().replace(/\s+/gu,"-");return Kt.includes(t)||ht.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 Ub(e){let t=K("registerExporter options.output",e),n=new Set(["channel","receipt","media_type"]);for(let r of Object.keys(t))if(!n.has(r))throw new TypeError(`registerExporter options.output contains unsupported field ${r}`);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 B("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 jl(e,t,n){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 r=Ub(t.output);return!n&&r.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."),r}function Ws(e,t,n){return{registration:t,action:n,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 Ll(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 we(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 Hb(e){let t=e.trim().toLowerCase();if(t.length===0)return"";let n=t.split(/[.:/]/).map(r=>r.replace(/[\s_-]+/g,"")).filter(r=>r.length>0);return n.length===0?"":n.length===1?n[0]:`${n[0]}.${n.slice(1).join("")}`}function tn(e){return new Set((e??[]).map(t=>Hb(t)).filter(t=>t.length>0))}function Fl(e){let t=we(e);return jr.includes(t)?t:"off"}function zl(e){let t=we(e);return Lr.includes(t)?t:"off"}function Gn(e){let t=we(e);return Fr.includes(t)?t:"none"}function Gs(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return kd.includes(t)?t:void 0}function Ul(e){if(typeof e=="string"){let t=Gs(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:Gs(e.global)??"block",project:Gs(e.project)??"block"}:{global:"block",project:"block"}}function qb(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function j(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function Vb(e){let t=we(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?Gn(e.sandbox_profile):void 0,allowedCapabilities:P(e.allowed_capabilities),blockedCapabilities:P(e.blocked_capabilities),allowedSurfaces:tn(e.allowed_surfaces),blockedSurfaces:tn(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 Hl(e){let t=new Map;for(let n of e??[]){let r=Vb(n);r&&t.set(r.name,r.normalized)}return t}function Bb(e){let t=[],n=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of j([...e.allowedCapabilities,...e.blockedCapabilities]))Be(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of n)for(let i of j([...o.allowedCapabilities,...o.blockedCapabilities]))Be(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let r=new Set(zr);for(let o of j([...e.allowedSurfaces,...e.blockedSurfaces]))r.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of n)for(let i of j([...o.allowedSurfaces,...o.blockedSurfaces]))r.has(i)||t.push(`extension_policy_unknown_surface:${o.name}:${i}`);return[...new Set(t)].sort((o,i)=>o.localeCompare(i))}function ql(e){let t=e.extensions?.policy??{},n=P(t.allowed_capabilities),r=P(t.blocked_capabilities),o=tn(t.allowed_surfaces),i=tn(t.blocked_surfaces),s=Hl(t.extension_overrides);return{mode:Fl(t.mode),trustMode:zl(t.trust_mode),pmMaxVersionExceededMode:Ul(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:P(t.trusted_extensions),defaultSandboxProfile:Gn(t.default_sandbox_profile),allowedExtensions:P(t.allowed_extensions),blockedExtensions:P(t.blocked_extensions),allowedCapabilities:n,blockedCapabilities:r,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:Bb({allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function Vl(e){let t=[...e.overridesByName.values()].sort((n,r)=>n.name.localeCompare(r.name)).map(n=>({name:n.name,...n.disabled?{disabled:!0}:{},...n.requireTrusted?{require_trusted:!0}:{},...n.requireProvenance?{require_provenance:!0}:{},...n.sandboxProfile?{sandbox_profile:n.sandboxProfile}:{},...n.allowedCapabilities.size>0?{allowed_capabilities:j(n.allowedCapabilities)}:{},...n.blockedCapabilities.size>0?{blocked_capabilities:j(n.blockedCapabilities)}:{},...n.allowedSurfaces.size>0?{allowed_surfaces:j(n.allowedSurfaces)}:{},...n.blockedSurfaces.size>0?{blocked_surfaces:j(n.blockedSurfaces)}:{},...n.allowedCommands.size>0?{allowed_commands:j(n.allowedCommands)}:{},...n.blockedCommands.size>0?{blocked_commands:j(n.blockedCommands)}:{},...n.allowedActions.size>0?{allowed_actions:j(n.allowedActions)}:{},...n.blockedActions.size>0?{blocked_actions:j(n.blockedActions)}:{},...n.allowedServices.size>0?{allowed_services:j(n.allowedServices)}:{},...n.blockedServices.size>0?{blocked_services:j(n.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:qb(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:j(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:j(e.allowedExtensions),blocked_extensions:j(e.blockedExtensions),allowed_capabilities:j(e.allowedCapabilities),blocked_capabilities:j(e.blockedCapabilities),allowed_surfaces:j(e.allowedSurfaces),blocked_surfaces:j(e.blockedSurfaces),allowed_commands:j(e.allowedCommands),blocked_commands:j(e.blockedCommands),allowed_actions:j(e.allowedActions),blocked_actions:j(e.blockedActions),allowed_services:j(e.allowedServices),blocked_services:j(e.blockedServices),extension_overrides:t}}function Bl(e){let t=Hl(e.extension_overrides);return{mode:Fl(e.mode),trustMode:zl(e.trust_mode),pmMaxVersionExceededMode:Ul(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:P(e.trusted_extensions),defaultSandboxProfile:Gn(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:tn(e.allowed_surfaces),blockedSurfaces:tn(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 Ge(e,t){return e.overridesByName.get(we(t))??null}function nn(e,t,n,r,o){return t.has(n)?o:e.size>0&&!e.has(n)?r:null}function Wl(e,t,n){let r=n.trim().toLowerCase(),o=Ge(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return nn(i,s,r,"capability_not_allowlisted","capability_blocked")}function Wb(e,t,n){let r=Ge(e,t.name),o=r&&r.allowedSurfaces.size>0?r.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...r?r.blockedSurfaces:[]]);return nn(o,i,n,"surface_not_allowlisted","surface_blocked")}function Gb(e,t,n){let r=z(n);if(r.length===0)return null;let o=Ge(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return nn(i,s,r,"command_not_allowlisted","command_blocked")}function Kb(e,t,n){let r=we(n).replace(/\s+/g,"-");if(r.length===0)return null;let o=Ge(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return nn(i,s,r,"action_not_allowlisted","action_blocked")}function Yb(e,t,n){let r=we(n);if(r.length===0)return null;let o=Ge(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return nn(i,s,r,"service_not_allowlisted","service_blocked")}function Xb(e,t){let n=we(t.name);return Ge(e,t.name)?.disabled===!0?"extension_override_disabled":nn(e.allowedExtensions,e.blockedExtensions,n,"extension_not_allowlisted","extension_blocked")}function Jb(e,t){if(e.trustMode==="off")return null;let n=Ge(e,t.name),r=we(t.name),o=t.trusted===!0,i=t.provenanceVerified===!0;return e.trustedExtensions.size>0&&!e.trustedExtensions.has(r)?"extension_not_trusted":(n?.requireTrusted===!0||e.trustMode==="warn"||e.trustMode==="enforce")&&!o?"extension_untrusted":(e.requireProvenance||n?.requireProvenance===!0)&&!i?"provenance_missing_or_unverified":null}function Zb(e,t){if(e.mode==="off")return null;let n=Ge(e,t.name)?.sandboxProfile??t.sandboxProfile??e.defaultSandboxProfile;if(n==="none")return null;let r=t.permissions;if(!r)return"sandbox_permissions_missing";let o=i=>r[i]===!0;return n==="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 go(e,t,n,r,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}:${n.layer}:${n.name}:reason=${r}${s}`}function Gl(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let n=[],r=Xb(e,t);r&&n.push({reason:r,scope:"extension",mode:e.mode});let o=Jb(e,t);o&&n.push({reason:o,scope:"trust",mode:e.trustMode});let i=Zb(e,t);i&&n.push({reason:i,scope:"extension",mode:e.mode});let s=n.find(c=>c.mode==="enforce");if(s)return{allowed:!1,warning:go("blocked",s.scope,t,s.reason)};let a=n.find(c=>c.mode==="warn");return a?{allowed:!0,warning:go("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function Kl(e,t,n){if(e.mode==="off")return{allowed:!0,warning:null};let r=Wl(e,t,n);return r?{allowed:e.mode==="warn",warning:go(e.mode==="warn"?"violation":"blocked","capability",t,r,{capability:n.trim().toLowerCase()})}:{allowed:!0,warning:null}}function Qb(e,t,n,r,o){let i=typeof r=="string"?Wl(e,t,r):null,s=Wb(e,t,n),a=o.command?Gb(e,t,o.command):null,c=o.action?Kb(e,t,o.action):null,d=o.service?Yb(e,t,o.service):null;return i??s??a??c??d}function ew(e,t,n,r){let o={method:we(e).replace(/\s+/g,"_"),surface:t};return n&&(o.capability=n),r.command&&(o.command=z(r.command)),r.action&&(o.action=we(r.action).replace(/\s+/g,"-")),r.service&&(o.service=we(r.service)),o}function Yl(e,t,n,r,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=Qb(e,t,n,o,s);if(!a)return{allowed:!0,warning:null};let c=go(e.mode==="warn"?"violation":"blocked","registration",t,a,ew(r,n,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 Jl=100;function Xl(e,t){let n=e[t];if(n!=null)return typeof n!="string"||n.trim().length===0?null:n.trim()}function tw(e){if(e==null)return;let t=Ve(e);if(!t)return null;let n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i))){if(r.trim().length===0)return null;let o=t[r];if(typeof o!="string"||o.trim().length===0)return null;n[r.trim()]=o.trim()}return Object.keys(n).length>0?n:void 0}function Ks(e,t){let n=e[t];return typeof n!="string"||n.trim().length===0?null:n.trim()}function Zl(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function bt(e){if(e!=null)return typeof e!="boolean"?null:e}function nw(e){let t=Zl(e.priority);return t===void 0?Jl:t}function rw(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let n=Gn(t);return n!==t.trim().toLowerCase()?null:n}function Ys(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function ow(e){if(e==null)return;let t=Ve(e);if(!t)return null;let n=Ys(t.source),r=Ys(t.signature),o=Ys(t.attestation),i=t.verified===void 0||t.verified===null?void 0:typeof t.verified=="boolean"?t.verified:null;return i===null?null:{...n?{source:n}:{},...r?{signature:r}:{},...o?{attestation:o}:{},...typeof i=="boolean"?{verified:i}:{}}}function iw(e){if(e==null)return;let t=Ve(e);if(!t)return null;let n=bt(t.fs_read),r=bt(t.fs_write),o=bt(t.network),i=bt(t.env_read),s=bt(t.env_write),a=bt(t.process_spawn);return[n,r,o,i,s,a].includes(null)?null:{...typeof n=="boolean"?{fs_read:n}:{},...typeof r=="boolean"?{fs_write:r}:{},...typeof o=="boolean"?{network:o}:{},...typeof i=="boolean"?{env_read:i}:{},...typeof s=="boolean"?{env_write:s}:{},...typeof a=="boolean"?{process_spawn:a}:{}}}function sw(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(n=>typeof n!="string"))return null;let t=vl(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function aw(e){if(e==null)return;let t=Ve(e);if(!t)return null;let n=t.commands;if(n==null)return;if(!Array.isArray(n)||n.some(o=>typeof o!="string"))return null;let r=[...new Set(n.map(o=>z(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return r.length>0?{commands:r}:void 0}function cw(e){let t=Zl(e.manifest_version);if(t===null)return null;let n=Xl(e,"pm_min_version");if(n===null)return null;let r=Xl(e,"pm_max_version");if(r===null)return null;let o=tw(e.engines);if(o===null)return null;let i=bt(e.trusted);if(i===null)return null;let s=rw(e);if(s===null)return null;let a=ow(e.provenance);if(a===null)return null;let c=iw(e.permissions);if(c===null)return null;let d=sw(e.capabilities);if(d===null)return null;let l=aw(e.activation);if(l===null)return null;let u=yo(e.contributions);return u===null?null:{manifest_version:t,pm_min_version:n,pm_max_version:r,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 Xs(e){if(typeof e!="object"||e===null)return null;let t=e,n=Ks(t,"name");if(n===null)return null;let r=Ks(t,"version");if(r===null)return null;let o=Ks(t,"entry");if(o===null)return null;let i=nw(t);if(i===null)return null;let s=cw(t);return s===null?null:{name:n,version:r,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 dw from"node:fs/promises";import Kn 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 Ql(e,t){let n=Kn.dirname(t.manifest_path),r=Kn.relative(n,t.entry_path);if(r.startsWith("..")||Kn.isAbsolute(r))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=Kn.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await Al("extension_module_graph_snapshot",()=>dw.cp(n,o,{recursive:!0,force:!0})),Kn.join(o,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]="bf5c3834-b388-507e-a13c-3beb5d096abb")}catch{}})();function eu(e){let t=typeof e=="function"?e:e.run;if(typeof t!="function")throw new TypeError("registerPreflight override requires a function handler");let n=[...new Set((typeof e=="function"?[]:e.commands??[]).map(r=>{if(typeof r!="string"||r.trim().length===0)throw new TypeError("registerPreflight ownership.commands must contain non-empty command paths");return z(r)}))];return{run:t,...n.length>0?{commands:n}:{}}}function tu(e){let t=[];for(let n=1;n<e.overrides.length;n+=1){let r=e.overrides[n];for(let o of e.overrides.slice(0,n))r.commands?.length&&o.commands?.length&&!o.commands.some(i=>r.commands.includes(i))||t.push(`extension_preflight_override_collision:${r.layer}:${r.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 bo=Xt;function nu(e){let t=e.trim().toLowerCase();return bo.includes(t)?t:null}function ru(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Math.max(1,Math.floor(t.length*.34));for(let r of bo)if(ao(t,r,n)!==null)return r;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 ou(e){return e==="toon"||e==="json"}function iu(e){return Gt.includes(e)}function wt(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}var su=Symbol("extension_registration_trace");function Le(e,t){let n=new TypeError(e);return Object.defineProperty(n,su,{value:t,enumerable:!1,configurable:!1,writable:!1}),n}function au(e){return e instanceof Error?e[su]:void 0}function Yn(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>Yn(t));if(typeof e=="function")return"[Function]";if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=Yn(t[r]);return n}return e}function Xn(e){if(Array.isArray(e))return e.map(t=>Xn(t));if(typeof e=="object"&&e!==null){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=Xn(t[r]);return n}return e}function rn(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Yn(t)}function Jn(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Xn(t)}function Zn(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(n=>rn(e,n))}function oe(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function Qn(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function Js(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Zs(e,t){return z(`${e} ${t}`)}function er(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}var lw=new Set(["low","medium","high"]),uw=new Set(["number","string_set"]),fw=new Set(["string","number","boolean"]);function cu(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function mw(e,t,n){let r=`registerAssuranceMeasurementProvider provider.keys.${t}`,o=K(r,n);if(!uw.has(String(o.value_type)))throw new TypeError(`${r}.value_type must be number or string_set`);if(B(`${r}.description`,o.description),o.parameters===void 0)return;let i=K(`${r}.parameters`,o.parameters);for(let[s,a]of Object.entries(i)){let c=`${r}.parameters.${s}`;cu(`${c}.name`,s);let d=K(c,a);if(!fw.has(String(d.type)))throw new TypeError(`${c}.type must be string, number, or boolean`);te(`${c}.required`,d.required),B(`${c}.description`,d.description)}if(Object.keys(i).length>50)throw new TypeError(`assurance provider ${e} key ${t} exceeds 50 parameters`)}function du(e){let t=K("registerAssuranceMeasurementProvider provider",e),n=cu("registerAssuranceMeasurementProvider provider.id",t.id);if(!/^[a-z0-9][a-z0-9-]*$/u.test(n))throw new TypeError("registerAssuranceMeasurementProvider provider.id must be a stable lowercase id");if(!lw.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 r=K("registerAssuranceMeasurementProvider provider.keys",t.keys);if(Object.keys(r).length===0)throw new TypeError("registerAssuranceMeasurementProvider provider.keys requires at least one key");for(let[o,i]of Object.entries(r)){if(!/^[a-z0-9][a-z0-9-]*$/u.test(o))throw new TypeError(`registerAssuranceMeasurementProvider provider key ${o} must be a stable lowercase id`);mw(n,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 pw=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","value_validation","visible"]);function wo(e,t){return Zn(e,t).map(n=>(n.repeatable===!0&&(n.list=!0),n))}function _w(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Qs(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 n=_w(t);if(n.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return n}function ea(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[r,o]of e.entries()){let i=K(`registerCommand definition.arguments[${r}]`,o),s=oe(`registerCommand definition.arguments[${r}].name`,i.name);if(te(`registerCommand definition.arguments[${r}].required`,i.required),te(`registerCommand definition.arguments[${r}].variadic`,i.variadic),B(`registerCommand definition.arguments[${r}].description`,i.description),s.includes(" "))throw new TypeError(`registerCommand definition.arguments[${r}].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 n=t.map((r,o)=>r.variadic?o:-1).filter(r=>r>=0);if(n.length>1)throw new TypeError("registerCommand definition.arguments supports at most one variadic argument");if(n.length===1&&n[0]!==t.length-1)throw new TypeError("registerCommand definition.arguments variadic argument must be the final argument");return t}function vo(e){if(!Array.isArray(e))throw new TypeError("registerFlags flags requires an array of object definitions");for(let[t,n]of e.entries()){let r=K(`registerFlags flags[${t}]`,n),o=Object.keys(r).filter(c=>!pw.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=r.long,s=r.short;if(i===void 0&&s===void 0)throw new TypeError(`registerFlags flags[${t}] requires at least one of long or short`);B(`registerFlags flags[${t}].long`,i),B(`registerFlags flags[${t}].short`,s);let a=sl(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${al(a.token,a.failure)}`);if(B(`registerFlags flags[${t}].value_name`,r.value_name),B(`registerFlags flags[${t}].description`,r.description),te(`registerFlags flags[${t}].required`,r.required),te(`registerFlags flags[${t}].enabled`,r.enabled),te(`registerFlags flags[${t}].visible`,r.visible),te(`registerFlags flags[${t}].list`,r.list),te(`registerFlags flags[${t}].repeatable`,r.repeatable),r.list!==void 0&&r.repeatable!==void 0&&r.list!==r.repeatable)throw new TypeError(`registerFlags flags[${t}].list and repeatable must match when both are provided`);if(Pl(`registerFlags flags[${t}].default`,r.default),Array.isArray(r.default)&&r.list!==!0&&r.repeatable!==!0)throw new TypeError(`registerFlags flags[${t}].default cannot be an array unless list is true.`);lu(`registerFlags flags[${t}]`,r),yw(`registerFlags flags[${t}]`,r)}}function yw(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 n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0),r=n===void 0?null:so(n);if(r!=="number"&&r!=="boolean")throw new TypeError(`${e}.value_validation "strict" requires value_type "number" or "boolean" (string values are never malformed).`)}function lu(e,t){let n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0);if(n===void 0)return;let r=so(n);if(r===null)throw new TypeError(`${e} value_type "${n}" 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?_l(t.default):[t.default];for(let[i,s]of o.entries())if(!yl(s,r)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${r}.`)}}function uu(e){if(!Array.isArray(e))throw new TypeError("registerItemFields fields requires an array of object definitions");for(let[t,n]of e.entries()){let r=K(`registerItemFields fields[${t}]`,n);oe(`registerItemFields fields[${t}].name`,r.name);let o=oe(`registerItemFields fields[${t}].type`,r.type);if(nu(o)===null){let i=ru(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${bo.join(", ")}).${s}`)}te(`registerItemFields fields[${t}].optional`,r.optional)}}function hw(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].command_option_policies`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=K(i,o);oe(`${i}.command`,s.command),oe(`${i}.option`,s.option),te(`${i}.enabled`,s.enabled),te(`${i}.required`,s.required),te(`${i}.visible`,s.visible)}}function gw(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].options`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=K(i,o);oe(`${i}.key`,s.key),gt(`${i}.values`,s.values),te(`${i}.required`,s.required),gt(`${i}.aliases`,s.aliases)}}function fu(e){if(!Array.isArray(e))throw new TypeError("registerItemTypes types requires an array of object definitions");for(let[t,n]of e.entries()){let r=`registerItemTypes types[${t}]`,o=K(r,n);oe(`${r}.name`,o.name),B(`${r}.folder`,o.folder),gt(`${r}.aliases`,o.aliases),gt(`${r}.required_create_fields`,o.required_create_fields),gt(`${r}.required_create_repeatables`,o.required_create_repeatables),hw(t,o.command_option_policies),gw(t,o.options)}}function mu(e){let t=K("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(te("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 pu=["types","statuses","fields","workflows","config","templates","packages"],bw={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[n,r]of t.allowed_transitions.entries())if(!Array.isArray(r))throw new TypeError(`${e}.allowed_transitions[${n}] 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 _u(e){let t=K("registerProfile profile",e);if(oe("registerProfile profile.name",t.name),oe("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 n of pu){let r=t[n];if(r!==void 0){if(!Array.isArray(r))throw new TypeError(`registerProfile profile.${n} must be an array when provided`);for(let[o,i]of r.entries()){if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`registerProfile profile.${n}[${o}] must be an object`);bw[n]?.(`registerProfile profile.${n}[${o}]`,i)}}}}function yu(e){e.summary===void 0&&(e.summary="");for(let t of pu)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 hu(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 gu(e){return typeof e=="string"?e:String(e)}function tr(e){let t=e.trim().replace(/^>=\s*/,"").replace(/^v/i,"").split(/[+-]/,1)[0];return/^\d+(?:[.-]\d+)*$/.test(t)?t.split(/[.-]/).map(n=>Number(n)):null}function ta(e,t){let n=tr(e),r=tr(t);if(!n||!r)return null;let o=Math.max(n.length,r.length);for(let i=0;i<o;i+=1){let s=n[i]??0,a=r[i]??0;if(s>a)return 1;if(s<a)return-1}return 0}function bu(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let n=gu(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(!tr(n))return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(t===null)return{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:null};let r=ta(t,n);return r===null?{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:t}:r<0?{kind:"pm_min_version",status:"unmet",allowed:!1,required:n,current:t}:{kind:"pm_min_version",status:"ok",allowed:!0,required:n,current:t}}function wu(e,t,n){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let r=gu(e);if(typeof e!="string"||r.trim().length===0)return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(/^[<>=~^]/.test(r.trim())||!tr(r))return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(t===null)return{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:null};let o=ta(t,r);return o===null?{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:t}:o>0?n==="warn"?{kind:"pm_max_version",status:"exceeded_warn",allowed:!0,required:r,current:t}:{kind:"pm_max_version",status:"exceeded",allowed:!1,required:r,current:t}:{kind:"pm_max_version",status:"ok",allowed:!0,required:r,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]="3abe36f7-3c97-58d2-a56d-b4e0ea958461")}catch{}})();var vu=null,vw=Object.freeze(Sd()),Eu=0;function Ew(e=Date.now()){return Eu+=1,`${Eu}-${e}`}function kw(e,t,n){return n.has(e)?!1:t.size===0?!0:t.has(e)}async function Sw(e,t){let[n,r]=await Promise.all([Et.realpath(e),Et.realpath(t)]);return zn(n,r)}function Ow(e,t=process.cwd()){return{global:vt.join(el(t),"extensions"),project:vt.join(e,"extensions")}}async function Aw(e){try{return(await Et.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}catch{return[]}}function Iw(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 ku(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function Tw(e){let t=new Map;try{let n=JSON.parse(await Et.readFile(vt.join(e,".managed-extensions.json"),"utf8")),r=Ve(n)?.entries;if(!Array.isArray(r))return t;for(let o of r){if(typeof o!="object"||o===null)continue;let i=o,s=ku(i.source?.package),a=[i.source?.input,i.source?.name,s].map(l=>ku(l)).filter(l=>l!==void 0),c=yo(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 Su(e){return[...e].sort((t,n)=>{if(t.manifest.priority!==n.manifest.priority)return t.manifest.priority-n.manifest.priority;let r=t.manifest.name.localeCompare(n.manifest.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function Cw(e,t){let n=[...Su(e),...Su(t)],r=[];for(let o of n){let i=r.findIndex(s=>s.manifest.name===o.manifest.name);i>=0&&r.splice(i,1),r.push(o)}return r}async function Ou(e,t,n,r,o){let i=[],s=[],a=[],c=await Aw(t),d=await Tw(t);for(let l of c){let u=await Nw(e,t,l,n,r,d,o);i.push(u.diagnostic),s.push(...u.warnings),u.candidate&&a.push(u.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function Rw(){return{diagnostics:[],warnings:[],candidates:[]}}function Au(e,t,n,r){return{diagnostic:{layer:e,directory:t,manifest_path:n,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[r],candidate:null}}function xw(e,t,n,r,o,i,s,a){let c=Sl(e,t,n);Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&c.push(kl(e,t.name,t.legacy_capability_aliases));for(let d of wl(t.capabilities))c.push(El(e,t.name,d));return r?o||c.push(`extension_entry_missing:${e}:${t.name}`):c.push(`extension_entry_outside_extension:${e}:${t.name}`),i.warning&&c.push(a?i.warning:i.warning.replace("extension_pm_","extension_disabled_pm_")),s.warning&&c.push(a?s.warning:s.warning.replace("extension_pm_","extension_disabled_pm_")),c}async function Nw(e,t,n,r,o,i,s){let a=vt.join(t,n),c=vt.join(a,"manifest.json");if(!await mt(c))return Au(e,n,c,`extension_manifest_missing:${e}:${n}`);let d,l;try{let de=JSON.parse(await Et.readFile(c,"utf8"));l=Ve(de),d=Xs(de)}catch{l=null,d=null}if(!d||!l)return Au(e,n,c,`extension_manifest_invalid:${e}:${n}`);let u=vt.resolve(a,d.entry),f=zn(a,u),m=f?await mt(u):!1,_=f&&m?await Sw(a,u):f,y=kw(d.name,r,o),w=await Mw(e,d),v=await $w(e,d,s),T=xw(e,d,l,_,m,w,v,y),H=_&&m&&w.allowed&&v.allowed,X=i.get(`directory:${n}`)??i.get(`name:${d.name}`);return{diagnostic:{layer:e,directory:n,manifest_path:c,name:d.name,version:d.version,entry:d.entry,priority:d.priority,entry_path:u,enabled:y,status:H?"ok":"warn"},warnings:T,candidate:Ll({layer:e,directory:n,manifestPath:c,entryPath:u,manifest:d,sourceIdentity:X,extensionReady:H,enabledForLoad:y})}}async function Dw(e){let t=Ow(e.pmRoot,e.cwd??process.cwd()),n=qn(e.settings.extensions.enabled),r=qn(e.settings.extensions.disabled),o=ql(e.settings),i=Vl(o);if(e.noExtensions)return{disabled_by_flag:!0,roots:t,configured_enabled:n,configured_disabled:r,discovered:[],effective:[],warnings:[...o.warnings],policy:i};let s=new Set(n),a=new Set(r),c=e.ignoreGlobalExtensions===!0?Rw():await Ou("global",t.global,s,a,o.pmMaxVersionExceededMode.global),d=await Ou("project",t.project,s,a,o.pmMaxVersionExceededMode.project),l=[...o.warnings],u=Cw(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=Gl(o,_);if(y.warning&&l.push(y.warning),!!y.allowed){for(let w of m.manifest.capabilities){let v=Kl(o,_,w);v.warning&&l.push(v.warning)}f.push(Iw(m))}}return{disabled_by_flag:!1,roots:t,configured_enabled:n,configured_disabled:r,discovered:[...c.diagnostics,...d.diagnostics],effective:f,warnings:[...new Set([...c.warnings,...d.warnings,...l])],policy:i}}function Eo(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function Pw(){try{let e=mo(import.meta.url,["../../.."]),t=await Et.readFile(vt.join(e,"package.json"),"utf8"),n=JSON.parse(t);return typeof n.version=="string"&&n.version.trim().length>0?n.version.trim():null}catch{return null}}function Cu(){return vu??=Pw(),vu}function Ru(e,t,n){let r=n.current??"unknown";if(n.kind==="pm_min_version")switch(n.status){case"invalid":return`extension_pm_min_version_invalid:${e}:${t.name}:required=${n.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${e}:${t.name}:required=${n.required}:current=${r}`;case"unmet":return`extension_pm_min_version_unmet:${e}:${t.name}:required=${n.required}:current=${r}`;default:return}switch(n.status){case"invalid":return`extension_pm_max_version_invalid:${e}:${t.name}:allowed=${n.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded":return`extension_pm_max_version_exceeded:${e}:${t.name}:allowed=${n.required}:current=${r}`;default:return}}async function Mw(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let n=bu(t.pm_min_version,await Cu()),r=Ru(e,t,n);return r?{allowed:n.allowed,warning:r}:{allowed:n.allowed}}async function $w(e,t,n){if(t.pm_max_version===void 0)return{allowed:!0};let r=wu(t.pm_max_version,await Cu(),n),o=Ru(e,t,r);return o?{allowed:r.allowed,warning:o}:{allowed:r.allowed}}async function Iu(e){try{let t=await Et.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function jw(e,t){let n=e.entry_path;t.module_graph_snapshot_root&&(n=await Ql(t.module_graph_snapshot_root,e));let r=new URL(ww(n).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return r.href;let[o,i]=await Promise.all([Iu(e.entry_path),Iu(e.manifest_path)]),s=t.reload_token??Ew();return r.searchParams.set("pm_ext_reload",s),r.searchParams.set("pm_ext_entry",o),r.searchParams.set("pm_ext_manifest",i),r.href}async function WD(e){let t=await Dw(e),n=[],r=[],o=[...t.warnings];if(t.disabled_by_flag)return{...t,warnings:o,loaded:n,failed:r};let i=typeof e.extensionFilter=="function"?t.effective.filter(e.extensionFilter):t.effective;for(let s of i)try{let a=await import(await jw(s,e));n.push({...s,module:a})}catch(a){o.push(`extension_load_failed:${s.layer}:${s.name}`),r.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:Eo(a)})}return{...t,warnings:o,loaded:n,failed:r}}var Tu=5e3,Lw=2147483647;function Fw(e){let t={activate:e.activate.bind(e)};if(typeof e.deactivate=="function"){let n=e.deactivate;t.deactivate=n.bind(e)}return t}function xu(e){let t=ll(e);return t?Fw(t):null}async function GD(e,t,n={}){let r=zw(n?.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=xu(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 Uw(u,r),{ok:!0}}catch(f){return{ok:!1,layer:l.layer,name:l.name,error:Eo(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 zw(e){return typeof e!="number"||e<0?Tu:e===0||e===1/0?0:Number.isFinite(e)?Math.min(Lw,Math.max(1,Math.floor(e))):Tu}async function Uw(e,t){if(t===0){await e();return}let n;try{let r=Promise.resolve().then(()=>e());r.catch(()=>{}),await Promise.race([r,new Promise((o,i)=>{n=setTimeout(()=>{i(new Error(`extension deactivate timed out after ${t}ms`))},t),n.unref?.()})])}finally{clearTimeout(n)}}function Hw(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let n of e.capabilities){let r=n.trim().toLowerCase();Be(r)&&t.add(r)}return t}function q(e,t,n){let r=Hw(e);if(r!==null&&!r.has(t))throw Le(`${n} requires capability '${t}' in extension manifest capabilities`,{method:n,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 ${n} registration call.`})}function qw(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>Pe.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function Vw(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 na=class{extension;hooks;#e;#n;#o;#r;#s;#a;#i;#c;#t;#d;#l;#u;constructor(t,n,r,o,i,s,a,c,d,l,u){this.#e=t,this.extension=qw(t),this.#n=Vw(t),this.#o=n,this.#r=r,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,n,r,o){let i=Yl(this.#u,this.#n,t,n,r,o);return i.warning&&this.#d.push(i.warning),i.allowed}registerCommandTrace(t,n,r,o,i){return{method:"registerCommand",registration_index:t==="override"?this.#r.overrides.length:this.#r.handlers.length,command:n,expected_schema:r,received:Yn(o),hint:i}}registerCommandOverride(t,n){let r=z(t);if(r.length===0)throw Le("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 n!="function"){let o=this.registerCommandTrace("override",r,'registerCommand("<command>", (context) => unknown)',n,"Provide a function as the second registerCommand argument.");throw Le(`registerCommand requires an override function when command name is provided (command="${r}", registration_index=${o.registration_index})`,o)}this.allowRegistration("commands.override","registerCommand","commands",{command:r})&&this.#r.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}resolveCommandDefinitionRunHandler(t,n){let r=typeof t.run=="function"?t.run:void 0,o=typeof t.handler=="function"?t.handler:void 0;return!r&&o&&this.#d.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${n}`),r??o}registerCommandDefinition(t){if(typeof t!="object"||t===null)throw Le("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 Le("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 n=z(t.name);if(n.length===0)throw Le("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 r=this.resolveCommandDefinitionRunHandler(t,n);if(typeof r!="function"){let o=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; }",r,"Define command definition.run as a function.");throw Le(`registerCommand requires a command definition run handler (command="${n}", registration_index=${o.registration_index})`,o)}try{Ml(t);let o=Qs(n,t.action),i=$l(t.read_output,n,o);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:n,action:o}))return;let s=t.description?.trim(),a=t.intent?.trim(),c=Wn("registerCommand definition.examples",t.examples),d=Wn("registerCommand definition.failure_hints",t.failure_hints),l=ea(t.arguments);t.flags!==void 0&&(q(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(vo(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:wo("registerCommand definition.flags",t.flags)})));let u={source_version:this.#e.version,read_output:i,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,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=Eo(o),s=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=Le(`registerCommand definition metadata invalid (command="${n}", registration_index=${s.registration_index}): ${i}`,s);this.#d.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${n}`),this.#l.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}registerCommand(t,n){if(q(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,n);return}this.registerCommandDefinition(t)}registerParser(t,n){if(q(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let r=z(oe("registerParser command",t));Qn("registerParser override",n),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerPreflight(t){if(q(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;let n=eu(t);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...n})}registerService(t,n,r={}){q(this.#e,"services","registerService");let o=String(t).trim().toLowerCase();if(!iu(o))throw new TypeError(`registerService service must be one of: ${Gt.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:o})&&(Qn("registerService override",n),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:o,run:n,...hu(r)?{passThrough:!0}:{}}))}registerRenderer(t,n,r={}){if(q(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof n!="function")throw new TypeError("registerRenderer requires a renderer function");let o=String(t).trim().toLowerCase();if(!ou(o))throw new Error(`registerRenderer format must be toon|json, received: ${String(t)}`);if(r.resultDiscriminator!==void 0&&typeof r.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");let i=[...new Set((r.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return z(s)}))];this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,format:o,run:n,commands:i,...r.resultDiscriminator?{resultDiscriminator:r.resultDiscriminator}:{}})}registerFlags(t,n){if(q(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let r=z(oe("registerFlags targetCommand",t));vo(n);let o=wo("registerFlags flags",n);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:r,flags:o})}registerItemFields(t){if(q(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;uu(t);let n=Zn("registerItemFields fields",t);if(n.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:n})}registerItemTypes(t){if(q(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;fu(t);let n=Zn("registerItemTypes types",t);if(n.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:n})}registerRelationshipKinds(t){if(q(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 n=Os();for(let o of this.#t.relationship_kinds)for(let i of o.definitions)n.register(i);let r=t.map(o=>(n.register(o),n.require(o.kind)));this.#t.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:r})}registerMigration(t){if(q(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;mu(t);let n=Jn("registerMigration definition",t);this.#t.migrations.push(er({layer:this.#e.layer,name:this.#e.name,definition:rn("registerMigration definition",t)},n))}registerProfile(t){if(q(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let n=Xn(t);_u(n),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:yu(n)})}registerImportExportCommandFlags(t,n,r){r.flags!==void 0&&(q(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(vo(r.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:wo(`${t} options.flags`,r.flags)})))}applyImportExportCommandMetadata(t,n,r){if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))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={...r,description:r?.description??o,arguments:r?.arguments??i},a=jl(t,s,r?.description!==void 0);B(`${t} options.action`,s.action),B(`${t} options.description`,s.description),B(`${t} options.intent`,s.intent);let c=Qs(n,s.action),d=Wn(`${t} options.examples`,s.examples),l=Wn(`${t} options.failure_hints`,s.failure_hints),u=ea(s.arguments);this.registerImportExportCommandFlags(t,n,s);let f={source_version:this.#e.version,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,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,n,r){if(q(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=Js(oe("registerImporter name",t));Qn("registerImporter importer",n);let i=Zs(o,"import");this.applyImportExportCommandMetadata("registerImporter",i,r),this.#t.importers.push({layer:this.#e.layer,name:this.#e.name,importer:o}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>n(Ws(s,o,"import"))})}registerExporter(t,n,r){if(q(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=Js(oe("registerExporter name",t));Qn("registerExporter exporter",n);let i=Zs(o,"export"),s=this.applyImportExportCommandMetadata("registerExporter",i,r);this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o,...s===void 0?{}:{output:s}}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async a=>{let c=await n(Ws(a,o,"export"));return s?.receipt==="suppress"&&!fo(c)?gl(c):c}})}registerSearchProvider(t){if(q(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let n=Jn("registerSearchProvider provider",t);this.#t.search_providers.push(er({layer:this.#e.layer,name:this.#e.name,definition:rn("registerSearchProvider provider",t)},n))}registerVectorStoreAdapter(t){if(q(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let n=Jn("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(er({layer:this.#e.layer,name:this.#e.name,definition:rn("registerVectorStoreAdapter adapter",t)},n))}registerAssuranceMeasurementProvider(t){if(q(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(du(t),t.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");let n=Jn("registerAssuranceMeasurementProvider provider",t);this.#t.assurance_providers.push(er({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:rn("registerAssuranceMeasurementProvider provider",t)},n))}registerBeforeCommand(t){q(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(wt("beforeCommand",t),this.#o.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerBeforeMutation(t){q(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(wt("beforeMutation",t),this.#o.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerAfterCommand(t){q(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(wt("afterCommand",t),this.#o.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnWrite(t){q(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(wt("onWrite",t),this.#o.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnRead(t){q(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(wt("onRead",t),this.#o.onRead.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnIndex(t){q(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(wt("onIndex",t),this.#o.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:t}))}};function Bw(e,t,n,r,o,i,s,a,c,d,l){return new na(e,t,n,r,o,i,s,a,c,d,l)}function Ww(e){let t=e.commands.length,n=e.flags.reduce((s,a)=>s+a.flags.length,0),r=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:n,item_fields:r,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 Gw(e){let t=[],n=(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}`)}};n(e.handlers,"extension_command_handler_collision"),n(e.overrides,"extension_command_override_collision");let r=new Set(e.handlers.map(i=>i.command)),o=[...new Set(e.overrides.map(i=>i.command))].filter(i=>r.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 Kw(e){let t=new Map;for(let r of e.overrides){let o=t.get(r.format)??[];o.push(r),t.set(r.format,o)}let n=[];for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r);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))||n.push(`extension_renderer_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return n}function Yw(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.command)??[];o.push(r),n.set(r.command,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);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:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}var Xw=new Set(["output_format"]);function Jw(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.service)??[];o.push(r),n.set(r.service,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1||Xw.has(r))continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_service_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}async function KD(e){let t=Bl(e.policy??vw),n=Vn(),r=Ts(),o=Cs(),i=Rs(),s=xs(),a=Ns(),c=Ds(),d=[],l=[];for(let m of e.loaded){let _=xu(m.module);if(!_)continue;let y=d.length,w=Dl({hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await _.activate(Bw(m,n,r,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 T=au(v);d.push({layer:m.layer,name:m.name,entry_path:m.entry_path,error:Eo(v),trace:T})}}let u=[...Gw(r),...Yw(o),...tu(i),...Jw(s),...Kw(a)],f=[...new Set([...l,...u])];return{hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:d,warnings:f,hook_counts:{before_command:n.beforeCommand.length,before_mutation:n.beforeMutation.length,after_command:n.afterCommand.length,on_write:n.onWrite.length,on_read:n.onRead.length,on_index:n.onIndex.length},command_override_count:r.overrides.length,command_handler_count:r.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:Ww(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 ZD(e){return{...e,hooks:Vn(),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 eP(){let e=Promise.resolve(),t=new Set;return{async read(n){let r=e,o,i=new Promise(s=>{o=s});t.add(i),await r;try{return await n()}finally{t.delete(i),o()}},write(n){let r=Promise.all([e,...t]).then(()=>n());return e=r.then(()=>{},()=>{}),r}}}function Zw(){let e=Promise.resolve(),t=0,n=[],r=()=>{if(t!==0)return;let o=n.splice(0);for(let i of o)i()};return{enqueue(o){t++;let i=e.then(()=>o());return e=i.then(()=>{},()=>{}).finally(()=>{t--,r()}),i},idle(){return t===0?Promise.resolve():new Promise(o=>n.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 Qw={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"]},Nu=":";function Du(e,t){return`${e}${Nu}${ra(t)}`}function ev(e){return e.slice(e.indexOf(Nu)+1)}function ra(e){return e.trim().toLowerCase()}function tv(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=bl(n);r!==null&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function Pu(e){let t=new Map,n=(l,u)=>{for(let f of l){let m=Du(f.layer,f.name),_=t.get(m);_===void 0&&(_=new Set,t.set(m,_)),_.add(u)}},{registrations:r,commands:o,parsers:i,preflight:s,services:a,renderers:c,hooks:d}=e;return n(r.commands,"commands"),n(o.overrides,"commands"),n(o.handlers,"commands"),n(r.flags,"schema"),n(r.item_fields,"schema"),n(r.item_types,"schema"),n(r.relationship_kinds??[],"schema"),n(r.migrations,"schema"),n(r.profiles,"schema"),n(r.importers,"importers"),n(r.exporters,"importers"),n(r.search_providers,"search"),n(r.vector_store_adapters,"search"),n(i.overrides,"parser"),n(s.overrides,"preflight"),n(a.overrides,"services"),n(r.assurance_providers??[],"services"),n(c.overrides,"renderers"),n(d.beforeCommand,"hooks"),n(d.beforeMutation,"hooks"),n(d.afterCommand,"hooks"),n(d.onWrite,"hooks"),n(d.onRead,"hooks"),n(d.onIndex,"hooks"),t}function nv(e,t={}){let n=Pu(e),r=new Set;t.extensionName!==void 0&&r.add(ra(t.extensionName));for(let i of t.extensionNames??[])r.add(ra(i));let o=new Set;for(let[i,s]of n)if(!(r.size>0&&!r.has(ev(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function rv(e,t){let n=Pu(t),r=[];for(let o of e){let i=tv(o.capabilities);if(i.length===0)continue;let s=n.get(Du(o.layer,o.name))??new Set,a=[...s].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>!s.has(d));r.push({layer:o.layer,name:o.name,declared:i,used:a,unused:c})}return r}import{existsSync as ov}from"node:fs";import{AsyncLocalStorage as iv}from"node:async_hooks";import Fe 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 ze=null,on=null,nr=null,rr=null,sn=null,or=null,ir=null,Ke=null,So,ko=[],$u=new iv;function M(){return $u.getStore()}function cP(e){return $u.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var sv=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function Mu(e){let t=Fe.resolve(e);for(;;){if(ov(Fe.join(t,".git")))return t;let n=Fe.dirname(t);if(n===t)return;t=n}}function Oo(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),n=Mu(t)??Fe.resolve(t),r=Mu(n);if(!e)return{source_workspace_root:n,...r?{repo_root:r}:{}};let o=Fe.relative(n,Fe.resolve(e)),i=o.length>0&&!o.startsWith(`..${Fe.sep}`)&&o!==".."&&!Fe.isAbsolute(o);return{source_workspace_root:n,...r?{repo_root:r}:{},...i?{pm_root_rel:o.split(Fe.sep).join("/")}:{}}}function dP(e){let t=M();if(t){t.hooks=e;return}ze=e}function lP(e){let t=M();if(t){t.commands=e;return}on=e}function uP(e){let t=M();if(t){t.parsers=e;return}nr=e}function fP(e){let t=M();if(t){t.preflight=e;return}rr=e}function mP(e){let t=M();if(t){t.services=e;return}sn=e}function pP(e){let t=M();if(t){t.renderers=e;return}or=e}function _P(e){let t=M();if(t){t.registrations=e;return}ir=e}function ju(){let e=M();return e?e.registrations:ir}function yP(){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}ze=null,on=null,nr=null,rr=null,sn=null,or=null,ir=null,Ke=null,So=null}function hP(e){let t=e?{...e,...Oo(e.pm_root)}:null,n=M();if(n){n.commandContext=t;return}Ke=t}function Lu(){let e=M(),t=e?e.commandContext:Ke;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function gP(e){let t=M()??{commandContext:Ke,hooks:ze,commands:on,parsers:nr,preflight:rr,services:sn,renderers:or,registrations:ir};return t.commandContext?.command!==e||[t.hooks,t.preflight,t.services,t.renderers].some(n=>Object.values(n??{}).some(r=>r.length>0))||[t.commands,t.parsers].some(n=>Object.values(n??{}).some(r=>r.some(o=>o.command===e)))?!1:!Object.entries(t.registrations??{}).some(([n,r])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(n)&&r.length>0)}function Ao(e){let t=M();if(t){t.commandResult=e;return}So=e}function bP(){let e=M();return e?e.commandResult:So}function wP(e){if(!e)return;let t=M();t?t.affectedItems.push(e):ko.push(e)}function vP(e,t){if(!e||!e.id)return{};let n={id:e.id,type:e.type,status:e.status};if(!Array.isArray(t))return n;let r=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"||sv.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}function EP(){let e=M(),t=e?.affectedItems??ko;if(t.length===0)return;let n=t;return e?e.affectedItems=[]:ko=[],n}function kP(){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}ze=null,on=null,nr=null,rr=null,sn=null,or=null,ir=null,Ke=null,So=void 0,ko=[]}async function Io(e){let t=M(),n=t?t.hooks:ze;return n?Ms(n,e):[]}async function SP(e){let t=M(),n=t?t.hooks:ze;n&&await Ps(n,e)}async function an(e){let t=M(),n=t?t.hooks:ze;return n?$s(n,e):[]}function OP(){let e=M();return((e?e.hooks:ze)?.onRead?.length??0)>0}async function AP(e){let t=M(),n=t?t.hooks:ze;return n?js(n,e):[]}function Fu(e){let t=M(),n=t?t.commands:on,r=t?t.commandContext:Ke;return!n||!r?{overridden:!1,result:e,warnings:[]}:qs(n,{command:r.command,args:[...r.args],options:r.options?{...r.options}:{},global:r.global?{...r.global}:void 0,pm_root:r.pm_root,source_workspace_root:r.source_workspace_root,repo_root:r.repo_root,pm_root_rel:r.pm_root_rel,result:e})}async function IP(e){let t=M(),n=t?t.commands:on;return n?Ls(n,{...e,...Oo(e.pm_root)}):{handled:!1,result:null,warnings:[]}}async function TP(e){let t=M(),n=t?t.parsers:nr;return n?Fs(n,{...e,...Oo(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 CP(e){let t=M(),n=t?t.preflight:rr;return n?zs(n,{...e,...Oo(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 zu(e,t){let n=M(),r=n?n.renderers:or,o=n?n.commandContext:Ke;return r?Vs(r,{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 Uu(e,t){let n=M(),r=n?n.commandContext:Ke;return{service:e,command:r?.command,args:r?[...r.args]:[],options:r?.options?{...r.options}:{},global:r?.global?{...r.global}:void 0,pm_root:r?.pm_root,source_workspace_root:r?.source_workspace_root,repo_root:r?.repo_root,pm_root_rel:r?.pm_root_rel,payload:t}}async function cn(e,t){let n=M(),r=n?n.services:sn;return r?Hs(r,Uu(e,t)):{handled:!1,result:t,warnings:[]}}function oa(e,t){let n=M(),r=n?n.services:sn;return r?Us(r,Uu(e,t)):{handled:!1,result:t,warnings:[]}}import{createHash as av}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 $P=["sha256","sha512"],cv="sha256",Hu="sha256";function kt(e){if(e===void 0)return cv;if(e==="sha256"||e==="sha512")return e;throw new TypeError(`unsupported_history_hash_algorithm:${String(e)}`)}function Ye(e,t){return av(kt(t)).update(e,"utf8").digest("hex")}(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 qu(e){let t=[],n=e[0]?.op==="history_compact_baseline",r=n?1:void 0,o=!1;for(let[i,s]of e.entries())s.op==="delete"&&(o=!0),s.op==="create"&&(r!==void 0&&t.push({prior_genesis_index:r,repeated_create_index:i+1,sequence:o?"delete_then_create":n?"checkpoint_then_create":"multiple_creates"}),r??=i+1,o=!1);return t}import Bu from"node:path";import{link as dv,mkdir as lv,mkdtemp as uv,rm as fv,writeFile as mv}from"node:fs/promises";import ia 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 Vu(e,t){let n=ia.dirname(e);await lv(n,{recursive:!0});let r=await uv(ia.join(n,".pm-seed-")),o=ia.join(r,"value");try{await mv(o,t,"utf8");try{return await dv(o,e),!0}catch(i){if(i.code==="EEXIST")return!1;throw i}}finally{await fv(r,{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 pv=2e3,To=new Map;function Xe(e){if(typeof e!="string")return"";let t=To.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return To.size>=pv&&oo(To),To.set(e,n),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]="6e07b1b6-1757-54dd-8833-9d3f984ccf79")}catch{}})();var ie=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),Ku=Ad,aa=Od,_v=["create","update"],yv=new Set(Kr),hv=new Set(Xt),gv=new Set(Yr),bv=new Set(Xr),wv=new Set(["string","number","boolean","array","object"]),vv=16;function Yu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ev=[e=>e.type===void 0||typeof e.type=="string"&&wv.has(e.type),e=>!Object.hasOwn(e,"const")||Ro(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Ro(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||Yu(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Ro(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 n=Array.isArray(e)?e.every(r=>Ro(r,t)):Object.values(e).every(r=>Ro(r,t));return t.delete(e),n}function Co(e,t=0,n=new Set){if(!Yu(e)||t>vv||n.has(e))return;n.add(e);let r=e,o=r.type,i=r.enum,s=r.one_of,a=r.properties,c=r.items,d=r.required,l=r.min_length,u=r.min_items,f=r.format,m=r.additional_properties;if(!Ev.every(v=>v(r))){n.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([v,T])=>[v,Co(T,t+1,n)])),y=c===void 0?void 0:Co(c,t+1,n),w=s===void 0?void 0:s.map(v=>Co(v,t+1,n));if([...Object.values(_??{}),...c===void 0?[]:[y],...w??[]].some(v=>v===void 0)){n.delete(e);return}return n.delete(e),Object.fromEntries(Object.entries({type:o,const:Object.hasOwn(r,"const")?r.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 ar(e){let t=Array.isArray(e)?e:[];return[...new Set(t.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r))}function ye(e){if(typeof e!="string"||e.length===0)return;let t=Xe(e);return t.length>0?t:void 0}function kv(e){return e.startsWith("--")?e.slice(2):e}function Wu(e){return typeof e=="string"?kv(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function Xu(e){return e.replaceAll("_","-")}function Sv(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[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function sa(e,t){let n=ye(e.id);if(!n)return null;let r=[...new Set(ar(e.aliases).map(Xe).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=ar(e.roles).filter(a=>yv.has(a)),i=e.description?.trim(),s=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:n,aliases:r,roles:o,description:i&&i.length>0?i:void 0,order:s}}function Ov(e){return{draft_status:ye(e?.draft_status),open_status:ye(e?.open_status),in_progress_status:ye(e?.in_progress_status),blocked_status:ye(e?.blocked_status),close_status:ye(e?.close_status),canceled_status:ye(e?.canceled_status)}}function Ju(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=Xe(t[0]),r=Xe(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function Av(e){let t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;let n={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(let r of e.allowed_transitions)Ju(n,r);return{typeKey:t.toLowerCase(),record:n}}function Iv(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=Av(r);if(o===null)continue;let i=t.get(o.typeKey)??o.record;i.denyAll||=o.record.denyAll;for(let s of o.record.pairs)Ju(i,s);t.set(o.typeKey,i)}let n=[];for(let r of t.values())(r.pairs.length>0||r.denyAll)&&n.push({type:r.type,allowed_transitions:r.pairs});return n.sort((r,o)=>r.type.localeCompare(o.type)),n.length>0?n:void 0}function Zu(e){let t=Xe(e.key??"");if(!t)return null;let n=Xe(e.metadata_key??e.front_matter_key??t),r=Wu(e.cli_flag??Xu(t));if(!r)return null;let o=ar(e.cli_aliases).map(u=>Wu(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=hv.has(i)?i:"string",a=(()=>{let u=ar(e.commands).filter(f=>gv.has(f));return u.length>0?u:[..._v]})(),c=e.description?.trim(),d=ar(e.required_types),l=e.value_schema===void 0?void 0:Co(e.value_schema);return e.value_schema!==void 0&&l===void 0?null:{key:t,metadata_key:n,cli_flag:r,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 Tv(e){let t=new Map;for(let[r,o]of e.entries()){let i=sa(o,r);i&&t.set(i.id,i)}let n=Gu([...t.values()]);return n.length>0?n:Gu(aa.map((r,o)=>sa(r,o)).filter(r=>r!==null))}function Gu(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function Cv(e){let t=new Map;for(let n of e??[]){let r=Zu(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function Rv(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 xv(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==Xu(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 Nv(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return bv.has(t)?t:"allow"}function Ce(e){let t={...ie,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:aa,r=Tv(n),o=Cv(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(Rv),fields:o.map(xv),workflow:{...Ku,...Ov(e?.workflow)},type_workflows:Iv(e?.type_workflows),unknown_field_policy:Nv(e?.unknown_field_policy)}}function Dv(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function Pv(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 n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function Mv(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 $v(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 jv(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 Lv(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 ue(e,t,n){let r=t?.trim()||n;return Bu.isAbsolute(r)?r:Bu.join(e,r)}function XP(e,t){return ue(e,t.files.types,ie.types)}async function JP(e,t){let n=Ce(t),r=[{path:ue(e,n.files.types,ie.types),seed:{definitions:[]}},{path:ue(e,n.files.statuses,ie.statuses),seed:{statuses:aa}},{path:ue(e,n.files.fields,ie.fields),seed:{fields:[]}},{path:ue(e,n.files.workflows,ie.workflows),seed:{workflow:Ku}}],o=[];for(let i of r)await mt(i.path)||await Vu(i.path,`${JSON.stringify(i.seed,null,2)}
3
+ `)&&o.push(i.path);return{created_paths:o}}async function Qu(e,t){let n=Ce(t),r=[],o=ue(e,n.files.types,ie.types),i=ue(e,n.files.statuses,ie.statuses),s=ue(e,n.files.fields,ie.fields),a=ue(e,n.files.workflows,ie.workflows),c,d,l,u,f,m=async(T,H)=>{let X=await Ae(T);if(X!==null)return Dv(X,H,r)},_=await m(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=Pv(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let y=await m(i,"runtime_schema_statuses_invalid_json");y!==void 0&&(d=Mv(y),d===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let w=await m(s,"runtime_schema_fields_invalid_json");w!==void 0&&(l=$v(w),l===void 0&&r.push("runtime_schema_fields_invalid_shape"));let v=await m(a,"runtime_schema_workflows_invalid_json");return v!==void 0&&(u=jv(v),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=Lv(v)),{schema:Ce({...n,statuses:[...n.statuses,...d??[]],fields:[...n.fields,...l??[]],workflow:{...n.workflow,...u},type_workflows:[...n.type_workflows??[],...f??[]]}),type_definitions_from_file:c,warnings:r,created_paths:[]}}function sr(e,t,n,r=!1){let o=n.map(s=>ye(s)).filter(s=>typeof s=="string").find(s=>e.some(a=>a.id===s));if(r&&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 Fv(e){let t=new Map,n=new Map;for(let r of e){n.set(r.id,r),t.set(r.id,r.id),t.set(r.id.replaceAll("_","-"),r.id),t.set(r.id.replaceAll("_"," "),r.id);for(let o of r.aliases)t.set(o,r.id),t.set(o.replaceAll("_","-"),r.id),t.set(o.replaceAll("_"," "),r.id)}return{aliasToId:t,byId:n}}function zv(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let n of e){let r=new Set(n.roles);(r.has("terminal")||r.has("terminal_done")||r.has("terminal_canceled"))&&t.terminalStatuses.add(n.id),r.has("terminal_done")&&t.terminalDoneStatuses.add(n.id),r.has("terminal_canceled")&&t.terminalCanceledStatuses.add(n.id),r.has("active")&&t.activeStatuses.add(n.id),r.has("blocked")&&t.blockedStatuses.add(n.id),r.has("draft")&&t.draftStatuses.add(n.id)}return t}function ef(e){let t=Ce(e),n=t.statuses.map((v,T)=>sa(v,T)).filter(v=>v!==null),{aliasToId:r,byId:o}=Fv(n),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:d,terminalStatuses:l}=zv(n),u=t.workflow,f=ye(u.open_status)??sr(n,"default_open",["open","in_progress",Yt[0]]),m=ye(u.in_progress_status)??sr(n,"active",["in_progress","in-progress",f],!0),_=ye(u.blocked_status)??sr(n,"blocked",["blocked"]),y=ye(u.close_status)??sr(n,"default_close",["closed","done","complete"]),w=ye(u.canceled_status)??sr(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,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 ca(e,t){let n=Xe(e);if(n)return t.alias_to_id.get(n)}function tf(e){let t=Ce(e),n=new Map,r=t.fields.map(c=>Zu(c)).filter(c=>c!==null);for(let c of r)n.set(c.key,c);let o=[...n.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 nf(e){return Sv(e.key)}function ZP(e,t){let n=ca(e,t);return n?t.terminal_statuses.has(n):!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]="6635e694-c788-5805-adb8-ed93cc931946")}catch{}})();var Uv=16;function xo(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[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function i1(e,t,n=new Set,r){if(af(e,t,r))return;let o=cf(e,t,n,r),i=No(e);return[xo(e.cli_flag),...i].find(s=>!o.has(s)&&sf(s,i,o))}function sf(e,t,n){for(let r of t){if(r===e)break;if(n.has(r))return!1}return!0}function af(e,t,n){return t.definitions.some(r=>r!==e&&r.metadata_key===e.metadata_key&&(n===void 0||r.commands.includes(n)))}function cf(e,t,n,r){return new Set([...n,...t.definitions.filter(o=>o!==e&&(r===void 0||o.commands.includes(r))).flatMap(o=>No(o))])}function df(e){return e.replace(/^-+/u,"").startsWith("no-")}function Hv(e){return e.startsWith("-")?e:`--${e}`}function s1(e,t,n,r){if(af(e,t,r))return;let o=cf(e,t,n.options,r),i=No(e);return[e.cli_flag,...e.cli_aliases].find(s=>{let a=lf(s);return df(s)||n.flags.has(Hv(s))||o.has(a)?!1:sf(a,i,o)})}function lf(e){return e.replace(/^-+/u,"").replace(/^no-/u,"").split("-").reduce((t,n)=>`${t}${n.charAt(0).toUpperCase()}${n.slice(1)}`)}function No(e){return[...new Set([nf(e),xo(e.key),xo(e.cli_flag),...e.cli_aliases.map(t=>xo(t)),...[e.cli_flag,...e.cli_aliases].filter(t=>!df(t)).map(t=>lf(t))])]}function uf(e,t){for(let n of No(t)){if(!Object.hasOwn(e,n))continue;let r=e[n];if(r!==void 0)return r}}function ff(e){return Array.isArray(e)?e.flatMap(t=>ff(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 rf(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 n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1}throw new g(`${t} must be one of true|false|1|0|yes|no`,h.USAGE)}function of(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;let n=typeof e=="string"?e.trim():String(e),r=Number(n);if(!Number.isFinite(r))throw new g(`${t} must be a number`,h.USAGE);return r}function qv(e,t,n){let r=typeof e=="string"?(()=>{try{return JSON.parse(e)}catch{return}})():e;if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r;throw new g(`${t} must be valid JSON ${n}`,h.USAGE)}function Vv(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 Bv(e,t,n){if(t.const!==void 0&&R(e)!==R(t.const))return`${n} must equal ${R(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>R(r)===R(e)))return`${n} must be one of ${t.enum.map(r=>R(r)).join("|")}`;if(!Vv(e,t.type))return`${n} must match configured type ${String(t.type)}`;if(typeof e=="string"){if(t.min_length!==void 0&&e.length<t.min_length)return`${n} must contain at least ${t.min_length} characters`;if(t.format==="date-time"&&!Un(e))return`${n} must be an RFC 3339 date-time`}}function Wv(e,t,n,r){if(Array.isArray(e)){if(t.min_items!==void 0&&e.length<t.min_items)return`${n} must contain at least ${t.min_items} items`;if(t.items)for(let[o,i]of e.entries()){let s=Do(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function Gv(e,t,n,r){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`${n}.${i} is required`;for(let[i,s]of Object.entries(o)){let a=t.properties?.[i];if(!a){if(t.additional_properties===!1)return`${n}.${i} is not allowed`;continue}let c=Do(s,a,`${n}.${i}`,r+1);if(c)return c}}function Do(e,t,n,r=0){if(r>Uv)return`${n} value schema exceeds maximum depth`;let o=Bv(e,t,n);if(o)return o;let i=Wv(e,t,n,r);if(i)return i;let s=Gv(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(Do(e,c,n,r+1)===void 0&&(a+=1,a>1))break;return a===1?void 0:`${n} must match exactly one configured schema variant`}function St(e,t,n){if(!e.value_schema||t===void 0)return t;let r=Do(t,e.value_schema,n);if(r)throw new g(r,h.USAGE);return t}function Kv(e,t,n,r){let o=r==="option"&&Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return St(e,qv(o,n,e.type),n)}function cr(e,t,n,r="option"){let o=n??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object")return Kv(e,t,o,r);if(e.repeatable||e.type==="string_array"){let s=ff(t);return e.type==="number"?St(e,s.map(a=>of(a,o)),o):e.type==="boolean"?St(e,s.map(a=>rf(a,o)),o):St(e,s,o)}let i=Array.isArray(t)?t[t.length-1]:t;if(i!==void 0)return e.type==="number"?St(e,of(i,o),o):e.type==="boolean"?St(e,rf(i,o),o):St(e,typeof i=="string"?i:String(i),o)}function Yv(e,t){return!e.required&&!e.required_on_create?!1:e.required_types.length===0?!0:t?e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function a1(e,t,n){let r={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=uf(e,i);if(s===void 0){Yv(i,n)&&o.push(`--${i.cli_flag}`);continue}r[i.metadata_key]=cr(i,s)}return{values:r,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function c1(e,t,n=["update"]){let r={},o=(n??["update"]).flatMap(s=>t.command_to_fields.get(s)??[]),i=new Set;for(let s of o){let a=uf(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),r[s.metadata_key]=cr(s,a)))}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]="c35d4830-d7d1-5ee4-99bc-ab52cc3e4e09")}catch{}})();var da=1,la=2;function l1(e){return Math.max(ua(e),e.tests?.some(t=>t.updated_by!==void 0||t.updated_at!==void 0)?2:1)}function ua(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:1}function mf(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=1))return e}function Xv(e,t=2,n=t){return e<n?"outdated":e>t?"ahead":"current"}function u1(e,t=2,n=t){let r=[],o=[];for(let i of e){let s=Xv(i.version,t,n);s==="outdated"?r.push(i.ref):s==="ahead"&&o.push(i.ref)}return{outdated:r.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 Jv={"in-progress":"in_progress",cancelled:"canceled"};function Po(e,t){if(t){let o=ca(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=Jv[n]??n;if(Yt.includes(r))return r}function Zv(e,t){return Po(e,t)??e}function _1(e,t){return t.terminal_statuses.has(Zv(e,t))}import{encode as nE}from"@toon-format/toon";import{isDeepStrictEqual as pf}from"node:util";import{decode as Qv}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 fa(e){return{value:Qv(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 eE=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function tE(e){if(e.length===0)return[];let t=e.split(/\r?\n/),n=[];for(let r=0;r<t.length;r+=1){let o=t[r]??"",i=o.match(eE);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Mo(e){return tE(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 ya=new Set(["schema","tracker","auto","none"]),bf=new Set(["source","isolated","snapshot"]),rE=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),oE=new Set(["passed","failed","stopped","canceled"]),iE=new Set(Fd);function un(e){return e.replaceAll("\\","/")}function wf(e){for(let t of e)if(t!==0)return t;return 0}function jo(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var vf=["id","title","description","created_at","updated_at"],sE=new Set(ve);function Ef(e){if(e?.schema)return{statusRegistry:ef(e.schema),fieldRegistry:tf(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function aE(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function Je(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 ur(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 kf(e,t){if(!t||typeof e!="object"||e===null)return;let n=ua(e);if(!(n<=la))throw new g(`Stored item uses format version ${n}; this runtime supports up to ${la}. Upgrade pm before reading or changing this item.`,h.CONFLICT,{code:"item_format_version_unsupported",format_version:n,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 Sf(e){let t=new Set(sE);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function O(e,t){e||Je(t)}function fr(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&Je(t),e}function ma(e,t){let n=e[t];O(typeof n=="string",`${t} must be a string`),O($e(n),`${t} must be a valid ISO timestamp`)}function _f(e,t,n){let r=e[t];r!==void 0&&O(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function ha(e,t,n){let r=e[t];r!==void 0&&(O(typeof r=="string",`${n} must be a string`),O($e(r),`${n} must be a valid ISO timestamp`))}function cE(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 n=t.trim().toLowerCase();O(jn.includes(n),`event.recurrence.by_weekday entries must be one of: ${jn.join(", ")}`)}}}function dE(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 lE(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($e(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function uE(e){let t=fr(e,"event.recurrence must be an object");O(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();O(Qr.includes(n),`event.recurrence.freq must be one of: ${Qr.join(", ")}`),_f(t,"interval","event.recurrence.interval"),_f(t,"count","event.recurrence.count"),ha(t,"until","event.recurrence.until"),cE(t.by_weekday),dE(t.by_month_day),lE(t.exdates)}function fE(e){for(let r of vf)O(typeof e[r]=="string",`${r} 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 n=e.pm_format_version;return n!==void 0&&O(typeof n=="number"&&Number.isInteger(n)&&n>=da,`pm_format_version must be an integer >= ${da}`),t}function mE(e,t){let n=e.status;O(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=Po(n,r),i=r?r.definitions.map(s=>s.id):[...Yt];O(o!==void 0,`status must be one of: ${i.join(", ")}`)}function pE(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 n=e.tags;O(Array.isArray(n),"tags must be an array");for(let r of n)O(typeof r=="string","tags entries must be strings")}function _E(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 n=t.trim().toLowerCase(),r=n==="med"||Zr.includes(n);O(r,`confidence string value must be one of: ${[...Zr,"med"].join(", ")}`);return}O(!1,"confidence must be a number or string")}}function yE(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&Je("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||Jr.includes(n);O(r,`severity value must be one of: ${[...Jr,"med"].join(", ")}`)}function hE(e){e.regression!==void 0&&typeof e.regression!="boolean"&&Je("regression must be a boolean")}function gE(e){let t=e.reminders;if(t!==void 0){O(Array.isArray(t),"reminders must be an array");for(let n of t){let r=fr(n,"reminders entries must be objects");O(typeof r.at=="string","reminder.at must be a string"),O($e(r.at),"reminder.at must be a valid ISO timestamp"),O(typeof r.text=="string","reminder.text must be a string"),O(r.text.trim().length>0,"reminder.text must not be empty")}}}function bE(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 wE(e){e.recurrence!==void 0&&(uE(e.recurrence),e.recurrence.until!==void 0&&O(re(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function vE(e){let t=fr(e,"events entries must be objects");O(typeof t.start_at=="string","event.start_at must be a string"),O($e(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($e(t.end_at),"event.end_at must be a valid ISO timestamp"),O(re(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),bE(t),t.all_day!==void 0&&O(typeof t.all_day=="boolean","event.all_day must be a boolean"),wE(t)}function EE(e){let t=e.events;if(t!==void 0){O(Array.isArray(t),"events must be an array");for(let n of t)vE(n)}}function kE(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&O(typeof n=="string",`${t} must be a string`)}}function SE(e){let t=e.type_options;if(t===void 0)return;let n=fr(t,"type_options must be an object");for(let[r,o]of Object.entries(n))O(r.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 OE(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){aE(r,t)&&Je(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=cr(r,o,`metadata field "${r.metadata_key}"`,"metadata")}catch(i){Je(String(i?.message).replace(/^Invalid\s+/u,""))}}}function AE(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Sf(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?Je(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function ga(e,t){let n=fr(e,"item metadata must be an object"),r=fE(n);mE(n,t),pE(n),_E(n),yE(n),hE(n),ma(n,"created_at"),ma(n,"updated_at"),n.deadline!==void 0&&ma(n,"deadline"),gE(n),EE(n),ha(n,"closed_at","closed_at"),ha(n,"completed_at","completed_at"),kE(n),SE(n),OE(n,r,t),AE(n,t)}function IE(e){if(!(!e||e.length===0))return[...e].map((t,n)=>(O(t.created_at===void 0||typeof t.created_at=="string"&&Un(t.created_at),`dependencies.${n}.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,n)=>{let r=re(t.created_at??"",n.created_at??"");if(r!==0)return r;let o=t.id.localeCompare(n.id);if(o!==0)return o;let i=t.kind.localeCompare(n.kind);return i!==0?i:(t.source_kind??"").localeCompare(n.source_kind??"")})}function pa(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=re(t.created_at,n.created_at);if(r!==0)return r;let o=t.text.localeCompare(n.text);return o!==0?o:t.author.localeCompare(n.author)})}function TE(e){if(!e||e.length===0)return;let t=[...e].map(n=>({at:n.at,text:n.text.trim()})).filter(n=>n.text.length>0).sort((n,r)=>{let o=re(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function CE(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!Qr.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>jn.includes(s)))).sort((s,a)=>ss(s)-ss(a)),r=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=>$e(s)))).sort((s,a)=>re(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:n.length>0?n:void 0,by_month_day:r.length>0?r: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 RE(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(xE).sort(NE)}function xE(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:CE(e.recurrence)};return jo(t),t}function NE(e,t){return wf([re(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 DE(e){if(!(!e||e.length===0))return e.map(t=>({path:un(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function PE(e){if(!e||e.length===0)return;let t=e.map(LE).filter(n=>n.run_id.length>0&&n.started_at.length>0&&n.finished_at.length>0&&n.recorded_at.length>0).sort((n,r)=>wf([re(n.recorded_at,r.recorded_at),n.run_id.localeCompare(r.run_id),n.kind.localeCompare(r.kind)]));return t.length>0?t:void 0}function dn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function ME(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function _a(e){return typeof e=="string"?e:""}function $E(e){if(!Array.isArray(e))return;let t=e.filter(r=>r!==null&&typeof r=="object"&&typeof r.name=="string"&&r.name.trim().length>0&&typeof r.value=="number"&&Number.isFinite(r.value)&&typeof r.recorded_at=="string"&&r.recorded_at.trim().length>0).map(r=>({name:r.name.trim(),value:r.value,unit:typeof r.unit=="string"&&r.unit.trim()||void 0,threshold:typeof r.threshold=="number"&&Number.isFinite(r.threshold)?r.threshold:void 0,recorded_at:r.recorded_at.trim()})),n=[...new Map(t.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,32);return n.length>0?n:void 0}function $o(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function jE(e){if(!Array.isArray(e))return;let t=e.filter(n=>n&&typeof n.command=="string"&&n.command.trim().length>0).slice(0,32).map(n=>({command:n.command.trim(),requested_pm_context_mode:$o(n.requested_pm_context_mode,ya),pm_context_mode:$o(n.pm_context_mode,ya),workspace_context_mode:$o(n.workspace_context_mode,bf),trust_reason:$o(n.trust_reason,rE)}));return t.length>0?t:void 0}function LE(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=oE.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:_a(e.started_at),finished_at:_a(e.finished_at),recorded_at:_a(e.recorded_at),attempt:ME(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:dn(e.passed)??0,failed:dn(e.failed)??0,skipped:dn(e.skipped)??0,items:dn(e.items),linked_tests:dn(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:$E(e.measurements),executions:jE(e.executions)};return jo(o),o}function FE(e){if(!(!Array.isArray(e)||e.length===0))return e.map(VE)}function dr(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}function Ea(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ka(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function yf(e){if(!Ea(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!ka(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function zE(e){if(!Ea(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!ka(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function UE(e){let t=e?.trim().toLowerCase();if(!(!t||!ya.has(t)))return t}function HE(e){let t=e?.trim().toLowerCase();if(!(!t||!bf.has(t)))return t}function qE(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Ea(e))return{provenance_invalid:!0};let n=E(e.author),r=E(e.created_at),o=e.source_kind;return!n||!r||!$e(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:E(e.source_ref)}}}function VE(e){let t={command:e.command?.trim()||void 0,path:e.path?un(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:UE(e.pm_context_mode),workspace_context_mode:HE(e.workspace_context_mode),...qE(e.provenance,e.provenance_invalid),updated_by:E(e.updated_by),updated_at:E(e.updated_at),env_set:yf(e.env_set),env_clear:dr(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:dr(e.assert_stdout_contains),assert_stdout_regex:dr(e.assert_stdout_regex),assert_stderr_contains:dr(e.assert_stderr_contains),assert_stderr_regex:dr(e.assert_stderr_regex),assert_stdout_min_lines:dn(e.assert_stdout_min_lines),assert_json_field_equals:yf(e.assert_json_field_equals),assert_json_field_gte:zE(e.assert_json_field_gte),note:e.note?.trim()||void 0};return jo(t),t}function BE(e){if(!(!e||e.length===0))return[...e].map(t=>({path:un(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.path.localeCompare(n.path);return o!==0?o:(t.note??"").localeCompare(n.note??"")})}function E(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function WE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.id),i=E(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=E(r.note);a&&(s.note=a),r.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function GE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.path);if(!o)continue;let i={path:un(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=E(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function KE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.command),i=E(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=un(i));let a=E(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function YE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.path);if(!o)continue;let i={path:un(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=E(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function XE(e){if(e===null||typeof e!="object")return;let t=e,n=E(t.id),r=E(t.title),o=E(t.status),i=o&&iE.has(o)?o:void 0,s=ro(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",c=typeof t.updated_at=="string"?t.updated_at:"";if(!n||!r||!i||!Number.isFinite(s)||!a||!c)return;let d={id:n,order:s,title:r,status:i,created_at:a,updated_at:c};return JE(d,t),d}function JE(e,t){let n=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(let[i,s]of n){let a=E(t[s]);a&&(e[i]=a)}let r=typeof t.completed_at=="string"?t.completed_at:void 0;r&&r.length>0&&(e.completed_at=r);let o=[["linked_items","linked_items",WE],["files","files",GE],["tests","tests",KE],["docs","docs",YE]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function ZE(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=XE(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function QE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=E(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=E(r.rationale);c&&(a.rationale=c);let d=E(r.evidence);d&&(a.evidence=d);let l=E(r.step_id);l&&(a.step_id=l),t.push(a)}return t.length>0?t:void 0}function e0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=E(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=E(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function t0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.text);if(!o)continue;let i={text:o},s=E(r.command);s&&(i.command=s);let a=E(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function n0(e){if(!e)return;let t=Object.entries(e).map(([n,r])=>[n.trim(),r.trim()]).filter(([n,r])=>n.length>0&&r.length>0).sort((n,r)=>n[0].localeCompare(r[0]));if(t.length!==0)return Object.fromEntries(t)}function ln(e){let t=0;for(;t<e.length&&e[t]===`
4
+ `;)t+=1;return e.slice(t).trimEnd()}function r0(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Zr.includes(t))return t}function o0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Jr.includes(t))return t}function lr(e){return e||void 0}function i0(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))ka(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function s0(e,t){if(!t?.fieldRegistry)return;let n=e;for(let r of t.fieldRegistry.definitions){let o=n[r.metadata_key];o!==void 0&&(n[r.metadata_key]=cr(r,o,`metadata field "${r.metadata_key}"`,"metadata"))}}function a0(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Sf(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length>0&&t.unknownFieldPolicy==="reject"&&Je(`unknown schema fields are not allowed: ${r.join(", ")}`),r.length>0&&t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`)}function Lo(e,t={}){let n=Ef(t),r=Po(e.status,n?.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:mf(e.pm_format_version),source_type:E(e.source_type),type_options:n0(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:IE(e.dependencies),comments:pa(e.comments),notes:pa(e.notes),learnings:pa(e.learnings),files:DE(e.files),tests:FE(e.tests),test_runs:PE(e.test_runs),docs:BE(e.docs),deadline:lr(e.deadline),reminders:TE(e.reminders),events:RE(e.events),closed_at:lr(e.closed_at),completed_at:lr(e.completed_at),assignee:E(e.assignee),claim_principal:E(e.claim_principal),source_owner:E(e.source_owner),author:lr(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:r0(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:o0(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:lr(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:ZE(e.plan_steps),plan_decisions:QE(e.plan_decisions),plan_discoveries:e0(e.plan_discoveries),plan_validation:t0(e.plan_validation)};return i0(i,e),s0(i,n),a0(i,n),jo(i),i}function Of(e){return A(e,ve)}function c0(e){let t=0,n=!1,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(n){if(r){r=!1;continue}if(i==="\\"){r=!0;continue}i==='"'&&(n=!1);continue}if(i==='"'){n=!0;continue}if(i==="{"){t+=1;continue}if(i==="}"&&(t-=1,t===0))return o}return-1}function d0(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=c0(e);if(t<0)return{frontMatter:"",body:e};let n=e.slice(0,t+1),r=e.slice(t+1).replace(/^\r?\n+/,"");return{frontMatter:n,body:r}}function l0(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!n)return{content:t,stripped:!1};let r=n[0].length;for(;r<t.length;){let o=t.indexOf(`
5
+ `,r),i=o===-1?t.length:o,s=t.slice(r,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};r=a}return{content:t,stripped:!1}}function ba(e,t){return Lo(e,{...t,onWarning:void 0})}function u0(e,t,n={}){let r=l0(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=d0(r.content);o||(e.trimStart().startsWith("{")&&ur("json_markdown","JSON front matter is not valid JSON"),ur("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{ur("json_markdown","JSON front matter is not valid JSON")}return kf(s,n.requireSupportedFormat),ga(s,t),{metadata:ba(s,n),body:ln(i)}}function f0(e,t,n={}){let r;try{r=fa(e).value}catch{ur("toon","TOON item document is not valid TOON")}O(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(kf(Object.prototype.hasOwnProperty.call(o,"front_matter")?o.front_matter:o,n.requireSupportedFormat),!vf.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&ur("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return ga(o.front_matter,t),O(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:ba(o.front_matter,n),body:ln(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"),ga(s,t),{metadata:ba(s,n),body:ln(typeof i=="string"?i:"")}}function m0(e,t={}){let n=Lo(e.metadata,t),r=Of(n),o=ln(e.body??"");va(JSON.parse(JSON.stringify(r))),va({body:o});let i=JSON.stringify(r,null,2);return o?`${i}
6
6
 
7
7
  ${o}
8
8
  `:`${i}
9
- `}var p0=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function wa(e,t){return typeof e=="string"?yf(e,t):e===null||typeof e!="object"?null:Array.isArray(e)?hf(e.map((n,r)=>()=>wa(n,`${t}[${r}]`))):hf(Object.entries(e).map(([n,r])=>()=>{let o=t?`${t}.${n}`:n;return yf(n,`${o} (key)`)??wa(r,o)}))}function yf(e,t){let n=e.search(p0);return n<0?null:{path:t,index:n}}function hf(e){for(let t of e){let n=t();if(n!==null)return n}return null}function va(e){let t=wa(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 _0(e,t={}){let n=Lo(e.metadata,t),r=Sf(n),o=ln(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i));va(s);let a=nE(s),c;try{c=fa(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(!mf(c,s)){let d=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},l=Object.keys(s).find(u=>!mf(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}
10
- `}function D1(e,t={}){let n=Mo(e);if(n)throw new g(`Merge conflict markers detected in item document at line ${n.line} (${n.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 r=t.format??"toon",o=vf(t);return r==="toon"?f0(e,o,t):u0(e,o,t)}function P1(e,t={}){return(t.format??"toon")==="toon"?_0(e,t):m0(e,t)}function fn(e,t={}){return{metadata:Lo(e.metadata,t),body:ln(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 Of(e){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]="7e894d1f-fe1a-53f2-9a29-4e9846a9f986")}catch{}})();var Af=["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"],If=["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","transaction_abandon"],Sa={"init:type-preset":"init:type_preset"},Tf=["^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_]*$"],j1={version:1,item:Af,workspace:If,aliases:Sa,patterns:Tf,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"]},y0=new Set([...Af,...If]),h0=Tf.map(e=>new RegExp(e,"u"));function Cf(e){return Object.hasOwn(Sa,e)?Sa[e]:e}function L1(e){let t=Cf(e);if(y0.has(t)||h0.some(n=>n.test(t)))return t;throw new TypeError("Undeclared history operation; use a native contract identity or extension:<package_name>:<snake_case_operation>.")}function Rf(e){let t=Cf(e),n=t.indexOf(":"),r=n<0?t:t.slice(0,n),o=n<0||n<t.length-1&&!/[\s\p{C}]/u.test(t.slice(n+1));if(/^[a-z][a-z0-9]*(?:[_.-][a-z0-9]+)*$/u.test(r)&&o)return t;throw new TypeError("History operation must use lowercase alphanumeric segments with an optional non-whitespace colon-suffixed retry key.")}import{AsyncLocalStorage as g0}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 Oa=new g0,xf=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function Fo(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function Ot(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=Fo(n.id,128),o=Fo(n.parent_id,128);if(r===void 0||!xf.test(r)||o!==void 0&&!xf.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=Fo(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function mn(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=Fo(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function b0(e,t,n){let r=Oa.getStore(),o=mn({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Ot(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={...mn(r?.provenance),...o,...mn(e?.provenance)},a=Ot(e?.episode,!1)??Ot(n,!1)??i??Ot(r?.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 Aa(e,t){return b0(e.session_context,t,e.client_info?.episode)??{}}function U1(e,t){let n=Oa.getStore(),r=Ot(e.episode,!0),o=Ot(n?.episode,!1),i=r!==void 0&&r.parent_id===void 0&&o!==void 0?{...r,parent_id:o.id}:r,s={...mn(n?.provenance),...mn(e.provenance)};return Oa.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function H1(e){let t=mn(e.provenance),n=Ot(e.episode,!0);return{...n===void 0?{}:{PM_AGENT_EPISODE_ID:n.id,...n.label===void 0?{}:{PM_AGENT_EPISODE_LABEL:n.label},...n.parent_id===void 0?{}:{PM_AGENT_EPISODE_PARENT_ID:n.parent_id}},...t.role===void 0?{}:{PM_AGENT_SESSION_ROLE:t.role},...t.topic===void 0?{}:{PM_AGENT_SESSION_TOPIC:t.topic}}}import{constants as S0}from"node:fs";import ne from"node:fs/promises";import Se from"node:path";import{createHash as O0,randomUUID as Bo}from"node:crypto";import zo from"node:fs/promises";import ke 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]="f1eb25ad-08b8-5826-9ec1-7b0a7a22d277")}catch{}})();var Df="lock_path_unsafe";function w0(e,t){return ke.relative(e,t).split(ke.sep).join("/")}function v0(e,t){return e==="lock_entry_symlink"?`Remove the symlinked lock entry ${t} (pm neither follows nor deletes it), then retry the same operation.`:e==="lock_directory_replaced"?`Restore ${t} as a real directory inside the tracker, then retry the same operation. The lock file created while it was replaced stays where the replacement pointed, because pm never deletes outside the tracker; remove it there if it is not wanted.`:"Replace the symlinked or replaced lock directory with a real directory inside the tracker (for example: remove the link, then let pm recreate locks/), then retry the same operation."}function mr(e){let t=e.component??ke.dirname(e.lockPath),n=w0(e.pmRoot,t);return new g(`Refused to acquire lock ${e.id}: ${n} is not a real directory inside the tracker (${e.reason}). Locks are never created through a symlinked or replaced lock directory.`,h.CONFLICT,{code:"lock_path_unsafe",item_id:e.id,reason:e.reason,lock_component:n,required:v0(e.reason,n)})}function Nf(e,t){return e.dev===t.dev&&e.ino===t.ino}async function Uo(e,t,n,r=!0){let o=ke.resolve(e),i=ke.dirname(ke.resolve(t)),s=ke.relative(o,i);if(s===".."||s.startsWith(`..${ke.sep}`)||ke.isAbsolute(s))throw mr({pmRoot:o,lockPath:t,id:n,reason:"lock_path_outside_tracker",component:i});let a=o,c=null;for(let l of s===""?[]:s.split(ke.sep)){a=ke.join(a,l);let u;try{u=await zo.lstat(a,{bigint:!0})}catch(f){if(r&&ee(f))return null;throw f}if(u.isSymbolicLink())throw mr({pmRoot:o,lockPath:t,id:n,reason:"lock_directory_symlink",component:a});if(!u.isDirectory())throw mr({pmRoot:o,lockPath:t,id:n,reason:"lock_directory_not_directory",component:a});c={dev:u.dev,ino:u.ino}}if(c!==null)return c;let d=await zo.stat(o,{bigint:!0});return{dev:d.dev,ino:d.ino}}async function Pf(e,t,n){let r;try{r=await zo.lstat(t)}catch{return}if(r.isSymbolicLink())throw mr({pmRoot:e,lockPath:t,id:n,reason:"lock_entry_symlink",component:t})}async function Mf(e){let t=await e.handle.stat({bigint:!0}),n={dev:t.dev,ino:t.ino},r=!1;try{let o=await Uo(e.pmRoot,e.lockPath,e.id,!1);if(Nf(e.directory,o)){let i=await zo.lstat(e.lockPath,{bigint:!0});r=!i.isSymbolicLink()&&Nf(n,i)}}catch{r=!1}if(!r)throw mr({pmRoot:e.pmRoot,lockPath:e.lockPath,id:e.id,reason:"lock_directory_replaced"})}import Ia from"node:fs/promises";import{createHash as E0}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 $f(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function k0(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!$f(t,"ESRCH")}}function jf(e){let t=e.lastIndexOf(")");if(t<0)return null;let n=e.slice(t+2).trim().split(/\s+/u)[19];return n!==void 0&&/^\d+$/u.test(n)?n:null}async function pn(e){try{return jf(await Ia.readFile(`/proc/${e}/stat`,"utf8"))}catch{return null}}async function pr(e=process.pid){let t=await pn(e);return{pid:e,...t===null?{}:{process_start_identity:t}}}async function _r(e,t,n){if(!k0(e.pid))return!1;let r=await pn(e.pid);return e.process_start_identity!==void 0&&r!==null?r===e.process_start_identity:t<=n}async function Lf(){try{let[e,t]=await Promise.all([Ia.readFile("/proc/sys/kernel/random/boot_id","utf8"),Ia.readlink("/proc/self/ns/pid")]);return!/^[a-f0-9-]{36}\s*$/u.test(e)||!/^pid:\[\d+\]$/u.test(t)?null:E0("sha256").update(`${e.trim()}:${t}`).digest("hex")}catch{return null}}async function Ta(){let[e,t]=await Promise.all([Lf(),pn(process.pid)]);return e!==null&&t!==null?{host_identity:e,process_start_identity:t}:{}}async function Ho(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 Lf();if(t===null||t!==e.host_identity)return"unknown";try{process.kill(e.pid,0)}catch(r){return $f(r,"ESRCH")?"dead":"unknown"}let n=await pn(e.pid);return n===null?"unknown":n===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]="7f116073-a02b-568b-a408-17c0fcc8b4a4")}catch{}})();function A0(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 n=t,r=n.id,o=n.pid,i=n.owner,s=n.token,a=n.created_at,c=n.ttl_seconds;return typeof r!="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:r,pid:o,owner:i,...typeof s=="string"?{token:s}:{},created_at:a,ttl_seconds:c,host_identity:n.host_identity,process_start_identity:n.process_start_identity},warnings:[]}}async function At(e,t=!0){try{let n=await ne.readFile(e,"utf8");return t&&await an({path:e,scope:"project"}),A0(n)}catch(n){return ee(n)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Ze(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function I0(e,t,n=process.platform){if(Ze(e,"EEXIST"))return!0;if(!Ze(e,"EPERM")&&!Ze(e,"EACCES")&&!Ze(e,"EBUSY"))return!1;try{return await ne.lstat(t),!0}catch(r){if(n!=="win32"||!ee(r)&&!Ze(r,"EPERM")&&!Ze(r,"EACCES")&&!Ze(r,"EBUSY"))return!1}try{return await ne.access(Se.dirname(t),S0.W_OK),!0}catch{return!1}}async function qf(e,t){await Io({path:e,scope:"project",op:t})}async function T0(e,t,n,r=Bo()){return{...await Ta(),id:e,pid:process.pid,owner:t,token:r,created_at:Te(),ttl_seconds:n}}async function C0(e,t,n,r,o,i,s){let a=await Uo(e,t,n);s&&a===null&&await ne.mkdir(Se.dirname(t),{recursive:!0});let c=await Yo(t,n);if(c===null)throw await ne.access(Se.dirname(t)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});let d;try{let l=await Uo(e,t,n,!1),u=await ne.open(t,"wx");try{await Mf({pmRoot:e,lockPath:t,id:n,handle:u,directory:l})}catch(f){throw await u.close(),f}try{try{let f=await T0(n,r,o,i);d=f.created_at,await u.writeFile(`${JSON.stringify(f,null,2)}
11
- `,"utf8")}finally{await u.close()}}catch(f){throw await xa(t,"lock:release"),f}}finally{await c()}return await qf(t,"lock:create"),d}async function xa(e,t){try{return await ne.unlink(e),await qf(e,t),!0}catch{return!1}}async function R0(e,t,n,r){let o=performance.now(),i=Wo;for(;;){let s=await Yo(e,t);if(s!==null){try{let d=await At(e,!1);Ca(d.info,t,n,r)&&await xa(e,"lock:release")}finally{await s()}return}let a=await At(e,!1);if(!Ca(a.info,t,n,r))return;let c=performance.now()-o;if(c>=qo)return;await Ko(Math.min(i,qo-c)),i=Math.min(i*2,Go)}}function Ca(e,t,n,r){return e?.id===t&&e.pid===process.pid&&e.owner===n&&e.token===r}function Vf(e,t){let n=e?.created_at?Date.parse(e.created_at):Number.NaN;return(Number.isFinite(n)?Date.now()-n:Number.POSITIVE_INFINITY)>t*1e3}async function Bf(e){return e!==null&&Number.isFinite(Date.parse(e.created_at))&&await Ho(e)==="dead"}async function Wf(e,t){return Vf(e,t)||await Bf(e)}async function Gf(e,t,n){let{info:r}=await At(fs(e,t),!1);return r!==null&&r.owner.startsWith(n)&&!await Wf(r,r.ttl_seconds)}function x0(e){return e?.owner?` (owner ${e.owner})`:""}var Wo=25,Go=200,Kf=250,N0=12e4,D0=3,P0=".stale-cleanup",Yf="owner.json",Xf=1e4,qo=Xf+Go;function Ra(e){if(typeof e=="string"){let t=e.trim();if(!/^\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0}if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e)}function M0(e){let t=process.env.PM_LOCK_WAIT_MS,n=Ra(t);if(n!==void 0)return n;let r=Ra(e);return r!==void 0?r:0}function $0(e,t){return Math.min(M0(e),t??1/0)}function Ko(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}async function Jf(e,t,n,r=0){n=Math.floor(n);let o=await Ho(t),i=r>0?` across ${r} owner handoff(s)`:"",s=n>0?` after waiting ${n}ms${i}`:"";return new g(`Item ${e} is locked${x0(t)} (owner process ${o})${s}`,h.CONFLICT,{code:"lock_conflict",item_id:e,reason:`lock_owner_${o}`,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:Kf,...n>0?{waited_ms:n,owner_handoffs:r}:{}}})}function j0(e,t){let n=performance.now(),r=n,o,i=0;return{startedAtMs:n,observe(s){let a=performance.now(),c=F0(s);o!==void 0&&c!==o&&(i+=1,r=a),o=c;let d=a-n,l=a-r;return{exhausted:e===0||l>=e||d>=t,elapsedMs:d,remainingMs:Math.min(e-l,t-d),ownerHandoffs:i}}}}function L0(e,t,n){return n!=="progress"||t!==void 0?e:Math.max(e,N0)}function F0(e){return e===null?"released":e.token??`${e.pid}:${e.owner}:${e.created_at}`}function z0(e){let t=Date.parse(e.acquiredAt)+e.ttlSeconds*1e3;return{owner:e.owner,acquired_at:e.acquiredAt,ttl_seconds:e.ttlSeconds,expires_at:new Date(t).toISOString()}}function U0(e,t,n,r){let o=`the lease acquired at ${t.acquiredAt} (ttl ${t.ttlSeconds}s)`;if(r==="fence_gate_unavailable")return{summary:`Lock for ${e} could not be verified before commit: ${o} could not enter its commit fence because the stale-cleanup gate stayed held.`,required:"Retry the same operation; this writer's change was not committed. Inspect pm gc --scope locks --dry-run if the stale-cleanup gate stays held."};let i=n===null?"the lock no longer exists":`it is now held by ${n.owner} since ${n.created_at}`;return{summary:`Lock for ${e} was lost before commit: ${o} is no longer owned by this writer, and ${i}.`,required:"Re-read the item and apply the mutation again; this writer's change was not committed and the newer value was kept. Keep mutation work shorter than locks.ttl_seconds, or raise locks.ttl_seconds for long-running callbacks."}}function Ff(e,t,n,r){let{summary:o,required:i}=U0(e,t,n,r);return new g(`${o} Nothing was written.`,h.CONFLICT,{code:"lock_lost",item_id:e,reason:r,lease:z0(t),current_owner:n===null?null:{owner:n.owner,pid:n.pid,created_at:n.created_at,ttl_seconds:n.ttl_seconds},required:i,recovery:{retry_after_ms:Kf}})}async function H0(e,t){let n=performance.now(),r=Wo;for(;;){let o=await Yo(e,t);if(o!==null)return o;let i=performance.now()-n;if(i>=qo)return null;await Ko(Math.min(r,qo-i)),r=Math.min(r*2,Go)}}async function q0(e,t,n,r){let o=await H0(e,t);if(o===null){let i=await At(e,!1);throw Ff(t,n,i.info,"fence_gate_unavailable")}try{let i=await At(e,!1);if(!Ca(i.info,t,n.owner,n.token))throw Ff(t,n,i.info,i.info===null?"lease_released":"lease_taken_over");return await r()}finally{await o()}}function V0(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 B0(e,t,n,r){if(!n&&r){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 W0(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r=n.pid,o=n.token,i=n.process_start_identity;return typeof r!="number"||!Number.isInteger(r)||r<=0||typeof o!="string"||o.length===0||i!==void 0&&(typeof i!="string"||!/^\d+$/u.test(i))?null:{pid:r,token:o,host_identity:n.host_identity,...typeof i=="string"?{process_start_identity:i}:{}}}async function Vo(e){try{return W0(await ne.readFile(Se.join(e,Yf),"utf8"))}catch(t){return ee(t)?null:void 0}}async function Na(e){try{return await ne.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function zf(e,t){let n=await Vo(e);for(let r=0;n===void 0&&r<3;r+=1)await Ko(Wo),n=await Vo(e);!n||n.token!==t||await Na(e)}async function Uf(e){try{await ne.mkdir(e)}catch(n){return Ze(n,"EEXIST"),null}let t={...await pr(),host_identity:(await Ta()).host_identity,token:Bo()};try{await ne.writeFile(Se.join(e,Yf),`${JSON.stringify(t)}
12
- `,"utf8")}catch{return await Na(e),null}return t}async function Hf(e,t){let n=Se.join(Se.dirname(e),"recoveries"),r=O0("sha256").update(t).digest("hex");try{return await ne.mkdir(n,{recursive:!0}),(await Vo(e))?.token!==t?!1:(await ne.rename(e,Se.join(n,`gate-${r}`)),!0)}catch{return!1}}async function G0(e){let t;try{let r=await ne.stat(e);t=Date.now()-r.mtimeMs}catch(r){return ee(r)}let n=await Vo(e);if(n===void 0)return!1;if(n!==null){if(await Ho(n)==="dead")return Hf(e,n.token);if(n.host_identity!==void 0)return!1}return t<=Xf||n!==null&&await _r(n,t,Number.POSITIVE_INFINITY)?!1:n!==null?Hf(e,n.token):Na(e)}async function Yo(e,t){let n=`${e}${P0}`,r=await Uf(n);if(r!==null)return async()=>zf(n,r.token);if(!await G0(n))return null;let o=await Uf(n);return o===null?null:async()=>zf(n,o.token)}async function K0(e,t){let n=Se.join(Se.dirname(e),"recoveries");await ne.mkdir(n,{recursive:!0}),await ne.writeFile(Se.join(n,`${Bo()}.json`),`${JSON.stringify({event:"owner_dead_recovery_attempt",recorded_at:Te(),lock:JSON.parse(t)})}
13
- `,{encoding:"utf8",flag:"wx",mode:384})}async function Y0(e){let t=await Yo(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await At(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};let r=await Bf(n.info);if(!Vf(n.info,e.ttlSeconds)&&!r)return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(B0(e.id,n,e.force||r,e.forceRequiredForStaleLock),e.staleRemovals>=D0)throw await Jf(e.id,n.info,performance.now()-e.startedAtMs);return r&&await K0(e.lockPath,JSON.stringify(n.info)),{lockInfo:n,shouldRetryCreate:await xa(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function X0(e,t,n,r){if(e instanceof g&&e.code===Df)throw e;if(!await I0(e,n))throw new g(`Failed to acquire lock for ${r}: ${cl(e)}`,h.GENERIC_FAILURE);await Pf(t,n,r)}async function fe(e,t,n,r,o=!1,i=!0,s,a={}){return(await J0(e,t,n,r,o,i,s,a)).release}async function J0(e,t,n,r,o=!1,i=!0,s,a={}){let c=Ra(a.maxWaitMs),d=await cn("lock_acquire",{pm_root:e,id:t,ttl_seconds:n,owner:r,force:o,force_required_for_stale_lock:i,...c===void 0?{}:{max_wait_ms:c}});if(d.handled){let T=V0(d.result);if(T)return{release:async()=>{await Promise.resolve(T()),await cn("lock_release",{pm_root:e,id:t,owner:r})},fence:H=>H()}}let l=fs(e,t),u=$0(s,c),f=L0(u,c,a.waitPolicy),m=j0(u,f),_=m.startedAtMs,y=0,w=Wo,v=Bo();for(;;)try{let T=await C0(e,l,t,r,n,v,a.createParentDirectories!==!1),H={owner:r,token:v,acquiredAt:T,ttlSeconds:n};return{release:async()=>{await R0(l,t,r,v),await cn("lock_release",{pm_root:e,id:t,owner:r})},fence:X=>q0(l,t,H,X)}}catch(T){await X0(T,e,l,t);let H=await At(l);if(await Wf(H.info,n)){let de=await Y0({lockPath:l,id:t,ttlSeconds:n,force:o,forceRequiredForStaleLock:i,staleRemovals:y,waitBudgetMs:u,startedAtMs:_,fallbackLockInfo:H});if(H=de.lockInfo,de.staleRemovalCounted&&(y+=1),de.shouldRetryCreate)continue}let X=m.observe(H.info);if(X.exhausted)throw await Jf(t,H.info,u===0?0:X.elapsedMs,X.ownerHandoffs);await Ko(Math.min(w,X.remainingMs)),w=Math.min(w*2,Go)}}import{createHash as Zf}from"node:crypto";import{existsSync as Da,promises as Qf,readFileSync as Z0}from"node:fs";import Re 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 Q0="session.json";function Pa(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function em(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=["implementer","planner","release-operator"].includes(String(t.role)),r=["high","medium"].includes(String(t.confidence)),o=Pa(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=>Pa(c,128)),a=t.focused_item_id===void 0||Pa(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function ek(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=Object.entries(e).slice(0,128).flatMap(([n,r])=>{let o=em(r);return o&&n.length<=128?[[n,o]]:[]});return t.length>0?Object.fromEntries(t):void 0}function Ma(e){return Re.join(ms(e),Q0)}async function tm(e){try{let t=await Qf.readFile(Ma(e),"utf8"),n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))return{};let r=n,o=r.focused_item,i=ek(r.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 $a(e,t){let n=await fe(e,"session-state",S.locks.ttl_seconds,"session-state",!1,!0,S.locks.wait_ms);try{let r=await tm(e);t(r);let o=Ma(e);await Qf.mkdir(Re.dirname(o),{recursive:!0}),await pt(o,JSON.stringify(r))}finally{await n()}}function ja(e){return/#([a-f0-9]{24})$/u.exec(e.trim())?.[1]??`author-${Zf("sha256").update(e).digest("hex").slice(0,24)}`}function La(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].slice(0,32).map(t=>t.slice(0,128))}function Fa(e){let t=[...new Set(e)].sort((r,o)=>r.localeCompare(o));if(t.length===1)return t[0];let n=`workset:${t.join("+")}`;return n.length<=256?n:`workset:${t.join("+").slice(0,230)}+${Zf("sha256").update(t.join("\0")).digest("hex").slice(0,12)}`}async function za(e,t,n){await $a(e,r=>{let o={...r.semantic_attribution},i=n(o[t]);i===void 0?delete o[t]:o[t]=i,Object.keys(o).length===0?delete r.semantic_attribution:r.semantic_attribution=o})}async function vM(e){let t=ja(e.principal);await za(e.pmRoot,t,n=>{let r=[...new Set([...n?.active_item_ids??[],e.itemId])].slice(-64).sort((i,s)=>i.localeCompare(s)),o=n?.focused_item_id;return{role:"implementer",topic:o??Fa(r),confidence:o?"high":"medium",rule_version:"v2",evidence:La([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}async function EM(e){let t=ja(e.principal);await za(e.pmRoot,t,n=>{if(!n)return;let r=n.active_item_ids.filter(i=>i!==e.itemId);if(r.length===0&&!n.focused_item_id)return;let o=n.focused_item_id;return{...n,role:"release-operator",topic:o??Fa(r),confidence:o?"high":"medium",evidence:La([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],`release:${e.itemId}`]),active_item_ids:r}})}async function kM(e){let t=ja(e.principal);await za(e.pmRoot,t,n=>{let r=n?.active_item_ids??[];if(!e.itemId&&r.length===0)return;let o=e.itemId;return{role:o?"planner":n.role,topic:o??Fa(r),confidence:o?"high":"medium",rule_version:"v2",evidence:La([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}function tk(e,t){let n=t.PM_PATH?.trim();if(n){let o=Re.resolve(e,n);if(Da(Re.join(o,"settings.json")))return o;let i=Re.join(o,".agents","pm");if(Da(Re.join(i,"settings.json")))return i}let r=Re.resolve(e);for(let o=0;o<32;o+=1){let i=Re.join(r,".agents","pm");if(Da(Re.join(i,"settings.json")))return i;let s=Re.dirname(r);if(s===r)break;r=s}}function nm(e){if(!e.key)return;let t=tk(e.cwd,e.env);if(t)try{let n=JSON.parse(Z0(Ma(t),"utf8"));return em(n.semantic_attribution?.[e.key])}catch{return}}async function SM(e){return(await tm(e)).focused_item}async function OM(e,t){await $a(e,n=>{n.focused_item=t})}async function AM(e){await $a(e,t=>{delete t.focused_item})}import{AsyncLocalStorage as Ba}from"node:async_hooks";import{createHash as nk}from"node:crypto";import me from"node:fs";import sm from"node:os";import Ct 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 Wa=["model","effort","role","topic","version"],Zo=new Ba,am=new Ba,Qo=new Ba,Ga=[{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:[]}],cm=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),rk=Object.freeze({...cm,max_bytes:4194304}),Ua=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function ok(e){let t=et(e).provenance_unavailable_dimensions,n=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([...n].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(r=>r?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?rk:cm,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(r=>[r,"Harness does not expose this dimension."])))})}var dm=Object.freeze(Ga.filter(e=>e.harness!=="ci").map(ok).sort((e,t)=>e.harness.localeCompare(t.harness))),Tt=new Map,_n=new Map;function V(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function Qe(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function et(e){let t=e.harness.trim().toLowerCase();if(!Ua.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:Qe(e.environment_keys),model_environment_keys:Qe(e.model_environment_keys),session_environment_keys:Qe(e.session_environment_keys),provenance_environment_keys:Object.fromEntries(Object.entries(e.provenance_environment_keys??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),Qe(r)]).filter(([n])=>Ua.test(n))),provenance_resolvers:Object.fromEntries(Object.entries(e.provenance_resolvers??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),r]).filter(n=>typeof n[0]=="string"&&Ua.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:Qe(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:Qe(e.argv_markers).map(n=>n.toLowerCase()),client_names:Qe(e.client_names).map(n=>n.toLowerCase())}}var lm=Ga.map(et);function ik(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Jo(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(n=>n.length>0).includes(t)||e.trim().toLowerCase()===t}function Ka(e=[]){let t=new Map(Ga.filter(o=>o.harness!=="ci").map(o=>[o.harness,et(o)]));for(let{adapter:o}of Tt.values())t.set(o.harness,et(o.descriptor));let n=[...t.values(),...lm.filter(o=>o.harness==="ci"),...[..._n.values()].map(o=>o.descriptor),...Qo.getStore()?.descriptors??[],...e.map(et)],r=new Set;for(let o of n){if(r.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);r.add(o.harness)}return n}function Ya(e,t){for(let n of t??[]){let r=V(e[n]);if(r)return r.slice(0,256)}}function sk(e,t){if(t==="role"){let n=e.slice(0,8).map(r=>r.trim().toLowerCase()).find(r=>["claim","create","update","close","release","review"].includes(r));if(n==="review")return"reviewer";if(n)return"implementer"}}function um(e,t){let n=t==="model"?["--model","--agent-model"]:[`--agent-${t}`],r=e.slice(0,8);for(let o=0;o<r.length;o+=1){let i=r[o].slice(0,512);if(n.includes(i))return V(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return V(i.slice(s.length+1))?.slice(0,256)}}var ak=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function It(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return ak.has(n)?n:void 0}function Ha(e,t){return V(e?.[t])?.slice(0,256)}var ck=1048576,Va=4194304,Xo=new Map,rm=Object.freeze({}),qa=new Map,om=Object.freeze({});function im(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function dk(e){let t;try{t=JSON.parse(e)}catch{return om}let n=im(t);if(!n)return om;let r=[{value:n,depth:0}],o=0,i,s;for(;r.length>0&&o<64;){let a=r.shift();if(o+=1,i??=V(a.value.model)?.slice(0,256),s??=V(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let d=im(c);d&&r.push({value:d,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function fm(e){try{return me.lstatSync(e).isFile()?"available":"missing"}catch(t){return be(t)?"missing":"failed"}}function lk(e,t){let n;try{n=me.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name)).slice(0,512).map(o=>{let i=Ct.join(e,o.name,`${t}.jsonl`);return{candidate:i,status:fm(i)}})}catch(o){return{status:be(o)?"missing":"failed"}}let r=n.filter(({status:o})=>o==="available").map(({candidate:o})=>o);return r.length===0?{status:n.some(({status:o})=>o==="failed")?"failed":"missing"}:r.length>1?{status:"ambiguous"}:{status:"available",path:r[0]}}function mm(e,t){let n=V(t.CLAUDE_CODE_SESSION_ID);if(!n||!/^[A-Za-z0-9_-]{1,128}$/u.test(n))return{status:"unavailable"};let r=Ct.resolve(e.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),o=Ct.join(e.home_dir??sm.homedir(),".claude","projects"),i=Ct.join(o,r,`${n}.jsonl`),s=V(e.session_file),a=s&&Ct.basename(s)===`${n}.jsonl`?s:void 0;for(let c of[a,i]){if(!c)continue;let d=fm(c);if(d==="available")return{status:d,path:c};if(d==="failed")return{status:d}}return lk(o,n)}function uk(e,t,n){let r=mm(t,n);if(r.status==="available")try{let o=me.openSync(r.path,me.constants.O_RDONLY|me.constants.O_NOFOLLOW);try{let i=me.fstatSync(o),s=`${r.path}\0${i.size}\0${i.mtimeMs}`,a=qa.get(s);if(a)return a[e];let c=Math.min(i.size,ck),d=Math.min(c,Math.ceil(c/2)),l=Math.min(c-d,i.size-d),u=Buffer.alloc(d);me.readSync(o,u,0,d,0);let f=Buffer.alloc(l);l>0&&me.readSync(o,f,0,l,i.size-l);let m={},_=i.size<=c?Buffer.concat([u,f]).toString("utf8").split(`
9
+ `}var p0=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function wa(e,t){return typeof e=="string"?hf(e,t):e===null||typeof e!="object"?null:Array.isArray(e)?gf(e.map((n,r)=>()=>wa(n,`${t}[${r}]`))):gf(Object.entries(e).map(([n,r])=>()=>{let o=t?`${t}.${n}`:n;return hf(n,`${o} (key)`)??wa(r,o)}))}function hf(e,t){let n=e.search(p0);return n<0?null:{path:t,index:n}}function gf(e){for(let t of e){let n=t();if(n!==null)return n}return null}function va(e){let t=wa(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 _0(e,t={}){let n=Lo(e.metadata,t),r=Of(n),o=ln(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i));va(s);let a=nE(s),c;try{c=fa(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(!pf(c,s)){let d=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},l=Object.keys(s).find(u=>!pf(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}
10
+ `}function P1(e,t={}){let n=Mo(e);if(n)throw new g(`Merge conflict markers detected in item document at line ${n.line} (${n.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 r=t.format??"toon",o=Ef(t);return r==="toon"?f0(e,o,t):u0(e,o,t)}function M1(e,t={}){return(t.format??"toon")==="toon"?_0(e,t):m0(e,t)}function fn(e,t={}){return{metadata:Lo(e.metadata,t),body:ln(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 Af(e){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]="7e894d1f-fe1a-53f2-9a29-4e9846a9f986")}catch{}})();var If=["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"],Tf=["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","transaction_abandon"],Sa={"init:type-preset":"init:type_preset"},Cf=["^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_]*$"],L1={version:1,item:If,workspace:Tf,aliases:Sa,patterns:Cf,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"]},y0=new Set([...If,...Tf]),h0=Cf.map(e=>new RegExp(e,"u"));function Rf(e){return Object.hasOwn(Sa,e)?Sa[e]:e}function F1(e){let t=Rf(e);if(y0.has(t)||h0.some(n=>n.test(t)))return t;throw new TypeError("Undeclared history operation; use a native contract identity or extension:<package_name>:<snake_case_operation>.")}function xf(e){let t=Rf(e),n=t.indexOf(":"),r=n<0?t:t.slice(0,n),o=n<0||n<t.length-1&&!/[\s\p{C}]/u.test(t.slice(n+1));if(/^[a-z][a-z0-9]*(?:[_.-][a-z0-9]+)*$/u.test(r)&&o)return t;throw new TypeError("History operation must use lowercase alphanumeric segments with an optional non-whitespace colon-suffixed retry key.")}import{AsyncLocalStorage as g0}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 Oa=new g0,Nf=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function Fo(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function Ot(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=Fo(n.id,128),o=Fo(n.parent_id,128);if(r===void 0||!Nf.test(r)||o!==void 0&&!Nf.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=Fo(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function mn(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=Fo(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function b0(e,t,n){let r=Oa.getStore(),o=mn({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Ot(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={...mn(r?.provenance),...o,...mn(e?.provenance)},a=Ot(e?.episode,!1)??Ot(n,!1)??i??Ot(r?.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 Aa(e,t){return b0(e.session_context,t,e.client_info?.episode)??{}}function H1(e,t){let n=Oa.getStore(),r=Ot(e.episode,!0),o=Ot(n?.episode,!1),i=r!==void 0&&r.parent_id===void 0&&o!==void 0?{...r,parent_id:o.id}:r,s={...mn(n?.provenance),...mn(e.provenance)};return Oa.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function q1(e){let t=mn(e.provenance),n=Ot(e.episode,!0);return{...n===void 0?{}:{PM_AGENT_EPISODE_ID:n.id,...n.label===void 0?{}:{PM_AGENT_EPISODE_LABEL:n.label},...n.parent_id===void 0?{}:{PM_AGENT_EPISODE_PARENT_ID:n.parent_id}},...t.role===void 0?{}:{PM_AGENT_SESSION_ROLE:t.role},...t.topic===void 0?{}:{PM_AGENT_SESSION_TOPIC:t.topic}}}import{constants as S0}from"node:fs";import ne from"node:fs/promises";import Se from"node:path";import{createHash as O0,randomUUID as Bo}from"node:crypto";import zo from"node:fs/promises";import ke 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]="f1eb25ad-08b8-5826-9ec1-7b0a7a22d277")}catch{}})();var Pf="lock_path_unsafe";function w0(e,t){return ke.relative(e,t).split(ke.sep).join("/")}function v0(e,t){return e==="lock_entry_symlink"?`Remove the symlinked lock entry ${t} (pm neither follows nor deletes it), then retry the same operation.`:e==="lock_directory_replaced"?`Restore ${t} as a real directory inside the tracker, then retry the same operation. The lock file created while it was replaced stays where the replacement pointed, because pm never deletes outside the tracker; remove it there if it is not wanted.`:"Replace the symlinked or replaced lock directory with a real directory inside the tracker (for example: remove the link, then let pm recreate locks/), then retry the same operation."}function mr(e){let t=e.component??ke.dirname(e.lockPath),n=w0(e.pmRoot,t);return new g(`Refused to acquire lock ${e.id}: ${n} is not a real directory inside the tracker (${e.reason}). Locks are never created through a symlinked or replaced lock directory.`,h.CONFLICT,{code:"lock_path_unsafe",item_id:e.id,reason:e.reason,lock_component:n,required:v0(e.reason,n)})}function Df(e,t){return e.dev===t.dev&&e.ino===t.ino}async function Uo(e,t,n,r=!0){let o=ke.resolve(e),i=ke.dirname(ke.resolve(t)),s=ke.relative(o,i);if(s===".."||s.startsWith(`..${ke.sep}`)||ke.isAbsolute(s))throw mr({pmRoot:o,lockPath:t,id:n,reason:"lock_path_outside_tracker",component:i});let a=o,c=null;for(let l of s===""?[]:s.split(ke.sep)){a=ke.join(a,l);let u;try{u=await zo.lstat(a,{bigint:!0})}catch(f){if(r&&ee(f))return null;throw f}if(u.isSymbolicLink())throw mr({pmRoot:o,lockPath:t,id:n,reason:"lock_directory_symlink",component:a});if(!u.isDirectory())throw mr({pmRoot:o,lockPath:t,id:n,reason:"lock_directory_not_directory",component:a});c={dev:u.dev,ino:u.ino}}if(c!==null)return c;let d=await zo.stat(o,{bigint:!0});return{dev:d.dev,ino:d.ino}}async function Mf(e,t,n){let r;try{r=await zo.lstat(t)}catch{return}if(r.isSymbolicLink())throw mr({pmRoot:e,lockPath:t,id:n,reason:"lock_entry_symlink",component:t})}async function $f(e){let t=await e.handle.stat({bigint:!0}),n={dev:t.dev,ino:t.ino},r=!1;try{let o=await Uo(e.pmRoot,e.lockPath,e.id,!1);if(Df(e.directory,o)){let i=await zo.lstat(e.lockPath,{bigint:!0});r=!i.isSymbolicLink()&&Df(n,i)}}catch{r=!1}if(!r)throw mr({pmRoot:e.pmRoot,lockPath:e.lockPath,id:e.id,reason:"lock_directory_replaced"})}import Ia from"node:fs/promises";import{createHash as E0}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 jf(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function k0(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!jf(t,"ESRCH")}}function Lf(e){let t=e.lastIndexOf(")");if(t<0)return null;let n=e.slice(t+2).trim().split(/\s+/u)[19];return n!==void 0&&/^\d+$/u.test(n)?n:null}async function pn(e){try{return Lf(await Ia.readFile(`/proc/${e}/stat`,"utf8"))}catch{return null}}async function pr(e=process.pid){let t=await pn(e);return{pid:e,...t===null?{}:{process_start_identity:t}}}async function _r(e,t,n){if(!k0(e.pid))return!1;let r=await pn(e.pid);return e.process_start_identity!==void 0&&r!==null?r===e.process_start_identity:t<=n}async function Ff(){try{let[e,t]=await Promise.all([Ia.readFile("/proc/sys/kernel/random/boot_id","utf8"),Ia.readlink("/proc/self/ns/pid")]);return!/^[a-f0-9-]{36}\s*$/u.test(e)||!/^pid:\[\d+\]$/u.test(t)?null:E0("sha256").update(`${e.trim()}:${t}`).digest("hex")}catch{return null}}async function Ta(){let[e,t]=await Promise.all([Ff(),pn(process.pid)]);return e!==null&&t!==null?{host_identity:e,process_start_identity:t}:{}}async function Ho(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(r){return jf(r,"ESRCH")?"dead":"unknown"}let n=await pn(e.pid);return n===null?"unknown":n===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]="7f116073-a02b-568b-a408-17c0fcc8b4a4")}catch{}})();function A0(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 n=t,r=n.id,o=n.pid,i=n.owner,s=n.token,a=n.created_at,c=n.ttl_seconds;return typeof r!="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:r,pid:o,owner:i,...typeof s=="string"?{token:s}:{},created_at:a,ttl_seconds:c,host_identity:n.host_identity,process_start_identity:n.process_start_identity},warnings:[]}}async function At(e,t=!0){try{let n=await ne.readFile(e,"utf8");return t&&await an({path:e,scope:"project"}),A0(n)}catch(n){return ee(n)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Ze(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function I0(e,t,n=process.platform){if(Ze(e,"EEXIST"))return!0;if(!Ze(e,"EPERM")&&!Ze(e,"EACCES")&&!Ze(e,"EBUSY"))return!1;try{return await ne.lstat(t),!0}catch(r){if(n!=="win32"||!ee(r)&&!Ze(r,"EPERM")&&!Ze(r,"EACCES")&&!Ze(r,"EBUSY"))return!1}try{return await ne.access(Se.dirname(t),S0.W_OK),!0}catch{return!1}}async function Vf(e,t){await Io({path:e,scope:"project",op:t})}async function T0(e,t,n,r=Bo()){return{...await Ta(),id:e,pid:process.pid,owner:t,token:r,created_at:Te(),ttl_seconds:n}}async function C0(e,t,n,r,o,i,s){let a=await Uo(e,t,n);s&&a===null&&await ne.mkdir(Se.dirname(t),{recursive:!0});let c=await Yo(t,n);if(c===null)throw await ne.access(Se.dirname(t)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});let d;try{let l=await Uo(e,t,n,!1),u=await ne.open(t,"wx");try{await $f({pmRoot:e,lockPath:t,id:n,handle:u,directory:l})}catch(f){throw await u.close(),f}try{try{let f=await T0(n,r,o,i);d=f.created_at,await u.writeFile(`${JSON.stringify(f,null,2)}
11
+ `,"utf8")}finally{await u.close()}}catch(f){throw await xa(t,"lock:release"),f}}finally{await c()}return await Vf(t,"lock:create"),d}async function xa(e,t){try{return await ne.unlink(e),await Vf(e,t),!0}catch{return!1}}async function R0(e,t,n,r){let o=performance.now(),i=Wo;for(;;){let s=await Yo(e,t);if(s!==null){try{let d=await At(e,!1);Ca(d.info,t,n,r)&&await xa(e,"lock:release")}finally{await s()}return}let a=await At(e,!1);if(!Ca(a.info,t,n,r))return;let c=performance.now()-o;if(c>=qo)return;await Ko(Math.min(i,qo-c)),i=Math.min(i*2,Go)}}function Ca(e,t,n,r){return e?.id===t&&e.pid===process.pid&&e.owner===n&&e.token===r}function Bf(e,t){let n=e?.created_at?Date.parse(e.created_at):Number.NaN;return(Number.isFinite(n)?Date.now()-n:Number.POSITIVE_INFINITY)>t*1e3}async function Wf(e){return e!==null&&Number.isFinite(Date.parse(e.created_at))&&await Ho(e)==="dead"}async function Gf(e,t){return Bf(e,t)||await Wf(e)}async function Kf(e,t,n){let{info:r}=await At(fs(e,t),!1);return r!==null&&r.owner.startsWith(n)&&!await Gf(r,r.ttl_seconds)}function x0(e){return e?.owner?` (owner ${e.owner})`:""}var Wo=25,Go=200,Yf=250,N0=12e4,D0=3,P0=".stale-cleanup",Xf="owner.json",Jf=1e4,qo=Jf+Go;function Ra(e){if(typeof e=="string"){let t=e.trim();if(!/^\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0}if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e)}function M0(e){let t=process.env.PM_LOCK_WAIT_MS,n=Ra(t);if(n!==void 0)return n;let r=Ra(e);return r!==void 0?r:0}function $0(e,t){return Math.min(M0(e),t??1/0)}function Ko(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}async function Zf(e,t,n,r=0){n=Math.floor(n);let o=await Ho(t),i=r>0?` across ${r} owner handoff(s)`:"",s=n>0?` after waiting ${n}ms${i}`:"";return new g(`Item ${e} is locked${x0(t)} (owner process ${o})${s}`,h.CONFLICT,{code:"lock_conflict",item_id:e,reason:`lock_owner_${o}`,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:Yf,...n>0?{waited_ms:n,owner_handoffs:r}:{}}})}function j0(e,t){let n=performance.now(),r=n,o,i=0;return{startedAtMs:n,observe(s){let a=performance.now(),c=F0(s);o!==void 0&&c!==o&&(i+=1,r=a),o=c;let d=a-n,l=a-r;return{exhausted:e===0||l>=e||d>=t,elapsedMs:d,remainingMs:Math.min(e-l,t-d),ownerHandoffs:i}}}}function L0(e,t,n){return n!=="progress"||t!==void 0?e:Math.max(e,N0)}function F0(e){return e===null?"released":e.token??`${e.pid}:${e.owner}:${e.created_at}`}function z0(e){let t=Date.parse(e.acquiredAt)+e.ttlSeconds*1e3;return{owner:e.owner,acquired_at:e.acquiredAt,ttl_seconds:e.ttlSeconds,expires_at:new Date(t).toISOString()}}function U0(e,t,n,r){let o=`the lease acquired at ${t.acquiredAt} (ttl ${t.ttlSeconds}s)`;if(r==="fence_gate_unavailable")return{summary:`Lock for ${e} could not be verified before commit: ${o} could not enter its commit fence because the stale-cleanup gate stayed held.`,required:"Retry the same operation; this writer's change was not committed. Inspect pm gc --scope locks --dry-run if the stale-cleanup gate stays held."};let i=n===null?"the lock no longer exists":`it is now held by ${n.owner} since ${n.created_at}`;return{summary:`Lock for ${e} was lost before commit: ${o} is no longer owned by this writer, and ${i}.`,required:"Re-read the item and apply the mutation again; this writer's change was not committed and the newer value was kept. Keep mutation work shorter than locks.ttl_seconds, or raise locks.ttl_seconds for long-running callbacks."}}function zf(e,t,n,r){let{summary:o,required:i}=U0(e,t,n,r);return new g(`${o} Nothing was written.`,h.CONFLICT,{code:"lock_lost",item_id:e,reason:r,lease:z0(t),current_owner:n===null?null:{owner:n.owner,pid:n.pid,created_at:n.created_at,ttl_seconds:n.ttl_seconds},required:i,recovery:{retry_after_ms:Yf}})}async function H0(e,t){let n=performance.now(),r=Wo;for(;;){let o=await Yo(e,t);if(o!==null)return o;let i=performance.now()-n;if(i>=qo)return null;await Ko(Math.min(r,qo-i)),r=Math.min(r*2,Go)}}async function q0(e,t,n,r){let o=await H0(e,t);if(o===null){let i=await At(e,!1);throw zf(t,n,i.info,"fence_gate_unavailable")}try{let i=await At(e,!1);if(!Ca(i.info,t,n.owner,n.token))throw zf(t,n,i.info,i.info===null?"lease_released":"lease_taken_over");return await r()}finally{await o()}}function V0(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 B0(e,t,n,r){if(!n&&r){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 W0(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r=n.pid,o=n.token,i=n.process_start_identity;return typeof r!="number"||!Number.isInteger(r)||r<=0||typeof o!="string"||o.length===0||i!==void 0&&(typeof i!="string"||!/^\d+$/u.test(i))?null:{pid:r,token:o,host_identity:n.host_identity,...typeof i=="string"?{process_start_identity:i}:{}}}async function Vo(e){try{return W0(await ne.readFile(Se.join(e,Xf),"utf8"))}catch(t){return ee(t)?null:void 0}}async function Na(e){try{return await ne.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function Uf(e,t){let n=await Vo(e);for(let r=0;n===void 0&&r<3;r+=1)await Ko(Wo),n=await Vo(e);!n||n.token!==t||await Na(e)}async function Hf(e){try{await ne.mkdir(e)}catch(n){return Ze(n,"EEXIST"),null}let t={...await pr(),host_identity:(await Ta()).host_identity,token:Bo()};try{await ne.writeFile(Se.join(e,Xf),`${JSON.stringify(t)}
12
+ `,"utf8")}catch{return await Na(e),null}return t}async function qf(e,t){let n=Se.join(Se.dirname(e),"recoveries"),r=O0("sha256").update(t).digest("hex");try{return await ne.mkdir(n,{recursive:!0}),(await Vo(e))?.token!==t?!1:(await ne.rename(e,Se.join(n,`gate-${r}`)),!0)}catch{return!1}}async function G0(e){let t;try{let r=await ne.stat(e);t=Date.now()-r.mtimeMs}catch(r){return ee(r)}let n=await Vo(e);if(n===void 0)return!1;if(n!==null){if(await Ho(n)==="dead")return qf(e,n.token);if(n.host_identity!==void 0)return!1}return t<=Jf||n!==null&&await _r(n,t,Number.POSITIVE_INFINITY)?!1:n!==null?qf(e,n.token):Na(e)}async function Yo(e,t){let n=`${e}${P0}`,r=await Hf(n);if(r!==null)return async()=>Uf(n,r.token);if(!await G0(n))return null;let o=await Hf(n);return o===null?null:async()=>Uf(n,o.token)}async function K0(e,t){let n=Se.join(Se.dirname(e),"recoveries");await ne.mkdir(n,{recursive:!0}),await ne.writeFile(Se.join(n,`${Bo()}.json`),`${JSON.stringify({event:"owner_dead_recovery_attempt",recorded_at:Te(),lock:JSON.parse(t)})}
13
+ `,{encoding:"utf8",flag:"wx",mode:384})}async function Y0(e){let t=await Yo(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await At(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};let r=await Wf(n.info);if(!Bf(n.info,e.ttlSeconds)&&!r)return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(B0(e.id,n,e.force||r,e.forceRequiredForStaleLock),e.staleRemovals>=D0)throw await Zf(e.id,n.info,performance.now()-e.startedAtMs);return r&&await K0(e.lockPath,JSON.stringify(n.info)),{lockInfo:n,shouldRetryCreate:await xa(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function X0(e,t,n,r){if(e instanceof g&&e.code===Pf)throw e;if(!await I0(e,n))throw new g(`Failed to acquire lock for ${r}: ${dl(e)}`,h.GENERIC_FAILURE);await Mf(t,n,r)}async function fe(e,t,n,r,o=!1,i=!0,s,a={}){return(await J0(e,t,n,r,o,i,s,a)).release}async function J0(e,t,n,r,o=!1,i=!0,s,a={}){let c=Ra(a.maxWaitMs),d=await cn("lock_acquire",{pm_root:e,id:t,ttl_seconds:n,owner:r,force:o,force_required_for_stale_lock:i,...c===void 0?{}:{max_wait_ms:c}});if(d.handled){let T=V0(d.result);if(T)return{release:async()=>{await Promise.resolve(T()),await cn("lock_release",{pm_root:e,id:t,owner:r})},fence:H=>H()}}let l=fs(e,t),u=$0(s,c),f=L0(u,c,a.waitPolicy),m=j0(u,f),_=m.startedAtMs,y=0,w=Wo,v=Bo();for(;;)try{let T=await C0(e,l,t,r,n,v,a.createParentDirectories!==!1),H={owner:r,token:v,acquiredAt:T,ttlSeconds:n};return{release:async()=>{await R0(l,t,r,v),await cn("lock_release",{pm_root:e,id:t,owner:r})},fence:X=>q0(l,t,H,X)}}catch(T){await X0(T,e,l,t);let H=await At(l);if(await Gf(H.info,n)){let de=await Y0({lockPath:l,id:t,ttlSeconds:n,force:o,forceRequiredForStaleLock:i,staleRemovals:y,waitBudgetMs:u,startedAtMs:_,fallbackLockInfo:H});if(H=de.lockInfo,de.staleRemovalCounted&&(y+=1),de.shouldRetryCreate)continue}let X=m.observe(H.info);if(X.exhausted)throw await Zf(t,H.info,u===0?0:X.elapsedMs,X.ownerHandoffs);await Ko(Math.min(w,X.remainingMs)),w=Math.min(w*2,Go)}}import{createHash as Qf}from"node:crypto";import{existsSync as Da,promises as em,readFileSync as Z0}from"node:fs";import Re 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 Q0="session.json";function Pa(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function tm(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=["implementer","planner","release-operator"].includes(String(t.role)),r=["high","medium"].includes(String(t.confidence)),o=Pa(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=>Pa(c,128)),a=t.focused_item_id===void 0||Pa(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function ek(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=Object.entries(e).slice(0,128).flatMap(([n,r])=>{let o=tm(r);return o&&n.length<=128?[[n,o]]:[]});return t.length>0?Object.fromEntries(t):void 0}function Ma(e){return Re.join(ms(e),Q0)}async function nm(e){try{let t=await em.readFile(Ma(e),"utf8"),n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))return{};let r=n,o=r.focused_item,i=ek(r.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 $a(e,t){let n=await fe(e,"session-state",S.locks.ttl_seconds,"session-state",!1,!0,S.locks.wait_ms);try{let r=await nm(e);t(r);let o=Ma(e);await em.mkdir(Re.dirname(o),{recursive:!0}),await pt(o,JSON.stringify(r))}finally{await n()}}function ja(e){return/#([a-f0-9]{24})$/u.exec(e.trim())?.[1]??`author-${Qf("sha256").update(e).digest("hex").slice(0,24)}`}function La(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].slice(0,32).map(t=>t.slice(0,128))}function Fa(e){let t=[...new Set(e)].sort((r,o)=>r.localeCompare(o));if(t.length===1)return t[0];let n=`workset:${t.join("+")}`;return n.length<=256?n:`workset:${t.join("+").slice(0,230)}+${Qf("sha256").update(t.join("\0")).digest("hex").slice(0,12)}`}async function za(e,t,n){await $a(e,r=>{let o={...r.semantic_attribution},i=n(o[t]);i===void 0?delete o[t]:o[t]=i,Object.keys(o).length===0?delete r.semantic_attribution:r.semantic_attribution=o})}async function EM(e){let t=ja(e.principal);await za(e.pmRoot,t,n=>{let r=[...new Set([...n?.active_item_ids??[],e.itemId])].slice(-64).sort((i,s)=>i.localeCompare(s)),o=n?.focused_item_id;return{role:"implementer",topic:o??Fa(r),confidence:o?"high":"medium",rule_version:"v2",evidence:La([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}async function kM(e){let t=ja(e.principal);await za(e.pmRoot,t,n=>{if(!n)return;let r=n.active_item_ids.filter(i=>i!==e.itemId);if(r.length===0&&!n.focused_item_id)return;let o=n.focused_item_id;return{...n,role:"release-operator",topic:o??Fa(r),confidence:o?"high":"medium",evidence:La([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],`release:${e.itemId}`]),active_item_ids:r}})}async function SM(e){let t=ja(e.principal);await za(e.pmRoot,t,n=>{let r=n?.active_item_ids??[];if(!e.itemId&&r.length===0)return;let o=e.itemId;return{role:o?"planner":n.role,topic:o??Fa(r),confidence:o?"high":"medium",rule_version:"v2",evidence:La([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}function tk(e,t){let n=t.PM_PATH?.trim();if(n){let o=Re.resolve(e,n);if(Da(Re.join(o,"settings.json")))return o;let i=Re.join(o,".agents","pm");if(Da(Re.join(i,"settings.json")))return i}let r=Re.resolve(e);for(let o=0;o<32;o+=1){let i=Re.join(r,".agents","pm");if(Da(Re.join(i,"settings.json")))return i;let s=Re.dirname(r);if(s===r)break;r=s}}function rm(e){if(!e.key)return;let t=tk(e.cwd,e.env);if(t)try{let n=JSON.parse(Z0(Ma(t),"utf8"));return tm(n.semantic_attribution?.[e.key])}catch{return}}async function OM(e){return(await nm(e)).focused_item}async function AM(e,t){await $a(e,n=>{n.focused_item=t})}async function IM(e){await $a(e,t=>{delete t.focused_item})}import{AsyncLocalStorage as Ba}from"node:async_hooks";import{createHash as nk}from"node:crypto";import me from"node:fs";import am from"node:os";import Ct 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 Wa=["model","effort","role","topic","version"],Zo=new Ba,cm=new Ba,Qo=new Ba,Ga=[{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:[]}],dm=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),rk=Object.freeze({...dm,max_bytes:4194304}),Ua=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function ok(e){let t=et(e).provenance_unavailable_dimensions,n=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([...n].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(r=>r?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?rk:dm,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(r=>[r,"Harness does not expose this dimension."])))})}var lm=Object.freeze(Ga.filter(e=>e.harness!=="ci").map(ok).sort((e,t)=>e.harness.localeCompare(t.harness))),Tt=new Map,_n=new Map;function V(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function Qe(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function et(e){let t=e.harness.trim().toLowerCase();if(!Ua.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:Qe(e.environment_keys),model_environment_keys:Qe(e.model_environment_keys),session_environment_keys:Qe(e.session_environment_keys),provenance_environment_keys:Object.fromEntries(Object.entries(e.provenance_environment_keys??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),Qe(r)]).filter(([n])=>Ua.test(n))),provenance_resolvers:Object.fromEntries(Object.entries(e.provenance_resolvers??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),r]).filter(n=>typeof n[0]=="string"&&Ua.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:Qe(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:Qe(e.argv_markers).map(n=>n.toLowerCase()),client_names:Qe(e.client_names).map(n=>n.toLowerCase())}}var um=Ga.map(et);function ik(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Jo(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(n=>n.length>0).includes(t)||e.trim().toLowerCase()===t}function Ka(e=[]){let t=new Map(Ga.filter(o=>o.harness!=="ci").map(o=>[o.harness,et(o)]));for(let{adapter:o}of Tt.values())t.set(o.harness,et(o.descriptor));let n=[...t.values(),...um.filter(o=>o.harness==="ci"),...[..._n.values()].map(o=>o.descriptor),...Qo.getStore()?.descriptors??[],...e.map(et)],r=new Set;for(let o of n){if(r.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);r.add(o.harness)}return n}function Ya(e,t){for(let n of t??[]){let r=V(e[n]);if(r)return r.slice(0,256)}}function sk(e,t){if(t==="role"){let n=e.slice(0,8).map(r=>r.trim().toLowerCase()).find(r=>["claim","create","update","close","release","review"].includes(r));if(n==="review")return"reviewer";if(n)return"implementer"}}function fm(e,t){let n=t==="model"?["--model","--agent-model"]:[`--agent-${t}`],r=e.slice(0,8);for(let o=0;o<r.length;o+=1){let i=r[o].slice(0,512);if(n.includes(i))return V(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return V(i.slice(s.length+1))?.slice(0,256)}}var ak=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function It(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return ak.has(n)?n:void 0}function Ha(e,t){return V(e?.[t])?.slice(0,256)}var ck=1048576,Va=4194304,Xo=new Map,om=Object.freeze({}),qa=new Map,im=Object.freeze({});function sm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function dk(e){let t;try{t=JSON.parse(e)}catch{return im}let n=sm(t);if(!n)return im;let r=[{value:n,depth:0}],o=0,i,s;for(;r.length>0&&o<64;){let a=r.shift();if(o+=1,i??=V(a.value.model)?.slice(0,256),s??=V(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let d=sm(c);d&&r.push({value:d,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function mm(e){try{return me.lstatSync(e).isFile()?"available":"missing"}catch(t){return be(t)?"missing":"failed"}}function lk(e,t){let n;try{n=me.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name)).slice(0,512).map(o=>{let i=Ct.join(e,o.name,`${t}.jsonl`);return{candidate:i,status:mm(i)}})}catch(o){return{status:be(o)?"missing":"failed"}}let r=n.filter(({status:o})=>o==="available").map(({candidate:o})=>o);return r.length===0?{status:n.some(({status:o})=>o==="failed")?"failed":"missing"}:r.length>1?{status:"ambiguous"}:{status:"available",path:r[0]}}function pm(e,t){let n=V(t.CLAUDE_CODE_SESSION_ID);if(!n||!/^[A-Za-z0-9_-]{1,128}$/u.test(n))return{status:"unavailable"};let r=Ct.resolve(e.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),o=Ct.join(e.home_dir??am.homedir(),".claude","projects"),i=Ct.join(o,r,`${n}.jsonl`),s=V(e.session_file),a=s&&Ct.basename(s)===`${n}.jsonl`?s:void 0;for(let c of[a,i]){if(!c)continue;let d=mm(c);if(d==="available")return{status:d,path:c};if(d==="failed")return{status:d}}return lk(o,n)}function uk(e,t,n){let r=pm(t,n);if(r.status==="available")try{let o=me.openSync(r.path,me.constants.O_RDONLY|me.constants.O_NOFOLLOW);try{let i=me.fstatSync(o),s=`${r.path}\0${i.size}\0${i.mtimeMs}`,a=qa.get(s);if(a)return a[e];let c=Math.min(i.size,ck),d=Math.min(c,Math.ceil(c/2)),l=Math.min(c-d,i.size-d),u=Buffer.alloc(d);me.readSync(o,u,0,d,0);let f=Buffer.alloc(l);l>0&&me.readSync(o,f,0,l,i.size-l);let m={},_=i.size<=c?Buffer.concat([u,f]).toString("utf8").split(`
14
14
  `):[...u.toString("utf8").split(`
15
15
  `).slice(0,4096),...f.toString("utf8").split(`
16
16
  `).slice(-4096)];for(let w of _){if(w.length===0||w.length>262144)continue;let v=dk(w);if(m.model??=v.model,m.version??=v.version,m.model&&m.version)break}let y=Object.freeze(m);return qa.clear(),qa.set(s,y),y[e]}finally{me.closeSync(o)}}catch{return}}function fk(e,t){let n=0,r=(o,i)=>{if(i>4||n>=512)return;let s;try{s=me.readdirSync(o,{withFileTypes:!0}).sort((a,c)=>c.name.localeCompare(a.name))}catch{return}for(let a of s){if(n+=1,n>512)return;let c=Ct.join(o,a.name);if(a.isFile()&&a.name.endsWith(`-${t}.jsonl`))return c;if(a.isDirectory()){let d=r(c,i+1);if(d)return d}}};return r(e,0)}function mk(e){if(e<=Va)return[{offset:0,length:e}];let t=Math.floor(Va/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function pk(e,t){if(t.length===0||t.length>262144)return;let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;let r=n;if(r.type!=="turn_context")return;let o=typeof r.payload=="object"&&r.payload!==null?r.payload:void 0;e.model??=V(o?.model)?.slice(0,256),e.effort??=V(o?.effort)?.slice(0,256)}function _k(e,t){let n={},r=4096;for(let o of mk(t)){let i=Buffer.alloc(o.length);me.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
17
- `).reverse().slice(0,r);r-=s.length;for(let a of s)if(pk(n,a),n.model&&n.effort)break;if(n.model&&n.effort||r<=0)break}return n}function yk(e,t,n){let r=V(n.CODEX_THREAD_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let o=Ct.join(t.home_dir??sm.homedir(),".codex","sessions"),i=`${o}\0${r}`,s=Xo.get(i);if(s)return s[e];let a=fk(o,r);if(!a){Xo.set(i,rm);return}try{let c=me.openSync(a,"r");try{let d=me.fstatSync(c).size,l=_k(c,d);return Xo.set(i,l),l[e]}finally{me.closeSync(c)}}catch{Xo.set(i,rm);return}}function hk(e,t,n,r){let o=Qo.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(V(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let i=r?.provenance_resolvers[e];if(i==="claude_session_file")return uk(e,t,n);if(i==="codex_session_file")return yk(e,t,n);if(i==="ai_agent_version"){let s=V(n.AI_AGENT);return!s||!r||!Jo(s,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(s)?.[1]?.slice(0,256)}}function gk(e,t,n,r){if(e==="ai_agent_version"){let o=V(r.AI_AGENT);return o!==void 0&&Jo(o,t.harness)?"available":"unavailable"}return e==="codex_session_file"?V(r.CODEX_THREAD_ID)!==void 0?"available":"unavailable":mm(n,r).status}function Xa(e){return e||(am.getStore()??{env:process.env,argv:process.argv})}function bk(e,t,n,r){let o=e.environment_keys.some(a=>V(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let d=c.replaceAll("\\","/");return Jo(d.slice(d.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||Jo(r,a));return o||i||s}function wk(e,t){if(!t)return;let n;if(e==="topic"&&(n=t.topic),e==="role"&&(n=t.role),!!n)return{value:n,source:"inferred",confidence:t.confidence,rule_version:t.rule_version,evidence:t.evidence}}function vk(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function Ek(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...Wa,...Object.keys(r?.provenance_environment_keys??{})]),c,d,l;a.has(e)&&(c=It(e,V(n[s])?.slice(0,256)),l=It(e,um(t.argv??[],e)),d=It(e,sk(t.argv??[],e)));let u={...r?.provenance_environment_keys,model:r?.model_environment_keys},f={...t.client_info?.provenance,model:t.client_info?.model},m=Ha(o?.provenance,e),_=It(e,Ya(n,u[e])),y=It(e,Ha(f,e)),w=It(e,Ha(t.provenance,e)),v=hk(e,t,n,r);return vk([[c,"override"],[m,"session"],[l,"argv"],[_,"environment"],[y,"mcp_client"],[w,"host"],[v,"probe"]])??wk(e,i)??(d?{value:d,source:"argv"}:void 0)}function kk(e,t){if(!(!e||!t))return nk("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function Sk(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...Wa,...i,...Object.keys(n?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(r?.provenance??{})]),a={};for(let c of s){let d=Ek(c,e,t,n,r,o);d?a[c]=d:n&&(c!=="version"||n.provenance_unavailable_dimensions.includes(c))&&(a[c]=null)}return a}function $M(e){let t=e.map(et),n=new Map(lm.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness)||n.has(i.harness))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);let s=_n.get(i.harness);if(s&&!ik(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);r.add(i.harness)}for(let i of t){let s=_n.get(i.harness);_n.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=_n.get(i.harness);!s||s.registrations<=1?_n.delete(i.harness):s.registrations-=1}}}}function Ok(e){let t=et(e.descriptor),n=e.harness.trim().toLowerCase();if(e.contract_version!==1)throw new Error(`Unsupported provenance adapter contract for "${n}": ${e.contract_version}`);if(t.harness!==n)throw new Error(`Provenance adapter harness "${n}" does not match descriptor "${t.harness}".`);let r=V(e.adapter_version)?.slice(0,64);if(!r)throw new Error(`Provenance adapter "${n}" requires a version.`);if(!Number.isSafeInteger(e.priority))throw new Error(`Provenance adapter "${n}" requires an integer priority.`);if(e.probe_policy.network_access!==!1||e.probe_policy.subprocess_access!==!1||e.probe_policy.max_bytes>Va||e.probe_policy.max_lines>4096)throw new Error(`Provenance adapter "${n}" exceeds the bounded local probe policy.`);return Object.freeze({...e,adapter_version:r,harness:n,descriptor:t,supported_dimensions:Object.freeze(Qe(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 jM(){let e=new Map(dm.map(t=>[t.harness,t]));for(let{adapter:t}of Tt.values())e.set(t.harness,t);return Object.freeze([...e.values()].sort((t,n)=>t.harness.localeCompare(n.harness)))}function LM(e){let t=e.map(Ok),n=new Map(dm.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness))throw new Error(`Provenance adapter collision for "${i.harness}".`);let s=n.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=Tt.get(i.harness);if(a&&JSON.stringify(a.adapter)!==JSON.stringify(i))throw new Error(`Provenance adapter collision for "${i.harness}".`);r.add(i.harness)}for(let i of t){let s=Tt.get(i.harness);Tt.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=Tt.get(i.harness);!s||s.registrations<=1?Tt.delete(i.harness):s.registrations-=1}}}}function FM(e,t){let n=t.trim().slice(0,256),r=n.toLowerCase();if(e==="model"){let o=/^(gpt-\d+(?:\.\d+)?)/u.exec(r)?.[1];o&&(r=o)}else r=r.replaceAll(/[_\s-]+/gu,""),r={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max",ultra:"ultra"}[r]??r;return{raw:n,normalized:r,vocabulary:"v1"}}function zM(e,t){return am.run(e,t)}function UM(e,t,n={}){let r=e.map(et);return Ka(r),Qo.run({descriptors:r,probesEnabled:n.probesEnabled!==!1},t)}function Ja(e){let t=Xa(e),n=t.env??{},r=Ka(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=r.find(_=>bk(_,n,o,i)),a=Aa(t,n),c=[Ya(n,s?.session_environment_keys),V(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),d=kk(s?.harness,c),l=nm({cwd:t.cwd??process.cwd(),env:n,key:d}),u=Sk(t,n,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 Ak(e){return e==="unavailable"?{status:"unavailable",reason:"harness_unavailable"}:e==="missing"?{status:"unavailable",reason:"resolver_input_missing"}:{status:"failed",reason:"resolver_failed"}}function Ik(e,t,n,r,o,i,s){let a=n?.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=gk(a,n,r,o);return{...Ak(c),resolver:a,rule_version:"v1"}}return{status:n?.provenance_unavailable_dimensions.includes(e)?"unavailable":"not_configured",reason:n?.provenance_unavailable_dimensions.includes(e)?"harness_unavailable":"resolver_not_configured",rule_version:"v1"}}function pm(e){let t=Xa(e),n=Ja(t),r=Ka(t.descriptors).find(d=>d.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&Qo.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(V(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=Aa(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,Ya(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,um(t.argv??[],"role")].some(d=>{let l=V(d)?.slice(0,256);return l!==void 0&&It("role",l)===void 0}),c=Object.fromEntries(Wa.map(d=>[d,Ik(d,n,r,t,o,i,d==="role"&&a)]));return{...n,provenance_outcomes:c}}function HM(){return process.env.PM_AUTHOR}function qM(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function VM(e){return Ja(e).harness}function Tk(e,t,n){let r=Xa(n),o=Ja(r);if(e!==void 0){let s=V(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=V(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=V(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function _m(e){let t=Zo.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function ym(e){let t=Zo.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 BM(e){let t=Zo.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function hm(e,t){let n=Tk(e,t);return Zo.enterWith(n),n.author}import Ck 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]="58661057-fa80-5571-9be7-b949723c274b")}catch{}})();async function ei(e,t){let n=await Ck.readFile(e).catch(s=>{if(be(s))return null;throw s}),r=n?.toString("utf8")??null;if(r===null)return{raw:r,raw_bytes:n,entries:[]};if(await an({path:e,scope:"project"}),r.trim()==="")return{raw:r,raw_bytes:n,entries:[]};let o=Mo(r);if(o)throw new g(`History for ${t} contains merge conflict markers at line ${o.line} (${o.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 i=[];for(let[s,a]of r.split(/\r?\n/).entries()){let c=a.trim();if(c)try{i.push(JSON.parse(c))}catch{throw new g(`History for ${t} contains invalid JSON at line ${s+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,raw_bytes:n,entries:i}}async function Rt(e,t){return(await ei(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 e$=1,Rk=["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"],xk=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],Nk=new Set(Rk),Dk=new Set(xk),Pk=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 Mk(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 yn(e){return e.event_class==="substantive"||e.event_class==="maintenance"?e.event_class:Nk.has(e.op)?"maintenance":Dk.has(e.op)||e.op!=="update"?"substantive":Array.isArray(e.patch)&&e.patch.length>0&&e.patch.every(t=>{let n=Mk(t);return n!==void 0&&Pk.has(n)})?"maintenance":"substantive"}(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 wm=new WeakMap;function o$(e,t){wm.set(e,new Set(t))}var ti='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',$k={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"}},jk=[{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 i$(e,t,n){if(e&&t)throw new g(`${n} cannot be combined with --full`,h.USAGE)}function xe(e,t=new Set){let n=e.filter(r=>!t.has(r.name)).map(r=>({...r}));return{has_omissions:n.length>0,omitted_field_group_count:n.length,omitted_field_groups:n}}function s$(e,t){let n=jk.find(o=>o.command===e);if(n===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===n.complete_mode)return xe([]);let r=n.omissions_by_mode[t];if(r===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return xe(r)}var Lk=[{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 se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Fk=new Set([void 0,"tabular_when_uniform"]),zk=new Set(["collection","none"]),Uk=new Set(["supported","unsupported"]);function gm(e,t){return Array.isArray(e)&&(t||e.length>0)&&e.every(n=>typeof n=="string"&&n.length>0)&&new Set(e).size===e.length}function Hk(e){return se(e)&&typeof e.command=="string"&&e.command.trim().length>0&&zk.has(e.row_kind)&&gm(e.row_keys,!0)&&(e.continuation_row_keys===void 0||gm(e.continuation_row_keys,!1))&&Uk.has(e.fields)&&Fk.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 qk={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"]},Vk={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 Bk(e,t){let n=e.trim().toLowerCase().split(/\s+/u,1)[0],r=n?.startsWith("list-")?"list":n;if(r==="graph"){let s=typeof t.subcommand=="string"?t.subcommand:"";if(s.length===0)return;let a=qk[s];if(a===void 0)return;let c=a.filter(d=>Array.isArray(t[d])||se(t[d]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:ti}:{},toon_encoding:"tabular_when_uniform"}}let o=$k[r],i=Vk[r];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)=>se(d)?d[l]:void 0,t);return Array.isArray(c)||se(c)});return{command:r,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:ti}:{},toon_encoding:"tabular_when_uniform"}})()}function Wk(e){if(!se(e.projection)||typeof e.projection.mode!="string"||e.projection.mode.trim().length===0)return;let t=e.projection.declared_field_groups,n=e.projection.included_field_groups;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(s=>se(s)&&typeof s.name=="string"&&s.name.trim().length>0&&typeof s.restore_with=="string"&&s.restore_with.trim().length>0),o=n.filter(s=>typeof s=="string");if(r.length!==t.length||o.length!==n.length)return;let i=new Set(r.map(s=>s.name));if(!(i.size!==r.length||new Set(o).size!==o.length||o.some(s=>!i.has(s))))return xe(r,new Set(o))}function Gk(e){if(!Array.isArray(e.sections_included))return;let t=xe(Lk,new Set(e.sections_included.filter(n=>typeof n=="string")));return se(e.summary)&&e.summary.scope==="matching_items"&&(t.summary_scope="matching_items"),t}function Kk(e,t,n){return e==="dependency_provenance"?!1:Object.hasOwn(t,e)||(e==="reminders"||e==="events")&&se(n.schedule)&&Object.hasOwn(n.schedule,e)||["files","tests","docs"].includes(e)&&se(n.linked)&&Array.isArray(n.linked[e])&&n.linked[e].length>0}function Yk(e){if(!se(e.item))return;let t=e.item,n=["comments","notes","learnings","files","tests","docs","reminders","events"],r=["body","children","claim_state","linked","schedule"],o=wm.get(e),i=a=>n.includes(a)||a==="body"||a==="dependency_provenance"?t:e,s=["body",...n,...r.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 xe(s,new Set(s.flatMap(({name:a})=>Kk(a,i(a),e)?[a]:[])))}function bm(e){if(se(e.projection))return xe([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function Xk(e){if(!se(e.projection))return xe([]);if(typeof e.projection.mode=="string")return xe([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function Jk(e){if(!(!se(e.selected)||typeof e.selected.summary!="boolean"))return xe([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function Zk(e,t){let n=Wk(t);if(n!==void 0)return n;let[r]=e.split(/\s+/u,1);if(r==="context")return Gk(t);if(r==="get")return Yk(t);if(r==="list"||r.startsWith("list-"))return bm(t);if(r==="search")return bm(t)??xe([{name:"projection_metadata",restore_with:"--full"}]);if(r==="health")return Xk(t);if(r==="contracts")return Jk(t)}function vm(e,t){if(e===void 0||!se(t))return t;let n=Zk(e,t),r=t.row_contract,o=Hk(r)?r:Bk(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 se(i.omission_receipt)||n===void 0?i:{...i,omission_receipt: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]="b6db58d1-5d89-56b2-adee-13e985ebc675")}catch{}})();var Qk=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 J(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Em(e,t){let n=e;for(let r of t.split("."))if(Array.isArray(n)){if(!/^\d+$/u.test(r))return;n=n[Number(r)]}else{if(!J(n))return;n=n[r]}return n}function Za(e,t,n){let r=t.split("."),o=(i,s)=>{if(s===r.length)return n;let a=r[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 km(e,t,n){let r=hn(e).find(s=>s.path===t);if(!r)return e;let o=Array.isArray(r.value)?r.value.slice(n):Object.fromEntries(Object.entries(r.value).slice(n)),i=Za(e,t,o);return J(i.summary)&&J(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(n)}}),gr(i),i}function ri(e){let t=e.row_contract;return J(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function eS(e){let t=e.row_contract;return J(t)&&Array.isArray(t.continuation_row_keys)?t.continuation_row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):ri(e)}function tt(e){return ri(e).flatMap(t=>{let n=Em(e,t);return Array.isArray(n)||J(n)?[{path:t,value:n}]:[]})}function hn(e){return eS(e).flatMap(t=>{let n=Em(e,t);return Array.isArray(n)||J(n)?[{path:t,value:n}]:[]})}function yr(e){let t=tt(e),n=new Set(t.map(o=>o.path)),r=(o,i)=>{if(Array.isArray(o)){n.has(i)||t.push({path:i,value:o}),o.forEach((s,a)=>r(s,`${i}.${a}`));return}if(J(o))for(let[s,a]of Object.entries(o))i.length===0&&Qk.has(s)||r(a,i.length===0?s:`${i}.${s}`)};return r(e,""),t}function oi(e){return tt(e).reduce((t,n)=>t+(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length),0)}function hr(e,t){let n=e;for(let r of tt(n)){let o=Array.isArray(r.value)?r.value.map((i,s)=>t(i,r.path,s)):Object.fromEntries(Object.entries(r.value).map(([i,s],a)=>[i,t(s,r.path,a)]));n=Za(n,r.path,o)}return n}function Sm(e,t){let n=e,r=!1;for(let o of tt(n)){let i=Array.isArray(o.value)?o.value:Object.entries(o.value);if(i.length<=t)continue;r=!0;let s=Array.isArray(o.value)?i.slice(0,t):Object.fromEntries(i.slice(0,t));n=Za(n,o.path,s)}return{result:n,truncated:r}}var Om=["high_level","low_level","blocked_fallback"];function ni(e){let t=e.status==="in_progress"?"i":"o";return e.blocked===!0?t.toUpperCase():t}function c$(e,t){if(!J(e.summary)||!J(e.summary.returned_focus))return;let n=new Map(t.map(r=>[r.id,r]));e.summary={...e.summary,focus_row_states:Object.fromEntries(Om.map(r=>[r,Array.isArray(e[r])?e[r].filter(J).map(o=>ni(n.get(o.id)??o)).join(""):""]))}}function tS(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 nS(e,t,n,r){let o=Array.isArray(t[n])?t[n].filter(J):[],i=tS(r[n],o.length)??o.map(ni).join(""),s=new Map(o.flatMap((d,l)=>d.id===void 0?[]:[[d.id,i[l]]])),a=Array.isArray(e[n])?e[n].filter(J):[],c=!1;return{states:a.map((d,l)=>{let u=s.get(d.id)??(d.id===void 0?i[l]:void 0)??ni(d);return u!==ni(d)&&(c=!0),u}).join(""),needsStates:c}}function rS(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 gr(e,t=e){if(rS(e,t),!J(e.summary)||!J(e.summary.returned_focus))return;let n={...e.summary},r=J(t.summary)&&J(t.summary.focus_row_states)?t.summary.focus_row_states:{},o=Om.map(c=>({key:c,...nS(e,t,c,r)})),i=Object.fromEntries(o.map(({key:c,states:d})=>[c,d])),s=o.some(c=>c.needsStates),a=Object.values(i).join("");typeof n.high_level=="number"&&(n.high_level=Array.isArray(e.high_level)?e.high_level.length:0),typeof n.low_level=="number"&&(n.low_level=Array.isArray(e.low_level)?e.low_level.length:0),n.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?n.focus_row_states=i:delete n.focus_row_states,e.summary=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]="ea19c980-44aa-54eb-b853-d829335e520e")}catch{}})();var ii="changed_fields",oS="changed_field_count",Qa="rows",iS=new Set(["apply","rollback"]),Cm=new Set(["deleted","would_delete"]),Am=256,Im={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function sS(e,t){if(!ae(e)||typeof e.action!="string"||typeof e.id!="string"||e.id.length===0)return null;let n=Object.hasOwn(Im,e.action)?Im[e.action]:void 0;if(!n||!n.every(i=>{let s=e[i];return ae(s)&&ae(s.item)&&s.item.id===e.id&&Array.isArray(s.changed_fields)&&s.changed_fields.every(a=>typeof a=="string")}))return null;let r=e[n.at(-1)],o=xm(r);return t.idOnly?o:!t.compactEnvelope&&t.changedFields!=="compact"?null:{...e,...t.compactEnvelope?{...o,changed_field_count:new Set(n.flatMap(i=>e[i].changed_fields)).size}:{},...Object.fromEntries(n.map(i=>[i,br(e[i],t)]))}}function Tm(e){return typeof e!="string"||e.length<=Am?e:`${Ee(e,Am-1)}\u2026`}function aS(e){if(!ae(e))return null;let t={...e};return t.reason=Tm(t.reason),ae(t.previous_terminal)&&(t.previous_terminal=Object.fromEntries(Object.entries(t.previous_terminal).map(([n,r])=>[n,Tm(r)]))),t}function ae(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Rm(e){let t=e[ii];if(!Array.isArray(t))return null;let n=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[r,o]of Object.entries(e))r!==ii&&(n[r]=o);return n[oS]=t.length,n}function cS(e){return"item"in e&&Array.isArray(e[ii])}function dS(e){return typeof e.mode=="string"&&iS.has(e.mode)&&Array.isArray(e[Qa])}function lS(e,t){let n=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(n,e),n[Qa]=t,n}function xm(e){if(!ae(e))return null;let t=ae(e.item)?e.item:ae(e.plan)?e.plan:null;if(t===null)return null;let n=typeof t.id=="string"?t.id:void 0,r=typeof e.outcome=="string"&&Cm.has(e.outcome)?e.outcome:typeof t.status=="string"?t.status:void 0;return n?r?{id:n,status:r,...typeof e.deleted=="boolean"?{deleted:e.deleted}:{}}:{id:n}:null}function uS(e,t){if(!ae(e))return null;if(ae(e.plan)&&ae(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||!ae(e.item)||typeof e.item.id!="string")return null;let n=e[ii];if(!Array.isArray(n))return null;let r={id:e.item.id,...typeof e.outcome=="string"&&Cm.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:n.length};return fS(e,e.item,r),r}function fS(e,t,n){let r=typeof e.close_reason=="string"?e.close_reason:typeof t.close_reason=="string"?t.close_reason:void 0;r!==void 0&&(n.close_reason=r);let o=aS(e.recurrence);o!==null&&(n.recurrence=o),Array.isArray(e.warnings)&&e.warnings.length>0&&(n.warnings=e.warnings);for(let i of["recovery","follow_up","handoff","completion","start"])ae(e[i])&&(n[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)&&(n[i]=e[i])}function mS(e){let t=dS(e)?e[Qa]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let n=!1,r=t.map(o=>{if(!ae(o))return o;let i=Rm(o);return i?(n=!0,i):o});return n?{projected:lS(e,r),changed:!0}:{projected:e,changed:!1}}function br(e,t={}){let n=sS(e,t);if(n!==null)return n;if(t.idOnly===!0){let a=xm(e);if(a!==null)return a}if(t.compactEnvelope===!0||t.changedFields==="compact"){let a=uS(e,t.compactEnvelope===!0);if(a!==null)return a}if((t.changedFields??"full")==="full"||!ae(e))return e;let r=!1,o=e,i=cS(e)?Rm(e):null;i!==null&&(o=i,r=!0);let s=mS(o);return s.changed&&(o=s.projected,r=!0),r?o:e}import{AsyncLocalStorage as UO}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 ec(e){let t=e.trim().toLowerCase().startsWith("extension:"),n=e.trim().toLowerCase().replace(/^extension:/u,"");if(en(n))return;let r=$u()?.commands??[],o=[...r].reverse().find(s=>s.command===n)?.command??(t?void 0:r.find(s=>s.action===n)?.command),i=[...r].reverse().find(s=>s.command===o);return i===void 0||en(i.command)||en(i.action)?void 0:i}function pS(e){let t=ec(e);return t?.read_output===void 0?void 0:t}function Nm(e,t){let n=pS(e),r=n?.read_output;if(r===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 r.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:${n.command}`,row_kind:r.row_keys.length>0?"collection":"none",row_keys:[...r.row_keys],fields:"supported",...r.row_keys.length>0?{jq_selector:ti}:{},toon_encoding:"tabular_when_uniform"}}}import{createHash as kO}from"node:crypto";import{createHash as gO}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]="03289358-031e-50aa-b94b-644697c4afc7")}catch{}})();var tc={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"],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","--after"],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:{}},nc=new Set(["--collapse","--fields","--section"]),si=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 ai(e){return e.slice(2).replaceAll("-","_")}function Dm(e,t={}){let n=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],r=n.startsWith("list-")?"list":n==="ctx"?"context":n;return ht.includes(r)?r:void 0}function rc(e){return new Map((tc[e]?.include??[]).filter(t=>!nc.has(t)&&si[t]===void 0).map(t=>[ai(t),oc(t)]))}function oc(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}import{stripVTControlCharacters as _S}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]="493a0675-0114-5b93-b3b4-5bd895ac691f")}catch{}})();var yS=["full","compact","brief","summary","counts"],S$=["mutation","read","discovery","governance"],Mm=["error","warning","validation_summary","recovery_bundle"],hS=["full","omit_explanation","limit_collections","compact_recovery","action_only"],gS=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"]),bS=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),wS=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),vS={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},ES=3,kS=2,SS=192,OS={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},AS=Mm.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:OS[e],minimum_max_estimated_tokens:SS,degradation_ladder:hS,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),IS=new Map(AS.map(e=>[e.diagnostic_class,e]));function TS(e){let[t=""]=$n(e).split(/\s+/u);return gS.has(t)?"mutation":bS.has(t)?"discovery":wS.has(t)?"governance":"read"}function $m(e,t=TS(e)){let n=e.trim().replace(/\s+/gu," ");if(n.length===0)throw new TypeError("command must be a non-empty command path");let r=vS[t];return CS({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*ES/kS)},degradation_ladder:yS,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function CS(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,n]of Object.entries(e.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${t} must be a positive safe integer`);return e}var RS=Gr.map(e=>$m(e)),xS=new Map(RS.map(e=>[e.command,e]));function jm(e,t={}){let n=e.trim().replace(/\s+/gu," "),[r]=$n(n).split(" "),o=xS.get(r);return o?{...o,command:n}:t.generateFallback?$m(n):null}function Nt(e){return Math.ceil(Math.max(0,e)/4)}function Lm(e){let t=IS.get(e);if(t===void 0)throw new TypeError(`diagnosticClass must be one of: ${Mm.join(", ")}`);return t}function nt(e){return Nt(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))}function NS(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ic(e){if(!NS(e))return;let t={};for(let n of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms","waited_ms","owner_handoffs"]){let r=e[n];Array.isArray(r)?t[n]=n==="suggested_retry_args"?r:r.slice(0,3):r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function DS(e,t){return typeof e!="string"||e.length<=t?e:`${Ee(e,Math.max(1,t-3))}...`}function xt(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let n="...",r=Array.from(e),o=0,i=r.length;for(;o<i;){let s=Math.ceil((o+i)/2),a=`${r.slice(0,s).join("")}${n}`;Buffer.byteLength(a,"utf8")<=t?o=s:i=s-1}return`${r.slice(0,o).join("")}${n}`}function Fm(e){let t={};for(let n of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(e,n)&&e[n]!==void 0&&(t[n]=e[n]);for(let[n,r]of Object.entries(e))n!=="__proto__"&&!Object.hasOwn(t,n)&&(t[n]=r);return t}var PS=new Set(["limit_collections","compact_recovery","action_only"]),MS=new Set(["compact_recovery","action_only"]);function $S(e){let t={code:typeof e.code=="string"?e.code:"diagnostic",required:DS(e.required,160)??"Inspect the diagnostic code and retry with corrected input."},n=ic(e.recovery);return n!==void 0?t.recovery=n: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 jS(e,t){let n=structuredClone(e);if(t!=="full"&&(delete n.why,delete n.examples),PS.has(t))for(let[r,o]of Object.entries(n))Array.isArray(o)&&(n[r]=o.slice(0,3));if(MS.has(t)){let r=ic(n.recovery);r?n.recovery=r:delete n.recovery}return t!=="action_only"?Fm(n):$S(n)}function gn(e,t){let n={...e,diagnostic_output:{...t,estimated_tokens:0}};for(let r=0;r<4;r+=1){let o=nt(n),i=n.diagnostic_output;if(i.estimated_tokens===o)break;i.estimated_tokens=o}return n}function LS(e,t,n){let r=gn(e,t);for(let i of["recovery","exit_code"])nt(r)<=n||e[i]===void 0||(delete e[i],r=gn(e,t));let o=40;for(;nt(r)>n&&o>4;)o-=4,e.code=xt(String(e.code),o),e.required=xt(String(e.required),o),r=gn(e,t);return r}function FS(e,t){let n=e.diagnostic_output,{estimated_tokens:r,...o}=n,i=o.omitted_fields.slice(0,8).map(u=>xt(u,32)),s={...o,omitted_fields:i,...o.omitted_fields.length>i.length?{omitted_fields_overflow_count:o.omitted_fields.length-i.length}:{}},a=ic(e.recovery),c=a&&nt(a)<=48?a:void 0,d={code:xt(String(e.code),320),required:xt(String(e.required),320),...c?{recovery:c}:{},...e.exit_code!==void 0?{exit_code:e.exit_code}:{}},l=gn(d,s);for(;nt(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=gn(d,s);return l=LS(d,s,t),l}function O$(e,t={}){let n=e,r=t.diagnosticClass??"error",o=Lm(r),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=nt(n),c=Object.keys(n);if(a<=s)return Fm(structuredClone(n));let d;for(let[l,u]of o.degradation_ladder.entries()){let f=jS(n,u),m=c.filter(y=>!Object.hasOwn(f,y)),_=gn(f,{diagnostic_class:r,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=_,nt(_)<=s)break}return nt(d)>s&&(d=FS(d,s)),d}function Pm(e){return _S(e).replace(/\r\n/gu,`
18
- `).replace(/[^\P{Cc}\n]/gu," ")}function A$(e,t,n={}){let r=n.diagnosticClass??"error",o=Lm(r),i=n.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=Pm(e),c=Nt(Buffer.byteLength(a,"utf8")),d=c>s,l=`What is required:
17
+ `).reverse().slice(0,r);r-=s.length;for(let a of s)if(pk(n,a),n.model&&n.effort)break;if(n.model&&n.effort||r<=0)break}return n}function yk(e,t,n){let r=V(n.CODEX_THREAD_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let o=Ct.join(t.home_dir??am.homedir(),".codex","sessions"),i=`${o}\0${r}`,s=Xo.get(i);if(s)return s[e];let a=fk(o,r);if(!a){Xo.set(i,om);return}try{let c=me.openSync(a,"r");try{let d=me.fstatSync(c).size,l=_k(c,d);return Xo.set(i,l),l[e]}finally{me.closeSync(c)}}catch{Xo.set(i,om);return}}function hk(e,t,n,r){let o=Qo.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(V(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let i=r?.provenance_resolvers[e];if(i==="claude_session_file")return uk(e,t,n);if(i==="codex_session_file")return yk(e,t,n);if(i==="ai_agent_version"){let s=V(n.AI_AGENT);return!s||!r||!Jo(s,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(s)?.[1]?.slice(0,256)}}function gk(e,t,n,r){if(e==="ai_agent_version"){let o=V(r.AI_AGENT);return o!==void 0&&Jo(o,t.harness)?"available":"unavailable"}return e==="codex_session_file"?V(r.CODEX_THREAD_ID)!==void 0?"available":"unavailable":pm(n,r).status}function Xa(e){return e||(cm.getStore()??{env:process.env,argv:process.argv})}function bk(e,t,n,r){let o=e.environment_keys.some(a=>V(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let d=c.replaceAll("\\","/");return Jo(d.slice(d.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||Jo(r,a));return o||i||s}function wk(e,t){if(!t)return;let n;if(e==="topic"&&(n=t.topic),e==="role"&&(n=t.role),!!n)return{value:n,source:"inferred",confidence:t.confidence,rule_version:t.rule_version,evidence:t.evidence}}function vk(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function Ek(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...Wa,...Object.keys(r?.provenance_environment_keys??{})]),c,d,l;a.has(e)&&(c=It(e,V(n[s])?.slice(0,256)),l=It(e,fm(t.argv??[],e)),d=It(e,sk(t.argv??[],e)));let u={...r?.provenance_environment_keys,model:r?.model_environment_keys},f={...t.client_info?.provenance,model:t.client_info?.model},m=Ha(o?.provenance,e),_=It(e,Ya(n,u[e])),y=It(e,Ha(f,e)),w=It(e,Ha(t.provenance,e)),v=hk(e,t,n,r);return vk([[c,"override"],[m,"session"],[l,"argv"],[_,"environment"],[y,"mcp_client"],[w,"host"],[v,"probe"]])??wk(e,i)??(d?{value:d,source:"argv"}:void 0)}function kk(e,t){if(!(!e||!t))return nk("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function Sk(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...Wa,...i,...Object.keys(n?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(r?.provenance??{})]),a={};for(let c of s){let d=Ek(c,e,t,n,r,o);d?a[c]=d:n&&(c!=="version"||n.provenance_unavailable_dimensions.includes(c))&&(a[c]=null)}return a}function jM(e){let t=e.map(et),n=new Map(um.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness)||n.has(i.harness))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);let s=_n.get(i.harness);if(s&&!ik(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);r.add(i.harness)}for(let i of t){let s=_n.get(i.harness);_n.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=_n.get(i.harness);!s||s.registrations<=1?_n.delete(i.harness):s.registrations-=1}}}}function Ok(e){let t=et(e.descriptor),n=e.harness.trim().toLowerCase();if(e.contract_version!==1)throw new Error(`Unsupported provenance adapter contract for "${n}": ${e.contract_version}`);if(t.harness!==n)throw new Error(`Provenance adapter harness "${n}" does not match descriptor "${t.harness}".`);let r=V(e.adapter_version)?.slice(0,64);if(!r)throw new Error(`Provenance adapter "${n}" requires a version.`);if(!Number.isSafeInteger(e.priority))throw new Error(`Provenance adapter "${n}" requires an integer priority.`);if(e.probe_policy.network_access!==!1||e.probe_policy.subprocess_access!==!1||e.probe_policy.max_bytes>Va||e.probe_policy.max_lines>4096)throw new Error(`Provenance adapter "${n}" exceeds the bounded local probe policy.`);return Object.freeze({...e,adapter_version:r,harness:n,descriptor:t,supported_dimensions:Object.freeze(Qe(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 LM(){let e=new Map(lm.map(t=>[t.harness,t]));for(let{adapter:t}of Tt.values())e.set(t.harness,t);return Object.freeze([...e.values()].sort((t,n)=>t.harness.localeCompare(n.harness)))}function FM(e){let t=e.map(Ok),n=new Map(lm.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness))throw new Error(`Provenance adapter collision for "${i.harness}".`);let s=n.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=Tt.get(i.harness);if(a&&JSON.stringify(a.adapter)!==JSON.stringify(i))throw new Error(`Provenance adapter collision for "${i.harness}".`);r.add(i.harness)}for(let i of t){let s=Tt.get(i.harness);Tt.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=Tt.get(i.harness);!s||s.registrations<=1?Tt.delete(i.harness):s.registrations-=1}}}}function zM(e,t){let n=t.trim().slice(0,256),r=n.toLowerCase();if(e==="model"){let o=/^(gpt-\d+(?:\.\d+)?)/u.exec(r)?.[1];o&&(r=o)}else r=r.replaceAll(/[_\s-]+/gu,""),r={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max",ultra:"ultra"}[r]??r;return{raw:n,normalized:r,vocabulary:"v1"}}function UM(e,t){return cm.run(e,t)}function HM(e,t,n={}){let r=e.map(et);return Ka(r),Qo.run({descriptors:r,probesEnabled:n.probesEnabled!==!1},t)}function Ja(e){let t=Xa(e),n=t.env??{},r=Ka(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=r.find(_=>bk(_,n,o,i)),a=Aa(t,n),c=[Ya(n,s?.session_environment_keys),V(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),d=kk(s?.harness,c),l=rm({cwd:t.cwd??process.cwd(),env:n,key:d}),u=Sk(t,n,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 Ak(e){return e==="unavailable"?{status:"unavailable",reason:"harness_unavailable"}:e==="missing"?{status:"unavailable",reason:"resolver_input_missing"}:{status:"failed",reason:"resolver_failed"}}function Ik(e,t,n,r,o,i,s){let a=n?.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=gk(a,n,r,o);return{...Ak(c),resolver:a,rule_version:"v1"}}return{status:n?.provenance_unavailable_dimensions.includes(e)?"unavailable":"not_configured",reason:n?.provenance_unavailable_dimensions.includes(e)?"harness_unavailable":"resolver_not_configured",rule_version:"v1"}}function _m(e){let t=Xa(e),n=Ja(t),r=Ka(t.descriptors).find(d=>d.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&Qo.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(V(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=Aa(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,Ya(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,fm(t.argv??[],"role")].some(d=>{let l=V(d)?.slice(0,256);return l!==void 0&&It("role",l)===void 0}),c=Object.fromEntries(Wa.map(d=>[d,Ik(d,n,r,t,o,i,d==="role"&&a)]));return{...n,provenance_outcomes:c}}function qM(){return process.env.PM_AUTHOR}function VM(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function BM(e){return Ja(e).harness}function Tk(e,t,n){let r=Xa(n),o=Ja(r);if(e!==void 0){let s=V(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=V(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=V(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function ym(e){let t=Zo.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function hm(e){let t=Zo.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 WM(e){let t=Zo.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function gm(e,t){let n=Tk(e,t);return Zo.enterWith(n),n.author}import Ck 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]="58661057-fa80-5571-9be7-b949723c274b")}catch{}})();async function ei(e,t){let n=await Ck.readFile(e).catch(s=>{if(be(s))return null;throw s}),r=n?.toString("utf8")??null;if(r===null)return{raw:r,raw_bytes:n,entries:[]};if(await an({path:e,scope:"project"}),r.trim()==="")return{raw:r,raw_bytes:n,entries:[]};let o=Mo(r);if(o)throw new g(`History for ${t} contains merge conflict markers at line ${o.line} (${o.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 i=[];for(let[s,a]of r.split(/\r?\n/).entries()){let c=a.trim();if(c)try{i.push(JSON.parse(c))}catch{throw new g(`History for ${t} contains invalid JSON at line ${s+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,raw_bytes:n,entries:i}}async function Rt(e,t){return(await ei(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 t$=1,Rk=["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"],xk=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],Nk=new Set(Rk),Dk=new Set(xk),Pk=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 Mk(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 yn(e){return e.event_class==="substantive"||e.event_class==="maintenance"?e.event_class:Nk.has(e.op)?"maintenance":Dk.has(e.op)||e.op!=="update"?"substantive":Array.isArray(e.patch)&&e.patch.length>0&&e.patch.every(t=>{let n=Mk(t);return n!==void 0&&Pk.has(n)})?"maintenance":"substantive"}(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 vm=new WeakMap;function i$(e,t){vm.set(e,new Set(t))}var ti='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',$k={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"}},jk=[{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 s$(e,t,n){if(e&&t)throw new g(`${n} cannot be combined with --full`,h.USAGE)}function xe(e,t=new Set){let n=e.filter(r=>!t.has(r.name)).map(r=>({...r}));return{has_omissions:n.length>0,omitted_field_group_count:n.length,omitted_field_groups:n}}function a$(e,t){let n=jk.find(o=>o.command===e);if(n===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===n.complete_mode)return xe([]);let r=n.omissions_by_mode[t];if(r===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return xe(r)}var Lk=[{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 se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Fk=new Set([void 0,"tabular_when_uniform"]),zk=new Set(["collection","none"]),Uk=new Set(["supported","unsupported"]);function bm(e,t){return Array.isArray(e)&&(t||e.length>0)&&e.every(n=>typeof n=="string"&&n.length>0)&&new Set(e).size===e.length}function Hk(e){return se(e)&&typeof e.command=="string"&&e.command.trim().length>0&&zk.has(e.row_kind)&&bm(e.row_keys,!0)&&(e.continuation_row_keys===void 0||bm(e.continuation_row_keys,!1))&&Uk.has(e.fields)&&Fk.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 qk={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"]},Vk={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 Bk(e,t){let n=e.trim().toLowerCase().split(/\s+/u,1)[0],r=n?.startsWith("list-")?"list":n;if(r==="graph"){let s=typeof t.subcommand=="string"?t.subcommand:"";if(s.length===0)return;let a=qk[s];if(a===void 0)return;let c=a.filter(d=>Array.isArray(t[d])||se(t[d]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:ti}:{},toon_encoding:"tabular_when_uniform"}}let o=$k[r],i=Vk[r];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)=>se(d)?d[l]:void 0,t);return Array.isArray(c)||se(c)});return{command:r,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:ti}:{},toon_encoding:"tabular_when_uniform"}})()}function Wk(e){if(!se(e.projection)||typeof e.projection.mode!="string"||e.projection.mode.trim().length===0)return;let t=e.projection.declared_field_groups,n=e.projection.included_field_groups;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(s=>se(s)&&typeof s.name=="string"&&s.name.trim().length>0&&typeof s.restore_with=="string"&&s.restore_with.trim().length>0),o=n.filter(s=>typeof s=="string");if(r.length!==t.length||o.length!==n.length)return;let i=new Set(r.map(s=>s.name));if(!(i.size!==r.length||new Set(o).size!==o.length||o.some(s=>!i.has(s))))return xe(r,new Set(o))}function Gk(e){if(!Array.isArray(e.sections_included))return;let t=xe(Lk,new Set(e.sections_included.filter(n=>typeof n=="string")));return se(e.summary)&&e.summary.scope==="matching_items"&&(t.summary_scope="matching_items"),t}function Kk(e,t,n){return e==="dependency_provenance"?!1:Object.hasOwn(t,e)||(e==="reminders"||e==="events")&&se(n.schedule)&&Object.hasOwn(n.schedule,e)||["files","tests","docs"].includes(e)&&se(n.linked)&&Array.isArray(n.linked[e])&&n.linked[e].length>0}function Yk(e){if(!se(e.item))return;let t=e.item,n=["comments","notes","learnings","files","tests","docs","reminders","events"],r=["body","children","claim_state","linked","schedule"],o=vm.get(e),i=a=>n.includes(a)||a==="body"||a==="dependency_provenance"?t:e,s=["body",...n,...r.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 xe(s,new Set(s.flatMap(({name:a})=>Kk(a,i(a),e)?[a]:[])))}function wm(e){if(se(e.projection))return xe([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function Xk(e){if(!se(e.projection))return xe([]);if(typeof e.projection.mode=="string")return xe([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function Jk(e){if(!(!se(e.selected)||typeof e.selected.summary!="boolean"))return xe([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function Zk(e,t){let n=Wk(t);if(n!==void 0)return n;let[r]=e.split(/\s+/u,1);if(r==="context")return Gk(t);if(r==="get")return Yk(t);if(r==="list"||r.startsWith("list-"))return wm(t);if(r==="search")return wm(t)??xe([{name:"projection_metadata",restore_with:"--full"}]);if(r==="health")return Xk(t);if(r==="contracts")return Jk(t)}function Em(e,t){if(e===void 0||!se(t))return t;let n=Zk(e,t),r=t.row_contract,o=Hk(r)?r:Bk(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 se(i.omission_receipt)||n===void 0?i:{...i,omission_receipt: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]="b6db58d1-5d89-56b2-adee-13e985ebc675")}catch{}})();var Qk=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 J(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function km(e,t){let n=e;for(let r of t.split("."))if(Array.isArray(n)){if(!/^\d+$/u.test(r))return;n=n[Number(r)]}else{if(!J(n))return;n=n[r]}return n}function Za(e,t,n){let r=t.split("."),o=(i,s)=>{if(s===r.length)return n;let a=r[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 Sm(e,t,n){let r=hn(e).find(s=>s.path===t);if(!r)return e;let o=Array.isArray(r.value)?r.value.slice(n):Object.fromEntries(Object.entries(r.value).slice(n)),i=Za(e,t,o);return J(i.summary)&&J(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(n)}}),gr(i),i}function ri(e){let t=e.row_contract;return J(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function eS(e){let t=e.row_contract;return J(t)&&Array.isArray(t.continuation_row_keys)?t.continuation_row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):ri(e)}function tt(e){return ri(e).flatMap(t=>{let n=km(e,t);return Array.isArray(n)||J(n)?[{path:t,value:n}]:[]})}function hn(e){return eS(e).flatMap(t=>{let n=km(e,t);return Array.isArray(n)||J(n)?[{path:t,value:n}]:[]})}function yr(e){let t=tt(e),n=new Set(t.map(o=>o.path)),r=(o,i)=>{if(Array.isArray(o)){n.has(i)||t.push({path:i,value:o}),o.forEach((s,a)=>r(s,`${i}.${a}`));return}if(J(o))for(let[s,a]of Object.entries(o))i.length===0&&Qk.has(s)||r(a,i.length===0?s:`${i}.${s}`)};return r(e,""),t}function oi(e){return tt(e).reduce((t,n)=>t+(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length),0)}function hr(e,t){let n=e;for(let r of tt(n)){let o=Array.isArray(r.value)?r.value.map((i,s)=>t(i,r.path,s)):Object.fromEntries(Object.entries(r.value).map(([i,s],a)=>[i,t(s,r.path,a)]));n=Za(n,r.path,o)}return n}function Om(e,t){let n=e,r=!1;for(let o of tt(n)){let i=Array.isArray(o.value)?o.value:Object.entries(o.value);if(i.length<=t)continue;r=!0;let s=Array.isArray(o.value)?i.slice(0,t):Object.fromEntries(i.slice(0,t));n=Za(n,o.path,s)}return{result:n,truncated:r}}var Am=["high_level","low_level","blocked_fallback"];function ni(e){let t=e.status==="in_progress"?"i":"o";return e.blocked===!0?t.toUpperCase():t}function d$(e,t){if(!J(e.summary)||!J(e.summary.returned_focus))return;let n=new Map(t.map(r=>[r.id,r]));e.summary={...e.summary,focus_row_states:Object.fromEntries(Am.map(r=>[r,Array.isArray(e[r])?e[r].filter(J).map(o=>ni(n.get(o.id)??o)).join(""):""]))}}function tS(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 nS(e,t,n,r){let o=Array.isArray(t[n])?t[n].filter(J):[],i=tS(r[n],o.length)??o.map(ni).join(""),s=new Map(o.flatMap((d,l)=>d.id===void 0?[]:[[d.id,i[l]]])),a=Array.isArray(e[n])?e[n].filter(J):[],c=!1;return{states:a.map((d,l)=>{let u=s.get(d.id)??(d.id===void 0?i[l]:void 0)??ni(d);return u!==ni(d)&&(c=!0),u}).join(""),needsStates:c}}function rS(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 gr(e,t=e){if(rS(e,t),!J(e.summary)||!J(e.summary.returned_focus))return;let n={...e.summary},r=J(t.summary)&&J(t.summary.focus_row_states)?t.summary.focus_row_states:{},o=Am.map(c=>({key:c,...nS(e,t,c,r)})),i=Object.fromEntries(o.map(({key:c,states:d})=>[c,d])),s=o.some(c=>c.needsStates),a=Object.values(i).join("");typeof n.high_level=="number"&&(n.high_level=Array.isArray(e.high_level)?e.high_level.length:0),typeof n.low_level=="number"&&(n.low_level=Array.isArray(e.low_level)?e.low_level.length:0),n.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?n.focus_row_states=i:delete n.focus_row_states,e.summary=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]="2335ae7f-c7aa-5bdd-ac2e-e6d7a74be2e1")}catch{}})();var ii="changed_fields",oS="changed_field_count",Qa="rows",iS=new Set(["apply","rollback"]),Rm=new Set(["deleted","would_delete"]),Im=256,Tm={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function sS(e,t){if(!ae(e)||typeof e.action!="string"||typeof e.id!="string"||e.id.length===0)return null;let n=Object.hasOwn(Tm,e.action)?Tm[e.action]:void 0;if(!n||!n.every(i=>{let s=e[i];return ae(s)&&ae(s.item)&&s.item.id===e.id&&Array.isArray(s.changed_fields)&&s.changed_fields.every(a=>typeof a=="string")}))return null;let r=e[n.at(-1)],o=Nm(r);return t.idOnly?o:!t.compactEnvelope&&t.changedFields!=="compact"?null:{...e,...t.compactEnvelope?{...o,changed_field_count:new Set(n.flatMap(i=>e[i].changed_fields)).size}:{},...Object.fromEntries(n.map(i=>[i,br(e[i],t)]))}}function Cm(e){return typeof e!="string"||e.length<=Im?e:`${Ee(e,Im-1)}\u2026`}function aS(e){if(!ae(e))return null;let t={...e};return t.reason=Cm(t.reason),ae(t.previous_terminal)&&(t.previous_terminal=Object.fromEntries(Object.entries(t.previous_terminal).map(([n,r])=>[n,Cm(r)]))),t}function ae(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function xm(e){let t=e[ii];if(!Array.isArray(t))return null;let n=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[r,o]of Object.entries(e))r!==ii&&(n[r]=o);return n[oS]=t.length,n}function cS(e){return"item"in e&&Array.isArray(e[ii])}function dS(e){return typeof e.mode=="string"&&iS.has(e.mode)&&Array.isArray(e[Qa])}function lS(e,t){let n=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(n,e),n[Qa]=t,n}function Nm(e){if(!ae(e))return null;let t=ae(e.item)?e.item:ae(e.plan)?e.plan:null;if(t===null)return null;let n=typeof t.id=="string"?t.id:void 0,r=typeof e.outcome=="string"&&Rm.has(e.outcome)?e.outcome:typeof t.status=="string"?t.status:void 0;return n?r?{id:n,status:r,...typeof e.deleted=="boolean"?{deleted:e.deleted}:{}}:{id:n}:null}function uS(e,t){if(!ae(e))return null;if(ae(e.plan)&&ae(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||!ae(e.item)||typeof e.item.id!="string")return null;let n=e[ii];if(!Array.isArray(n))return null;let r={id:e.item.id,...typeof e.outcome=="string"&&Rm.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:n.length};return fS(e,e.item,r),r}function fS(e,t,n){let r=typeof e.close_reason=="string"?e.close_reason:typeof t.close_reason=="string"?t.close_reason:void 0;r!==void 0&&(n.close_reason=r);let o=aS(e.recurrence);o!==null&&(n.recurrence=o),Array.isArray(e.warnings)&&e.warnings.length>0&&(n.warnings=e.warnings);for(let i of["recovery","follow_up","handoff","completion","start"])ae(e[i])&&(n[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","start_refused","suggestions"])Object.hasOwn(e,i)&&(n[i]=e[i])}function mS(e){let t=dS(e)?e[Qa]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let n=!1,r=t.map(o=>{if(!ae(o))return o;let i=xm(o);return i?(n=!0,i):o});return n?{projected:lS(e,r),changed:!0}:{projected:e,changed:!1}}function br(e,t={}){let n=sS(e,t);if(n!==null)return n;if(t.idOnly===!0){let a=Nm(e);if(a!==null)return a}if(t.compactEnvelope===!0||t.changedFields==="compact"){let a=uS(e,t.compactEnvelope===!0);if(a!==null)return a}if((t.changedFields??"full")==="full"||!ae(e))return e;let r=!1,o=e,i=cS(e)?xm(e):null;i!==null&&(o=i,r=!0);let s=mS(o);return s.changed&&(o=s.projected,r=!0),r?o:e}import{AsyncLocalStorage as UO}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 ec(e){let t=e.trim().toLowerCase().startsWith("extension:"),n=e.trim().toLowerCase().replace(/^extension:/u,"");if(en(n))return;let r=ju()?.commands??[],o=[...r].reverse().find(s=>s.command===n)?.command??(t?void 0:r.find(s=>s.action===n)?.command),i=[...r].reverse().find(s=>s.command===o);return i===void 0||en(i.command)||en(i.action)?void 0:i}function pS(e){let t=ec(e);return t?.read_output===void 0?void 0:t}function Dm(e,t){let n=pS(e),r=n?.read_output;if(r===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 r.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:${n.command}`,row_kind:r.row_keys.length>0?"collection":"none",row_keys:[...r.row_keys],fields:"supported",...r.row_keys.length>0?{jq_selector:ti}:{},toon_encoding:"tabular_when_uniform"}}}import{createHash as kO}from"node:crypto";import{createHash as gO}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]="03289358-031e-50aa-b94b-644697c4afc7")}catch{}})();var tc={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"],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","--after"],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:{}},nc=new Set(["--collapse","--fields","--section"]),si=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 ai(e){return e.slice(2).replaceAll("-","_")}function Pm(e,t={}){let n=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],r=n.startsWith("list-")?"list":n==="ctx"?"context":n;return ht.includes(r)?r:void 0}function rc(e){return new Map((tc[e]?.include??[]).filter(t=>!nc.has(t)&&si[t]===void 0).map(t=>[ai(t),oc(t)]))}function oc(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}import{stripVTControlCharacters as _S}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]="493a0675-0114-5b93-b3b4-5bd895ac691f")}catch{}})();var yS=["full","compact","brief","summary","counts"],O$=["mutation","read","discovery","governance"],$m=["error","warning","validation_summary","recovery_bundle"],hS=["full","omit_explanation","limit_collections","compact_recovery","action_only"],gS=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"]),bS=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),wS=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),vS={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},ES=3,kS=2,SS=192,OS={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},AS=$m.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:OS[e],minimum_max_estimated_tokens:SS,degradation_ladder:hS,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),IS=new Map(AS.map(e=>[e.diagnostic_class,e]));function TS(e){let[t=""]=$n(e).split(/\s+/u);return gS.has(t)?"mutation":bS.has(t)?"discovery":wS.has(t)?"governance":"read"}function jm(e,t=TS(e)){let n=e.trim().replace(/\s+/gu," ");if(n.length===0)throw new TypeError("command must be a non-empty command path");let r=vS[t];return CS({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*ES/kS)},degradation_ladder:yS,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function CS(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,n]of Object.entries(e.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${t} must be a positive safe integer`);return e}var RS=Gr.map(e=>jm(e)),xS=new Map(RS.map(e=>[e.command,e]));function Lm(e,t={}){let n=e.trim().replace(/\s+/gu," "),[r]=$n(n).split(" "),o=xS.get(r);return o?{...o,command:n}:t.generateFallback?jm(n):null}function Nt(e){return Math.ceil(Math.max(0,e)/4)}function Fm(e){let t=IS.get(e);if(t===void 0)throw new TypeError(`diagnosticClass must be one of: ${$m.join(", ")}`);return t}function nt(e){return Nt(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))}function NS(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ic(e){if(!NS(e))return;let t={};for(let n of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms","waited_ms","owner_handoffs"]){let r=e[n];Array.isArray(r)?t[n]=n==="suggested_retry_args"?r:r.slice(0,3):r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function DS(e,t){return typeof e!="string"||e.length<=t?e:`${Ee(e,Math.max(1,t-3))}...`}function xt(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let n="...",r=Array.from(e),o=0,i=r.length;for(;o<i;){let s=Math.ceil((o+i)/2),a=`${r.slice(0,s).join("")}${n}`;Buffer.byteLength(a,"utf8")<=t?o=s:i=s-1}return`${r.slice(0,o).join("")}${n}`}function zm(e){let t={};for(let n of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(e,n)&&e[n]!==void 0&&(t[n]=e[n]);for(let[n,r]of Object.entries(e))n!=="__proto__"&&!Object.hasOwn(t,n)&&(t[n]=r);return t}var PS=new Set(["limit_collections","compact_recovery","action_only"]),MS=new Set(["compact_recovery","action_only"]);function $S(e){let t={code:typeof e.code=="string"?e.code:"diagnostic",required:DS(e.required,160)??"Inspect the diagnostic code and retry with corrected input."},n=ic(e.recovery);return n!==void 0?t.recovery=n: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 jS(e,t){let n=structuredClone(e);if(t!=="full"&&(delete n.why,delete n.examples),PS.has(t))for(let[r,o]of Object.entries(n))Array.isArray(o)&&(n[r]=o.slice(0,3));if(MS.has(t)){let r=ic(n.recovery);r?n.recovery=r:delete n.recovery}return t!=="action_only"?zm(n):$S(n)}function gn(e,t){let n={...e,diagnostic_output:{...t,estimated_tokens:0}};for(let r=0;r<4;r+=1){let o=nt(n),i=n.diagnostic_output;if(i.estimated_tokens===o)break;i.estimated_tokens=o}return n}function LS(e,t,n){let r=gn(e,t);for(let i of["recovery","exit_code"])nt(r)<=n||e[i]===void 0||(delete e[i],r=gn(e,t));let o=40;for(;nt(r)>n&&o>4;)o-=4,e.code=xt(String(e.code),o),e.required=xt(String(e.required),o),r=gn(e,t);return r}function FS(e,t){let n=e.diagnostic_output,{estimated_tokens:r,...o}=n,i=o.omitted_fields.slice(0,8).map(u=>xt(u,32)),s={...o,omitted_fields:i,...o.omitted_fields.length>i.length?{omitted_fields_overflow_count:o.omitted_fields.length-i.length}:{}},a=ic(e.recovery),c=a&&nt(a)<=48?a:void 0,d={code:xt(String(e.code),320),required:xt(String(e.required),320),...c?{recovery:c}:{},...e.exit_code!==void 0?{exit_code:e.exit_code}:{}},l=gn(d,s);for(;nt(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=gn(d,s);return l=LS(d,s,t),l}function A$(e,t={}){let n=e,r=t.diagnosticClass??"error",o=Fm(r),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=nt(n),c=Object.keys(n);if(a<=s)return zm(structuredClone(n));let d;for(let[l,u]of o.degradation_ladder.entries()){let f=jS(n,u),m=c.filter(y=>!Object.hasOwn(f,y)),_=gn(f,{diagnostic_class:r,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=_,nt(_)<=s)break}return nt(d)>s&&(d=FS(d,s)),d}function Mm(e){return _S(e).replace(/\r\n/gu,`
18
+ `).replace(/[^\P{Cc}\n]/gu," ")}function I$(e,t,n={}){let r=n.diagnosticClass??"error",o=Fm(r),i=n.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=Mm(e),c=Nt(Buffer.byteLength(a,"utf8")),d=c>s,l=`What is required:
19
19
  `,u=`
20
20
 
21
21
  ${xt(a.trimStart().split(/\r?\n/u,1)[0].trim(),320)}
22
22
 
23
- Diagnostic output exceeded its declared ${s}-token ceiling; rerun with structured JSON for the bounded recovery envelope.`,f=Pm(t).trim()||"Inspect the diagnostic code and retry with corrected input.",m=Math.max(1,s*4-Buffer.byteLength(`${l}${u}`,"utf8")),_=d?`${l}${xt(f,m)}${u}`:a;return{output:_,diagnostic_output:{diagnostic_class:r,format:"text",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:c,estimated_tokens:Nt(Buffer.byteLength(_,"utf8")),truncated:d,degradation_steps:d?[...o.degradation_ladder]:["full"],omitted_fields:d?["explanation","collections"]:[]}}}var sc=Object.freeze({required:"Adjust command input or tracker state and retry.",why:Object.freeze(["pm enforces explicit, deterministic contracts for data and command semantics.","Commander validates CLI contracts before execution.","Unexpected runtime failures can occur from environment or extension-level issues.","Validation protects data consistency and deterministic behavior across commands.","Required options define command intent and enforce deterministic write contracts."]),examples:Object.freeze(["pm --help","pm <command> --help"])});function I$(e){return e?.trim()===sc.required}function T$(e){let t=e?.trim();return t!==void 0&&sc.why.includes(t)}function C$(e){return(e??[]).filter(t=>!sc.examples.includes(t.trim()))}var R$=Object.freeze(["attempted_command","normalized_args","provided_fields"]);function x$(e){if(!e)return;let{attempted_command:t,normalized_args:n,provided_fields:r,...o}=e;return Object.values(o).some(i=>i!==void 0)?o: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]="24a8de41-54f9-5b59-8e58-7ac924ba6e08")}catch{}})();function j$(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"&&"context_ref"in e&&typeof e.context_ref=="string"&&e.context_ref.startsWith("session:")&&e.context_ref.endsWith(`:${e.id}`)}var ac=256,cc=1e4,zS=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,zm=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,US=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),HS=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&zS.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=ac,reason:`token_budget must be a safe integer of at least ${ac}.`},{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<=cc&&e.seen_item_ids.every(t=>typeof t=="string"&&zm.test(t)),reason:`seen_item_ids must contain at most ${cc} portable item identifiers.`}];function di(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ci(e){throw new g(`--output-session ${e}`,h.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function li(e){if(e===void 0)return;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{ci("must be a valid JSON object.")}di(t)||ci("must be a JSON object.");let n=Object.keys(t).filter(i=>!US.has(i));n.length>0&&ci(`contains unknown field "${n.sort()[0]}".`);let r=HS.find(i=>!i.valid(t));r!==void 0&&ci(r.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 Um(e){if(di(e))return typeof e.id=="string"?e.id:typeof e.item_id=="string"?e.item_id:di(e.item)&&typeof e.item.id=="string"?e.item.id:void 0}function qS(e){let t=new Set,n=0,r=tt(e),o=new Set(r.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[...r,...i]){let a=Array.isArray(s.value)?s.value:Object.values(s.value);for(let c of a){if(!di(c))continue;if(typeof c.context_ref=="string"){n+=1;continue}let d=Um(c);d!==void 0&&zm.test(d)&&t.add(d)}}return{deliveredIds:t,suppressedRepeatCount:n}}function Hm(e,t){let n=new Set(t.seen_item_ids);return hr(e,r=>{let o=Um(r);return o!==void 0&&n.has(o)?{id:o,context_ref:`session:${t.id}:${o}`}:r})}function dc(e,t,n){let{deliveredIds:r,suppressedRepeatCount:o}=qS(e),i=new Set(t.seen_item_ids),s=[...r].filter(y=>!i.has(y)).sort(),a=s.slice(0,cc-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:r.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> --depth 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<ac,l.next_state.spent_tokens=l.spent_total_tokens},m=0,_=0;for(let y=0;y<8;y+=1){f(m);let w=wr(u,n);if(w===m)return u;_=Math.max(_,w),m=w}return f(_),u}function qm(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 vr=Symbol.for("pm.readOutputInvocationProvenance");function F$(e,t){return Reflect.set(e,vr,{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]="dd173d3c-f3da-53f3-b24c-118364961db7")}catch{}})();var Dt=["include","amount","cost","encoding"],Jm=["canonical","legacy","intent","default"],kr=po,rj=Object.freeze(Dt.map(e=>kr[e])),oj=_o;function VS(e,t){let n=si[e];if(n!==void 0)return n;let r=t==="include"?nc.has(e)?"<csv>":ai(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${kr[t]} ${r}.`}function Zm(e){let t=tc[e]??{},n=Object.freeze(Object.fromEntries(Dt.map(r=>[r,Object.freeze({dimension:r,canonical_option:kr[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:si[o]===void 0?"replacement":"behavior_preserving",migration_hint:VS(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:Jm,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...rc(e).keys()])})}var BS=Object.freeze(ht.map(Zm)),WS=new Map(BS.map(e=>[e.command,e]));function vn(e,t={}){let n=$n(e.trim().toLowerCase()),r=ec(n);return r!==void 0?r.read_output===void 0?void 0:`extension:${r.command}`:Dm(n,t)}var GS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],KS={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 YS(e){return GS.some(t=>t!=="outputFormat"&&t!=="output_format"&&e[t]!==void 0)}var XS=[{keys:["outputInclude","output_include"],valid:e=>Er(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||wn(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>e==="unbounded"||wn(e)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:e=>(li(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 ij(e,t){let n=t.outputFormat??t.output_format;if(n!==void 0&&n!=="json"&&n!=="toon")throw new g("--output-format must be toon or json.",h.USAGE);if(!YS(t))return;let r=vn(e,t);if(!r)throw new g(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,h.USAGE);if((KS[r]??[]).some(o=>t[o]!==void 0&&t[o]!==!1))throw new g(`Universal output controls cannot be combined with a ${r} mutation.`,h.USAGE);for(let o of XS){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 Qm(e){let t=vn(e);return t?rc(t):new Map}function JS(e,t,n){let r=Er(t)??[],o=Qm(e),i=[],s=[],a=n,c=a[vr],d=new Set(c?.canonical_include_modes??[]),l=new Set(c?.explicit_legacy_aliases??[]);for(let m of r){let _=o.get(m);if(_===void 0){i.push(m);continue}let y=`--${m.replaceAll("_","-")}`;fc(uc(n,y))&&l.add(y),n[_]=!0,s.push(m),d.add(m)}let u=vn(e)==="get"?i.filter(m=>m!=="item"):[],f=u.length>0;return f&&(n.fields=[...new Set([...Er(n.fields)??[],...u])].join(","),d.add("fields")),(s.length>0||f)&&(a[vr]={canonical_include_modes:[...d],explicit_legacy_aliases:[...l],...c?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:s}}function sj(e,t){let n=t.outputInclude??t.output_include;if(n===void 0)return;let{selectors:r,modes:o}=JS(e,n,t);if(o.length===0)return;let i=r.length>0?r.join(","):void 0;t.outputInclude=i,Object.hasOwn(t,"output_include")&&(t.output_include=i)}function uc(e,t){let n=oc(t);if(Object.hasOwn(e,n))return e[n];let r=t.slice(2).replaceAll("-","_");if(Object.hasOwn(e,r))return e[r];if(t==="--no-truncate"&&e.truncate===!1)return!0}function fc(e){return e!==void 0&&e!==!1&&e!==null}function Er(e){let t=(Array.isArray(e)?e:[e]).flatMap(n=>typeof n=="string"?n.split(","):[]).map(n=>n.trim()).filter(Boolean);return t.length>0?[...new Set(t)]:void 0}function wn(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 ZS(e,t,n,r){for(let o of e.legacy_aliases){if(r(o.flag))continue;let i=uc(t,o.flag),s={value:i,flag:o.flag};if(fc(i)&&n(s))return s}}function Vm(e,t){let n=Er(e);if(n)return{source:"canonical",value:n};if(t)return{source:"legacy",value:Er(t.value)??[ai(t.flag)]}}function Bm(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=wn(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;if(t.flag==="--no-truncate"||t.flag==="--unbounded")return{source:"legacy",value:"unbounded"};let r=wn(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function Wm(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=wn(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;let r=wn(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function Gm(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 ep(e,t,n){if(!e)return!1;let r=new Set(e.explicit_legacy_aliases);if(e.cli_invocation_observed===!0||e.sdk_invocation_observed===!0)return!r.has(n);let o=new Set(e.canonical_include_modes.map(i=>`--${i.replaceAll("_","-")}`));return t==="include"&&o.has(n)&&!r.has(n)}function QS(e,t,n,r){return e.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||fc(uc(r,"--no-truncate"))&&!ep(n,"amount","--no-truncate")||t.amount?.flag==="--no-truncate"||t.include?.flag==="--full"||n?.canonical_include_modes.includes("full")===!0}function eO(e,t){return Dt.flatMap(n=>e[n]?.source==="canonical"||n==="include"&&(t?.canonical_include_modes.length??0)>0?[kr[n]]:[])}function tp(e,t){let n=vn(e,t);if(!n)return;let r=WS.get(n)??Zm(n),o=t[vr],i={include:v=>Vm(void 0,v),amount:v=>Bm(void 0,v),cost:v=>Wm(void 0,v),encoding:v=>Gm(void 0,v)},s=Object.fromEntries(Dt.map(v=>[v,ZS(r.dimensions[v],t,T=>i[v](T)!==void 0,T=>ep(o,v,T))])),a=Dt.flatMap(v=>{let T=s[v];return T?[T.flag]:[]}),c=Dt.flatMap(v=>{let T=s[v];return T?[r.dimensions[v].legacy_aliases.find(H=>H.flag===T.flag).migration_hint]:[]}),d=Gm(t.outputFormat??t.output_format,s.encoding),l=Vm(t.outputInclude??t.output_include,s.include),u=Bm(t.outputLimit??t.output_limit,s.amount),f=Wm(t.outputBudget??t.output_budget,s.cost),m=QS(e,s,o,t),_=jm(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:n,include:l,amount:u,cost:w,encoding:d,canonical_options_used:eO({include:l,amount:u,cost:w,encoding:d},o),legacy_aliases_used:a,migration_hints:c,precedence:Jm}}function Z(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var mc=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"]),tO=["collection_counts","notes_count","tests_count"];function np(e,t){let n=new Set(t.map(r=>r.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)))}function nO(e){let t=Z(e.item)?e.item:{},n=[...new Set([...Object.keys(t),...tO.filter(o=>Object.hasOwn(t,o))])].sort((o,i)=>o.localeCompare(i)),r=Object.keys(e).filter(o=>o!=="item"&&o!=="read_output"&&!mc.has(o)).sort((o,i)=>o.localeCompare(i));return{item:t,itemFields:n,sections:r,valid:[...n,"item",...n.map(o=>`item.${o}`),...r]}}function rO(e,t){let n=nO(e),r=t.filter(l=>!n.valid.includes(l));if(r.length>0)throw new g(`Unknown --output-include selector(s) for get: ${r.join(", ")}. Valid selectors: ${n.valid.join(", ")}.`,h.USAGE);let o=t.includes("item"),i=t.flatMap(l=>l.startsWith("item.")?[l.slice(5)]:n.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=>n.sections.includes(l))),a=Object.fromEntries(Object.entries(e).filter(([l])=>mc.has(l)||s.has(l)));o?a.item=n.item:i.length>0&&(a.item=np(n.item,i));let c=[...o?[]:i.length>0?n.itemFields.filter(l=>!i.includes(l)).map(l=>({name:`item.${l}`,restore_with:`--output-include item.${l}`})):[{name:"item",restore_with:"--output-include item"}],...n.sections.filter(l=>!s.has(l)).map(l=>({name:l,restore_with:`--output-include ${l}`}))],d=[...Z(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 Km(e){let t=0;return hr({...e},n=>(Z(n)&&Object.keys(n).length>0&&(t+=1),n)),t}function oO(e,t,n,r){if(Km(t)===0||Km(n)>0)return;let o=[...Qm(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}: ${r.join(", ")}. No selector matched any returned row field.${i}`,h.USAGE)}function iO(e,t,n){if(e==="get")return rO(t,n);let r=ri(t),o=n.flatMap(s=>r.flatMap(a=>s.startsWith(`${a}.`)?[s.slice(a.length+1)]:[])),i=n.some(s=>Object.hasOwn(t,s.split(".")[0])&&!r.some(a=>s.startsWith(`${a}.`)));if(r.length>0&&(!i||o.length>0)){let s={...t},a=o.length>0?o:n,c=hr(s,d=>Z(d)?np(d,a):d);return oO(e,t,c,a),c}return Object.fromEntries(Object.entries(t).filter(([s])=>n.some(a=>a.split(".")[0]===s)||mc.has(s)))}function sO(e,t){if(t==="unbounded")return e;let{result:n,truncated:r}=Sm(e,t);if(!r)return n;if(n.has_more=!0,n.truncated=!0,typeof n.count=="number"){let o=Z(n.projection)?n.projection.row_key:void 0;n.count=typeof o=="string"&&Array.isArray(n[o])?n[o].length:oi(n)}return n.applied_bound={kind:"output_limit",source:"explicit",value:t},n}function aO(e){return Dt.filter(t=>e[t]!==void 0&&e[t]?.source!=="default"||e.canonical_options_used.includes(kr[t]))}function rp(e){let t=e.resolvedOutputFormat??e.outputFormat??e.output_format??e.format;return t==="json"||t==="toon"?t:void 0}function ui(e,t,n,r){let o=dc(e,t,r);bn(e,o);for(let i=0;i<8;i+=1){let s=n.estimated_tokens,a=o.read_session.spent_this_call_tokens;rt(o,n,r);let c=o;o=dc(o,t,r),bn(c,o);let d=o.read_session.spent_this_call_tokens;if(n.estimated_tokens===s&&d===a)return o}return o}function pc(e,t){if(!Z(e.read_output))return e;let n=rp(t),r=e.read_output,o=li(t.outputSession??t.output_session);return o===void 0?(rt(e,r,n),e):ui(e,o,r,n)}function cO(e,t){if(e!=="validate")return t;let n=Z(t.projection)?t.projection:void 0;if(!(Array.isArray(n?.declared_field_groups)?n.declared_field_groups:[]).some(l=>Z(l)&&l.name==="diagnostic_rows"))return t;let r=[...new Set(yr(t).map(({path:l})=>l).filter(l=>/^checks\.\d+\.details\./u.test(l)))],o=r.filter(l=>!r.some(u=>u!==l&&l.startsWith(`${u}.`)));if(o.length===0)return t;let i=Z(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 dO(e,t,n,r,o){let i={...e};if(t.include?.source==="canonical"&&(i=iO(t.command,i,t.include.value)),t.command==="assurance"&&(i=fp(i)),gr(i,e),i=mp(i,t.command,r),t.command==="history"&&r){let c=["compact_history","provenance_history","history","diff"];if(i=Object.fromEntries(Object.entries(i).filter(([d])=>!c.includes(d)||d===r.path)),Z(i.projection)&&(i.projection={...i.projection,row_key:r.path}),Z(i.row_contract)){let d=i.row_contract;i.row_contract={...d,row_keys:[r.path],...Array.isArray(d.continuation_row_keys)?{continuation_row_keys:[r.path]}:{}}}i.count=Object.keys(i[r.path]).length}let s=e.count_only===!0?{...i,count_only:!0,count:e.count}:i,a=yO(i,e,t.command,r,o);return t.amount?.source==="canonical"&&(i=sO(i,t.amount.value),a.cursorContinuesExistingPage&&ap(i,a.originalItems,a.cursorSource,!0,a.originalItemOffset)),gr(i,s),{projected:n===void 0?i:Hm(i,n),continuationState:a}}function lO(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:qm(t)}]].sort((n,r)=>n.tokens-r.tokens)[0]}function op(e){let t=e.canonical_options_used;return t&&t.length>0?{canonical_options_used:t}:{}}function ip(e,t){return Z(e.context_intent)&&e.context_intent.command==="context"&&e.context_intent.token_budget===t&&e.context_intent.within_budget===!0}function uO(e,t,n){return e.command!=="next"||(t.tokenBudget??t.token_budget)===void 0?!1:!(Z(n.context_intent)&&n.context_intent.command==="next"&&n.context_intent.within_budget===!0)}function sp(e,t={}){return e?.source==="default"||e?.source==="legacy"&&!ip(t,e.tokens)?{budget_source:e.source,budget_tokens:e.tokens}:{}}function fO(e,t,n,r,o,i){let s={contract_version:1,command:e.command,requested_dimensions:t,...sp(r),precedence:e.precedence,...op(e),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...n===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=n===void 0?a:ui(a,n,s,i);if(n===void 0&&rt(c,s,i),n!==void 0&&s.estimated_tokens>r.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 mO(e,t,n){return e.command==="context"&&e.cost?.source==="legacy"&&!ip(n,e.cost.value)||uO(e,t,n)||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 pO(e,t,n,r,o){if(t!==void 0||mO(e,o,n))return!1;if(e.amount?.source==="canonical"&&e.amount.value!=="unbounded"){let i=e.amount.value;if(tt(n).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"||wr(o.outputRowContract===!1?Object.fromEntries(Object.entries(n).filter(([i])=>i!=="row_contract")):n,r)<=e.cost.value}function _O(e,t,n,r,o,i,s){if(!n.rows_compacted)return;let a=t.amount?.value==="unbounded"?["amount"]:[],c=new Map(hn(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:_c({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=r.source==="session"?`Truncated by the remaining ${r.tokens}-token session budget; start a new output session with a larger token_budget${u}.`:`${r.tokens}-token: raise --output-budget${u}`;n.migration_hints=[f,...t.migration_hints];let m=lc({effective_budget_tokens:r.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:r.source,budget_tokens:r.tokens,overridden_dimensions:a,compacted_row_paths:n.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 ap(e,t,n,r,o){if(typeof n!="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=yc(n)}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=r?c-(s-i):c+o+i;return u<0?!1:(e.next_cursor=Or(a.fingerprint,l,u,a.snapshot),!0)}function yO(e,t,n,r,o){let i=new Map(hn(e).map(c=>{let d=Array.isArray(c.value)?c.value.length:Object.keys(c.value).length,l=r?.path===c.path;return[c.path,{rows:d,totalRows:l?r.total_rows:d,baseOffset:l?r.offset:0,fingerprint:l?r.fingerprint:fi(c.path,c.value,n)}]})),s=typeof e.next_cursor=="string",a=r?.path==="items"?r.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 hO(e,t,n,r,o,i,s,a,c,d){let l={...t,count_only:n},u=r.command==="assurance"&&Array.isArray(e.assertions)?e.assertions.filter(m=>Z(m)&&m.verdict!=="pass").length:0,f=new Map;if(u>0&&f.set("assertions",u),r.command==="history"&&Array.isArray(e.diff))for(let m of yr(e))m.path.startsWith("diff.")&&f.set(m.path,Object.keys(m.value).length);return Xm(e,o,i.tokens,f,d,m=>{gr(m,l);let _=ap(m,a.originalItems,a.cursorSource,a.cursorContinuesExistingPage,a.originalItemOffset);if(_O(m,r,o,i,_,c,a.collectionsBeforeBudget),r.command==="history"&&Z(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,ui(m,s,o,d))},r.command==="history"&&Array.isArray(e.diff))}function cp(e,t,n){let r=tp(e,t);if(!r)return n;let o=rp(t),i=li(t.outputSession??t.output_session),s=t.outputCursor??t.output_cursor,a=typeof s=="string"?Sr(s):void 0,c=aO(r),d=cO(r.command,n);if(a===void 0&&pO(r,i,d,o,t))return d;let l=lO(r,i),u=dO(d,r,i,a,t),f=u.projected;bn(f,f,t.outputRowContract===!1);let m={contract_version:1,command:r.command,requested_dimensions:c,...sp(l,f),precedence:r.precedence,...op(r),legacy_aliases_used:r.legacy_aliases_used,migration_hints:r.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:ui(f,i,m,o),rt(f,m,o),l!==void 0&&m.estimated_tokens>l.tokens){let _=Ym(r.command,t,f);_!==void 0&&(m.applied_depth="brief",m.degradation_reason="output_budget_reached",bn(f,_),f=pc(_,t)),m.estimated_tokens>l.tokens&&(f=hO(f,f,d.count_only===!0,r,m,l,i,u.continuationState,m.estimated_tokens,o))}return l!==void 0&&m.estimated_tokens>l.tokens?fO(r,c,i,l,m.estimated_tokens,o):f}function dp(e){return Z(e)&&Z(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function lp(e,t){let n=t.outputFormat??t.output_format;if(n==="json"||n==="toon")return n;let r=tp(e,t)?.encoding;return r?.value==="json"||r?.value==="toon"?r.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 bO=4096,wO=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"]),up=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:wO}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});function Ir(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ar(e){return Array.isArray(e)?e.map(Ar):Ir(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ar(n)])):e}function pp(e,t){if(!Ir(e))return Ar(e);let n=typeof e.name=="string"?e.name:void 0,r=n!==void 0&&Object.hasOwn(t.ignored_detail_field_names_by_row,n)?t.ignored_detail_field_names_by_row[n]:void 0;return Object.fromEntries(Object.entries(e).map(([o,i])=>o!=="details"||!r||!Ir(i)?[o,Ar(i)]:[o,Object.fromEntries(Object.entries(i).filter(([s])=>!r.includes(s)).map(([s,a])=>[s,Ar(a)]))]))}function vO(e,t){return Array.isArray(e)?e.map(n=>pp(n,t)):pp(e,t)}function fi(e,t,n){let r=n?up[n]:void 0,o=r?.paths.includes(e)===!0;return gO("sha256").update(R({path:e,value:o?vO(t,r):t,...o?{fingerprint_policy_version:r.version}:{}})).digest("base64url").slice(0,16)}function _c(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 EO(e){return typeof e=="string"&&(vn(e)===e||/^extension:\S(?:[^\r\n]*\S)?$/u.test(e))}function Sr(e){if(e.length>bO)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(!Ir(t)||t.v!==1||!EO(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 fp(e){if(!Array.isArray(e.assertions))return e;let t=n=>!Ir(n)||n.verdict==="pass"?4:n.verdict==="retired"?3:n.enforcement==="block"?0:n.enforcement==="warn"?1:2;return{...e,assertions:e.assertions.map((n,r)=>({row:n,index:r})).sort((n,r)=>t(n.row)-t(r.row)||n.index-r.index).map(({row:n})=>n),budget_retention_policy:"verdict_priority"}}function mp(e,t,n){if(!n)return e;if(n.command!==t)throw new g(`The read-output cursor belongs to ${n.command}, not ${t}.`,h.USAGE,{code:"read_output_cursor_command_mismatch"});let r=hn(e).find(i=>i.path===n.path),o=r?Array.isArray(r.value)?r.value.length:Object.keys(r.value).length:0;if(!r||o!==n.total_rows||n.offset>o||fi(n.path,r.value,t)!==n.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 km(e,n.path,n.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 gc=1,_p=4096,SO=/^[A-Za-z0-9_-]+$/;function hc(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,n)=>n.toUpperCase())}function vj(e,t){let n=[...Object.values(po),..._o],r=new Set(n.flatMap(o=>[hc(o),o.slice(2).replaceAll("-","_")]));for(let o of t)if(o.cursor_semantics==="presentation"){r.add(hc(o.flag));for(let i of o.aliases??[])r.add(hc(i))}return Object.fromEntries(Object.entries(e).filter(([o])=>!r.has(o)))}function Ej(e,t){return kO("sha256").update(e).update("\0").update(R(t)).digest("hex").slice(0,24)}function Or(e,t,n,r){return Buffer.from(JSON.stringify({version:gc,fingerprint:e,after_id:t,...n===void 0?{}:{after_index:n},...r===void 0?{}:{snapshot:r}})).toString("base64url")}function Pt(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 OO(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===gc&&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 yc(e,t="--after"){if(typeof e!="string")throw Pt("Query cursor is malformed.",t);let n=e.trim();if(n.length===0||n.length>_p||!SO.test(n))throw Pt("Query cursor is malformed.",t);let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw Pt("Query cursor is malformed.",t)}if(!OO(r)){let o=!1;try{Sr(n),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 ${n}; retain any producer ${t} cursor from the original page.`]}):Pt("Query cursor version or payload is unsupported.",t)}return r}function bc(e,t,n="--after"){let r=yc(e,n);if(r.fingerprint!==t)throw Pt(`Query cursor does not match the current filters, sort, or query (${r.fingerprint} != ${t}).`,n);return{after_id:r.after_id,...r.after_index===void 0?{}:{after_index:r.after_index},...r.snapshot===void 0?{}:{snapshot:r.snapshot}}}function kj(e,t){return bc(e,t).after_id}function AO(e,t,n,r,o="--after"){if(t===void 0)return 0;let i=bc(t,n,o),s=e.findIndex(a=>r(a)===i.after_id);if(s<0){if(i.after_index!==void 0)return Math.min(i.after_index,e.length);throw Pt(`Query cursor item ${i.after_id} is no longer present in this result set.`,o)}return s+1}function Sj(e,t){if(t.cursor!==void 0&&bc(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw Pt("Query cursor does not match the requested snapshot.","--after");let n=AO(e,t.cursor,t.fingerprint,t.readId),r=e.slice(n,n+t.limit),o=r.length>0&&n+r.length<e.length,i=r.at(-1);return{rows:r,has_more:o,...o&&i!==void 0?{next_cursor:Or(t.fingerprint,t.readId(i),n+r.length-1,t.snapshot)}:{}}}var Oj=Object.freeze({version:gc,max_length:_p});import{randomUUID as xO}from"node:crypto";import{randomUUID as IO}from"node:crypto";import{constants as En}from"node:fs";import{lstat as yp,mkdir as TO,open as gp,rename as CO,rm as RO}from"node:fs/promises";import mi 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]="71b65888-baa5-5c5f-a02c-4a0fd818fadb")}catch{}})();var Ue={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 Mt(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 bp(e){let t=e.maxBytes??Ue.max_bytes,n=e.maxEvents??Ue.max_events,r=e.retentionDays??Ue.retention_days;if(!Number.isSafeInteger(t)||t<1024||t>Ue.max_bytes||!Number.isSafeInteger(n)||n<1||!Number.isFinite(r)||r<=0)throw new Y("Context usage retention requires positive maxEvents and retentionDays, and maxBytes from 1024 through 262144");return{maxBytes:t,maxEvents:n,cutoff:Mt(e).ms-r*864e5}}async function wp(e,t){if(!(await yp(mi.dirname(e))).isDirectory())throw new Y("Context usage runtime must be a real directory");try{if((await yp(e)).isSymbolicLink())throw new Y("Context usage ledger must not be a symbolic link")}catch(r){if(!ee(r))throw r}let n=await gp(e,t|En.O_NOFOLLOW|En.O_NONBLOCK,384);try{let r=await n.stat();if(!r.isFile()||r.nlink!==1)throw new Y("Context usage ledger must be an unshared regular file");return n}catch(r){throw await n.close(),r}}async function pi(e){let t=bp(e);try{let n=await wp(mi.join(e.pmRoot,"runtime","context-usage.jsonl"),En.O_RDONLY);try{let r=(await n.stat()).size,o=Math.max(0,r-t.maxBytes),i=Buffer.alloc(Math.min(r,t.maxBytes)),{bytesRead:s}=await n.read(i,0,i.length,o),a=i.subarray(0,s).toString("utf8");return(o>0?a.includes(`
23
+ Diagnostic output exceeded its declared ${s}-token ceiling; rerun with structured JSON for the bounded recovery envelope.`,f=Mm(t).trim()||"Inspect the diagnostic code and retry with corrected input.",m=Math.max(1,s*4-Buffer.byteLength(`${l}${u}`,"utf8")),_=d?`${l}${xt(f,m)}${u}`:a;return{output:_,diagnostic_output:{diagnostic_class:r,format:"text",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:c,estimated_tokens:Nt(Buffer.byteLength(_,"utf8")),truncated:d,degradation_steps:d?[...o.degradation_ladder]:["full"],omitted_fields:d?["explanation","collections"]:[]}}}var sc=Object.freeze({required:"Adjust command input or tracker state and retry.",why:Object.freeze(["pm enforces explicit, deterministic contracts for data and command semantics.","Commander validates CLI contracts before execution.","Unexpected runtime failures can occur from environment or extension-level issues.","Validation protects data consistency and deterministic behavior across commands.","Required options define command intent and enforce deterministic write contracts."]),examples:Object.freeze(["pm --help","pm <command> --help"])});function T$(e){return e?.trim()===sc.required}function C$(e){let t=e?.trim();return t!==void 0&&sc.why.includes(t)}function R$(e){return(e??[]).filter(t=>!sc.examples.includes(t.trim()))}var x$=Object.freeze(["attempted_command","normalized_args","provided_fields"]);function N$(e){if(!e)return;let{attempted_command:t,normalized_args:n,provided_fields:r,...o}=e;return Object.values(o).some(i=>i!==void 0)?o: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]="24a8de41-54f9-5b59-8e58-7ac924ba6e08")}catch{}})();function L$(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"&&"context_ref"in e&&typeof e.context_ref=="string"&&e.context_ref.startsWith("session:")&&e.context_ref.endsWith(`:${e.id}`)}var ac=256,cc=1e4,zS=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,Um=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,US=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),HS=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&zS.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=ac,reason:`token_budget must be a safe integer of at least ${ac}.`},{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<=cc&&e.seen_item_ids.every(t=>typeof t=="string"&&Um.test(t)),reason:`seen_item_ids must contain at most ${cc} portable item identifiers.`}];function di(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ci(e){throw new g(`--output-session ${e}`,h.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function li(e){if(e===void 0)return;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{ci("must be a valid JSON object.")}di(t)||ci("must be a JSON object.");let n=Object.keys(t).filter(i=>!US.has(i));n.length>0&&ci(`contains unknown field "${n.sort()[0]}".`);let r=HS.find(i=>!i.valid(t));r!==void 0&&ci(r.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 Hm(e){if(di(e))return typeof e.id=="string"?e.id:typeof e.item_id=="string"?e.item_id:di(e.item)&&typeof e.item.id=="string"?e.item.id:void 0}function qS(e){let t=new Set,n=0,r=tt(e),o=new Set(r.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[...r,...i]){let a=Array.isArray(s.value)?s.value:Object.values(s.value);for(let c of a){if(!di(c))continue;if(typeof c.context_ref=="string"){n+=1;continue}let d=Hm(c);d!==void 0&&Um.test(d)&&t.add(d)}}return{deliveredIds:t,suppressedRepeatCount:n}}function qm(e,t){let n=new Set(t.seen_item_ids);return hr(e,r=>{let o=Hm(r);return o!==void 0&&n.has(o)?{id:o,context_ref:`session:${t.id}:${o}`}:r})}function dc(e,t,n){let{deliveredIds:r,suppressedRepeatCount:o}=qS(e),i=new Set(t.seen_item_ids),s=[...r].filter(y=>!i.has(y)).sort(),a=s.slice(0,cc-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:r.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> --depth 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<ac,l.next_state.spent_tokens=l.spent_total_tokens},m=0,_=0;for(let y=0;y<8;y+=1){f(m);let w=wr(u,n);if(w===m)return u;_=Math.max(_,w),m=w}return f(_),u}function Vm(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 vr=Symbol.for("pm.readOutputInvocationProvenance");function z$(e,t){return Reflect.set(e,vr,{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]="dd173d3c-f3da-53f3-b24c-118364961db7")}catch{}})();var Dt=["include","amount","cost","encoding"],Zm=["canonical","legacy","intent","default"],kr=po,oj=Object.freeze(Dt.map(e=>kr[e])),ij=_o;function VS(e,t){let n=si[e];if(n!==void 0)return n;let r=t==="include"?nc.has(e)?"<csv>":ai(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${kr[t]} ${r}.`}function Qm(e){let t=tc[e]??{},n=Object.freeze(Object.fromEntries(Dt.map(r=>[r,Object.freeze({dimension:r,canonical_option:kr[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:si[o]===void 0?"replacement":"behavior_preserving",migration_hint:VS(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:Zm,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...rc(e).keys()])})}var BS=Object.freeze(ht.map(Qm)),WS=new Map(BS.map(e=>[e.command,e]));function vn(e,t={}){let n=$n(e.trim().toLowerCase()),r=ec(n);return r!==void 0?r.read_output===void 0?void 0:`extension:${r.command}`:Pm(n,t)}var GS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],KS={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 YS(e){return GS.some(t=>t!=="outputFormat"&&t!=="output_format"&&e[t]!==void 0)}var XS=[{keys:["outputInclude","output_include"],valid:e=>Er(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||wn(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>e==="unbounded"||wn(e)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:e=>(li(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 sj(e,t){let n=t.outputFormat??t.output_format;if(n!==void 0&&n!=="json"&&n!=="toon")throw new g("--output-format must be toon or json.",h.USAGE);if(!YS(t))return;let r=vn(e,t);if(!r)throw new g(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,h.USAGE);if((KS[r]??[]).some(o=>t[o]!==void 0&&t[o]!==!1))throw new g(`Universal output controls cannot be combined with a ${r} mutation.`,h.USAGE);for(let o of XS){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 ep(e){let t=vn(e);return t?rc(t):new Map}function JS(e,t,n){let r=Er(t)??[],o=ep(e),i=[],s=[],a=n,c=a[vr],d=new Set(c?.canonical_include_modes??[]),l=new Set(c?.explicit_legacy_aliases??[]);for(let m of r){let _=o.get(m);if(_===void 0){i.push(m);continue}let y=`--${m.replaceAll("_","-")}`;fc(uc(n,y))&&l.add(y),n[_]=!0,s.push(m),d.add(m)}let u=vn(e)==="get"?i.filter(m=>m!=="item"):[],f=u.length>0;return f&&(n.fields=[...new Set([...Er(n.fields)??[],...u])].join(","),d.add("fields")),(s.length>0||f)&&(a[vr]={canonical_include_modes:[...d],explicit_legacy_aliases:[...l],...c?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:s}}function aj(e,t){let n=t.outputInclude??t.output_include;if(n===void 0)return;let{selectors:r,modes:o}=JS(e,n,t);if(o.length===0)return;let i=r.length>0?r.join(","):void 0;t.outputInclude=i,Object.hasOwn(t,"output_include")&&(t.output_include=i)}function uc(e,t){let n=oc(t);if(Object.hasOwn(e,n))return e[n];let r=t.slice(2).replaceAll("-","_");if(Object.hasOwn(e,r))return e[r];if(t==="--no-truncate"&&e.truncate===!1)return!0}function fc(e){return e!==void 0&&e!==!1&&e!==null}function Er(e){let t=(Array.isArray(e)?e:[e]).flatMap(n=>typeof n=="string"?n.split(","):[]).map(n=>n.trim()).filter(Boolean);return t.length>0?[...new Set(t)]:void 0}function wn(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 ZS(e,t,n,r){for(let o of e.legacy_aliases){if(r(o.flag))continue;let i=uc(t,o.flag),s={value:i,flag:o.flag};if(fc(i)&&n(s))return s}}function Bm(e,t){let n=Er(e);if(n)return{source:"canonical",value:n};if(t)return{source:"legacy",value:Er(t.value)??[ai(t.flag)]}}function Wm(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=wn(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;if(t.flag==="--no-truncate"||t.flag==="--unbounded")return{source:"legacy",value:"unbounded"};let r=wn(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function Gm(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=wn(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;let r=wn(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function Km(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 tp(e,t,n){if(!e)return!1;let r=new Set(e.explicit_legacy_aliases);if(e.cli_invocation_observed===!0||e.sdk_invocation_observed===!0)return!r.has(n);let o=new Set(e.canonical_include_modes.map(i=>`--${i.replaceAll("_","-")}`));return t==="include"&&o.has(n)&&!r.has(n)}function QS(e,t,n,r){return e.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||fc(uc(r,"--no-truncate"))&&!tp(n,"amount","--no-truncate")||t.amount?.flag==="--no-truncate"||t.include?.flag==="--full"||n?.canonical_include_modes.includes("full")===!0}function eO(e,t){return Dt.flatMap(n=>e[n]?.source==="canonical"||n==="include"&&(t?.canonical_include_modes.length??0)>0?[kr[n]]:[])}function np(e,t){let n=vn(e,t);if(!n)return;let r=WS.get(n)??Qm(n),o=t[vr],i={include:v=>Bm(void 0,v),amount:v=>Wm(void 0,v),cost:v=>Gm(void 0,v),encoding:v=>Km(void 0,v)},s=Object.fromEntries(Dt.map(v=>[v,ZS(r.dimensions[v],t,T=>i[v](T)!==void 0,T=>tp(o,v,T))])),a=Dt.flatMap(v=>{let T=s[v];return T?[T.flag]:[]}),c=Dt.flatMap(v=>{let T=s[v];return T?[r.dimensions[v].legacy_aliases.find(H=>H.flag===T.flag).migration_hint]:[]}),d=Km(t.outputFormat??t.output_format,s.encoding),l=Bm(t.outputInclude??t.output_include,s.include),u=Wm(t.outputLimit??t.output_limit,s.amount),f=Gm(t.outputBudget??t.output_budget,s.cost),m=QS(e,s,o,t),_=Lm(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:n,include:l,amount:u,cost:w,encoding:d,canonical_options_used:eO({include:l,amount:u,cost:w,encoding:d},o),legacy_aliases_used:a,migration_hints:c,precedence:Zm}}function Z(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var mc=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"]),tO=["collection_counts","notes_count","tests_count"];function rp(e,t){let n=new Set(t.map(r=>r.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)))}function nO(e){let t=Z(e.item)?e.item:{},n=[...new Set([...Object.keys(t),...tO.filter(o=>Object.hasOwn(t,o))])].sort((o,i)=>o.localeCompare(i)),r=Object.keys(e).filter(o=>o!=="item"&&o!=="read_output"&&!mc.has(o)).sort((o,i)=>o.localeCompare(i));return{item:t,itemFields:n,sections:r,valid:[...n,"item",...n.map(o=>`item.${o}`),...r]}}function rO(e,t){let n=nO(e),r=t.filter(l=>!n.valid.includes(l));if(r.length>0)throw new g(`Unknown --output-include selector(s) for get: ${r.join(", ")}. Valid selectors: ${n.valid.join(", ")}.`,h.USAGE);let o=t.includes("item"),i=t.flatMap(l=>l.startsWith("item.")?[l.slice(5)]:n.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=>n.sections.includes(l))),a=Object.fromEntries(Object.entries(e).filter(([l])=>mc.has(l)||s.has(l)));o?a.item=n.item:i.length>0&&(a.item=rp(n.item,i));let c=[...o?[]:i.length>0?n.itemFields.filter(l=>!i.includes(l)).map(l=>({name:`item.${l}`,restore_with:`--output-include item.${l}`})):[{name:"item",restore_with:"--output-include item"}],...n.sections.filter(l=>!s.has(l)).map(l=>({name:l,restore_with:`--output-include ${l}`}))],d=[...Z(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 Ym(e){let t=0;return hr({...e},n=>(Z(n)&&Object.keys(n).length>0&&(t+=1),n)),t}function oO(e,t,n,r){if(Ym(t)===0||Ym(n)>0)return;let o=[...ep(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}: ${r.join(", ")}. No selector matched any returned row field.${i}`,h.USAGE)}function iO(e,t,n){if(e==="get")return rO(t,n);let r=ri(t),o=n.flatMap(s=>r.flatMap(a=>s.startsWith(`${a}.`)?[s.slice(a.length+1)]:[])),i=n.some(s=>Object.hasOwn(t,s.split(".")[0])&&!r.some(a=>s.startsWith(`${a}.`)));if(r.length>0&&(!i||o.length>0)){let s={...t},a=o.length>0?o:n,c=hr(s,d=>Z(d)?rp(d,a):d);return oO(e,t,c,a),c}return Object.fromEntries(Object.entries(t).filter(([s])=>n.some(a=>a.split(".")[0]===s)||mc.has(s)))}function sO(e,t){if(t==="unbounded")return e;let{result:n,truncated:r}=Om(e,t);if(!r)return n;if(n.has_more=!0,n.truncated=!0,typeof n.count=="number"){let o=Z(n.projection)?n.projection.row_key:void 0;n.count=typeof o=="string"&&Array.isArray(n[o])?n[o].length:oi(n)}return n.applied_bound={kind:"output_limit",source:"explicit",value:t},n}function aO(e){return Dt.filter(t=>e[t]!==void 0&&e[t]?.source!=="default"||e.canonical_options_used.includes(kr[t]))}function op(e){let t=e.resolvedOutputFormat??e.outputFormat??e.output_format??e.format;return t==="json"||t==="toon"?t:void 0}function ui(e,t,n,r){let o=dc(e,t,r);bn(e,o);for(let i=0;i<8;i+=1){let s=n.estimated_tokens,a=o.read_session.spent_this_call_tokens;rt(o,n,r);let c=o;o=dc(o,t,r),bn(c,o);let d=o.read_session.spent_this_call_tokens;if(n.estimated_tokens===s&&d===a)return o}return o}function pc(e,t){if(!Z(e.read_output))return e;let n=op(t),r=e.read_output,o=li(t.outputSession??t.output_session);return o===void 0?(rt(e,r,n),e):ui(e,o,r,n)}function cO(e,t){if(e!=="validate")return t;let n=Z(t.projection)?t.projection:void 0;if(!(Array.isArray(n?.declared_field_groups)?n.declared_field_groups:[]).some(l=>Z(l)&&l.name==="diagnostic_rows"))return t;let r=[...new Set(yr(t).map(({path:l})=>l).filter(l=>/^checks\.\d+\.details\./u.test(l)))],o=r.filter(l=>!r.some(u=>u!==l&&l.startsWith(`${u}.`)));if(o.length===0)return t;let i=Z(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 dO(e,t,n,r,o){let i={...e};if(t.include?.source==="canonical"&&(i=iO(t.command,i,t.include.value)),t.command==="assurance"&&(i=mp(i)),gr(i,e),i=pp(i,t.command,r),t.command==="history"&&r){let c=["compact_history","provenance_history","history","diff"];if(i=Object.fromEntries(Object.entries(i).filter(([d])=>!c.includes(d)||d===r.path)),Z(i.projection)&&(i.projection={...i.projection,row_key:r.path}),Z(i.row_contract)){let d=i.row_contract;i.row_contract={...d,row_keys:[r.path],...Array.isArray(d.continuation_row_keys)?{continuation_row_keys:[r.path]}:{}}}i.count=Object.keys(i[r.path]).length}let s=e.count_only===!0?{...i,count_only:!0,count:e.count}:i,a=yO(i,e,t.command,r,o);return t.amount?.source==="canonical"&&(i=sO(i,t.amount.value),a.cursorContinuesExistingPage&&cp(i,a.originalItems,a.cursorSource,!0,a.originalItemOffset)),gr(i,s),{projected:n===void 0?i:qm(i,n),continuationState:a}}function lO(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:Vm(t)}]].sort((n,r)=>n.tokens-r.tokens)[0]}function ip(e){let t=e.canonical_options_used;return t&&t.length>0?{canonical_options_used:t}:{}}function sp(e,t){return Z(e.context_intent)&&e.context_intent.command==="context"&&e.context_intent.token_budget===t&&e.context_intent.within_budget===!0}function uO(e,t,n){return e.command!=="next"||(t.tokenBudget??t.token_budget)===void 0?!1:!(Z(n.context_intent)&&n.context_intent.command==="next"&&n.context_intent.within_budget===!0)}function ap(e,t={}){return e?.source==="default"||e?.source==="legacy"&&!sp(t,e.tokens)?{budget_source:e.source,budget_tokens:e.tokens}:{}}function fO(e,t,n,r,o,i){let s={contract_version:1,command:e.command,requested_dimensions:t,...ap(r),precedence:e.precedence,...ip(e),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...n===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=n===void 0?a:ui(a,n,s,i);if(n===void 0&&rt(c,s,i),n!==void 0&&s.estimated_tokens>r.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 mO(e,t,n){return e.command==="context"&&e.cost?.source==="legacy"&&!sp(n,e.cost.value)||uO(e,t,n)||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 pO(e,t,n,r,o){if(t!==void 0||mO(e,o,n))return!1;if(e.amount?.source==="canonical"&&e.amount.value!=="unbounded"){let i=e.amount.value;if(tt(n).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"||wr(o.outputRowContract===!1?Object.fromEntries(Object.entries(n).filter(([i])=>i!=="row_contract")):n,r)<=e.cost.value}function _O(e,t,n,r,o,i,s){if(!n.rows_compacted)return;let a=t.amount?.value==="unbounded"?["amount"]:[],c=new Map(hn(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:_c({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=r.source==="session"?`Truncated by the remaining ${r.tokens}-token session budget; start a new output session with a larger token_budget${u}.`:`${r.tokens}-token: raise --output-budget${u}`;n.migration_hints=[f,...t.migration_hints];let m=lc({effective_budget_tokens:r.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:r.source,budget_tokens:r.tokens,overridden_dimensions:a,compacted_row_paths:n.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 cp(e,t,n,r,o){if(typeof n!="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=yc(n)}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=r?c-(s-i):c+o+i;return u<0?!1:(e.next_cursor=Or(a.fingerprint,l,u,a.snapshot),!0)}function yO(e,t,n,r,o){let i=new Map(hn(e).map(c=>{let d=Array.isArray(c.value)?c.value.length:Object.keys(c.value).length,l=r?.path===c.path;return[c.path,{rows:d,totalRows:l?r.total_rows:d,baseOffset:l?r.offset:0,fingerprint:l?r.fingerprint:fi(c.path,c.value,n)}]})),s=typeof e.next_cursor=="string",a=r?.path==="items"?r.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 hO(e,t,n,r,o,i,s,a,c,d){let l={...t,count_only:n},u=r.command==="assurance"&&Array.isArray(e.assertions)?e.assertions.filter(m=>Z(m)&&m.verdict!=="pass").length:0,f=new Map;if(u>0&&f.set("assertions",u),r.command==="history"&&Array.isArray(e.diff))for(let m of yr(e))m.path.startsWith("diff.")&&f.set(m.path,Object.keys(m.value).length);return Jm(e,o,i.tokens,f,d,m=>{gr(m,l);let _=cp(m,a.originalItems,a.cursorSource,a.cursorContinuesExistingPage,a.originalItemOffset);if(_O(m,r,o,i,_,c,a.collectionsBeforeBudget),r.command==="history"&&Z(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,ui(m,s,o,d))},r.command==="history"&&Array.isArray(e.diff))}function dp(e,t,n){let r=np(e,t);if(!r)return n;let o=op(t),i=li(t.outputSession??t.output_session),s=t.outputCursor??t.output_cursor,a=typeof s=="string"?Sr(s):void 0,c=aO(r),d=cO(r.command,n);if(a===void 0&&pO(r,i,d,o,t))return d;let l=lO(r,i),u=dO(d,r,i,a,t),f=u.projected;bn(f,f,t.outputRowContract===!1);let m={contract_version:1,command:r.command,requested_dimensions:c,...ap(l,f),precedence:r.precedence,...ip(r),legacy_aliases_used:r.legacy_aliases_used,migration_hints:r.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:ui(f,i,m,o),rt(f,m,o),l!==void 0&&m.estimated_tokens>l.tokens){let _=Xm(r.command,t,f);_!==void 0&&(m.applied_depth="brief",m.degradation_reason="output_budget_reached",bn(f,_),f=pc(_,t)),m.estimated_tokens>l.tokens&&(f=hO(f,f,d.count_only===!0,r,m,l,i,u.continuationState,m.estimated_tokens,o))}return l!==void 0&&m.estimated_tokens>l.tokens?fO(r,c,i,l,m.estimated_tokens,o):f}function lp(e){return Z(e)&&Z(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function up(e,t){let n=t.outputFormat??t.output_format;if(n==="json"||n==="toon")return n;let r=np(e,t)?.encoding;return r?.value==="json"||r?.value==="toon"?r.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 bO=4096,wO=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"]),fp=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:wO}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});function Ir(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ar(e){return Array.isArray(e)?e.map(Ar):Ir(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ar(n)])):e}function _p(e,t){if(!Ir(e))return Ar(e);let n=typeof e.name=="string"?e.name:void 0,r=n!==void 0&&Object.hasOwn(t.ignored_detail_field_names_by_row,n)?t.ignored_detail_field_names_by_row[n]:void 0;return Object.fromEntries(Object.entries(e).map(([o,i])=>o!=="details"||!r||!Ir(i)?[o,Ar(i)]:[o,Object.fromEntries(Object.entries(i).filter(([s])=>!r.includes(s)).map(([s,a])=>[s,Ar(a)]))]))}function vO(e,t){return Array.isArray(e)?e.map(n=>_p(n,t)):_p(e,t)}function fi(e,t,n){let r=n?fp[n]:void 0,o=r?.paths.includes(e)===!0;return gO("sha256").update(R({path:e,value:o?vO(t,r):t,...o?{fingerprint_policy_version:r.version}:{}})).digest("base64url").slice(0,16)}function _c(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 EO(e){return typeof e=="string"&&(vn(e)===e||/^extension:\S(?:[^\r\n]*\S)?$/u.test(e))}function Sr(e){if(e.length>bO)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(!Ir(t)||t.v!==1||!EO(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 mp(e){if(!Array.isArray(e.assertions))return e;let t=n=>!Ir(n)||n.verdict==="pass"?4:n.verdict==="retired"?3:n.enforcement==="block"?0:n.enforcement==="warn"?1:2;return{...e,assertions:e.assertions.map((n,r)=>({row:n,index:r})).sort((n,r)=>t(n.row)-t(r.row)||n.index-r.index).map(({row:n})=>n),budget_retention_policy:"verdict_priority"}}function pp(e,t,n){if(!n)return e;if(n.command!==t)throw new g(`The read-output cursor belongs to ${n.command}, not ${t}.`,h.USAGE,{code:"read_output_cursor_command_mismatch"});let r=hn(e).find(i=>i.path===n.path),o=r?Array.isArray(r.value)?r.value.length:Object.keys(r.value).length:0;if(!r||o!==n.total_rows||n.offset>o||fi(n.path,r.value,t)!==n.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 Sm(e,n.path,n.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 gc=1,yp=4096,SO=/^[A-Za-z0-9_-]+$/;function hc(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,n)=>n.toUpperCase())}function Ej(e,t){let n=[...Object.values(po),..._o],r=new Set(n.flatMap(o=>[hc(o),o.slice(2).replaceAll("-","_")]));for(let o of t)if(o.cursor_semantics==="presentation"){r.add(hc(o.flag));for(let i of o.aliases??[])r.add(hc(i))}return Object.fromEntries(Object.entries(e).filter(([o])=>!r.has(o)))}function kj(e,t){return kO("sha256").update(e).update("\0").update(R(t)).digest("hex").slice(0,24)}function Or(e,t,n,r){return Buffer.from(JSON.stringify({version:gc,fingerprint:e,after_id:t,...n===void 0?{}:{after_index:n},...r===void 0?{}:{snapshot:r}})).toString("base64url")}function Pt(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 OO(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===gc&&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 yc(e,t="--after"){if(typeof e!="string")throw Pt("Query cursor is malformed.",t);let n=e.trim();if(n.length===0||n.length>yp||!SO.test(n))throw Pt("Query cursor is malformed.",t);let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw Pt("Query cursor is malformed.",t)}if(!OO(r)){let o=!1;try{Sr(n),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 ${n}; retain any producer ${t} cursor from the original page.`]}):Pt("Query cursor version or payload is unsupported.",t)}return r}function bc(e,t,n="--after"){let r=yc(e,n);if(r.fingerprint!==t)throw Pt(`Query cursor does not match the current filters, sort, or query (${r.fingerprint} != ${t}).`,n);return{after_id:r.after_id,...r.after_index===void 0?{}:{after_index:r.after_index},...r.snapshot===void 0?{}:{snapshot:r.snapshot}}}function Sj(e,t){return bc(e,t).after_id}function AO(e,t,n,r,o="--after"){if(t===void 0)return 0;let i=bc(t,n,o),s=e.findIndex(a=>r(a)===i.after_id);if(s<0){if(i.after_index!==void 0)return Math.min(i.after_index,e.length);throw Pt(`Query cursor item ${i.after_id} is no longer present in this result set.`,o)}return s+1}function Oj(e,t){if(t.cursor!==void 0&&bc(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw Pt("Query cursor does not match the requested snapshot.","--after");let n=AO(e,t.cursor,t.fingerprint,t.readId),r=e.slice(n,n+t.limit),o=r.length>0&&n+r.length<e.length,i=r.at(-1);return{rows:r,has_more:o,...o&&i!==void 0?{next_cursor:Or(t.fingerprint,t.readId(i),n+r.length-1,t.snapshot)}:{}}}var Aj=Object.freeze({version:gc,max_length:yp});import{randomUUID as xO}from"node:crypto";import{randomUUID as IO}from"node:crypto";import{constants as En}from"node:fs";import{lstat as hp,mkdir as TO,open as bp,rename as CO,rm as RO}from"node:fs/promises";import mi 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]="71b65888-baa5-5c5f-a02c-4a0fd818fadb")}catch{}})();var Ue={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 Mt(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 wp(e){let t=e.maxBytes??Ue.max_bytes,n=e.maxEvents??Ue.max_events,r=e.retentionDays??Ue.retention_days;if(!Number.isSafeInteger(t)||t<1024||t>Ue.max_bytes||!Number.isSafeInteger(n)||n<1||!Number.isFinite(r)||r<=0)throw new Y("Context usage retention requires positive maxEvents and retentionDays, and maxBytes from 1024 through 262144");return{maxBytes:t,maxEvents:n,cutoff:Mt(e).ms-r*864e5}}async function vp(e,t){if(!(await hp(mi.dirname(e))).isDirectory())throw new Y("Context usage runtime must be a real directory");try{if((await hp(e)).isSymbolicLink())throw new Y("Context usage ledger must not be a symbolic link")}catch(r){if(!ee(r))throw r}let n=await bp(e,t|En.O_NOFOLLOW|En.O_NONBLOCK,384);try{let r=await n.stat();if(!r.isFile()||r.nlink!==1)throw new Y("Context usage ledger must be an unshared regular file");return n}catch(r){throw await n.close(),r}}async function pi(e){let t=wp(e);try{let n=await vp(mi.join(e.pmRoot,"runtime","context-usage.jsonl"),En.O_RDONLY);try{let r=(await n.stat()).size,o=Math.max(0,r-t.maxBytes),i=Buffer.alloc(Math.min(r,t.maxBytes)),{bytesRead:s}=await n.read(i,0,i.length,o),a=i.subarray(0,s).toString("utf8");return(o>0?a.includes(`
24
24
  `)?a.slice(a.indexOf(`
25
25
  `)+1):"":a).split(`
26
- `).flatMap(c=>{try{let d=JSON.parse(c);return d&&Date.parse(d.at)>=t.cutoff?[d]:[]}catch{return[]}}).slice(-t.maxEvents)}finally{await n.close()}}catch{return[]}}function hp(e,t,n){let r=[],o=0;for(let i=e.length-1;i>=0&&r.length<n;i-=1){let s=`${JSON.stringify(e[i])}
27
- `;if(o+=Buffer.byteLength(s),o>t)break;r.push(s)}return r.reverse().join("")}async function Tr(e,t,n){let r=bp(e),o=mi.join(e.pmRoot,"runtime","context-usage.jsonl"),i=Math.floor(r.maxBytes*Ue.retained_byte_fraction),s=Math.min(Ue.max_event_bytes,i);if(t.some(f=>Buffer.byteLength(`${JSON.stringify(f)}
28
- `)>s))throw new Y("Context usage event exceeds the declared byte ceiling");let a=t.filter(f=>Date.parse(f.at)>=r.cutoff),c=hp(a,i,r.maxEvents),d=performance.now(),l=await fe(e.pmRoot,"context-usage-ledger",30,`context-usage:${process.pid}`,!1,!1,3e3),u=performance.now()-d;try{await TO(mi.dirname(o),{recursive:!0});let f=await wp(o,En.O_WRONLY|En.O_CREAT|En.O_APPEND);try{let m=(await f.stat()).size,_=n===void 0?void 0:await pi(e);if(_?.some(T=>T.kind==="delivery"&&T.serve_id===n))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)<=r.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=hp([..._??await pi(e),...a],i,r.maxEvents),w=`${o}.${process.pid}.${IO()}.tmp`,v=await gp(w,"wx",384);try{try{await v.writeFile(y,"utf8")}finally{await v.close()}return await f.close(),f=void 0,await CO(w,o),{written_bytes:Buffer.byteLength(y),ledger_bytes:Buffer.byteLength(y),compacted:!0,lock_wait_ms:u}}finally{await RO(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 NO=864e5,_i=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function jj(e,t){let n=Q(e);n!==null&&t!==null&&(n[_i]=t)}function kn(e,t){let n=Q(e),r=Q(t),o=n?.[_i];r!==null&&o!==void 0&&(r[_i]=o)}function DO(e){return Q(e)?.[_i]??null}function Ep(e){let t=Q(e);for(let n of["read_output","context_intent"])if(Q(t?.[n])?.result_omitted===!0)return!0;return!1}function ot(e,t){typeof t=="string"&&t.trim().length>0&&e.add(t.trim())}function kp(e,t){if(Array.isArray(t))for(let n of t)ot(e,Q(n)?.id)}function vp(e,t){if(Array.isArray(t))for(let n of t)ot(e,n)}function PO(e,t){let n=Q(e.recommended)===null?[]:[e.recommended];for(let r of["ready","decision_needed","gate_needed","containers","blocked","held_by_others"])Array.isArray(e[r])&&n.push(...e[r]);for(let r of n){let o=Q(r);ot(t,o?.id);for(let i of Array.isArray(o?.blockers)?o.blockers:[])ot(t,Q(i)?.id);for(let i of Array.isArray(o?.unblocks)?o.unblocks:[])ot(t,i)}}function MO(e,t){for(let n of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"])kp(t,e[n]);for(let n of Array.isArray(e.blockers)?e.blockers:[])ot(t,Q(n)?.blocked_by);$O(e,t)}function $O(e,t){for(let o of Array.isArray(e.hierarchy)?e.hierarchy:[]){let i=Q(o);ot(t,i?.id),kp(t,i?.children)}for(let o of["files","workload"])for(let i of Array.isArray(e[o])?e[o]:[])vp(t,Q(i)?.items);let n=Q(e.agenda);for(let o of Array.isArray(n?.events)?n.events:[])ot(t,Q(o)?.item_id);let r=Q(e.tests);vp(t,r?.items_failing)}function jO(e,t){let n=Q(e);if(n===null||Ep(e))return[];let r=new Set;return t==="next"?PO(n,r):MO(n,r),[...r]}async function Lj(e){let t=DO(e.result);if(t===null)return!1;let n=Ep(e.result);return await LO({pmRoot:e.pmRoot,receipt:t,deliveredItemIds:jO(e.result,t.surface),resultOmitted:n}),!0}async function Fj(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 n=t.slice(0,Ue.max_serving_rows),r={serve_id:xO(),author:e.author.trim(),surface:e.surface,rows:t,recorded_item_ids:n.map(o=>o.id)};return r.storage=await Tr(e,[{kind:"serve",schema_version:2,serve_id:r.serve_id,at:Mt(e).iso,author:e.author.trim(),surface:e.surface,profile:e.profile.trim()||"balanced",rows:n,candidate_count:t.length,omitted_row_count:t.length-n.length,result_omitted:!1,packed_item_ids:n.filter(o=>o.included).map(o=>o.id)}]),r}async function LO(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)),n=[...new Set(e.deliveredItemIds.map(i=>i.trim()))];if(n.some(i=>i.length===0||!t.has(i))||e.resultOmitted&&n.length>0)throw new Y("Context usage delivery requires emitted ranked ids and zero ids for an omitted result");let r=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:Mt(e).iso,author:e.receipt.author,surface:e.receipt.surface,result_omitted:e.resultOmitted,delivered_item_ids:n.filter(i=>r.has(i))};await Tr(e,[o],o.serve_id)}async function zj(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 Tr(e,[{kind:"touch",at:Mt(e).iso,author:e.author.trim(),item_id:e.itemId.trim(),intent:e.intent.trim()}])}}async function Uj(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1||e.itemIds.length===0)return;let t=e.author.trim(),n=e.intent.trim();if(!t||!n)throw new Y("Context usage touch requires author and intent");let r=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");r.add(a)}let o=Mt(e).iso,i=[...r].map(s=>({kind:"touch",at:o,author:t,item_id:s,intent:n}));await Tr(e,i)}function FO(e,t,n,r){return e.find(({entry:o,time:i})=>o.item_id===t&&i>=n&&i-n<=r)?.time}function zO(e,t){let n=new Map;for(let r of e)r.kind==="delivery"&&r.schema_version===2&&r.author===t&&!n.has(r.serve_id)&&n.set(r.serve_id,r);return n}async function Hj(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 pi(e),n=Mt(e).ms,r=(e.horizonHours??24)*36e5;if(![Number.isFinite(r),r>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=zO(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=FO(i,w.id,m,r);if(v===void 0)continue;d+=1;let T=Math.max(0,(n-v)/NO);s.set(w.id,(s.get(w.id)??0)+Math.exp(-T/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]="4c8b43ab-cada-5adf-8c00-aed8de1a8bc1")}catch{}})();var HO="limit_overridden_by_intent",Op=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"}]),Ap=new UO;function qO(){return Ap.getStore()??Op}function eL(e,t){return Ap.run(BO(e.workspaceContracts,e.packageContracts),t)}function VO(e,t){let n=e.command.trim().toLowerCase(),r=e.intent.trim().toLowerCase(),o=`${n}:${r}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(n)||!/^[a-z0-9][a-z0-9-]*$/.test(r))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:n,intent:r,description:e.description.trim(),included_field_groups:i,token_budget:e.token_budget,source:t}}function BO(e=[],t=[]){let n=[{source:"core",contracts:Op,allowOverride:!1},{source:"package",contracts:t,allowOverride:!1},{source:"workspace",contracts:e,allowOverride:!0}],r=new Map,o=new Set;for(let i of n){o.clear();for(let s of i.contracts){let a=VO(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&&r.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);r.set(c,a)}}return[...r.values()].sort((i,s)=>i.command.localeCompare(s.command)||i.intent.localeCompare(s.intent))}function Ip(e,t,n=qO(),r=[]){let o=e.trim().toLowerCase(),i=t.trim().toLowerCase(),s=n.find(f=>f.command===o&&f.intent===i);if(s)return{...s,source:s.source??"core"};let a=n.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,...r,"--for",i],l=[o,...r,"--for",c],u=Jt(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:Jt(d),allowed_values:[...a].sort(),suggested_retry:u,suggested_retry_args:l}})}function wc(e,t){let n=On(e.limit),r=String(n===void 0?t:Math.min(n,t));return(e.limit===void 0||n!==void 0)&&(e.limit=r),r}var Tp={context:(e,t,n)=>{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 r=hi(e.tokenBudget,t.token_budget),o=gi("context",t.intent,r,n),i=wc(e,o);e.activityLimit===void 0&&(e.activityLimit=i)},get:e=>{e.depth===void 0&&e.fields===void 0&&(e.depth="standard")},list:(e,t,n)=>{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 r=hi(e.tokenBudget,t.token_budget),o=gi("list",t.intent,r,n);wc(e,o)},next:e=>{e.readyOnly===void 0&&(e.readyOnly=!0)},search:(e,t,n)=>{e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.compact=!0);let r=hi(e.tokenBudget,t.token_budget),o=gi("search",t.intent,r,n);wc(e,o)}};function tL(e,t,n=[]){let r=t.tokenBudget??t.token_budget;if(typeof t.for!="string"){if(r!==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:r};return delete a.token_budget,a}let o=Ip(e,t.for,void 0,n),i=On(r)!==void 0,s={...t};return s.tokenBudget===void 0&&r!==void 0&&(s.tokenBudget=r),delete s.token_budget,s.tokenBudget===void 0&&(s.tokenBudget=String(o.token_budget)),Tp[e](s,o,i),s}var WO={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},yi=256;function vc(e){return Array.isArray(e)?e.map(vc):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,vc(n)])):typeof e=="string"&&e.length>240?`${Ee(e,240)}\u2026`:e}function On(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 hi(e,t){let n=On(e);if(n===void 0)return t;if(n<yi)throw new g(`Context intent token budget must be at least ${yi}`,h.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(e),required:`Use an integer token budget of at least ${yi}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${yi} or omit the override.`]});return n}function Cp(e,t){return e==="context"?e==="context"&&t==="orient"?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:e==="list"?520:480,rowCost:16}}function gi(e,t,n,r){if(e==="get"||e==="next")return;let{overhead:o,rowCost:i}=Cp(e,t),s=Math.max(e==="context"?1:2,Math.floor((n-o)/i));return r?s:Math.min(e==="context"?20:100,s)}function it(e,t){let n=t.estimated_tokens;for(;;){t.estimated_tokens=n;let r=Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4);if(r===n)return;n=r}}var Sp={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 Rp(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 GO(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 KO(e,t,n){let r=!1;for(;;){if(it(e,t),t.estimated_tokens<=t.token_budget||n.length<=1)return r;let o=Buffer.byteLength(JSON.stringify(n),"utf8"),i=(t.estimated_tokens-t.token_budget)*4;n.splice(-Math.min(n.length-1,Math.max(1,Math.ceil(i/Math.max(1,Math.ceil(o/n.length)))))),r=!0}}function YO(e,t,n){let r=e.items,o=typeof e.next_cursor=="string",i=o?e.next_cursor:n.after;if(!Array.isArray(r)||typeof i!="string")return!1;let s=Rp(i);if(s===void 0)return!1;let a=r.length,c=[...r],d=!1;for(;;){if(d=KO(e,t,r)||d,!d)return!1;let l=GO(r.at(-1));if(l===void 0)return r.splice(0,r.length,...c),it(e,t),!1;if(e.next_cursor=Or(s.fingerprint,l,o?s.after_index-(a-r.length):s.after_index+r.length,s.snapshot),it(e,t),t.estimated_tokens<=t.token_budget||r.length<=1)break}return typeof e.count=="number"&&(e.count=r.length),typeof e.applied_limit=="number"&&(e.applied_limit=r.length),!0}function XO(e,t,n,r){if(e==="list"||e==="search")return YO(t,n,r);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if(it(t,n),n.estimated_tokens<=n.token_budget)return o;let i=Sp[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=Sp[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=(n.estimated_tokens-n.token_budget)*4,u=Math.min(a,Math.max(1,Math.ceil(l/d)));i.rows.splice(-u,u),o=!0}}function JO(e,t,n){if(typeof t.for!="string")return n;let r=e.startsWith("list-")?"list":e;if(!(r in Tp))return n;let o=r,i=Ip(o,t.for),s=hi(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:WO[o],declaration_feasible:!0,result_omitted:!1},c={...n},d=gi(o,i.intent,a.token_budget,On(t.tokenBudget??t.token_budget)!==void 0);if(d!==void 0){let u=On(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,tA({builtInCommand:o,intent:i.intent},a,c,t)}let l={...c,context_intent:a};return it(l,a),a.estimated_tokens>a.token_budget&&(a.degradation="recursive_budget_compaction",l={...vc(c),context_intent:a},it(l,a)),a.estimated_tokens>a.token_budget&&XO(o,l,a,t)&&(a.degradation="budget_row_compaction",it(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:nA(e,o,i.intent,a,c)},context_intent:a}),l}var ZO=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function QO(e,t){if(typeof e.after!="string"||e.after.length===0)return t;let n=Rp(e.after)?.fingerprint??"opaque_cursor",r={...t};for(let o of ZO)delete r[o];return r.continuation_contract={fingerprint:n,metadata:"reference",restore_with:"omit --after"},r}function bi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function eA(e,t){let n=e==="get"&&bi(t.item)&&typeof t.item.id=="string"?t.item.id:e==="search"&&typeof t.query=="string"?t.query:void 0;return n===void 0?"":` '${n.replaceAll("'",`'"'"'`)}'`}function tA(e,t,n,r){let o=On(r.limit),i=t.budget_derived_limit;if(o===void 0||o<=i)return;let{overhead:s,rowCost:a}=Cp(e.builtInCommand,e.intent),c=Math.max(t.token_budget,s+a*o);t.limit_reason=`The ${t.token_budget}-token ${e.intent} budget carries ${i} rows, so it reduced the caller's --limit ${o}.`,t.limit_override={flag:"--limit",requested:o,effective:i,...Number.isSafeInteger(c)?{token_budget_for_requested:c,restore_with:`--token-budget ${c}`}:{}};let d=`${HO}:--limit ${o}->${i}`;n.warnings=Array.isArray(n.warnings)?[...n.warnings,d]:[d],bi(n.filters)&&(n.filters={...n.filters,requested_limit:String(o)})}function nA(e,t,n,r,o){let i=eA(t,o),s=t==="get"?"":` --limit ${r.budget_derived_limit??1}`;return`pm ${e}${i} --for ${n} --token-budget ${Math.ceil(r.estimated_tokens/100)*100}${s}`}function Sn(e,t){if(bi(e))return typeof e[t]=="number"?e[t]:void 0}function rA(e,t){let n=e;for(let r=0;r<8;r+=1){let o=Sn(n.context_intent,"estimated_tokens"),i=Sn(n.read_output,"estimated_tokens"),s=Sn(n.read_session,"spent_this_call_tokens");if(bi(n.context_intent)&&it(n,n.context_intent),n=pc(n,t),Sn(n.context_intent,"estimated_tokens")===o&&Sn(n.read_output,"estimated_tokens")===i&&Sn(n.read_session,"spent_this_call_tokens")===s)break}return n}function xp(e,t,n){let r=vm(e,Nm(e??"",n)),o=typeof r=="object"&&r!==null&&!Array.isArray(r)?cp(e??"",{...t,outputRowContract:t.outputRowContract===!0||t.output_row_contract===!0},QO(t,JO(e??"",t,r))):r;if(kn(n,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=rA(i,t);return delete s.row_contract,kn(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 An=["result_rows","envelope","diagnostics","hints"],oA=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,iA=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,sA=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,aA=8;function Ec(e){return Buffer.byteLength(e,"utf8")}function Np(e){return Ec(JSON.stringify(e)??"null")}function cA(e,t){return iA.test(e)?"diagnostics":sA.test(e)?"hints":oA.test(e)||Array.isArray(t)?"result_rows":"envelope"}function dA(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"]=Np(e),t;for(let[n,r]of Object.entries(e))t[cA(n,r)]+=Np({[n]:r});return Object.values(t).every(n=>n===0)&&(t.envelope=1),t}function lA(e,t){let n=An.reduce((s,a)=>s+t[a],0),r=An.map(s=>({section:s,value:e*t[s]/n})),o={result_rows:0,envelope:0,diagnostics:0,hints:0};for(let s of r)o[s.section]=Math.floor(s.value);let i=e-An.reduce((s,a)=>s+o[a],0);for(let s of[...r].sort((a,c)=>c.value-Math.floor(c.value)-(a.value-Math.floor(a.value))||An.indexOf(a.section)-An.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function Dp(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function Pp(e,t){let n=Ec(t(e)),r=lA(n,dA(e)),o=Object.fromEntries(An.map(a=>[a,{bytes:r[a],estimated_tokens:Nt(r[a])}])),i={version:1,measurement_scope:"output_before_token_accounting",estimator:"ceil(utf8_bytes / 4)",total_bytes:n,total_estimated_tokens:Nt(n),sections:o,accounting_receipt_bytes:0,accounting_receipt_estimated_tokens:0,excluded_fields:["token_accounting"],section_allocation:"proportional_canonical_json"},s=Dp(e,i);for(let a=0;a<aA;a+=1){let c=Ec(t(s))-n;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:Nt(c)},s=Dp(e,i)}return s}import{encode as Oc}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]="d3d21124-3c8a-5049-803d-00c63c0c2b61")}catch{}})();function Mp(e,t={}){let n=[...new Set(e.flatMap(l=>Object.keys(l)))],r=t.compact?n.filter(l=>e.every(u=>Object.hasOwn(u,l)&&u[l]===null)):[],o=t.compact?n.filter(l=>e.every(u=>{if(!Object.hasOwn(u,l))return!0;let f=u[l];return Array.isArray(f)&&f.every(m=>typeof m=="string"&&m!==""&&!m.includes(";"))})):[],i=new Set(o),s=new Set(r),a=n.filter(l=>!i.has(l)&&e.some(u=>{let f=u[l];return f!==null&&typeof f=="object"})),c=new Set(a),d=[];return{rows:e.map((l,u)=>Object.fromEntries(n.filter(f=>!s.has(f)).map(f=>{if(!Object.hasOwn(l,f))return d.push([u,f]),[f,null];let m=l[f];return i.has(f)?[f,m.join(";")]:[f,c.has(f)?JSON.stringify(m):m]}))),encoding:{json_columns:a,absent:d,...o.length?{list_columns:Object.fromEntries(o.map(l=>[l,";"]))}:{},...r.length?{null_columns:r,null_column_index:r.map(l=>n.indexOf(l))}:{}}}}function uA(e,t){let n=t.null_columns??[],r=t.null_column_index??[],o=[...e],i=n.map((s,a)=>({column:s,position:r[a]})).filter(s=>typeof s.position=="number").sort((s,a)=>s.position-a.position);for(let{column:s,position:a}of i)o.splice(Math.min(a,o.length),0,s);for(let s of n)o.includes(s)||o.push(s);return o}function iL(e){let t=new Set(e.encoding.json_columns),n=new Map(Object.entries(e.encoding.list_columns??{})),r=new Set(e.encoding.absent.map(([o,i])=>JSON.stringify([o,i])));return e.rows.map((o,i)=>{let s=new Map(Object.entries(o).flatMap(([c,d])=>{if(r.has(JSON.stringify([i,c])))return[];let l=n.get(c),u=l!==void 0?d===""?[]:String(d).split(l):t.has(c)?JSON.parse(String(d)):d;return[[c,u]]}));for(let c of e.encoding.null_columns??[])s.set(c,null);let a=e.encoding.column_order??uA(Object.keys(o),e.encoding);return Object.fromEntries(a.filter(c=>s.has(c)).map(c=>[c,s.get(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]="3a93b3f4-9511-5c8d-a176-6d8bf97981c7")}catch{}})();var cL=["id","title","status","type","priority","parent","updated_at"],wi=["id","status","type","title"],dL={list:"brief","list-all":"full","list-draft":"full","list-open":"brief","list-in-progress":"brief","list-blocked":"brief","list-closed":"brief","list-canceled":"full"},fA=["tree_depth","tree_parent","tree_children","tree_title"];function lL(e=[]){return[...new Set([...ve,"body",...fA,...e])].flatMap(t=>[t,`item.${t}`]).sort()}var mA=["brief","standard","deep"],uL=[...mA,"full"],fL=["brief","standard","deep"],pA=["body","item_hash","linked","claim_state","children","schedule","blockers"],_A=["linked.files","linked.tests","linked.docs"],yA=["claim_state.claimed","claim_state.assignee","claim_state.last_claim","claim_state.last_release"],hA=["schedule.deadline","schedule.start_at","schedule.end_at","schedule.location","schedule.reminders","schedule.events"];function mL(e=[]){return[...[...new Set([...ve,...e,"notes_count","tests_count","collection_counts"])].flatMap(t=>[t,`item.${t}`]),...pA,..._A,...yA,...hA].sort()}var pL=["id","title","status","type","priority","updated_at","score","matched_fields"],gA=["score","matched_fields","highlights"],$p=["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 _L(e=[]){let t=[...new Set(e)];return[...gA,...$p,...$p.map(n=>`item.${n}`),...t,...t.map(n=>`item.${n}`)].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]="0841394b-c439-5002-8451-c538a17acf47")}catch{}})();function He(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bA(e){if(!He(e))return!1;let t=e.fields;return e.mode==="brief"&&Object.keys(e).length===2&&Array.isArray(t)&&(t.length===wi.length||t.length===wi.length+1&&t.at(-1)==="priority")&&wi.every((n,r)=>t[r]===n)}function jp(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 wA(e){return He(e)&&(e.status==="complete"||e.status==="unchecked")&&e.unreadable_item_count===0&&e.unreadable_directory_count===0}function Lp(e,t="full_item_fields"){if(!He(e)||!Array.isArray(e.omitted_field_groups))return!1;let n=e.omitted_field_groups,r=n[0];return e.has_omissions===!0&&e.omitted_field_group_count===1&&Object.keys(e).length===3&&n.length===1&&He(r)&&Object.keys(r).length===2&&r.name===t&&r.restore_with==="--full"}function Fp(e){if(!He(e)||!Array.isArray(e.items)||Object.hasOwn(e,"details")||!bA(e.projection)||!wA(e.completeness)||!jp(e,e.items.length)||!Lp(e.omission_receipt))return e;let{total:t,has_more:n,truncated:r,next_cursor:o,completeness:i,projection:s,now:a,omission_receipt:c,sorting:d,filters:l,...u}=e,f=i.status==="complete"&&!n&&Object.keys(i).length===3,{unreadable_item_count:m,unreadable_directory_count:_,...y}=i;return{...u,...f?{}:{total:t,has_more:n,completeness:y},...n?{next_cursor:o}:{},...kA(d),...zp(l,u.applied_limit),details:"--full"}}function vA(e){return He(e)&&e.sort==="default"&&e.order==="asc"&&Object.keys(e).every(t=>t==="sort"||t==="order"||t==="effective_keys")}function EA(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&(e[1]==="asc"||e[1]==="desc")}function kA(e){if(!vA(e))return{sorting:e};let t=e.effective_keys;return t===void 0?{}:!Array.isArray(t)||!t.every(EA)?{sorting:e}:{sorting:{effective_keys:t.map(([n,r])=>`${n} ${r}`).join(", ")}}}function zp(e,t){if(!He(e))return e===void 0?{}:{filters:e};let n=Object.fromEntries(Object.entries(e).filter(([r,o])=>!(r==="limit"&&String(o)===String(t))&&!(r==="runtime_filters"&&He(o)&&Object.keys(o).length===0)));return Object.keys(n).length===0?{}:{filters:n}}function SA(e,t){return e.count===t&&!Object.hasOwn(e,"has_more")&&!Object.hasOwn(e,"truncated")&&e.next_cursor==null&&(e.total===void 0||e.total===t)}function Up(e){if(!He(e)||typeof e.query!="string"||!Array.isArray(e.items)||Object.hasOwn(e,"details")||Object.hasOwn(e,"projection")||!(jp(e,e.items.length)||SA(e,e.items.length))||!Lp(e.omission_receipt,"projection_metadata"))return e;let{truncated:t,omission_receipt:n,filters:r,...o}=e;return{...o,...zp(r,o.applied_limit),details:"--full"}}import{isBoxedPrimitive as OA}from"node:util/types";(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]="1b399abd-460a-55a5-9df2-db23537aac0d")}catch{}})();var Hp=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/gu;function EL(e){return e.replaceAll(Hp,"\uFFFD")}function AA(e,t,n){return n&&/^\d+$/u.test(t)?`${e}[${t}]`:/^[A-Za-z_$][\w$]*$/u.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function kc(e,t,n){if(typeof e=="string"){let r=e.search(Hp);return r<0?void 0:{field:t,index:r}}if(!(e===null||typeof e!="object"||n.has(e))){n.add(e);for(let[r,o]of Object.entries(e)){let i=AA(t,r,Array.isArray(e)),s=kc(r,`${i} (key)`,n)??kc(o,i,n);if(s)return s}}}function qp(e,t,n){if(e===null||typeof e!="object")return e;if(OA(e)||typeof e.toJSON=="function")return JSON.parse(JSON.stringify({[t]:e}))[t];if(n.has(e))return n.get(e);let r=Array.isArray(e)?new Array(e.length):{};n.set(e,r);for(let o of Object.keys(e))Object.defineProperty(r,o,{value:qp(e[o],o,n),enumerable:!0,configurable:!0,writable:!0});return r}function Sc(e){let t=qp(e,"",new WeakMap),n=kc(t,"$",new WeakSet);return n&&IA(n),t}function IA(e){throw new g(`Output field ${e.field} contains an unpaired surrogate code unit at index ${e.index}; structured output requires well-formed Unicode.`,h.USAGE,{code:"text_unpaired_surrogate",field:e.field,required:"Well-formed UTF-16 strings and object keys in both JSON and TOON output.",nextSteps:["Repair the producer's text before returning output; use toWellFormedText from @unbrained/pm-cli/sdk when replacement is intended."]})}function kL(e){Sc(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]="d47af602-51bb-592c-8dce-3de5c8a96636")}catch{}})();var TA=new Set(Object.values(h)),CA=new Map([["notes_count","notes"],["tests_count","tests"]]),Ac="__pm_native_output",Vp=!1;function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rc(e){let t={read_output:{result_omitted:!0}};kn(e,t),Ao(t)}function RA(e,t,n){if(n){Ao(e);return}Rc(t)}function xA(e){if(!L(e)||e[Ac]!==!0)return e;let{[Ac]:t,...n}=e;return n}function Ic(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function NA(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function DA(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function Tc(e){if(e==="stdout"){NA();return}DA()}function Bp(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function PA(){Vp||(Vp=!0,process.stdout.on("error",e=>{if(Ic(e)){Tc("stdout");return}Bp(e)}),process.stderr.on("error",e=>{if(Ic(e)){Tc("stderr");return}Bp(e)}))}function Wp(e,t){PA();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(Ic(n))return Tc(e),!1;throw n}}function MA(e){return Wp("stdout",e)}function Cr(e){return Wp("stderr",e)}function Gp(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function Cc(e,t){let n=" ".repeat(t);return e.split(`
26
+ `).flatMap(c=>{try{let d=JSON.parse(c);return d&&Date.parse(d.at)>=t.cutoff?[d]:[]}catch{return[]}}).slice(-t.maxEvents)}finally{await n.close()}}catch{return[]}}function gp(e,t,n){let r=[],o=0;for(let i=e.length-1;i>=0&&r.length<n;i-=1){let s=`${JSON.stringify(e[i])}
27
+ `;if(o+=Buffer.byteLength(s),o>t)break;r.push(s)}return r.reverse().join("")}async function Tr(e,t,n){let r=wp(e),o=mi.join(e.pmRoot,"runtime","context-usage.jsonl"),i=Math.floor(r.maxBytes*Ue.retained_byte_fraction),s=Math.min(Ue.max_event_bytes,i);if(t.some(f=>Buffer.byteLength(`${JSON.stringify(f)}
28
+ `)>s))throw new Y("Context usage event exceeds the declared byte ceiling");let a=t.filter(f=>Date.parse(f.at)>=r.cutoff),c=gp(a,i,r.maxEvents),d=performance.now(),l=await fe(e.pmRoot,"context-usage-ledger",30,`context-usage:${process.pid}`,!1,!1,3e3),u=performance.now()-d;try{await TO(mi.dirname(o),{recursive:!0});let f=await vp(o,En.O_WRONLY|En.O_CREAT|En.O_APPEND);try{let m=(await f.stat()).size,_=n===void 0?void 0:await pi(e);if(_?.some(T=>T.kind==="delivery"&&T.serve_id===n))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)<=r.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=gp([..._??await pi(e),...a],i,r.maxEvents),w=`${o}.${process.pid}.${IO()}.tmp`,v=await bp(w,"wx",384);try{try{await v.writeFile(y,"utf8")}finally{await v.close()}return await f.close(),f=void 0,await CO(w,o),{written_bytes:Buffer.byteLength(y),ledger_bytes:Buffer.byteLength(y),compacted:!0,lock_wait_ms:u}}finally{await RO(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 NO=864e5,_i=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function Lj(e,t){let n=Q(e);n!==null&&t!==null&&(n[_i]=t)}function kn(e,t){let n=Q(e),r=Q(t),o=n?.[_i];r!==null&&o!==void 0&&(r[_i]=o)}function DO(e){return Q(e)?.[_i]??null}function kp(e){let t=Q(e);for(let n of["read_output","context_intent"])if(Q(t?.[n])?.result_omitted===!0)return!0;return!1}function ot(e,t){typeof t=="string"&&t.trim().length>0&&e.add(t.trim())}function Sp(e,t){if(Array.isArray(t))for(let n of t)ot(e,Q(n)?.id)}function Ep(e,t){if(Array.isArray(t))for(let n of t)ot(e,n)}function PO(e,t){let n=Q(e.recommended)===null?[]:[e.recommended];for(let r of["ready","decision_needed","gate_needed","containers","blocked","held_by_others"])Array.isArray(e[r])&&n.push(...e[r]);for(let r of n){let o=Q(r);ot(t,o?.id);for(let i of Array.isArray(o?.blockers)?o.blockers:[])ot(t,Q(i)?.id);for(let i of Array.isArray(o?.unblocks)?o.unblocks:[])ot(t,i)}}function MO(e,t){for(let n of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"])Sp(t,e[n]);for(let n of Array.isArray(e.blockers)?e.blockers:[])ot(t,Q(n)?.blocked_by);$O(e,t)}function $O(e,t){for(let o of Array.isArray(e.hierarchy)?e.hierarchy:[]){let i=Q(o);ot(t,i?.id),Sp(t,i?.children)}for(let o of["files","workload"])for(let i of Array.isArray(e[o])?e[o]:[])Ep(t,Q(i)?.items);let n=Q(e.agenda);for(let o of Array.isArray(n?.events)?n.events:[])ot(t,Q(o)?.item_id);let r=Q(e.tests);Ep(t,r?.items_failing)}function jO(e,t){let n=Q(e);if(n===null||kp(e))return[];let r=new Set;return t==="next"?PO(n,r):MO(n,r),[...r]}async function Fj(e){let t=DO(e.result);if(t===null)return!1;let n=kp(e.result);return await LO({pmRoot:e.pmRoot,receipt:t,deliveredItemIds:jO(e.result,t.surface),resultOmitted:n}),!0}async function zj(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 n=t.slice(0,Ue.max_serving_rows),r={serve_id:xO(),author:e.author.trim(),surface:e.surface,rows:t,recorded_item_ids:n.map(o=>o.id)};return r.storage=await Tr(e,[{kind:"serve",schema_version:2,serve_id:r.serve_id,at:Mt(e).iso,author:e.author.trim(),surface:e.surface,profile:e.profile.trim()||"balanced",rows:n,candidate_count:t.length,omitted_row_count:t.length-n.length,result_omitted:!1,packed_item_ids:n.filter(o=>o.included).map(o=>o.id)}]),r}async function LO(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)),n=[...new Set(e.deliveredItemIds.map(i=>i.trim()))];if(n.some(i=>i.length===0||!t.has(i))||e.resultOmitted&&n.length>0)throw new Y("Context usage delivery requires emitted ranked ids and zero ids for an omitted result");let r=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:Mt(e).iso,author:e.receipt.author,surface:e.receipt.surface,result_omitted:e.resultOmitted,delivered_item_ids:n.filter(i=>r.has(i))};await Tr(e,[o],o.serve_id)}async function Uj(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 Tr(e,[{kind:"touch",at:Mt(e).iso,author:e.author.trim(),item_id:e.itemId.trim(),intent:e.intent.trim()}])}}async function Hj(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1||e.itemIds.length===0)return;let t=e.author.trim(),n=e.intent.trim();if(!t||!n)throw new Y("Context usage touch requires author and intent");let r=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");r.add(a)}let o=Mt(e).iso,i=[...r].map(s=>({kind:"touch",at:o,author:t,item_id:s,intent:n}));await Tr(e,i)}function FO(e,t,n,r){return e.find(({entry:o,time:i})=>o.item_id===t&&i>=n&&i-n<=r)?.time}function zO(e,t){let n=new Map;for(let r of e)r.kind==="delivery"&&r.schema_version===2&&r.author===t&&!n.has(r.serve_id)&&n.set(r.serve_id,r);return n}async function qj(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 pi(e),n=Mt(e).ms,r=(e.horizonHours??24)*36e5;if(![Number.isFinite(r),r>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=zO(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=FO(i,w.id,m,r);if(v===void 0)continue;d+=1;let T=Math.max(0,(n-v)/NO);s.set(w.id,(s.get(w.id)??0)+Math.exp(-T/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]="4c8b43ab-cada-5adf-8c00-aed8de1a8bc1")}catch{}})();var HO="limit_overridden_by_intent",Ap=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"}]),Ip=new UO;function qO(){return Ip.getStore()??Ap}function tL(e,t){return Ip.run(BO(e.workspaceContracts,e.packageContracts),t)}function VO(e,t){let n=e.command.trim().toLowerCase(),r=e.intent.trim().toLowerCase(),o=`${n}:${r}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(n)||!/^[a-z0-9][a-z0-9-]*$/.test(r))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:n,intent:r,description:e.description.trim(),included_field_groups:i,token_budget:e.token_budget,source:t}}function BO(e=[],t=[]){let n=[{source:"core",contracts:Ap,allowOverride:!1},{source:"package",contracts:t,allowOverride:!1},{source:"workspace",contracts:e,allowOverride:!0}],r=new Map,o=new Set;for(let i of n){o.clear();for(let s of i.contracts){let a=VO(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&&r.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);r.set(c,a)}}return[...r.values()].sort((i,s)=>i.command.localeCompare(s.command)||i.intent.localeCompare(s.intent))}function Tp(e,t,n=qO(),r=[]){let o=e.trim().toLowerCase(),i=t.trim().toLowerCase(),s=n.find(f=>f.command===o&&f.intent===i);if(s)return{...s,source:s.source??"core"};let a=n.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,...r,"--for",i],l=[o,...r,"--for",c],u=Jt(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:Jt(d),allowed_values:[...a].sort(),suggested_retry:u,suggested_retry_args:l}})}function wc(e,t){let n=On(e.limit),r=String(n===void 0?t:Math.min(n,t));return(e.limit===void 0||n!==void 0)&&(e.limit=r),r}var Cp={context:(e,t,n)=>{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 r=hi(e.tokenBudget,t.token_budget),o=gi("context",t.intent,r,n),i=wc(e,o);e.activityLimit===void 0&&(e.activityLimit=i)},get:e=>{e.depth===void 0&&e.fields===void 0&&(e.depth="standard")},list:(e,t,n)=>{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 r=hi(e.tokenBudget,t.token_budget),o=gi("list",t.intent,r,n);wc(e,o)},next:e=>{e.readyOnly===void 0&&(e.readyOnly=!0)},search:(e,t,n)=>{e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.compact=!0);let r=hi(e.tokenBudget,t.token_budget),o=gi("search",t.intent,r,n);wc(e,o)}};function nL(e,t,n=[]){let r=t.tokenBudget??t.token_budget;if(typeof t.for!="string"){if(r!==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:r};return delete a.token_budget,a}let o=Tp(e,t.for,void 0,n),i=On(r)!==void 0,s={...t};return s.tokenBudget===void 0&&r!==void 0&&(s.tokenBudget=r),delete s.token_budget,s.tokenBudget===void 0&&(s.tokenBudget=String(o.token_budget)),Cp[e](s,o,i),s}var WO={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},yi=256;function vc(e){return Array.isArray(e)?e.map(vc):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,vc(n)])):typeof e=="string"&&e.length>240?`${Ee(e,240)}\u2026`:e}function On(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 hi(e,t){let n=On(e);if(n===void 0)return t;if(n<yi)throw new g(`Context intent token budget must be at least ${yi}`,h.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(e),required:`Use an integer token budget of at least ${yi}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${yi} or omit the override.`]});return n}function Rp(e,t){return e==="context"?e==="context"&&t==="orient"?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:e==="list"?520:480,rowCost:16}}function gi(e,t,n,r){if(e==="get"||e==="next")return;let{overhead:o,rowCost:i}=Rp(e,t),s=Math.max(e==="context"?1:2,Math.floor((n-o)/i));return r?s:Math.min(e==="context"?20:100,s)}function it(e,t){let n=t.estimated_tokens;for(;;){t.estimated_tokens=n;let r=Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4);if(r===n)return;n=r}}var Op={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 xp(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 GO(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 KO(e,t,n){let r=!1;for(;;){if(it(e,t),t.estimated_tokens<=t.token_budget||n.length<=1)return r;let o=Buffer.byteLength(JSON.stringify(n),"utf8"),i=(t.estimated_tokens-t.token_budget)*4;n.splice(-Math.min(n.length-1,Math.max(1,Math.ceil(i/Math.max(1,Math.ceil(o/n.length)))))),r=!0}}function YO(e,t,n){let r=e.items,o=typeof e.next_cursor=="string",i=o?e.next_cursor:n.after;if(!Array.isArray(r)||typeof i!="string")return!1;let s=xp(i);if(s===void 0)return!1;let a=r.length,c=[...r],d=!1;for(;;){if(d=KO(e,t,r)||d,!d)return!1;let l=GO(r.at(-1));if(l===void 0)return r.splice(0,r.length,...c),it(e,t),!1;if(e.next_cursor=Or(s.fingerprint,l,o?s.after_index-(a-r.length):s.after_index+r.length,s.snapshot),it(e,t),t.estimated_tokens<=t.token_budget||r.length<=1)break}return typeof e.count=="number"&&(e.count=r.length),typeof e.applied_limit=="number"&&(e.applied_limit=r.length),!0}function XO(e,t,n,r){if(e==="list"||e==="search")return YO(t,n,r);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if(it(t,n),n.estimated_tokens<=n.token_budget)return o;let i=Op[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=Op[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=(n.estimated_tokens-n.token_budget)*4,u=Math.min(a,Math.max(1,Math.ceil(l/d)));i.rows.splice(-u,u),o=!0}}function JO(e,t,n){if(typeof t.for!="string")return n;let r=e.startsWith("list-")?"list":e;if(!(r in Cp))return n;let o=r,i=Tp(o,t.for),s=hi(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:WO[o],declaration_feasible:!0,result_omitted:!1},c={...n},d=gi(o,i.intent,a.token_budget,On(t.tokenBudget??t.token_budget)!==void 0);if(d!==void 0){let u=On(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,tA({builtInCommand:o,intent:i.intent},a,c,t)}let l={...c,context_intent:a};return it(l,a),a.estimated_tokens>a.token_budget&&(a.degradation="recursive_budget_compaction",l={...vc(c),context_intent:a},it(l,a)),a.estimated_tokens>a.token_budget&&XO(o,l,a,t)&&(a.degradation="budget_row_compaction",it(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:nA(e,o,i.intent,a,c)},context_intent:a}),l}var ZO=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function QO(e,t){if(typeof e.after!="string"||e.after.length===0)return t;let n=xp(e.after)?.fingerprint??"opaque_cursor",r={...t};for(let o of ZO)delete r[o];return r.continuation_contract={fingerprint:n,metadata:"reference",restore_with:"omit --after"},r}function bi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function eA(e,t){let n=e==="get"&&bi(t.item)&&typeof t.item.id=="string"?t.item.id:e==="search"&&typeof t.query=="string"?t.query:void 0;return n===void 0?"":` '${n.replaceAll("'",`'"'"'`)}'`}function tA(e,t,n,r){let o=On(r.limit),i=t.budget_derived_limit;if(o===void 0||o<=i)return;let{overhead:s,rowCost:a}=Rp(e.builtInCommand,e.intent),c=Math.max(t.token_budget,s+a*o);t.limit_reason=`The ${t.token_budget}-token ${e.intent} budget carries ${i} rows, so it reduced the caller's --limit ${o}.`,t.limit_override={flag:"--limit",requested:o,effective:i,...Number.isSafeInteger(c)?{token_budget_for_requested:c,restore_with:`--token-budget ${c}`}:{}};let d=`${HO}:--limit ${o}->${i}`;n.warnings=Array.isArray(n.warnings)?[...n.warnings,d]:[d],bi(n.filters)&&(n.filters={...n.filters,requested_limit:String(o)})}function nA(e,t,n,r,o){let i=eA(t,o),s=t==="get"?"":` --limit ${r.budget_derived_limit??1}`;return`pm ${e}${i} --for ${n} --token-budget ${Math.ceil(r.estimated_tokens/100)*100}${s}`}function Sn(e,t){if(bi(e))return typeof e[t]=="number"?e[t]:void 0}function rA(e,t){let n=e;for(let r=0;r<8;r+=1){let o=Sn(n.context_intent,"estimated_tokens"),i=Sn(n.read_output,"estimated_tokens"),s=Sn(n.read_session,"spent_this_call_tokens");if(bi(n.context_intent)&&it(n,n.context_intent),n=pc(n,t),Sn(n.context_intent,"estimated_tokens")===o&&Sn(n.read_output,"estimated_tokens")===i&&Sn(n.read_session,"spent_this_call_tokens")===s)break}return n}function Np(e,t,n){let r=Em(e,Dm(e??"",n)),o=typeof r=="object"&&r!==null&&!Array.isArray(r)?dp(e??"",{...t,outputRowContract:t.outputRowContract===!0||t.output_row_contract===!0},QO(t,JO(e??"",t,r))):r;if(kn(n,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=rA(i,t);return delete s.row_contract,kn(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 An=["result_rows","envelope","diagnostics","hints"],oA=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,iA=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,sA=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,aA=8;function Ec(e){return Buffer.byteLength(e,"utf8")}function Dp(e){return Ec(JSON.stringify(e)??"null")}function cA(e,t){return iA.test(e)?"diagnostics":sA.test(e)?"hints":oA.test(e)||Array.isArray(t)?"result_rows":"envelope"}function dA(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"]=Dp(e),t;for(let[n,r]of Object.entries(e))t[cA(n,r)]+=Dp({[n]:r});return Object.values(t).every(n=>n===0)&&(t.envelope=1),t}function lA(e,t){let n=An.reduce((s,a)=>s+t[a],0),r=An.map(s=>({section:s,value:e*t[s]/n})),o={result_rows:0,envelope:0,diagnostics:0,hints:0};for(let s of r)o[s.section]=Math.floor(s.value);let i=e-An.reduce((s,a)=>s+o[a],0);for(let s of[...r].sort((a,c)=>c.value-Math.floor(c.value)-(a.value-Math.floor(a.value))||An.indexOf(a.section)-An.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function Pp(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function Mp(e,t){let n=Ec(t(e)),r=lA(n,dA(e)),o=Object.fromEntries(An.map(a=>[a,{bytes:r[a],estimated_tokens:Nt(r[a])}])),i={version:1,measurement_scope:"output_before_token_accounting",estimator:"ceil(utf8_bytes / 4)",total_bytes:n,total_estimated_tokens:Nt(n),sections:o,accounting_receipt_bytes:0,accounting_receipt_estimated_tokens:0,excluded_fields:["token_accounting"],section_allocation:"proportional_canonical_json"},s=Pp(e,i);for(let a=0;a<aA;a+=1){let c=Ec(t(s))-n;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:Nt(c)},s=Pp(e,i)}return s}import{encode as Oc}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]="d3d21124-3c8a-5049-803d-00c63c0c2b61")}catch{}})();function $p(e,t={}){let n=[...new Set(e.flatMap(l=>Object.keys(l)))],r=t.compact?n.filter(l=>e.every(u=>Object.hasOwn(u,l)&&u[l]===null)):[],o=t.compact?n.filter(l=>e.every(u=>{if(!Object.hasOwn(u,l))return!0;let f=u[l];return Array.isArray(f)&&f.every(m=>typeof m=="string"&&m!==""&&!m.includes(";"))})):[],i=new Set(o),s=new Set(r),a=n.filter(l=>!i.has(l)&&e.some(u=>{let f=u[l];return f!==null&&typeof f=="object"})),c=new Set(a),d=[];return{rows:e.map((l,u)=>Object.fromEntries(n.filter(f=>!s.has(f)).map(f=>{if(!Object.hasOwn(l,f))return d.push([u,f]),[f,null];let m=l[f];return i.has(f)?[f,m.join(";")]:[f,c.has(f)?JSON.stringify(m):m]}))),encoding:{json_columns:a,absent:d,...o.length?{list_columns:Object.fromEntries(o.map(l=>[l,";"]))}:{},...r.length?{null_columns:r,null_column_index:r.map(l=>n.indexOf(l))}:{}}}}function uA(e,t){let n=t.null_columns??[],r=t.null_column_index??[],o=[...e],i=n.map((s,a)=>({column:s,position:r[a]})).filter(s=>typeof s.position=="number").sort((s,a)=>s.position-a.position);for(let{column:s,position:a}of i)o.splice(Math.min(a,o.length),0,s);for(let s of n)o.includes(s)||o.push(s);return o}function sL(e){let t=new Set(e.encoding.json_columns),n=new Map(Object.entries(e.encoding.list_columns??{})),r=new Set(e.encoding.absent.map(([o,i])=>JSON.stringify([o,i])));return e.rows.map((o,i)=>{let s=new Map(Object.entries(o).flatMap(([c,d])=>{if(r.has(JSON.stringify([i,c])))return[];let l=n.get(c),u=l!==void 0?d===""?[]:String(d).split(l):t.has(c)?JSON.parse(String(d)):d;return[[c,u]]}));for(let c of e.encoding.null_columns??[])s.set(c,null);let a=e.encoding.column_order??uA(Object.keys(o),e.encoding);return Object.fromEntries(a.filter(c=>s.has(c)).map(c=>[c,s.get(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]="3a93b3f4-9511-5c8d-a176-6d8bf97981c7")}catch{}})();var dL=["id","title","status","type","priority","parent","updated_at"],wi=["id","status","type","title"],lL={list:"brief","list-all":"full","list-draft":"full","list-open":"brief","list-in-progress":"brief","list-blocked":"brief","list-closed":"brief","list-canceled":"full"},fA=["tree_depth","tree_parent","tree_children","tree_title"];function uL(e=[]){return[...new Set([...ve,"body",...fA,...e])].flatMap(t=>[t,`item.${t}`]).sort()}var mA=["brief","standard","deep"],fL=[...mA,"full"],mL=["brief","standard","deep"],pA=["body","item_hash","linked","claim_state","children","schedule","blockers"],_A=["linked.files","linked.tests","linked.docs"],yA=["claim_state.claimed","claim_state.assignee","claim_state.last_claim","claim_state.last_release"],hA=["schedule.deadline","schedule.start_at","schedule.end_at","schedule.location","schedule.reminders","schedule.events"];function pL(e=[]){return[...[...new Set([...ve,...e,"notes_count","tests_count","collection_counts"])].flatMap(t=>[t,`item.${t}`]),...pA,..._A,...yA,...hA].sort()}var _L=["id","title","status","type","priority","updated_at","score","matched_fields"],gA=["score","matched_fields","highlights"],jp=["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 yL(e=[]){let t=[...new Set(e)];return[...gA,...jp,...jp.map(n=>`item.${n}`),...t,...t.map(n=>`item.${n}`)].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]="0841394b-c439-5002-8451-c538a17acf47")}catch{}})();function He(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bA(e){if(!He(e))return!1;let t=e.fields;return e.mode==="brief"&&Object.keys(e).length===2&&Array.isArray(t)&&(t.length===wi.length||t.length===wi.length+1&&t.at(-1)==="priority")&&wi.every((n,r)=>t[r]===n)}function Lp(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 wA(e){return He(e)&&(e.status==="complete"||e.status==="unchecked")&&e.unreadable_item_count===0&&e.unreadable_directory_count===0}function Fp(e,t="full_item_fields"){if(!He(e)||!Array.isArray(e.omitted_field_groups))return!1;let n=e.omitted_field_groups,r=n[0];return e.has_omissions===!0&&e.omitted_field_group_count===1&&Object.keys(e).length===3&&n.length===1&&He(r)&&Object.keys(r).length===2&&r.name===t&&r.restore_with==="--full"}function zp(e){if(!He(e)||!Array.isArray(e.items)||Object.hasOwn(e,"details")||!bA(e.projection)||!wA(e.completeness)||!Lp(e,e.items.length)||!Fp(e.omission_receipt))return e;let{total:t,has_more:n,truncated:r,next_cursor:o,completeness:i,projection:s,now:a,omission_receipt:c,sorting:d,filters:l,...u}=e,f=i.status==="complete"&&!n&&Object.keys(i).length===3,{unreadable_item_count:m,unreadable_directory_count:_,...y}=i;return{...u,...f?{}:{total:t,has_more:n,completeness:y},...n?{next_cursor:o}:{},...kA(d),...Up(l,u.applied_limit),details:"--full"}}function vA(e){return He(e)&&e.sort==="default"&&e.order==="asc"&&Object.keys(e).every(t=>t==="sort"||t==="order"||t==="effective_keys")}function EA(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&(e[1]==="asc"||e[1]==="desc")}function kA(e){if(!vA(e))return{sorting:e};let t=e.effective_keys;return t===void 0?{}:!Array.isArray(t)||!t.every(EA)?{sorting:e}:{sorting:{effective_keys:t.map(([n,r])=>`${n} ${r}`).join(", ")}}}function Up(e,t){if(!He(e))return e===void 0?{}:{filters:e};let n=Object.fromEntries(Object.entries(e).filter(([r,o])=>!(r==="limit"&&String(o)===String(t))&&!(r==="runtime_filters"&&He(o)&&Object.keys(o).length===0)));return Object.keys(n).length===0?{}:{filters:n}}function SA(e,t){return e.count===t&&!Object.hasOwn(e,"has_more")&&!Object.hasOwn(e,"truncated")&&e.next_cursor==null&&(e.total===void 0||e.total===t)}function Hp(e){if(!He(e)||typeof e.query!="string"||!Array.isArray(e.items)||Object.hasOwn(e,"details")||Object.hasOwn(e,"projection")||!(Lp(e,e.items.length)||SA(e,e.items.length))||!Fp(e.omission_receipt,"projection_metadata"))return e;let{truncated:t,omission_receipt:n,filters:r,...o}=e;return{...o,...Up(r,o.applied_limit),details:"--full"}}import{isBoxedPrimitive as OA}from"node:util/types";(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]="1b399abd-460a-55a5-9df2-db23537aac0d")}catch{}})();var qp=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/gu;function kL(e){return e.replaceAll(qp,"\uFFFD")}function AA(e,t,n){return n&&/^\d+$/u.test(t)?`${e}[${t}]`:/^[A-Za-z_$][\w$]*$/u.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function kc(e,t,n){if(typeof e=="string"){let r=e.search(qp);return r<0?void 0:{field:t,index:r}}if(!(e===null||typeof e!="object"||n.has(e))){n.add(e);for(let[r,o]of Object.entries(e)){let i=AA(t,r,Array.isArray(e)),s=kc(r,`${i} (key)`,n)??kc(o,i,n);if(s)return s}}}function Vp(e,t,n){if(e===null||typeof e!="object")return e;if(OA(e)||typeof e.toJSON=="function")return JSON.parse(JSON.stringify({[t]:e}))[t];if(n.has(e))return n.get(e);let r=Array.isArray(e)?new Array(e.length):{};n.set(e,r);for(let o of Object.keys(e))Object.defineProperty(r,o,{value:Vp(e[o],o,n),enumerable:!0,configurable:!0,writable:!0});return r}function Sc(e){let t=Vp(e,"",new WeakMap),n=kc(t,"$",new WeakSet);return n&&IA(n),t}function IA(e){throw new g(`Output field ${e.field} contains an unpaired surrogate code unit at index ${e.index}; structured output requires well-formed Unicode.`,h.USAGE,{code:"text_unpaired_surrogate",field:e.field,required:"Well-formed UTF-16 strings and object keys in both JSON and TOON output.",nextSteps:["Repair the producer's text before returning output; use toWellFormedText from @unbrained/pm-cli/sdk when replacement is intended."]})}function SL(e){Sc(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]="d47af602-51bb-592c-8dce-3de5c8a96636")}catch{}})();var TA=new Set(Object.values(h)),CA=new Map([["notes_count","notes"],["tests_count","tests"]]),Ac="__pm_native_output",Bp=!1;function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rc(e){let t={read_output:{result_omitted:!0}};kn(e,t),Ao(t)}function RA(e,t,n){if(n){Ao(e);return}Rc(t)}function xA(e){if(!L(e)||e[Ac]!==!0)return e;let{[Ac]:t,...n}=e;return n}function Ic(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function NA(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function DA(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function Tc(e){if(e==="stdout"){NA();return}DA()}function Wp(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function PA(){Bp||(Bp=!0,process.stdout.on("error",e=>{if(Ic(e)){Tc("stdout");return}Wp(e)}),process.stderr.on("error",e=>{if(Ic(e)){Tc("stderr");return}Wp(e)}))}function Gp(e,t){PA();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(Ic(n))return Tc(e),!1;throw n}}function MA(e){return Gp("stdout",e)}function Cr(e){return Gp("stderr",e)}function Kp(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function Cc(e,t){let n=" ".repeat(t);return e.split(`
29
29
  `).map(r=>`${n}${r}`).join(`
30
- `)}function $A(e){let t=new Set,n=0;for(let r of e){let o=Object.keys(r);n+=o.length;for(let i of o)t.add(i)}return e.length*t.size<=n*2}function jA(e,t,n,r){let o=" ".repeat(n);if(!L(t)&&!Array.isArray(t))return`${o}${e}: ${Gp(t)}`;if(Array.isArray(t)){if(t.length===0)return`${o}${e}: []`;let i=Cc(Oc({[e]:t}),n);return r&&t.length>=1&&t.every(L)&&$A(t)?[!1,!0].map(s=>{let a=Mp(t,{compact:s});return Cc(Oc({[e]:a.rows,[`${e}_encoding`]:a.encoding}),n)}).reduce((s,a)=>Buffer.byteLength(a)<Buffer.byteLength(s)?a:s,i):i}return L(t)&&Object.keys(t).length===0?`${o}${e}: {}`:`${o}${e}:
31
- ${Kp(t,n+1)}`}function LA(e,t,n){let r=e.map(o=>Ei(o,t,n||t.preserveRowFacts&&L(o))).filter(o=>o!==void 0);return r.length>0||n?r:void 0}function Ei(e,t={omitDuplicateCountAliases:!0,preserveRowFacts:!0},n=!1){if(e===null)return n?null:void 0;if(Array.isArray(e))return LA(e,t,n);if(L(e)){let r=[],o=Object.entries(e).filter(([i,s])=>{let a=CA.get(i);return!t.omitDuplicateCountAliases||a===void 0||!L(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){r.push([i,[]]);continue}let a=Ei(s,t,n);a!==void 0&&r.push([i,a])}return r.length>0||n?Object.fromEntries(r):void 0}return e}function Kp(e,t){let n=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":Cc(Oc(e),t);if(L(e)){let r=Object.entries(e);return r.length===0?"{}":r.map(([o,i])=>jA(o,i,t,!Object.hasOwn(e,`${o}_encoding`)&&!(o==="checks"&&L(e.verdict)&&e.verdict.authority==="ok"))).join(`
32
- `)}return`${n}${Gp(e)}`}function FA(e){if(!L(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})`,""],n=L(e.summary)?e.summary:{};if(t.push(`- events: ${String(n.events??0)}`),t.push(""),e.events.length===0)return t.push("No calendar events matched the selected filters."),`${t.join(`
30
+ `)}function $A(e){let t=new Set,n=0;for(let r of e){let o=Object.keys(r);n+=o.length;for(let i of o)t.add(i)}return e.length*t.size<=n*2}function jA(e,t,n,r){let o=" ".repeat(n);if(!L(t)&&!Array.isArray(t))return`${o}${e}: ${Kp(t)}`;if(Array.isArray(t)){if(t.length===0)return`${o}${e}: []`;let i=Cc(Oc({[e]:t}),n);return r&&t.length>=1&&t.every(L)&&$A(t)?[!1,!0].map(s=>{let a=$p(t,{compact:s});return Cc(Oc({[e]:a.rows,[`${e}_encoding`]:a.encoding}),n)}).reduce((s,a)=>Buffer.byteLength(a)<Buffer.byteLength(s)?a:s,i):i}return L(t)&&Object.keys(t).length===0?`${o}${e}: {}`:`${o}${e}:
31
+ ${Yp(t,n+1)}`}function LA(e,t,n){let r=e.map(o=>Ei(o,t,n||t.preserveRowFacts&&L(o))).filter(o=>o!==void 0);return r.length>0||n?r:void 0}function Ei(e,t={omitDuplicateCountAliases:!0,preserveRowFacts:!0},n=!1){if(e===null)return n?null:void 0;if(Array.isArray(e))return LA(e,t,n);if(L(e)){let r=[],o=Object.entries(e).filter(([i,s])=>{let a=CA.get(i);return!t.omitDuplicateCountAliases||a===void 0||!L(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){r.push([i,[]]);continue}let a=Ei(s,t,n);a!==void 0&&r.push([i,a])}return r.length>0||n?Object.fromEntries(r):void 0}return e}function Yp(e,t){let n=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":Cc(Oc(e),t);if(L(e)){let r=Object.entries(e);return r.length===0?"{}":r.map(([o,i])=>jA(o,i,t,!Object.hasOwn(e,`${o}_encoding`)&&!(o==="checks"&&L(e.verdict)&&e.verdict.authority==="ok"))).join(`
32
+ `)}return`${n}${Kp(e)}`}function FA(e){if(!L(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})`,""],n=L(e.summary)?e.summary:{};if(t.push(`- events: ${String(n.events??0)}`),t.push(""),e.events.length===0)return t.push("No calendar events matched the selected filters."),`${t.join(`
33
33
  `)}
34
34
  `;for(let r of e.events){if(!L(r))continue;let o=typeof r.kind=="string"?r.kind:"event",i=typeof r.item_title=="string"?r.item_title:"",s=typeof r.item_id=="string"?r.item_id:"",a=typeof r.reminder_text=="string"&&r.reminder_text.length>0?` ${r.reminder_text}`:"";t.push(`- [${o}] ${s} ${i}${a}`.trim())}return`${t.join(`
35
35
  `)}
36
36
  `}var zA=new Set(["filters","now","projection","sorting"]);function UA(e){let t=Ei(e,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!L(t)||!Array.isArray(t.items))return t??null;let n=Object.fromEntries(Object.entries(t).filter(([r])=>!zA.has(r)));return n.has_more!==!0&&delete n.next_cursor,n}function HA(e,t){if(!L(e)||!Array.isArray(e.run_results)||!e.run_results.every(L))return e;let n=e.run_results,r=qA(n),o=n.map(i=>{let{execution_context:s,stdout:a,stderr:c,...d}=i;return r===void 0?i:!t||i.status!=="passed"?{...d,stdout:a,stderr:c}:d});return t&&VA(e,r,n)?BA(e,r,o):{...e,...r===void 0?{}:{execution_context:r},run_results:o}}function qA(e){let t=e.map(r=>r.execution_context).filter(r=>r!==void 0);if(t.length!==e.length||t.length===0)return;let n=JSON.stringify(t[0]);return t.every(r=>JSON.stringify(r)===n)?t[0]:void 0}function VA(e,t,n){if(e.ok!==!0||!L(t)||t.mismatch_detected!==!1||!n.every(o=>o.status==="passed"))return!1;let r=e.failure_categories;return!(L(r)&&Object.values(r).some(o=>o!==0))}function BA(e,t,n){let{failure_categories:r,...o}=e,i=L(t.trust)?t.trust:{};return{...o,execution_context:{pm_context_mode:t.pm_context_mode,workspace_context_mode:t.workspace_context_mode,mismatch_detected:!1,...typeof i.trusted=="boolean"?{trusted:i.trusted}:{},...i.reason===void 0?{}:{trust_reason:i.reason},restore_with:"not retained; a run without --lean reports the full context"},run_results:n}}function WA(e){return!L(e)||e.ok!==!0||!L(e.verdict)||e.verdict.authority!=="ok"||!Array.isArray(e.checks)?e:{...e,checks:e.checks.map(GA)}}function GA(e){if(!L(e)||e.ok!==!0||!L(e.details)||Object.keys(e.details).length!==0)return e;let{details:t,...n}=e;return n}function vi(e,t,n=!1){if(e=Sc(e),t==="json"){let o=n?UA(e):e,i=L(e)&&L(e.projection)&&e.projection.mode==="brief"&&Array.isArray(e.items);return`${JSON.stringify(o,null,i?void 0:2)}
37
- `}let r=Ei(WA(Up(Fp(e))),{omitDuplicateCountAliases:!0,preserveRowFacts:!0});return r===void 0?`{}
38
- `:`${Kp(r,0)}
37
+ `}let r=Ei(WA(Hp(zp(e))),{omitDuplicateCountAliases:!0,preserveRowFacts:!0});return r===void 0?`{}
38
+ `:`${Yp(r,0)}
39
39
  `}function KA(e,t,n,r){let o=t?{handled:!1,result:e,warnings:[]}:oa("output_format",{command:n.command,args:n.commandArgs,command_options:n.commandOptions,global:{...n},pm_root:n.pmRoot,format:r,options:{...n},result:e}),i=o.warnings.find(s=>s.startsWith("extension_output_format_payload_echo_deprecated:"));return i!==void 0&&Cr(`Warning: ${i}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
40
40
  `),o.handled&&typeof o.result=="string"?{result:o.result,rendered:o.result.endsWith(`
41
41
  `)?o.result:`${o.result}
42
- `,structuredDeliveryPreserved:!1}:{result:o.handled?o.result:e,rendered:null,structuredDeliveryPreserved:!o.handled||L(o.result)}}function YA(e,t,n,r){let o=ju(),i=n.command??o?.command,s={...o?.options,...n.commandOptions,...Object.fromEntries([["outputInclude",n.outputInclude],["outputLimit",n.outputLimit],["outputBudget",n.outputBudget],["outputFormat",n.outputFormat],["outputSession",n.outputSession],["outputCursor",n.outputCursor],["outputRowContract",n.outputRowContract]].filter(T=>T[1]!==void 0))},a=lp(i??"",s)??r,c={...s,resolvedOutputFormat:a},d={...n,command:i,commandOptions:c},l=KA(e,t,d,a);if(l.rendered!==null)return Rc(e),l.rendered;let u=l.result;kn(e,u);let f=i==="test"?HA(u,n.lean===!0):u,m=xp(i,c,f);dp(m)&&(process.exitCode||=h.USAGE);let{structuredDeliveryPreserved:_}=l,y=T=>{if(a==="toon"){let X=FA(T);if(X!==null)return X}let H=t?{rendered:null}:Fu(a,T);return H.rendered!==null?(_=!1,H.rendered.endsWith(`
42
+ `,structuredDeliveryPreserved:!1}:{result:o.handled?o.result:e,rendered:null,structuredDeliveryPreserved:!o.handled||L(o.result)}}function YA(e,t,n,r){let o=Lu(),i=n.command??o?.command,s={...o?.options,...n.commandOptions,...Object.fromEntries([["outputInclude",n.outputInclude],["outputLimit",n.outputLimit],["outputBudget",n.outputBudget],["outputFormat",n.outputFormat],["outputSession",n.outputSession],["outputCursor",n.outputCursor],["outputRowContract",n.outputRowContract]].filter(T=>T[1]!==void 0))},a=up(i??"",s)??r,c={...s,resolvedOutputFormat:a},d={...n,command:i,commandOptions:c},l=KA(e,t,d,a);if(l.rendered!==null)return Rc(e),l.rendered;let u=l.result;kn(e,u);let f=i==="test"?HA(u,n.lean===!0):u,m=Np(i,c,f);lp(m)&&(process.exitCode||=h.USAGE);let{structuredDeliveryPreserved:_}=l,y=T=>{if(a==="toon"){let X=FA(T);if(X!==null)return X}let H=t?{rendered:null}:zu(a,T);return H.rendered!==null?(_=!1,H.rendered.endsWith(`
43
43
  `)?H.rendered:`${H.rendered}
44
- `):a==="json"?vi(T,"json",n.lean===!0):vi(T,"toon")},w=n.tokenAccounting===!0?Pp(m,y):m,v=y(w);return RA(w,e,n.quiet!==!0&&_),v}function XA(e,t){let n=Lu(e),r=fo(n.result)?n.result:null,o=n.result,i=L(o)&&o[Ac]===!0,s=r?r.result:xA(n.result);if(Ao(s),r)return Rc(s),"";let a=t.json===!0||t.json===void 0&&t.defaultOutputFormat==="json"?"json":"toon";return YA(s,i,t,a)}function jL(e,t){L(e)&&Number.isInteger(e.exit_code)&&TA.has(Number(e.exit_code))&&(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=Number(e.exit_code));let n=t.idOnly?br(e,{idOnly:!0}):t.fullChangedFields?e:t.noChangedFields?br(e,{changedFields:"compact"}):br(e,{compactEnvelope:!0}),r=XA(n,t);t.quiet||MA(r)}function LL(e){let t=oa("error_format",{message:e}),n=t.handled&&typeof t.result=="string"?t.result:e;Cr(n.endsWith(`
44
+ `):a==="json"?vi(T,"json",n.lean===!0):vi(T,"toon")},w=n.tokenAccounting===!0?Mp(m,y):m,v=y(w);return RA(w,e,n.quiet!==!0&&_),v}function XA(e,t){let n=Fu(e),r=fo(n.result)?n.result:null,o=n.result,i=L(o)&&o[Ac]===!0,s=r?r.result:xA(n.result);if(Ao(s),r)return Rc(s),"";let a=t.json===!0||t.json===void 0&&t.defaultOutputFormat==="json"?"json":"toon";return YA(s,i,t,a)}function LL(e,t){L(e)&&Number.isInteger(e.exit_code)&&TA.has(Number(e.exit_code))&&(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=Number(e.exit_code));let n=t.idOnly?br(e,{idOnly:!0}):t.fullChangedFields?e:t.noChangedFields?br(e,{changedFields:"compact"}):br(e,{compactEnvelope:!0}),r=XA(n,t);t.quiet||MA(r)}function FL(e){let t=oa("error_format",{message:e}),n=t.handled&&typeof t.result=="string"?t.result:e;Cr(n.endsWith(`
45
45
  `)?n:`${n}
46
- `)}(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 JA=8,ZA=64,QA=5,eI=4,Yp=100;function Ym(e,t,n){if(e!=="get"||!xc(n.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 r=n.item,o=["linked","claim_state","schedule"],i=o.filter(c=>Object.hasOwn(n,c)),s=Object.fromEntries(Object.entries(n).filter(([c])=>!o.includes(c)));s.item=Object.fromEntries(Object.entries(r).filter(([c])=>c!=="body")),Object.hasOwn(r,"body")&&i.push("body");let a=[...xc(n.omission_receipt)&&Array.isArray(n.omission_receipt.omitted_field_groups)?n.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 lc(e){let t=Math.trunc(e.effective_budget_tokens),n=Math.trunc(e.measured_result_tokens);if(!Number.isSafeInteger(t)||t<=0||!Number.isSafeInteger(n)||n<=0)return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"};let r=Math.max(t+1,n),o=Math.ceil(r*QA/eI),i=Math.ceil(o/Yp)*Yp;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 bn(e,t,n=!1){let r=Object.getOwnPropertyDescriptor(e,"row_contract");r&&(n||r.enumerable===!1)&&Object.defineProperty(t,"row_contract",{...r,enumerable:!1})}function wr(e,t){let n=t===void 0?JSON.stringify(e):vi(e,t);return Math.ceil(Buffer.byteLength(n,"utf8")/4)}function xc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Nc(e,t,n=!1){return typeof e=="string"?n||e.length<=240?e:(t.compacted=!0,`${Ee(e,240)}\u2026`):Array.isArray(e)?e.map(r=>Nc(r,t,n)):xc(e)?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Nc(o,t,n||r==="focus_row_states")])):e}function rt(e,t,n){let r=t.estimated_tokens;for(let o=0;o<JA;o+=1){t.estimated_tokens=r;let i=wr(e,n);if(i===r)return;r=i}t.estimated_tokens=r}function tI(e,t){return yr(e).filter(n=>(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length)>Math.max(1,t.get(n.path)??0)).map(n=>({collection:n,length:Array.isArray(n.value)?n.value.length:Object.keys(n.value).length})).sort((n,r)=>r.length-n.length||n.collection.path.localeCompare(r.collection.path))[0]?.collection}function nI(e,t,n,r,o,i){for(let s=0;s<ZA;s+=1){if(i?.(e),rt(e,t,o),t.estimated_tokens<=n)return;let a=tI(e,r);if(!a)return;let c=Math.max(1,r.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=oi(e)),a.path==="items"&&(e.applied_limit=_),i?.(e),rt(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<=n?(m=_,u=_+1):f=_-1}l(m)}}function Xm(e,t,n,r=new Map,o,i,s=!1){let a={compacted:!1},c=Object.fromEntries(Object.entries(e).map(([d,l])=>[d,Nc(l,a,s&&d==="diff")]));return bn(e,c),t.strings_compacted=a.compacted,c.read_output=t,nI(c,t,n,r,o,i),rt(c,t,o),c}import D_ from"fast-json-patch";import C_ from"node:fs/promises";import VI from"node:path";import $ from"node:fs/promises";import U from"node:path";import{createHash as Ri,randomUUID as Uc}from"node:crypto";import{createRequire as _I}from"node:module";import{setImmediate as s_}from"node:timers/promises";import Mc 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 rI={metadata:{},body:""};function Si(){return structuredClone(rI)}function ZL(e,t=$t,n){return Dc(e,t,n)[0]}function Dc(e,t,n){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return Qp(Oi(e),t,n)}catch{}let r=Ye(R({replay_fallback:!0,metadata:e.metadata,body:e.body}),n);return t===2?[r,r]:[r]}function e_(e,t,n,r,o){let i=kt(r.hash_algorithm),s=`${n}:${i}`,a=o?.before.get(s)??Dc(e,n,i),c=Dc(t,n,i);return o?.after.set(s,c),{beforeHashes:a,afterHashes:c,pairIndex:a.findIndex((d,l)=>d===r.before_hash&&c[l]===r.after_hash),beforeIndex:a.indexOf(r.before_hash),afterIndex:c.indexOf(r.after_hash)}}function Oi(e){return{metadata:e.metadata,body:e.body}}function QL(e,t={}){return fn(Oi(e),t)}function eF(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=fn(e);return{metadata:A(t.metadata,ve),body:t.body}}function Xp(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function oI(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function t_(e){return Array.isArray(e)?e.filter(oI).map(t=>({...t,path:Xp(t.path),from:typeof t.from=="string"?Xp(t.from):void 0})):[]}function iI(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 Ai(e,t){try{let n=t_(t),r=Mc.applyPatch(structuredClone(e),n,!0,!0).newDocument;return iI(r)?{ok:!0,document:{metadata:r.metadata,body:r.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(n){return{ok:!1,error:n}}}function sI(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&Rr.includes(t)))]}function n_(e){return e!==void 0&&!Rr.includes(e)}function aI(e,t){return e!==void 0?[e]:t===void 0?[...Rr]:[t]}function r_(e){let t=ki(e);if(!t.ok)return t.error;let n=Pc(e);return n.ok?void 0:n.error}function cI(e,t){let n=r_(e);if(n)return{ok:!1,error:n};let r=Ai(t,e.patch);return r.ok?{ok:!0,document:r.document}:{ok:!1,error:"patch_apply_failed"}}function dI(e,t){let n=r_(e);if(n)throw new TypeError(`${n}:entry_${t+1}`)}function lI(e,t,n,r,o){let i=[];for(let s of n){let a=e_(e,t,s,r,o);if(i.push({version:s,match:a}),a.pairIndex>=0)break}return i}function Ii(e){let t=Si(),n=new Map,r,o,i=Hu(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=n_(c);d&&i.push(`verify_failed:unsupported_item_hash_version:${String(c)}:entry_${s+1}`);let l=cI(a,t);if(!l.ok)return{ok:!1,errors:[...i,`verify_failed:${l.error}:entry_${s+1}`]};if(d){t=l.document,n=new Map,r=void 0,o=void 0;continue}let u=aI(c,o),f={before:n,after:new Map},m=lI(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,n=f.after,r=y,o=c??o}return i.length>0?{ok:!1,errors:i,...r===void 0?{}:{item_hash_version:r}}:{ok:!0,errors:[],...r===void 0?{}:{item_hash_version:r}}}function jt(e){let t=Ii(e);return{ok:t.ok,errors:t.errors}}function Jp(e,t){try{return{ok:!0,document:Mc.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function uI(e,t){let n=structuredClone(e),r=0,o=0;for(let s of t_(t)){let a=Jp(n,s);if(a.ok){n=a.document;continue}if(s.op==="replace"){let c=Jp(n,{...s,op:"add"});if(c.ok){n=c.document,r+=1;continue}}o+=1}let i=n;return{document:{metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:{},body:typeof i.body=="string"?i.body:e.body},convertedReplaceToAdd:r,skippedOps:o}}function fI(e){let t=sI(e);if(t.length===1)return t[0];let n=Ii(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:$t}function mI(e,t,n=t.patch){let r=Ai(e,n);if(r.ok)return{next:r.document,patch:n,repaired:R(n)!==R(t.patch),converted:0,skipped:0};let o=uI(e,n);return{next:o.document,patch:Mc.compare(e,o.document),repaired:!0,converted:o.convertedReplaceToAdd,skipped:o.skippedOps}}function pI(e,t,n){return mI(e,t,n.projectPatch?.(t,e))}function tF(e,t=fI(e),n={}){let r=e.findIndex(m=>n_(m.item_hash_version));if(r>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[r]?.item_hash_version)}:entry_${r+1}`);let o=Si(),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];dI(_,m);let y=pI(o,_,n),{next:w,patch:v,repaired:T,converted:H,skipped:X}=y;d+=H,l+=X,c+=Number(T);let de=e_(o,w,t,_);u===void 0||n.continuousHashSurface!==!0?u=[de.pairIndex,de.beforeIndex,de.afterIndex,Math.min(u??0,de.beforeHashes.length-1)].find(Py=>Py>=0):u=Math.min(u,de.beforeHashes.length-1);let bd=de.beforeHashes[u],wd=de.afterHashes[u],ts=bd!==_.before_hash||wd!==_.after_hash;ts&&(a+=1);let Wt={..._,patch:v,before_hash:bd,after_hash:wd};f?Wt.item_hash_version=t:delete Wt.item_hash_version;let Dy=Wt.item_hash_version!==_.item_hash_version;(ts||T||Dy)&&(Wt=Zp(_,Wt,{retainOriginalPatch:T})),i.push(Wt),s.push({index:m+1,rehashed:ts,patch_repaired:T,converted_replace_to_add:H,skipped_ops:X}),o=w}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:c,convertedReplaceToAdd:d,skippedOps:l,details:s,itemHashVersion:t,explicitItemHashVersion:f}}function nF(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
46
+ `)}(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 JA=8,ZA=64,QA=5,eI=4,Xp=100;function Xm(e,t,n){if(e!=="get"||!xc(n.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 r=n.item,o=["linked","claim_state","schedule"],i=o.filter(c=>Object.hasOwn(n,c)),s=Object.fromEntries(Object.entries(n).filter(([c])=>!o.includes(c)));s.item=Object.fromEntries(Object.entries(r).filter(([c])=>c!=="body")),Object.hasOwn(r,"body")&&i.push("body");let a=[...xc(n.omission_receipt)&&Array.isArray(n.omission_receipt.omitted_field_groups)?n.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 lc(e){let t=Math.trunc(e.effective_budget_tokens),n=Math.trunc(e.measured_result_tokens);if(!Number.isSafeInteger(t)||t<=0||!Number.isSafeInteger(n)||n<=0)return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"};let r=Math.max(t+1,n),o=Math.ceil(r*QA/eI),i=Math.ceil(o/Xp)*Xp;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 bn(e,t,n=!1){let r=Object.getOwnPropertyDescriptor(e,"row_contract");r&&(n||r.enumerable===!1)&&Object.defineProperty(t,"row_contract",{...r,enumerable:!1})}function wr(e,t){let n=t===void 0?JSON.stringify(e):vi(e,t);return Math.ceil(Buffer.byteLength(n,"utf8")/4)}function xc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Nc(e,t,n=!1){return typeof e=="string"?n||e.length<=240?e:(t.compacted=!0,`${Ee(e,240)}\u2026`):Array.isArray(e)?e.map(r=>Nc(r,t,n)):xc(e)?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Nc(o,t,n||r==="focus_row_states")])):e}function rt(e,t,n){let r=t.estimated_tokens;for(let o=0;o<JA;o+=1){t.estimated_tokens=r;let i=wr(e,n);if(i===r)return;r=i}t.estimated_tokens=r}function tI(e,t){return yr(e).filter(n=>(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length)>Math.max(1,t.get(n.path)??0)).map(n=>({collection:n,length:Array.isArray(n.value)?n.value.length:Object.keys(n.value).length})).sort((n,r)=>r.length-n.length||n.collection.path.localeCompare(r.collection.path))[0]?.collection}function nI(e,t,n,r,o,i){for(let s=0;s<ZA;s+=1){if(i?.(e),rt(e,t,o),t.estimated_tokens<=n)return;let a=tI(e,r);if(!a)return;let c=Math.max(1,r.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=oi(e)),a.path==="items"&&(e.applied_limit=_),i?.(e),rt(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<=n?(m=_,u=_+1):f=_-1}l(m)}}function Jm(e,t,n,r=new Map,o,i,s=!1){let a={compacted:!1},c=Object.fromEntries(Object.entries(e).map(([d,l])=>[d,Nc(l,a,s&&d==="diff")]));return bn(e,c),t.strings_compacted=a.compacted,c.read_output=t,nI(c,t,n,r,o,i),rt(c,t,o),c}import P_ from"fast-json-patch";import R_ from"node:fs/promises";import VI from"node:path";import $ from"node:fs/promises";import U from"node:path";import{createHash as Ri,randomUUID as Uc}from"node:crypto";import{createRequire as _I}from"node:module";import{setImmediate as a_}from"node:timers/promises";import Mc 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 rI={metadata:{},body:""};function Si(){return structuredClone(rI)}function QL(e,t=$t,n){return Dc(e,t,n)[0]}function Dc(e,t,n){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return e_(Oi(e),t,n)}catch{}let r=Ye(R({replay_fallback:!0,metadata:e.metadata,body:e.body}),n);return t===2?[r,r]:[r]}function t_(e,t,n,r,o){let i=kt(r.hash_algorithm),s=`${n}:${i}`,a=o?.before.get(s)??Dc(e,n,i),c=Dc(t,n,i);return o?.after.set(s,c),{beforeHashes:a,afterHashes:c,pairIndex:a.findIndex((d,l)=>d===r.before_hash&&c[l]===r.after_hash),beforeIndex:a.indexOf(r.before_hash),afterIndex:c.indexOf(r.after_hash)}}function Oi(e){return{metadata:e.metadata,body:e.body}}function eF(e,t={}){return fn(Oi(e),t)}function tF(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=fn(e);return{metadata:A(t.metadata,ve),body:t.body}}function Jp(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function oI(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function n_(e){return Array.isArray(e)?e.filter(oI).map(t=>({...t,path:Jp(t.path),from:typeof t.from=="string"?Jp(t.from):void 0})):[]}function iI(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 Ai(e,t){try{let n=n_(t),r=Mc.applyPatch(structuredClone(e),n,!0,!0).newDocument;return iI(r)?{ok:!0,document:{metadata:r.metadata,body:r.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(n){return{ok:!1,error:n}}}function sI(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&Rr.includes(t)))]}function r_(e){return e!==void 0&&!Rr.includes(e)}function aI(e,t){return e!==void 0?[e]:t===void 0?[...Rr]:[t]}function o_(e){let t=ki(e);if(!t.ok)return t.error;let n=Pc(e);return n.ok?void 0:n.error}function cI(e,t){let n=o_(e);if(n)return{ok:!1,error:n};let r=Ai(t,e.patch);return r.ok?{ok:!0,document:r.document}:{ok:!1,error:"patch_apply_failed"}}function dI(e,t){let n=o_(e);if(n)throw new TypeError(`${n}:entry_${t+1}`)}function lI(e,t,n,r,o){let i=[];for(let s of n){let a=t_(e,t,s,r,o);if(i.push({version:s,match:a}),a.pairIndex>=0)break}return i}function Ii(e){let t=Si(),n=new Map,r,o,i=qu(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=r_(c);d&&i.push(`verify_failed:unsupported_item_hash_version:${String(c)}:entry_${s+1}`);let l=cI(a,t);if(!l.ok)return{ok:!1,errors:[...i,`verify_failed:${l.error}:entry_${s+1}`]};if(d){t=l.document,n=new Map,r=void 0,o=void 0;continue}let u=aI(c,o),f={before:n,after:new Map},m=lI(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,n=f.after,r=y,o=c??o}return i.length>0?{ok:!1,errors:i,...r===void 0?{}:{item_hash_version:r}}:{ok:!0,errors:[],...r===void 0?{}:{item_hash_version:r}}}function jt(e){let t=Ii(e);return{ok:t.ok,errors:t.errors}}function Zp(e,t){try{return{ok:!0,document:Mc.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function uI(e,t){let n=structuredClone(e),r=0,o=0;for(let s of n_(t)){let a=Zp(n,s);if(a.ok){n=a.document;continue}if(s.op==="replace"){let c=Zp(n,{...s,op:"add"});if(c.ok){n=c.document,r+=1;continue}}o+=1}let i=n;return{document:{metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:{},body:typeof i.body=="string"?i.body:e.body},convertedReplaceToAdd:r,skippedOps:o}}function fI(e){let t=sI(e);if(t.length===1)return t[0];let n=Ii(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:$t}function mI(e,t,n=t.patch){let r=Ai(e,n);if(r.ok)return{next:r.document,patch:n,repaired:R(n)!==R(t.patch),converted:0,skipped:0};let o=uI(e,n);return{next:o.document,patch:Mc.compare(e,o.document),repaired:!0,converted:o.convertedReplaceToAdd,skipped:o.skippedOps}}function pI(e,t,n){return mI(e,t,n.projectPatch?.(t,e))}function nF(e,t=fI(e),n={}){let r=e.findIndex(m=>r_(m.item_hash_version));if(r>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[r]?.item_hash_version)}:entry_${r+1}`);let o=Si(),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];dI(_,m);let y=pI(o,_,n),{next:w,patch:v,repaired:T,converted:H,skipped:X}=y;d+=H,l+=X,c+=Number(T);let de=t_(o,w,t,_);u===void 0||n.continuousHashSurface!==!0?u=[de.pairIndex,de.beforeIndex,de.afterIndex,Math.min(u??0,de.beforeHashes.length-1)].find(Py=>Py>=0):u=Math.min(u,de.beforeHashes.length-1);let wd=de.beforeHashes[u],vd=de.afterHashes[u],ts=wd!==_.before_hash||vd!==_.after_hash;ts&&(a+=1);let Wt={..._,patch:v,before_hash:wd,after_hash:vd};f?Wt.item_hash_version=t:delete Wt.item_hash_version;let Dy=Wt.item_hash_version!==_.item_hash_version;(ts||T||Dy)&&(Wt=Qp(_,Wt,{retainOriginalPatch:T})),i.push(Wt),s.push({index:m+1,rehashed:ts,patch_repaired:T,converted_replace_to_add:H,skipped_ops:X}),o=w}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:c,convertedReplaceToAdd:d,skippedOps:l,details:s,itemHashVersion:t,explicitItemHashVersion:f}}function rF(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
47
47
  `)}
48
- `}(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 o_(e){let t=process.emitWarning;process.emitWarning=(n,...r)=>{n==="SQLite is an experimental feature and might change at any time"&&r[0]==="ExperimentalWarning"||Reflect.apply(t,process,[n,...r])};try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}finally{process.emitWarning=t}}function i_(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?o_(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]="c5f096f6-4af4-568e-89ef-1aa0a8718973")}catch{}})();var yI="history-event-index.sqlite",Hc="7",hI=8,a_=32,p_="history-event-index",gI="history-event-index:append:",bI=5e3,qc=300,__=3e4,wI="history-event-index-invalidation",vI="history-event-index-invalidations",EI=qc*2*1e3,st=Symbol("history-index-changed"),Lt=new Map;function zt(e){return U.join(e,"runtime",yI)}function y_(e){return U.join(e,"runtime","history-event-index-repair-deferred")}async function h_(e){try{let t=Number(await $.readFile(y_(e),"utf8")),n=Date.now()-t;return n>=0&&n<bI}catch{return!1}}async function c_(e){try{await $.writeFile(y_(e),`${Date.now()}
49
- `)}catch{}}function xr(e){return U.join(e,"runtime",vI)}async function xi(e){let t=await $.readdir(xr(e)).catch(n=>{if(ee(n))return[];throw n});return{pending:t.filter(n=>n.endsWith(".pending")).sort(),committed:t.filter(n=>n.endsWith(".committed")).sort()}}async function d_(e){let t=await xi(e);return{pending:(await Promise.all(t.pending.map(async n=>{let r=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(n);if(r!==null){let o=r[2];if(await _r({pid:Number(r[1]),...o==="unknown"?{}:{process_start_identity:o}},Math.max(0,Date.now()-Number(r[3])),EI))return n}return await $.rm(U.join(xr(e),n),{force:!0}),null}))).filter(n=>n!==null),committed:t.committed}}async function Fc(e,t,n=__){let r=await fe(e,wI,qc,`history-event-index-invalidation:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await r()}}async function kI(e){let t=xr(e);await $.mkdir(t,{recursive:!0});let n=Uc(),r=await pr(),o=U.join(t,`${r.pid}-${r.process_start_identity??"unknown"}-${Date.now()}-${n}.pending`);return await $.writeFile(o,`pending
48
+ `}(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 i_(e){let t=process.emitWarning;process.emitWarning=(n,...r)=>{n==="SQLite is an experimental feature and might change at any time"&&r[0]==="ExperimentalWarning"||Reflect.apply(t,process,[n,...r])};try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}finally{process.emitWarning=t}}function s_(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?i_(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]="c5f096f6-4af4-568e-89ef-1aa0a8718973")}catch{}})();var yI="history-event-index.sqlite",Hc="7",hI=8,c_=32,__="history-event-index",gI="history-event-index:append:",bI=5e3,qc=300,y_=3e4,wI="history-event-index-invalidation",vI="history-event-index-invalidations",EI=qc*2*1e3,st=Symbol("history-index-changed"),Lt=new Map;function zt(e){return U.join(e,"runtime",yI)}function h_(e){return U.join(e,"runtime","history-event-index-repair-deferred")}async function g_(e){try{let t=Number(await $.readFile(h_(e),"utf8")),n=Date.now()-t;return n>=0&&n<bI}catch{return!1}}async function d_(e){try{await $.writeFile(h_(e),`${Date.now()}
49
+ `)}catch{}}function xr(e){return U.join(e,"runtime",vI)}async function xi(e){let t=await $.readdir(xr(e)).catch(n=>{if(ee(n))return[];throw n});return{pending:t.filter(n=>n.endsWith(".pending")).sort(),committed:t.filter(n=>n.endsWith(".committed")).sort()}}async function l_(e){let t=await xi(e);return{pending:(await Promise.all(t.pending.map(async n=>{let r=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(n);if(r!==null){let o=r[2];if(await _r({pid:Number(r[1]),...o==="unknown"?{}:{process_start_identity:o}},Math.max(0,Date.now()-Number(r[3])),EI))return n}return await $.rm(U.join(xr(e),n),{force:!0}),null}))).filter(n=>n!==null),committed:t.committed}}async function Fc(e,t,n=y_){let r=await fe(e,wI,qc,`history-event-index-invalidation:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await r()}}async function kI(e){let t=xr(e);await $.mkdir(t,{recursive:!0});let n=Uc(),r=await pr(),o=U.join(t,`${r.pid}-${r.process_start_identity??"unknown"}-${Date.now()}-${n}.pending`);return await $.writeFile(o,`pending
50
50
  `,{flag:"wx"}),{pendingPath:o,committedPath:U.join(t,`${n}.committed`)}}function SI(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}async function Ni(e){try{await $.rm(zt(e),{force:!0})}catch{}}async function $c(e,t){let n=xr(e);await $.mkdir(n,{recursive:!0}),await $.writeFile(U.join(n,`${Uc()}${t?".contended":""}.committed`),`committed
51
- `,{flag:"wx"}),t||await Ni(e)}function Di(e){return e.committed.some(t=>t.endsWith(".contended.committed"))}function zc(e,t){let n;try{return n=new t(zt(e)),n.exec("PRAGMA busy_timeout = 0"),n.exec("BEGIN EXCLUSIVE"),!1}catch(r){return Ft(r)}finally{n?.close()}}async function l_(e,t){return t.pending.length>0||await Gf(e,p_,gI)}async function g_(e,t,n=__,r="rebuild"){let o=await fe(e,p_,qc,`history-event-index:${r}:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await o()}}async function b_(e,t,n=!1){let r=U.join(e,"history"),o=await $.readdir(r,{withFileTypes:!0}).catch(u=>{if(typeof u=="object"&&u!==null&&"code"in u&&u.code==="ENOENT")return[];throw u}),i=Lt.get(e)??{streams:new Map,ordered_events:[]},s=new Map(i.streams),a=i.ordered_events,c=new Set,d=!Lt.has(e);for(let u of o.filter(f=>f.isFile()&&f.name.endsWith(".jsonl")).sort((f,m)=>f.name.localeCompare(m.name))){let f=u.name.slice(0,-6);c.add(f);let m=U.join(r,u.name);if(!jc(f,t))continue;let _=await AI(m,f,s.get(f),n);_!==void 0&&(s.set(f,_),d=!0)}for(let u of s.keys())c.has(u)||(s.delete(u),d=!0);d&&(a=[...s.values()].flatMap(u=>u.events).sort(Vc));let l={streams:s,ordered_events:a};if(Lt.delete(e),Lt.set(e,l),Lt.size>hI){let u=Lt.keys().next().value;Lt.delete(u)}return{events:l.ordered_events.filter(u=>jc(u.stream_id,t)).map(u=>OI(u,n)),stream_receipts:new Map([...l.streams].filter(([u])=>jc(u,t)).map(([u,f])=>[u,{byte_size:f.byte_size,content_hash:f.signature}]))}}function OI(e,t){return t||e.recorded_entry===void 0?e:{stream_id:e.stream_id,stream_offset:e.stream_offset,entry:e.entry}}function jc(e,t){return!t?.length||t.includes(e)}async function AI(e,t,n,r){if(!r&&n!==void 0&&n.byte_size===(await $.stat(e)).size){let o=Ri("sha256").update(await $.readFile(e)).digest("hex");if(n.signature===o)return}return II(e,t,r)}async function II(e,t,n){let r=await ei(e,t);if(n){let i=Ii(r.entries);if(!i.ok)throw new g(`Authoritative history integrity verification failed for ${t}.`,h.GENERIC_FAILURE,{code:"event_history_integrity_failed",why:i.errors.join(", "),nextSteps:[`Run pm history ${t} --verify to inspect the authoritative chain before retrying.`]})}let o=r.raw_bytes??new Uint8Array;return{signature:Ri("sha256").update(o).digest("hex"),byte_size:o.byteLength,events:w_(r.entries,t).map((i,s)=>({stream_id:t,stream_offset:s,entry:i,...n?{recorded_entry:r.entries[s]}:{}}))}}async function TI(e,t){return w_((await ei(e,t)).entries,t)}function w_(e,t){for(let[n,r]of e.entries())if(typeof r.ts!="string"||!Zt(r.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 e.map(n=>({...n,ts:new Date(n.ts.trim()).toISOString()}))}var Lc;function Mi(){return Lc!==void 0||(Lc=i_(process.versions.node,_I(import.meta.url))),Lc}function CI(e){e.exec(`
51
+ `,{flag:"wx"}),t||await Ni(e)}function Di(e){return e.committed.some(t=>t.endsWith(".contended.committed"))}function zc(e,t){let n;try{return n=new t(zt(e)),n.exec("PRAGMA busy_timeout = 0"),n.exec("BEGIN EXCLUSIVE"),!1}catch(r){return Ft(r)}finally{n?.close()}}async function u_(e,t){return t.pending.length>0||await Kf(e,__,gI)}async function b_(e,t,n=y_,r="rebuild"){let o=await fe(e,__,qc,`history-event-index:${r}:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await o()}}async function w_(e,t,n=!1){let r=U.join(e,"history"),o=await $.readdir(r,{withFileTypes:!0}).catch(u=>{if(typeof u=="object"&&u!==null&&"code"in u&&u.code==="ENOENT")return[];throw u}),i=Lt.get(e)??{streams:new Map,ordered_events:[]},s=new Map(i.streams),a=i.ordered_events,c=new Set,d=!Lt.has(e);for(let u of o.filter(f=>f.isFile()&&f.name.endsWith(".jsonl")).sort((f,m)=>f.name.localeCompare(m.name))){let f=u.name.slice(0,-6);c.add(f);let m=U.join(r,u.name);if(!jc(f,t))continue;let _=await AI(m,f,s.get(f),n);_!==void 0&&(s.set(f,_),d=!0)}for(let u of s.keys())c.has(u)||(s.delete(u),d=!0);d&&(a=[...s.values()].flatMap(u=>u.events).sort(Vc));let l={streams:s,ordered_events:a};if(Lt.delete(e),Lt.set(e,l),Lt.size>hI){let u=Lt.keys().next().value;Lt.delete(u)}return{events:l.ordered_events.filter(u=>jc(u.stream_id,t)).map(u=>OI(u,n)),stream_receipts:new Map([...l.streams].filter(([u])=>jc(u,t)).map(([u,f])=>[u,{byte_size:f.byte_size,content_hash:f.signature}]))}}function OI(e,t){return t||e.recorded_entry===void 0?e:{stream_id:e.stream_id,stream_offset:e.stream_offset,entry:e.entry}}function jc(e,t){return!t?.length||t.includes(e)}async function AI(e,t,n,r){if(!r&&n!==void 0&&n.byte_size===(await $.stat(e)).size){let o=Ri("sha256").update(await $.readFile(e)).digest("hex");if(n.signature===o)return}return II(e,t,r)}async function II(e,t,n){let r=await ei(e,t);if(n){let i=Ii(r.entries);if(!i.ok)throw new g(`Authoritative history integrity verification failed for ${t}.`,h.GENERIC_FAILURE,{code:"event_history_integrity_failed",why:i.errors.join(", "),nextSteps:[`Run pm history ${t} --verify to inspect the authoritative chain before retrying.`]})}let o=r.raw_bytes??new Uint8Array;return{signature:Ri("sha256").update(o).digest("hex"),byte_size:o.byteLength,events:v_(r.entries,t).map((i,s)=>({stream_id:t,stream_offset:s,entry:i,...n?{recorded_entry:r.entries[s]}:{}}))}}async function TI(e,t){return v_((await ei(e,t)).entries,t)}function v_(e,t){for(let[n,r]of e.entries())if(typeof r.ts!="string"||!Zt(r.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 e.map(n=>({...n,ts:new Date(n.ts.trim()).toISOString()}))}var Lc;function Mi(){return Lc!==void 0||(Lc=s_(process.versions.node,_I(import.meta.url))),Lc}function CI(e){e.exec(`
52
52
  PRAGMA journal_mode = OFF;
53
53
  PRAGMA synchronous = OFF;
54
54
  CREATE TABLE metadata (
@@ -84,14 +84,14 @@ ${Kp(t,n+1)}`}function LA(e,t,n){let r=e.map(o=>Ei(o,t,n||t.preserveRowFacts&&L(
84
84
  ON events(agent_harness, ts, stream_id, stream_offset);
85
85
  CREATE INDEX events_instance_order
86
86
  ON events(agent_instance, ts, stream_id, stream_offset);
87
- `),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(Hc)}function v_(e,t){let n={...t.entry,ts:new Date(t.entry.ts.trim()).toISOString()};e.prepare(`INSERT INTO events(
87
+ `),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(Hc)}function E_(e,t){let n={...t.entry,ts:new Date(t.entry.ts.trim()).toISOString()};e.prepare(`INSERT INTO events(
88
88
  stream_id, stream_offset, ts, author, agent_harness,
89
89
  agent_instance, op, event_class, entry_json
90
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,n.ts,n.author,n.agent_harness??null,n.agent_instance??null,n.op,yn(n),JSON.stringify(n))}function E_(e){let t=JSON.parse(String(e.entry_json));return typeof t.ts!="string"||!Zt(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 k_(e,t,n){e.prepare(`INSERT INTO streams(stream_id, byte_size, content_hash) VALUES (?, ?, ?)
91
- ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size, content_hash = excluded.content_hash`).run(t,n.byte_size,n.content_hash)}async function RI(e,t={}){let n=Mi();return n?g_(e,async()=>{let r;try{r=await Fc(e,()=>d_(e),t.lockWaitMs)}catch(a){if(a instanceof g&&a.code==="lock_conflict")return!1;throw a}if(r.pending.length>0||Di(r)&&zc(e,n))return!1;let o=zt(e);await $.mkdir(U.dirname(o),{recursive:!0});let i=`${o}.${Uc()}.tmp`,s;try{s=new n(i),CI(s),s.exec("BEGIN IMMEDIATE");let a=await b_(e);await xI(s,a),s.exec("COMMIT"),s.close(),s=void 0;let c=await Fc(e,async()=>{let d=await d_(e);return d.pending.length>0||!SI(r.committed,d.committed)||Di(d)&&zc(e,n)?!1:(await $.rm(o,{force:!0}),await $.rename(i,o),!0)},t.lockWaitMs);return c&&await Promise.all(r.committed.map(d=>$.rm(U.join(xr(e),d),{force:!0}))),c||(await c_(e),await $.rm(i,{force:!0})),c}catch(a){throw await c_(e),s?.close(),await $.rm(i,{force:!0}),a}},t.lockWaitMs):!1}async function xI(e,t){let n=0;for(let r of t.events)v_(e,r),++n%500===0&&await s_();for(let[r,o]of t.stream_receipts)k_(e,r,o),++n%500===0&&await s_()}function Ti(e,t){return!t||t.length===0||t.includes(e)}function Vc(e,t){return e.entry.ts.localeCompare(t.entry.ts)||e.stream_id.localeCompare(t.stream_id)||e.stream_offset-t.stream_offset}function Pi(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():e}function NI(e,t){if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){if(Vc(e,{stream_id:t.after_stream_id,stream_offset:t.after_stream_offset,entry:{...e.entry,ts:Pi(t.after_ts)}})<=0)return!1}else if(t.since_ts!==void 0&&e.entry.ts<Pi(t.since_ts))return!1;return!0}function DI(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 PI(e,t){return!NI(e,t)||!Ti(e.entry.op,t.ops)||!Ti(e.entry.author,t.authors)||!Ti(e.entry.agent_instance??"",t.agent_instances)||!Ti(e.stream_id,t.stream_ids)||!DI(e,t)?!1:(t.provenance??[]).every(n=>{let r=e.entry.agent_provenance?.[n.dimension]?.value;return r!==void 0&&n.values.includes(r)})}async function MI(e,t){let n=Math.max(0,Math.floor(t.limit)),r=await b_(e,t.stream_ids,t.verify),o=r.events.filter(i=>PI(i,t)).slice(0,n+1);return{events:o.slice(0,t.limit),has_more:o.length>t.limit,...t.verify?{verified_streams:r.stream_receipts.size}:{}}}async function $I(e,t){let n=e.prepare("SELECT byte_size, content_hash FROM streams WHERE stream_id = ?").get(U.basename(t,".jsonl")),r=0;try{r=(await $.stat(t)).size}catch(i){if(!ee(i))throw i}if(Number(n?.byte_size??0)!==r)return!1;let o=await Wc(U.dirname(U.dirname(t)),U.basename(t,".jsonl"));return n===void 0?o?.byte_size===0:o?.content_hash===n.content_hash}async function S_(e,t,n){let r=U.dirname(U.dirname(e)),o=Mi(),i=!1,s=async()=>{await n(),i=!0};if(!o){await u_(r,s);return}try{await g_(r,async()=>{let a=zt(r);try{await $.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!==Hc)throw new TypeError("Unsupported history event index version");if(!await $I(c,e))throw new TypeError("Stale history event index append base")}catch(l){if(c?.close(),Ft(l))throw l;await $c(r,!0),await s();return}try{c.exec("PRAGMA busy_timeout = 0"),c.exec("BEGIN IMMEDIATE")}catch(l){if(c.close(),Ft(l)||!(l instanceof Error)||l.code!=="ERR_SQLITE_ERROR")throw l;await $c(r,!1),await s();return}let d=!1;try{await s(),d=!0;let l=U.basename(e,".jsonl"),u=c.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(l);v_(c,{stream_id:l,stream_offset:Number(u.value),entry:t}),k_(c,l,await Wc(r,l)),c.exec("COMMIT"),c.close()}catch(l){if(c?.close(),!d)throw l;await $c(r,Ft(l))}},0,"append")}catch(a){if(i){await Ni(r);return}if(!LI(a))throw a;await u_(r,s,Ft(a))}}async function u_(e,t,n=!1){let r=!1,o;try{await Fc(e,async()=>{let i=n||Di(await xi(e)),s=await kI(e);o=s.pendingPath;try{await t(),r=!0}catch(a){throw await $.rm(s.pendingPath,{force:!0}),a}await $.rename(s.pendingPath,i?s.committedPath.replace(/\.committed$/u,".contended.committed"):s.committedPath),i||await Ni(e)})}catch(i){if(r){await Ni(e);try{await $.rm(o,{force:!0})}catch{}return}throw i}}async function Bc(e){await $.rm(zt(U.dirname(U.dirname(e))),{force:!0})}function Ci(e,t,n,r){!r||r.length===0||(e.push(`${n} IN (${r.map(()=>"?").join(", ")})`),t.push(...r))}function jI(e,t,n,r){if(!n||n.length===0)return;let o=n.map(()=>"?").join(", "),i=r??[];if(i.length>0){e.push(`(agent_harness IN (${o}) OR (agent_harness IS NULL AND author IN (${i.map(()=>"?").join(", ")})))`),t.push(...n,...i);return}e.push(`agent_harness IN (${o})`),t.push(...n)}async function O_(e,t,n,r){let o;try{let i=await xi(e);if(await l_(e,i))return st;let s=await f_(e);if(i.committed.length>0)return Di(i)&&zc(e,t)?st:null;if(o=new t(zt(e),{readOnly:!0}),o.exec("BEGIN"),o.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Hc)return null;let a=r(o);if(a===null)return null;let c=FI(o,n),d=o;o=void 0,d.close();let l=await UI([...c.keys()],e,n),u=await zI(c,e,l),f=await xi(e);return f.committed.length>0||await l_(e,f)||s!==await f_(e)?st:u?a:null}catch(i){return Ft(i)?st:null}finally{o?.close()}}function Ft(e){return typeof e=="object"&&e!==null&&"errcode"in e&&[5,6].includes(e.errcode)}function LI(e){return Ft(e)||e instanceof g&&e.code==="lock_conflict"}function FI(e,t){let n=new Map,r=t&&t.length>0?[...new Set(t)]:void 0;if(r===void 0)for(let o of e.prepare("SELECT stream_id, byte_size, content_hash FROM streams").all())n.set(String(o.stream_id),{byte_size:Number(o.byte_size),content_hash:String(o.content_hash)});else for(let o=0;o<r.length;o+=500){let i=r.slice(o,o+500);for(let s of e.prepare(`SELECT stream_id, byte_size, content_hash FROM streams WHERE stream_id IN (${i.map(()=>"?").join(", ")})`).all(...i))n.set(String(s.stream_id),{byte_size:Number(s.byte_size),content_hash:String(s.content_hash)})}return n}async function f_(e){let t=await $.stat(zt(e),{bigint:!0});return[t.dev,t.ino,t.size,t.mtimeNs,t.ctimeNs].join(":")}async function bF(e,t){if(t.verify)return{result:await MI(e,t),repair_needed:!1};let n=Mi();if(!n)return{result:null,repair_needed:!1};let r=[],o=[];if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){r.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");let a=Pi(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&&(r.push("ts >= ?"),o.push(Pi(t.since_ts)));Ci(r,o,"op",t.ops),Ci(r,o,"author",t.authors),jI(r,o,t.harnesses,t.harness_alias_authors),Ci(r,o,"agent_instance",t.agent_instances);for(let a of t.provenance??[])r.push(`json_extract(entry_json, '$.agent_provenance.${a.dimension}.value') IN (${a.values.map(()=>"?").join(", ")})`),o.push(...a.values);Ci(r,o,"stream_id",t.stream_ids);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`,s=await O_(e,n,t.stream_ids,a=>{let c=a.prepare(`SELECT stream_id, stream_offset, entry_json
90
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,n.ts,n.author,n.agent_harness??null,n.agent_instance??null,n.op,yn(n),JSON.stringify(n))}function k_(e){let t=JSON.parse(String(e.entry_json));return typeof t.ts!="string"||!Zt(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 S_(e,t,n){e.prepare(`INSERT INTO streams(stream_id, byte_size, content_hash) VALUES (?, ?, ?)
91
+ ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size, content_hash = excluded.content_hash`).run(t,n.byte_size,n.content_hash)}async function RI(e,t={}){let n=Mi();return n?b_(e,async()=>{let r;try{r=await Fc(e,()=>l_(e),t.lockWaitMs)}catch(a){if(a instanceof g&&a.code==="lock_conflict")return!1;throw a}if(r.pending.length>0||Di(r)&&zc(e,n))return!1;let o=zt(e);await $.mkdir(U.dirname(o),{recursive:!0});let i=`${o}.${Uc()}.tmp`,s;try{s=new n(i),CI(s),s.exec("BEGIN IMMEDIATE");let a=await w_(e);await xI(s,a),s.exec("COMMIT"),s.close(),s=void 0;let c=await Fc(e,async()=>{let d=await l_(e);return d.pending.length>0||!SI(r.committed,d.committed)||Di(d)&&zc(e,n)?!1:(await $.rm(o,{force:!0}),await $.rename(i,o),!0)},t.lockWaitMs);return c&&await Promise.all(r.committed.map(d=>$.rm(U.join(xr(e),d),{force:!0}))),c||(await d_(e),await $.rm(i,{force:!0})),c}catch(a){throw await d_(e),s?.close(),await $.rm(i,{force:!0}),a}},t.lockWaitMs):!1}async function xI(e,t){let n=0;for(let r of t.events)E_(e,r),++n%500===0&&await a_();for(let[r,o]of t.stream_receipts)S_(e,r,o),++n%500===0&&await a_()}function Ti(e,t){return!t||t.length===0||t.includes(e)}function Vc(e,t){return e.entry.ts.localeCompare(t.entry.ts)||e.stream_id.localeCompare(t.stream_id)||e.stream_offset-t.stream_offset}function Pi(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():e}function NI(e,t){if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){if(Vc(e,{stream_id:t.after_stream_id,stream_offset:t.after_stream_offset,entry:{...e.entry,ts:Pi(t.after_ts)}})<=0)return!1}else if(t.since_ts!==void 0&&e.entry.ts<Pi(t.since_ts))return!1;return!0}function DI(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 PI(e,t){return!NI(e,t)||!Ti(e.entry.op,t.ops)||!Ti(e.entry.author,t.authors)||!Ti(e.entry.agent_instance??"",t.agent_instances)||!Ti(e.stream_id,t.stream_ids)||!DI(e,t)?!1:(t.provenance??[]).every(n=>{let r=e.entry.agent_provenance?.[n.dimension]?.value;return r!==void 0&&n.values.includes(r)})}async function MI(e,t){let n=Math.max(0,Math.floor(t.limit)),r=await w_(e,t.stream_ids,t.verify),o=r.events.filter(i=>PI(i,t)).slice(0,n+1);return{events:o.slice(0,t.limit),has_more:o.length>t.limit,...t.verify?{verified_streams:r.stream_receipts.size}:{}}}async function $I(e,t){let n=e.prepare("SELECT byte_size, content_hash FROM streams WHERE stream_id = ?").get(U.basename(t,".jsonl")),r=0;try{r=(await $.stat(t)).size}catch(i){if(!ee(i))throw i}if(Number(n?.byte_size??0)!==r)return!1;let o=await Wc(U.dirname(U.dirname(t)),U.basename(t,".jsonl"));return n===void 0?o?.byte_size===0:o?.content_hash===n.content_hash}async function O_(e,t,n){let r=U.dirname(U.dirname(e)),o=Mi(),i=!1,s=async()=>{await n(),i=!0};if(!o){await f_(r,s);return}try{await b_(r,async()=>{let a=zt(r);try{await $.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!==Hc)throw new TypeError("Unsupported history event index version");if(!await $I(c,e))throw new TypeError("Stale history event index append base")}catch(l){if(c?.close(),Ft(l))throw l;await $c(r,!0),await s();return}try{c.exec("PRAGMA busy_timeout = 0"),c.exec("BEGIN IMMEDIATE")}catch(l){if(c.close(),Ft(l)||!(l instanceof Error)||l.code!=="ERR_SQLITE_ERROR")throw l;await $c(r,!1),await s();return}let d=!1;try{await s(),d=!0;let l=U.basename(e,".jsonl"),u=c.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(l);E_(c,{stream_id:l,stream_offset:Number(u.value),entry:t}),S_(c,l,await Wc(r,l)),c.exec("COMMIT"),c.close()}catch(l){if(c?.close(),!d)throw l;await $c(r,Ft(l))}},0,"append")}catch(a){if(i){await Ni(r);return}if(!LI(a))throw a;await f_(r,s,Ft(a))}}async function f_(e,t,n=!1){let r=!1,o;try{await Fc(e,async()=>{let i=n||Di(await xi(e)),s=await kI(e);o=s.pendingPath;try{await t(),r=!0}catch(a){throw await $.rm(s.pendingPath,{force:!0}),a}await $.rename(s.pendingPath,i?s.committedPath.replace(/\.committed$/u,".contended.committed"):s.committedPath),i||await Ni(e)})}catch(i){if(r){await Ni(e);try{await $.rm(o,{force:!0})}catch{}return}throw i}}async function Bc(e){await $.rm(zt(U.dirname(U.dirname(e))),{force:!0})}function Ci(e,t,n,r){!r||r.length===0||(e.push(`${n} IN (${r.map(()=>"?").join(", ")})`),t.push(...r))}function jI(e,t,n,r){if(!n||n.length===0)return;let o=n.map(()=>"?").join(", "),i=r??[];if(i.length>0){e.push(`(agent_harness IN (${o}) OR (agent_harness IS NULL AND author IN (${i.map(()=>"?").join(", ")})))`),t.push(...n,...i);return}e.push(`agent_harness IN (${o})`),t.push(...n)}async function A_(e,t,n,r){let o;try{let i=await xi(e);if(await u_(e,i))return st;let s=await m_(e);if(i.committed.length>0)return Di(i)&&zc(e,t)?st:null;if(o=new t(zt(e),{readOnly:!0}),o.exec("BEGIN"),o.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Hc)return null;let a=r(o);if(a===null)return null;let c=FI(o,n),d=o;o=void 0,d.close();let l=await UI([...c.keys()],e,n),u=await zI(c,e,l),f=await xi(e);return f.committed.length>0||await u_(e,f)||s!==await m_(e)?st:u?a:null}catch(i){return Ft(i)?st:null}finally{o?.close()}}function Ft(e){return typeof e=="object"&&e!==null&&"errcode"in e&&[5,6].includes(e.errcode)}function LI(e){return Ft(e)||e instanceof g&&e.code==="lock_conflict"}function FI(e,t){let n=new Map,r=t&&t.length>0?[...new Set(t)]:void 0;if(r===void 0)for(let o of e.prepare("SELECT stream_id, byte_size, content_hash FROM streams").all())n.set(String(o.stream_id),{byte_size:Number(o.byte_size),content_hash:String(o.content_hash)});else for(let o=0;o<r.length;o+=500){let i=r.slice(o,o+500);for(let s of e.prepare(`SELECT stream_id, byte_size, content_hash FROM streams WHERE stream_id IN (${i.map(()=>"?").join(", ")})`).all(...i))n.set(String(s.stream_id),{byte_size:Number(s.byte_size),content_hash:String(s.content_hash)})}return n}async function m_(e){let t=await $.stat(zt(e),{bigint:!0});return[t.dev,t.ino,t.size,t.mtimeNs,t.ctimeNs].join(":")}async function wF(e,t){if(t.verify)return{result:await MI(e,t),repair_needed:!1};let n=Mi();if(!n)return{result:null,repair_needed:!1};let r=[],o=[];if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){r.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");let a=Pi(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&&(r.push("ts >= ?"),o.push(Pi(t.since_ts)));Ci(r,o,"op",t.ops),Ci(r,o,"author",t.authors),jI(r,o,t.harnesses,t.harness_alias_authors),Ci(r,o,"agent_instance",t.agent_instances);for(let a of t.provenance??[])r.push(`json_extract(entry_json, '$.agent_provenance.${a.dimension}.value') IN (${a.values.map(()=>"?").join(", ")})`),o.push(...a.values);Ci(r,o,"stream_id",t.stream_ids);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`,s=await A_(e,n,t.stream_ids,a=>{let c=a.prepare(`SELECT stream_id, stream_offset, entry_json
92
92
  FROM events${i}
93
93
  ORDER BY ts, stream_id, stream_offset
94
- LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),d=c.slice(0,t.limit).map(E_);return d.includes(null)?null:{events:d,has_more:c.length>t.limit}});return{result:s===st?null:s,repair_needed:s===null&&!await h_(e)}}function A_(e,t){let n=Object.create(null);for(let r of e){if(!t.has(r.stream_id)||yn(r.entry)!=="substantive")continue;let o=n[r.stream_id];(o===void 0||Vc(o,r)<0)&&(n[r.stream_id]=r)}return n}async function Wc(e,t){if(U.basename(t)!==t)return null;try{let n=U.join(e,"history",`${t}.jsonl`),r=await $.stat(n),o=await $.readFile(n);return r.size!==o.length?null:{byte_size:o.length,content_hash:Ri("sha256").update(o).digest("hex")}}catch(n){if(ee(n))return{byte_size:0,content_hash:Ri("sha256").digest("hex")};throw n}}async function zI(e,t,n){for(let r=0;r<n.length;r+=a_){let o=n.slice(r,r+a_),i=await Promise.all(o.map(s=>Wc(t,s)));for(let[s,a]of i.entries()){if(a===null)return!1;let c=o[s],d=e.get(c);if(!(a.byte_size===0&&d===void 0)&&(a.byte_size!==d?.byte_size||a.content_hash!==d.content_hash))return!1}}return!0}async function UI(e,t,n){if(n&&n.length>0)return[...new Set(n.filter(o=>o.trim().length>0))];let r=await $.readdir(U.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(ee(o))return[];throw o});return[...new Set([...e,...r])]}async function m_(e,t,n,r){return e?O_(t,e,n,o=>{let i=[];for(let s=0;s<n.length;s+=500){let a=n.slice(s,s+500),c=o.prepare(`SELECT stream_id, stream_offset, entry_json
94
+ LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),d=c.slice(0,t.limit).map(k_);return d.includes(null)?null:{events:d,has_more:c.length>t.limit}});return{result:s===st?null:s,repair_needed:s===null&&!await g_(e)}}function I_(e,t){let n=Object.create(null);for(let r of e){if(!t.has(r.stream_id)||yn(r.entry)!=="substantive")continue;let o=n[r.stream_id];(o===void 0||Vc(o,r)<0)&&(n[r.stream_id]=r)}return n}async function Wc(e,t){if(U.basename(t)!==t)return null;try{let n=U.join(e,"history",`${t}.jsonl`),r=await $.stat(n),o=await $.readFile(n);return r.size!==o.length?null:{byte_size:o.length,content_hash:Ri("sha256").update(o).digest("hex")}}catch(n){if(ee(n))return{byte_size:0,content_hash:Ri("sha256").digest("hex")};throw n}}async function zI(e,t,n){for(let r=0;r<n.length;r+=c_){let o=n.slice(r,r+c_),i=await Promise.all(o.map(s=>Wc(t,s)));for(let[s,a]of i.entries()){if(a===null)return!1;let c=o[s],d=e.get(c);if(!(a.byte_size===0&&d===void 0)&&(a.byte_size!==d?.byte_size||a.content_hash!==d.content_hash))return!1}}return!0}async function UI(e,t,n){if(n&&n.length>0)return[...new Set(n.filter(o=>o.trim().length>0))];let r=await $.readdir(U.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(ee(o))return[];throw o});return[...new Set([...e,...r])]}async function p_(e,t,n,r){return e?A_(t,e,n,o=>{let i=[];for(let s=0;s<n.length;s+=500){let a=n.slice(s,s+500),c=o.prepare(`SELECT stream_id, stream_offset, entry_json
95
95
  FROM (
96
96
  SELECT stream_id, stream_offset, entry_json,
97
97
  ROW_NUMBER() OVER (
@@ -102,14 +102,15 @@ ${Kp(t,n+1)}`}function LA(e,t,n){let r=e.map(o=>Ei(o,t,n||t.preserveRowFacts&&L(
102
102
  WHERE event_class = 'substantive'
103
103
  AND stream_id IN (${a.map(()=>"?").join(", ")})
104
104
  )
105
- WHERE recency_rank = 1`).all(...a).map(E_);if(c.includes(null))return null;i.push(...c)}return A_(i,r)}):null}async function wF(e,t){let n=[...new Set(t.filter(a=>a.trim().length>0&&U.basename(a)===a))];if(n.length===0)return{};let r=new Set(n),o=Mi(),i=await m_(o,e,n,r);if(i!==null&&i!==st)return i;if(o&&i!==st&&!await h_(e))try{if(await RI(e,{lockWaitMs:0})){let a=await m_(o,e,n,r);if(a!==null&&a!==st)return a}}catch{}let s=[];return await Promise.all(n.map(async a=>{let c=U.join(e,"history",`${a}.jsonl`);(await TI(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})})})),A_(s,r)}import Gc from"node:fs/promises";import In 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 HI=In.join("runtime","history-drift-cache.json"),I_={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 T_(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function qI(e){let t=In.join(e,HI),n=!1,r="invalid_cache_path";try{n=(await Gc.stat(await Gc.realpath(e))).isDirectory()}catch(o){let i=T_(o);r=i===void 0?"unknown":I_[i]??"filesystem_error"}if(!n){Cr(`[pm] warning: history_drift_cache_invalidation_failed:${r}
106
- `);return}try{await Gc.rm(t,{force:!0})}catch(o){let i=T_(o);if(ee(o))return;let s=i===void 0?"unknown":I_[i]??"filesystem_error";Cr(`[pm] warning: history_drift_cache_invalidation_failed:${s}
107
- `)}}async function $i(e){let t=In.dirname(In.resolve(e));In.basename(t)==="history"&&await qI(In.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 BI={front_matter:{},body:""},$t=3,Rr=[1,2,3],WI=1,GI=[1];function P_(e){return Ye(R(e),e.hash_algorithm)}function Tn(e){return Vr(R(e))}function VF(e){return Vr(R(e))}function Jc(e){let t={...e,record_hash_version:WI},{record_hash:n,...r}=t;return{...t,record_hash:P_(r)}}function ki(e){try{kt(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(!GI.includes(e.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};let{record_hash:t,...n}=e;return P_(n)===e.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function KI(e,t){let n={before_hash:e.before_hash,after_hash:e.after_hash,patch_hash:Tn(e.patch)};return e.hash_algorithm!==void 0&&(n.hash_algorithm=e.hash_algorithm),e.item_hash_version!==void 0&&(n.item_hash_version=e.item_hash_version),t.retainOriginalPatch&&(n.patch=structuredClone(e.patch)),t.retainPriorRecordHash!==!1&&e.record_hash_version!==void 0&&e.record_hash!==void 0&&(n.record_hash_version=e.record_hash_version,n.record_hash=e.record_hash,n.record=structuredClone(e)),n}function Zp(e,t,n={}){let r=ki(e);if(!r.ok)throw new TypeError(r.error);let o=Tn(e.patch),i=n.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!==Tn(t.patch),s=Jc({...t,...i?{reanchor_evidence:[...t.reanchor_evidence??[],KI(e,n)]}:{}}),a=Pc(s);if(!a.ok)throw new TypeError(a.error);return s}function M_(e){return!Array.isArray(e)||Object.keys(e).length!==e.length?!1:e.every(t=>!Ut(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 YI(e){return Ut(e)&&typeof e.ts=="string"&&typeof e.author=="string"&&typeof e.op=="string"&&typeof e.before_hash=="string"&&typeof e.after_hash=="string"&&M_(e.patch)}function XI(e){let t=e.record_hash_version!==void 0,n=e.record_hash!==void 0;return t===n}function JI(e){return!Ut(e)||!XI(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&&!M_(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||YI(e.record)}function ZI(e){try{for(let t of e){if(!JI(t))return!1;kt(t.hash_algorithm)}return!0}catch{return!1}}function QI(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&&Tn(t.patch)===e.patch_hash}function eT(e,t,n){if(t.patch&&Tn(t.patch)!==t.patch_hash)return{kind:"patch_hash_mismatch"};if(t.record)return QI(t)?{kind:"record",entry:t.record}:{kind:"record_hash_mismatch"};let r=t.patch??e.patch;if(Tn(r)!==t.patch_hash)return{kind:"digest_only"};let o={...e,before_hash:t.before_hash,after_hash:t.after_hash,patch:r,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},...n.length===0?{}:{reanchor_evidence:n}};return t.hash_algorithm===void 0&&delete o.hash_algorithm,n.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 Pc(e){let t=e.reanchor_evidence;if(t===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(t)||!ZI(t))return{ok:!1,error:"rewrite_evidence_invalid"};if(t.length===0)return{ok:!0,coverage:"none"};let n=e;for(let r=t.length-1;r>=0;r-=1){let o=t[r],i=eT(n,o,t.slice(0,r));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(!ki(i.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};n=i.entry}return{ok:!0,coverage:"complete"}}function ji(e,t){return(e??"").localeCompare(t??"")}function R_(e,t){return(e??0)-(t??0)}function at(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function tT(e,t){return[e.scope.localeCompare(t.scope),ji(e.path,t.path),ji(e.command,t.command),R_(e.timeout_seconds,t.timeout_seconds),ji(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,[]),R_(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,{}),ji(e.note,t.note)].find(n=>n!==0)??0}function nT(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function rT(e,t){let n=nT(t);if(n.length===0)return!0;let r=e;for(let o of n){let i=/^(0|[1-9]\d*)$/.test(o)?Number(o):-1,s=Array.isArray(r)?i>=0&&i<r.length?r[i]:void 0:Ut(r)&&Object.prototype.hasOwnProperty.call(r,o)?r[o]:void 0;if(s===void 0)return!1;r=s}return!0}function oT(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!rT(r,o.path)?{...o,op:"add"}:o;n.push(i),r=D_.applyPatch(r,[i],!0,!0).newDocument}return n}function Li(e,t,n=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let r=fn(e),o=t===1||t===2&&n?{...r.metadata,...r.metadata.dependencies===void 0?{}:{dependencies:r.metadata.dependencies.map(s=>({...s,id:s.id.toLowerCase()}))},...r.metadata.tests===void 0?{}:{tests:r.metadata.tests.map(({workspace_context_mode:s,provenance:a,provenance_invalid:c,...d})=>d)},...r.metadata.test_runs===void 0?{}:{test_runs:r.metadata.test_runs.map(({executions:s,...a})=>a)}}:r.metadata,i=t===1&&o.tests?{...o,tests:[...o.tests].sort(tT)}:o;return{front_matter:A(i,ve),body:r.body}}function x_(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let t=fn(e);return{metadata:A(t.metadata,ve),body:t.body}}function BF(e){return $_(e,$t)}function $_(e,t,n){if(!Rr.some(r=>r===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return Ye(R(Li(e,t)),n)}function Qp(e,t,n){let r=$_(e,t,n);return t===2?[r,Ye(R(Li(e,t,!0)),n)]:[r]}function WF(){return Vr(R(BI))}function Nr(e){let t=Rf(e.op),n=Li(e.before,$t),r=Li(e.after,$t),o=x_(e.before),i=x_(e.after),s=D_.compare(o,i),a=oT(o,s),c=ym(e.author),d=c.harness?Object.fromEntries(Object.entries(pm().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??Uu,f={hash_algorithm:u,ts:e.nowIso,author:e.author,author_source:e.authorSource??_m(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:Ye(R(n),u),after_hash:Ye(R(r),u),item_hash_version:$t,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}};return Jc({...f,event_class:yn(f)})}function Ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kc(e){return new g(e,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function j_(e){let t=e.ts.trim();if(t.length===0)return Te();if(!Zt(t))throw Kc("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(t!==e.ts)throw Kc("History timestamp must not contain surrounding whitespace");return e.ts}function N_(e,t){let n=e.ts;if(typeof n=="string"&&n.trim().length>0){if(!Zt(n))throw Kc("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return e}return{...e,ts:t}}function Yc(e,t){let n=j_(t);if(typeof e=="string"){let r;try{r=JSON.parse(e)}catch{return e}return Ut(r)?JSON.stringify(N_(r,n)):e}return Ut(e)?JSON.stringify(N_(e,n)):JSON.stringify(e)}async function iT(e,t,n){if(n===!1)return!0;if(typeof n=="string"){let s=Yc(n,t);return await Xc(e,s),await $i(e),await Bc(e),!0}if(typeof n!="object"||n===null)return!1;let r=n;if(r.skip===!0)return!0;let o=typeof r.history_path=="string"?r.history_path:e,i=Yc(typeof r.line=="string"?r.line:r.entry??t,t);return await Xc(o,i),await $i(o),await Bc(o),!0}async function Xc(e,t){let n;try{n=JSON.parse(t)}catch{n=null}if(!Ut(n)||n.op!=="create"){await Td(e,t);return}await C_.mkdir(VI.dirname(e),{recursive:!0});try{await C_.writeFile(e,`${t}
108
- `,{encoding:"utf8",flag:"wx"})}catch(r){throw r.code!=="EEXIST"?r: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 Dr(e,t){let n=await cn("history_append",{history_path:e,entry:t});if(n.handled&&await iT(e,t,n.result))return;let r=t.ts.trim().length>0?t:{...t,ts:j_(t)},o=Jc({...r,hash_algorithm:kt(r.hash_algorithm),event_class:yn(r)});await S_(e,o,async()=>{await Xc(e,Yc(o,o))}),await $i(e)}import L_ from"node:fs/promises";import Cn 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 Ht(e){return Cn.join(e,"history",`${ct}.jsonl`)}function Zc(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 qt(e,t=e.length){let n=Si();for(let r of e.slice(0,t))n=Ai(n,r.patch).document;return Oi(n)}function Rn(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function xn(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 Fi(e,t){let n=Cn.resolve(t),r=Cn.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||Cn.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function iz(e){let t=await Rt(Ht(e),ct),n=jt(t);n.ok||xn(n.errors);let r=Rn(t.length===0?Pn:qt(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let d;try{let l=Fi(e,Cn.resolve(e,c));if(d=await Ae(l.absolutePath),d===null){s.push(c);continue}let u=JSON.parse(d);(R(u)===R(r[c])?o:i).push(c)}catch{a.push(c)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(r).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}async function F_(e){let t=Ht(e.pmRoot),n=await Rt(t,ct),r=jt(n);r.ok||xn(r.errors);let o=e.idempotencyKey===void 0?void 0:n.find(u=>u.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=Te(),s=n.length===0?Pn:qt(n),a=Rn(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=Zc({...a,[e.documentPath]:e.after},n.length===0?i:s.metadata.created_at),l=Nr({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 Dr(t,l),{entry:l,historyPath:t}}async function sz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await F_(e)}finally{await t()}}async function az(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=Ht(e.pmRoot),r=await Rt(n,ct),o=jt(r);o.ok||xn(o.errors);let i=r.length===0?Pn:qt(r),s=Nr({nowIso:Te(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Dr(n,s),{entry:s,historyPath:n}}finally{await t()}}async function z_(e,t){if(t===e.raw)return!1;let n=t===null?null:JSON.parse(t),r=JSON.parse(e.raw);await pt(e.filePath,e.raw);try{(t!==null||e.recordCreation!==!1)&&await F_({pmRoot:e.pmRoot,documentPath:Cn.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:n,after:r,op:e.op,idempotencyKey:e.idempotencyKey,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(o){throw t===null?await L_.rm(e.filePath,{force:!0}):await pt(e.filePath,t),o}return!0}async function U_(e){let{documentPath:t}=Fi(e.pmRoot,e.filePath),n=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let r=await Ae(e.filePath);if(e.dryRun===!0||e.idempotencyKey!==void 0){let i=await Rt(Ht(e.pmRoot),ct),s=jt(i);s.ok||xn(s.errors);let a=Rn(i.length===0?Pn:qt(i))[t];if(a!==void 0&&R(a)!==R(r===null?null:JSON.parse(r)))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(r);return JSON.parse(o.raw),e.dryRun===!0?{changed:r!==o.raw,result:o.result}:{changed:await z_({...e,raw:o.raw},r),result:o.result}}finally{await n()}}async function cz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await z_(e,await Ae(e.filePath))}finally{await t()}}async function dz(e){let t=e.authorizationDecision.trim();if(!t)throw new TypeError("Workspace history reconciliation requires an authorization decision");let n=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:r,absolutePath:o}=Fi(e.pmRoot,e.filePath),i=Ht(e.pmRoot),s=await Rt(i,ct),a=jt(s);a.ok||xn(a.errors);let c=qt(s),d=Rn(c);if(!Object.hasOwn(d,r))throw new TypeError(`Workspace history does not govern document ${r}`);let l=await Ae(o);if(l===null)throw new TypeError(`Workspace history document is missing: ${r}`);let u=JSON.parse(l);if(R(d[r])===R(u))return{changed:!1,historyPath:i};let f=Te(),m=Nr({nowIso:f,author:e.author,op:e.op,before:c,after:Zc({...d,[r]:u},c.metadata.created_at),message:e.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:r,authorization_decision:t}});return await Dr(i,m),{changed:!0,entry:m,historyPath:i}}finally{await n()}}async function lz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:n,absolutePath:r}=Fi(e.pmRoot,e.filePath),o=await Rt(Ht(e.pmRoot),ct),i=jt(o);if(i.ok||xn(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=Rn(qt(o,e.targetVersion))[n];if(s===void 0)throw new TypeError(`Workspace history version ${e.targetVersion} does not contain ${n}`);let a=await Ae(r),c=`${JSON.stringify(s,null,2)}
109
- `;if(a===c)return{document_path:n,restored_from_version:e.targetVersion,changed:!1};let d=qt(o),l=Te(),u=Nr({nowIso:l,author:e.author,op:e.op,before:d,after:Zc({...Rn(d),[n]:s},d.metadata.created_at),message:e.message,context:{reason:"workspace_state_restore",document_path:n,restored_from_version:e.targetVersion,replaced_out_of_band_state:!0}});await pt(r,c);try{await Dr(Ht(e.pmRoot),u)}catch(f){throw a===null?await L_.rm(r,{force:!0}):await pt(r,a),f}return{document_path:n,restored_from_version:e.targetVersion,changed:!0}}finally{await 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]="33d6dc97-17d3-5db3-ab0d-6857be0e5827")}catch{}})();var Ne={ok:!1,path:[]};function ed(e,t){return{ok:!1,path:[e,...t.path]}}var b=e=>typeof e=="string"?{ok:!0,value:e}:Ne,x=e=>typeof e=="boolean"?{ok:!0,value:e}:Ne;function F(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?Ne:{ok:!0,value:t}}function N(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:Ne}function k(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return Ne;let r=[];for(let[o,i]of n.entries()){let s=e(i);if(!s.ok)return ed(String(o),s);r.push(s.value)}return{ok:!0,value:r}}}function td(e,t){return n=>typeof n=="string"&&n.length>0&&n.length<=e&&n===n.trim()&&(t===void 0||t.test(n))?{ok:!0,value:n}:Ne}function p(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function zi(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return Ne;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return ed(r,i);n[r]=i.value}return{ok:!0,value:n}}}function I(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return Ne;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return ed(o,s);s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var sT=I({key:b,values:k(b),required:p(x),aliases:p(k(b)),description:p(b)}),aT=I({command:N("create","update"),option:b,required:p(x),visible:p(x),enabled:p(x)}),cT=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(sT)),command_option_policies:p(k(aT))}),dT=I({id:b,aliases:p(k(b)),roles:p(k(N(...Kr))),description:p(b),order:p(F())}),lT=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(...Xt)),commands:p(k(N(...Yr))),repeatable:p(x),required:p(x),required_on_create:p(x),required_types:p(k(b)),allow_unset:p(x)}),uT=e=>{if(!Array.isArray(e)||e.length!==2)return Ne;let[t,n]=e;return typeof t!="string"||typeof n!="string"?Ne:{ok:!0,value:[t,n]}},fT=I({type:b,allowed_transitions:k(uT)}),mT=p(I({version:p(F({int:!0})),files:p(I({types:p(b),statuses:p(b),fields:p(b),workflows:p(b)})),statuses:p(k(dT)),fields:p(k(lT)),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(fT)),unknown_field_policy:p(N(...Xr))})),pT=p(I({preset:p(N(...$d)),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")),start_blocker_enforcement:p(N("off","warn","strict")),duplicate_detection_mode:p(N("off","advisory","strict")),duplicate_detection_threshold:p(F({min:0,max:1})),duplicate_detection_limit:p(F({int:!0,min:0,max:20}))})),_T=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))}),Qc=N("block","warn"),yT=e=>typeof e=="string"?Qc(e):I({global:p(Qc),project:p(Qc)})(e),hT=p(I({mode:p(N("off","warn","enforce")),trust_mode:p(N("off","warn","enforce")),pm_max_version_exceeded_mode:p(yT),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(_T))})),Vt=td(128),gT=I({harness:td(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:p(k(Vt,64)),model_environment_keys:p(k(Vt,64)),session_environment_keys:p(k(Vt,64)),provenance_environment_keys:p(zi(k(Vt,64))),provenance_resolvers:p(zi(N("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:p(k(Vt,64)),argv_markers:p(k(Vt,64)),client_names:p(k(Vt,64))}),H_={version:F({int:!0}),id_prefix:b,ids:p(I({token_length:p(F({int:!0,min:4,max:12}))})),author_default:b,agent_identity:p(I({probes_enabled:p(x),identity_vocabulary:p(I({version:F({int:!0,positive:!0}),aliases:zi(td(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:k(gT)})),mutation_guard:p(I({require_attributed_author:p(x),secret_guard:p(N("off","advise","block")),stale_in_progress_hours:p(F({int:!0,positive:!0}))})),item_format:p(N("toon","json_markdown")),locks:I({ttl_seconds:F({int:!0}),wait_ms:p(F({int:!0,min:0}))}),checkpoints:p(I({retention_days:p(F({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(F({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(zi(F({int:!0,positive:!0})))})),governance:pT,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(F({int:!0,positive:!0}))})),agent_guidance:p(I({prompt_completed:p(x),declined:p(x),declined_at:p(b),template_version:p(F({int:!0,positive:!0})),last_checked_files:p(k(b))})),item_types:p(I({definitions:k(cT)})),schema:mT,context:p(I({default_depth:p(N("brief","standard","deep")),activity_limit:p(F({int:!0,positive:!0})),stale_threshold_days:p(F({int:!0,positive:!0})),next_ranking_policy:p(N("priority_floor","weighted")),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:hT}),search:I({score_threshold:F(),hybrid_semantic_weight:p(F()),max_results:F({int:!0}),embedding_model:b,embedding_corpus_max_characters:p(F()),embedding_batch_size:F({int:!0}),embedding_timeout_ms:p(F({int:!0})),scanner_max_batch_retries:F({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(F({int:!0,positive:!0}))})),bm25:p(I({k1:p(F()),b:p(F())}))}),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})})},bT=I(H_),q_=Object.freeze(Object.keys(H_));function Ui(e){let t=bT(e);return t.ok?{success:!0,data:t.value}:{success:!1,path:t.path.join(".")}}import{AsyncLocalStorage as OT}from"node:async_hooks";import{lstat as AT,realpath as ey}from"node:fs/promises";import ty 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]="a0ca9902-540c-50fe-a4e2-9c234c4a01f3")}catch{}})();function Hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nd(e,t,n,r=[]){if(W(e,t)&&(r.length>0||Hi(n)))return n;if(W(e,n)||W(t,n))return t;if((e===void 0||Hi(e))&&Hi(t)&&Hi(n)){let o=e??{},i=new Set([...Object.keys(o),...Object.keys(t),...Object.keys(n)]);return Object.fromEntries([...i].flatMap(s=>{let a=nd(Object.hasOwn(o,s)?o[s]:void 0,Object.hasOwn(t,s)?t[s]:void 0,Object.hasOwn(n,s)?n[s]:void 0,[...r,s]);return a===void 0?[]:[[s,a]]}))}throw new g(`Settings changed concurrently at ${r.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 wT={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},V_=120;function rd(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function W_(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var vT=W_(wT),B_=new WeakMap;function ET(e){let t=B_.get(e);if(t)return t;let n=W_(e);return B_.set(e,n),n}function gz(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return V_;if(t){let o=ET(t).get(n);if(rd(o))return Math.floor(o)}let r=vT.get(n);return rd(r)?Math.floor(r):V_}function od(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!rd(r)||(t[o]=Math.floor(r))}return t}import{stat as kT}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 qi=new Map;function G_(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function ST(e){try{let t=await kT(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=G_(e),n=await Promise.all(t.map(r=>ST(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Pr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.path!==o.path||r.mtime_ms!==o.mtime_ms||r.size!==o.size)return!1}return!0}function K_(e){return qi.get(e)}function Vi(e,t){let n=G_(t.tracked_paths),r=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));qi.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Bt(e){if(e){qi.delete(e);return}qi.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]="aa89cd28-76a1-5eaf-b6f7-7501acefa5f2")}catch{}})();var cd=new OT;async function zz(e,t,n=()=>!0){let r=new Set([ty.resolve(e)]);try{r.add(await ey(e))}catch{}return cd.run([...cd.getStore()??[],[r,n]],t)}function IT(e){let t=ty.resolve(e);return cd.getStore()?.some(([n,r])=>n.has(t)&&r())??!1}var TT="settings:write",ny=Symbol("pm.settings.persist_source"),ry=Symbol("pm.settings.fallback_origin"),oy=Symbol("pm.settings.fallback_baseline"),CT=128,RT=new Set(["off","advisory","strict"]);function Y_(e){return structuredClone(Ad[e])}function xT(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:S.governance.preset}var NT=new Set(jd);function iy(e){return NT.has(e)}function X_(e,t){let n=typeof t.create_default_type=="string"?t.create_default_type.trim():void 0;return n&&n.length>0&&(e.create_default_type=n),(t.workflow_enforcement==="off"||t.workflow_enforcement==="warn"||t.workflow_enforcement==="strict")&&(e.workflow_enforcement=t.workflow_enforcement),iy(t.start_blocker_enforcement)&&(e.start_blocker_enforcement=t.start_blocker_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 DT(e){return e.preset==="custom"?X_({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):X_({preset:e.preset},e)}function PT(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,n={};t&&t.length>0&&(n.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(n.workflow_enforcement=e.workflow_enforcement),iy(e.start_blocker_enforcement)&&(n.start_blocker_enforcement=e.start_blocker_enforcement),typeof e.require_close_reason=="boolean"&&(n.require_close_reason=e.require_close_reason),RT.has(String(e.duplicate_detection_mode))&&(n.duplicate_detection_mode=e.duplicate_detection_mode);let r=e.duplicate_detection_threshold;[typeof r=="number",Number.isFinite(r),Number(r)>=0,Number(r)<=1].every(Boolean)&&(n.duplicate_detection_threshold=r);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(n.duplicate_detection_limit=o),n}function sy(e){let t=e.governance??{},n=xT(t.preset),r=PT(t);if(n==="custom"){let s=Y_("default"),a=r.require_close_reason??s.require_close_reason;return{preset:n,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,...r,require_close_reason:a,duplicate_detection_mode:r.duplicate_detection_mode??s.duplicate_detection_mode,duplicate_detection_threshold:r.duplicate_detection_threshold??s.duplicate_detection_threshold,duplicate_detection_limit:r.duplicate_detection_limit??s.duplicate_detection_limit}}let o=Y_(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function ud(){return structuredClone(S)}function ay(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:S.search.mutation_refresh_policy}function cy(e){return e==="auto"||e==="keyword"||e==="semantic"||e==="hybrid"?e:"auto"}function dy(e){return typeof e=="boolean"?e:S.search.query_expansion.enabled}function ly(e){return typeof e!="string"?S.search.query_expansion.provider:e.trim()}function uy(e){return typeof e=="boolean"?e:S.search.rerank.enabled}function fy(e){return typeof e!="string"?S.search.rerank.model:e.trim()}function my(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:S.search.rerank.top_k}function py(e){if(typeof e!="string")return S.vector_store.collection_name;let t=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,CT);return t.length>0?t:S.vector_store.collection_name}function id(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function _y(e,t){let n=e.schema,r=id(n?.statuses),o=id(n?.fields),i=id(n?.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:Nn(e.item_types?.definitions),has_source_schema_statuses:r.present,source_schema_statuses:r.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:Nn(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 Gi(e,t){Object.defineProperty(e,ny,{value:t,writable:!0,configurable:!0,enumerable:!1})}function fd(e){let t=e[ny];if(!(!t||typeof t!="object"))return t}function Uz(e){let t=fd(e);if(t){let n=structuredClone(t);n.source_settings.item_format=e.item_format,Gi(e,n)}}function Bi(e){let t=structuredClone(e.settings),n=fd(e.settings);n&&Gi(t,n);let r=md(e.settings);return r!==void 0&&yy(t,r),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function MT(e,t,n){let r=Ce(t);return[n,ue(e,r.files.types,ie.types),ue(e,r.files.statuses,ie.statuses),ue(e,r.files.fields,ie.fields),ue(e,r.files.workflows,ie.workflows)]}async function $T(e,t,n){let r=await dt(t);Vi(e,{tracked_paths:t,signatures:r,value:Bi(n)})}async function jT(e,t,n){try{await $T(e,t,n)}catch{Bt(e)}}function J_(e,t){return e.find(n=>n.path===t)}function LT(e,t,n){for(let r of n){let o=J_(e,r),i=J_(t,r);if(!o||!i||!Pr([o],[i]))return!1}return!0}async function sd(e,t,n,r,o){try{let i=await dt(t);if(!LT(r,i,o)){Bt(e);return}Vi(e,{tracked_paths:t,signatures:i,value:Bi(n)})}catch{Bt(e)}}function FT(e,t){let n=Ce(e.schema),r=Nn(e.item_types?.definitions);if(!t)return{item_type_definitions:r,schema_statuses:n.statuses,schema_fields:n.fields,schema_type_workflows:n.type_workflows};let o=n.type_workflows??[],i=W(r,t.runtime_item_type_definitions),s=W(n.statuses,t.runtime_schema_statuses),a=W(n.fields,t.runtime_schema_fields),c=W(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?Nn(t.source_item_type_definitions):[]:r,schema_statuses:s?t.has_source_schema_statuses?structuredClone(t.source_schema_statuses):[]:n.statuses,schema_fields:a?t.has_source_schema_fields?structuredClone(t.source_schema_fields):[]:n.fields,schema_type_workflows:c?t.has_source_schema_type_workflows?structuredClone(t.source_schema_type_workflows):void 0:n.type_workflows}}function yy(e,t){Object.defineProperty(e,ry,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Hz(e){return md(e)!==void 0}function md(e){let t=e[ry];return typeof t=="string"?t:void 0}function zT(e){return e[oy]}function UT(e,t){Object.defineProperty(e,oy,{value:t,writable:!0,configurable:!0,enumerable:!1})}function De(e){let t=ud();return e!==void 0&&yy(t,e),{settings:t,metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function hy(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function dd(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function gy(e){let t=S.agent_guidance,n=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 n=="number"&&Number.isInteger(n)&&n>0?n:t.template_version,last_checked_files:dd(e?.last_checked_files??t.last_checked_files)}}function Oe(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function HT(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.mode}function qT(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.trust_mode}function by(e){return e==="none"||e==="restricted"||e==="strict"?e:S.extensions.policy.default_sandbox_profile}function VT(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let n={name:t};e.disabled===!0&&(n.disabled=!0),e.require_trusted===!0&&(n.require_trusted=!0),e.require_provenance===!0&&(n.require_provenance=!0),e.sandbox_profile!==void 0&&(n.sandbox_profile=by(e.sandbox_profile));let r=Oe(e.allowed_capabilities),o=Oe(e.blocked_capabilities),i=Oe(e.allowed_surfaces),s=Oe(e.blocked_surfaces),a=Oe(e.allowed_commands),c=Oe(e.blocked_commands),d=Oe(e.allowed_actions),l=Oe(e.blocked_actions),u=Oe(e.allowed_services),f=Oe(e.blocked_services);return r.length>0&&(n.allowed_capabilities=r),o.length>0&&(n.blocked_capabilities=o),i.length>0&&(n.allowed_surfaces=i),s.length>0&&(n.blocked_surfaces=s),a.length>0&&(n.allowed_commands=a),c.length>0&&(n.blocked_commands=c),d.length>0&&(n.allowed_actions=d),l.length>0&&(n.blocked_actions=l),u.length>0&&(n.allowed_services=u),f.length>0&&(n.blocked_services=f),n}function BT(e){let t=new Map;for(let n of e??[]){let r=VT(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function ad(e){return e==="block"||e==="warn"?e:void 0}function WT(e){if(typeof e=="string")return ad(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=ad(e.global),n=ad(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function he(e,t){return Oe(e?.[t]??S.extensions.policy[t])}function wy(e){let t=WT(e?.pm_max_version_exceeded_mode);return{mode:HT(e?.mode),trust_mode:qT(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:he(e,"trusted_extensions"),default_sandbox_profile:by(e?.default_sandbox_profile),allowed_extensions:he(e,"allowed_extensions"),blocked_extensions:he(e,"blocked_extensions"),allowed_capabilities:he(e,"allowed_capabilities"),blocked_capabilities:he(e,"blocked_capabilities"),allowed_surfaces:he(e,"allowed_surfaces"),blocked_surfaces:he(e,"blocked_surfaces"),allowed_commands:he(e,"allowed_commands"),blocked_commands:he(e,"blocked_commands"),allowed_actions:he(e,"allowed_actions"),blocked_actions:he(e,"blocked_actions"),allowed_services:he(e,"allowed_services"),blocked_services:he(e,"blocked_services"),extension_overrides:BT(e?.extension_overrides??S.extensions.policy.extension_overrides)}}function vy(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].filter(t=>t.length>0).sort((t,n)=>t.localeCompare(n)).filter(t=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(t))}function lt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function G(e,t){return e===void 0?t:e}function ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function ld(e){return Array.isArray(e)?e:[]}function GT(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:vy(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:lt(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:lt(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:lt(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:lt(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:od(e.validation?.estimate_defaults_by_type)}}function KT(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 YT(e,t){return{...t.search,...e.search,default_mode:cy(e.search?.default_mode),mutation_refresh_policy:ay(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:dy(e.search?.query_expansion?.enabled),provider:ly(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:uy(e.search?.rerank?.enabled),model:fy(e.search?.rerank?.model),top_k:my(e.search?.rerank?.top_k)}}}function XT(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:py(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function JT(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function ZT(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,next_ranking_policy:e.context?.next_ranking_policy??t.context.next_ranking_policy,sections:{...t.context.sections,...e.context?.sections}}}function QT(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Nn(e){let t=(e??[]).map(r=>eo(r)).filter(r=>r!==null),n=new Map;for(let r of t)n.set(r.name.toLowerCase(),r);return[...n.values()].sort((r,o)=>r.name.localeCompare(o.name))}function Wi(e){let t=ud(),n=sy({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:JT(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:GT(e,t,n),governance:n,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:KT(e,t),agent_guidance:gy(e.agent_guidance??t.agent_guidance),item_types:{definitions:Nn(e.item_types?.definitions)},schema:Ce(e.schema??t.schema),context:ZT(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:wy(e.extensions.policy??t.extensions.policy)},search:YT(e,t),providers:QT(e,t),vector_store:XT(e,t)}}function eC(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(ge(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=ld(e.agent_identity.harness_signals).map(n=>A(ge(n),["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(ge(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=A(ge(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","next_ranking_policy","sections"]),e.context.sections=A(ge(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=A(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=A(ge(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=ld(e.extensions.policy.extension_overrides).map(n=>A(ge(n),["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(ge(e.search.query_expansion),["enabled","provider"]),e.search.rerank=A(ge(e.search.rerank),["enabled","model","top_k"]),e.providers=A(e.providers,["openai","ollama"]),e.providers.openai=A(ge(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=A(ge(e.providers.ollama),["base_url","model"]),e.vector_store=A(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=A(ge(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=A(ge(e.vector_store.lancedb),["path"])}function tC(e){return{...e,locks:G(e.locks,S.locks),ids:G(e.ids,S.ids),agent_identity:G(e.agent_identity,S.agent_identity),mutation_guard:G(e.mutation_guard,S.mutation_guard),checkpoints:G(e.checkpoints,S.checkpoints),output:G(e.output,S.output),ux:G(e.ux,S.ux),history:G(e.history,S.history),validation:G(e.validation,S.validation),workflow:G(e.workflow,S.workflow),testing:G(e.testing,S.testing),telemetry:G(e.telemetry,S.telemetry),agent_guidance:G(e.agent_guidance,S.agent_guidance),item_types:G(e.item_types,S.item_types),schema:G(e.schema,S.schema),context:G(e.context,S.context),extensions:G(e.extensions,S.extensions),search:G(e.search,S.search),providers:G(e.providers,S.providers),vector_store:G(e.vector_store,S.vector_store)}}function nC(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:vy(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:lt(e.validation?.lifecycle_stale_blocker_reason_patterns??S.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:lt(e.validation?.lifecycle_closure_like_blocked_reason_patterns??S.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:lt(e.validation?.lifecycle_closure_like_resolution_patterns??S.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:lt(e.validation?.lifecycle_closure_like_actual_result_patterns??S.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:od(e.validation?.estimate_defaults_by_type)}}function rC(e){return{...S.search,...e.search,default_mode:cy(e.search?.default_mode),mutation_refresh_policy:ay(e.search?.mutation_refresh_policy),query_expansion:{...S.search.query_expansion,...e.search?.query_expansion,enabled:dy(e.search?.query_expansion?.enabled),provider:ly(e.search?.query_expansion?.provider)},rerank:{...S.search.rerank,...e.search?.rerank,enabled:uy(e.search?.rerank?.enabled),model:fy(e.search?.rerank?.model),top_k:my(e.search?.rerank?.top_k)}}}function oC(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,next_ranking_policy:e.context?.next_ranking_policy??S.context.next_ranking_policy,sections:{...S.context.sections,...e.context?.sections}}}function iC(e){return{...e.vector_store,adapter:e.vector_store?.adapter??S.vector_store.adapter,collection_name:py(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function sC(e,t,n,r){return{...e,item_format:"toon",validation:nC(e,t),governance:t,agent_guidance:gy(e.agent_guidance),item_types:{definitions:r.item_type_definitions},schema:{...n,statuses:r.schema_statuses,fields:r.schema_fields,type_workflows:r.schema_type_workflows},search:rC(e),context:oC(e),extensions:{enabled:dd(e.extensions?.enabled),disabled:dd(e.extensions?.disabled),policy:wy(e.extensions?.policy)},vector_store:iC(e)}}function Ey(e,t){for(let n of Object.keys(t)){let r=Reflect.get(t,n),o=e[n];typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?Ey(o,r):e[n]=structuredClone(r)}}function pd(e,t,n){let r=new Set([...Object.keys(t),...Object.keys(n)]);for(let o of r){let i=t[o],s=n[o];if(!W(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:{};pd(c,i,s),Object.keys(c).length>0?e[o]=c:delete e[o];continue}e[o]=structuredClone(s)}}}var Ki=["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 Z_(e,t){let n=tC(e),r=sy(n),o=Ce(n.schema),i=FT(n,t),s=sC(n,r,o,i),a=A({...s,governance:DT(r)},Ki);return eC(a),a}function ky(e,t={}){let n=t.source===void 0?t.persist_source:_y(t.source.validated,Wi(t.source.validated)),r=Z_(e,n);if(n){let o=Wi(n.source_settings);o.item_types={definitions:structuredClone(n.runtime_item_type_definitions)},o.schema={...o.schema,statuses:structuredClone(n.runtime_schema_statuses),fields:structuredClone(n.runtime_schema_fields),type_workflows:structuredClone(n.runtime_schema_type_workflows)};let i=Z_(o,n);t.source!==void 0&&Ey(i,t.source.validated);let s=structuredClone(t.source===void 0?n.source_settings:t.source.raw);return pd(s,i,r),`${JSON.stringify(A(s,Ki),null,2)}
105
+ WHERE recency_rank = 1`).all(...a).map(k_);if(c.includes(null))return null;i.push(...c)}return I_(i,r)}):null}async function vF(e,t){let n=[...new Set(t.filter(a=>a.trim().length>0&&U.basename(a)===a))];if(n.length===0)return{};let r=new Set(n),o=Mi(),i=await p_(o,e,n,r);if(i!==null&&i!==st)return i;if(o&&i!==st&&!await g_(e))try{if(await RI(e,{lockWaitMs:0})){let a=await p_(o,e,n,r);if(a!==null&&a!==st)return a}}catch{}let s=[];return await Promise.all(n.map(async a=>{let c=U.join(e,"history",`${a}.jsonl`);(await TI(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})})})),I_(s,r)}import Gc from"node:fs/promises";import In 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 HI=In.join("runtime","history-drift-cache.json"),T_={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 C_(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function qI(e){let t=In.join(e,HI),n=!1,r="invalid_cache_path";try{n=(await Gc.stat(await Gc.realpath(e))).isDirectory()}catch(o){let i=C_(o);r=i===void 0?"unknown":T_[i]??"filesystem_error"}if(!n){Cr(`[pm] warning: history_drift_cache_invalidation_failed:${r}
106
+ `);return}try{await Gc.rm(t,{force:!0})}catch(o){let i=C_(o);if(ee(o))return;let s=i===void 0?"unknown":T_[i]??"filesystem_error";Cr(`[pm] warning: history_drift_cache_invalidation_failed:${s}
107
+ `)}}async function $i(e){let t=In.dirname(In.resolve(e));In.basename(t)==="history"&&await qI(In.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 BI={front_matter:{},body:""},$t=3,Rr=[1,2,3],WI=1,GI=[1];function M_(e){return Ye(R(e),e.hash_algorithm)}function Tn(e){return Vr(R(e))}function BF(e){return Vr(R(e))}function Jc(e){let t={...e,record_hash_version:WI},{record_hash:n,...r}=t;return{...t,record_hash:M_(r)}}function ki(e){try{kt(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(!GI.includes(e.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};let{record_hash:t,...n}=e;return M_(n)===e.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function KI(e,t){let n={before_hash:e.before_hash,after_hash:e.after_hash,patch_hash:Tn(e.patch)};return e.hash_algorithm!==void 0&&(n.hash_algorithm=e.hash_algorithm),e.item_hash_version!==void 0&&(n.item_hash_version=e.item_hash_version),t.retainOriginalPatch&&(n.patch=structuredClone(e.patch)),t.retainPriorRecordHash!==!1&&e.record_hash_version!==void 0&&e.record_hash!==void 0&&(n.record_hash_version=e.record_hash_version,n.record_hash=e.record_hash,n.record=structuredClone(e)),n}function Qp(e,t,n={}){let r=ki(e);if(!r.ok)throw new TypeError(r.error);let o=Tn(e.patch),i=n.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!==Tn(t.patch),s=Jc({...t,...i?{reanchor_evidence:[...t.reanchor_evidence??[],KI(e,n)]}:{}}),a=Pc(s);if(!a.ok)throw new TypeError(a.error);return s}function $_(e){return!Array.isArray(e)||Object.keys(e).length!==e.length?!1:e.every(t=>!Ut(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 YI(e){return Ut(e)&&typeof e.ts=="string"&&typeof e.author=="string"&&typeof e.op=="string"&&typeof e.before_hash=="string"&&typeof e.after_hash=="string"&&$_(e.patch)}function XI(e){let t=e.record_hash_version!==void 0,n=e.record_hash!==void 0;return t===n}function JI(e){return!Ut(e)||!XI(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&&!$_(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||YI(e.record)}function ZI(e){try{for(let t of e){if(!JI(t))return!1;kt(t.hash_algorithm)}return!0}catch{return!1}}function QI(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&&Tn(t.patch)===e.patch_hash}function eT(e,t,n){if(t.patch&&Tn(t.patch)!==t.patch_hash)return{kind:"patch_hash_mismatch"};if(t.record)return QI(t)?{kind:"record",entry:t.record}:{kind:"record_hash_mismatch"};let r=t.patch??e.patch;if(Tn(r)!==t.patch_hash)return{kind:"digest_only"};let o={...e,before_hash:t.before_hash,after_hash:t.after_hash,patch:r,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},...n.length===0?{}:{reanchor_evidence:n}};return t.hash_algorithm===void 0&&delete o.hash_algorithm,n.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 Pc(e){let t=e.reanchor_evidence;if(t===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(t)||!ZI(t))return{ok:!1,error:"rewrite_evidence_invalid"};if(t.length===0)return{ok:!0,coverage:"none"};let n=e;for(let r=t.length-1;r>=0;r-=1){let o=t[r],i=eT(n,o,t.slice(0,r));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(!ki(i.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};n=i.entry}return{ok:!0,coverage:"complete"}}function ji(e,t){return(e??"").localeCompare(t??"")}function x_(e,t){return(e??0)-(t??0)}function at(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function tT(e,t){return[e.scope.localeCompare(t.scope),ji(e.path,t.path),ji(e.command,t.command),x_(e.timeout_seconds,t.timeout_seconds),ji(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,[]),x_(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,{}),ji(e.note,t.note)].find(n=>n!==0)??0}function nT(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function rT(e,t){let n=nT(t);if(n.length===0)return!0;let r=e;for(let o of n){let i=/^(0|[1-9]\d*)$/.test(o)?Number(o):-1,s=Array.isArray(r)?i>=0&&i<r.length?r[i]:void 0:Ut(r)&&Object.prototype.hasOwnProperty.call(r,o)?r[o]:void 0;if(s===void 0)return!1;r=s}return!0}function oT(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!rT(r,o.path)?{...o,op:"add"}:o;n.push(i),r=P_.applyPatch(r,[i],!0,!0).newDocument}return n}function Li(e,t,n=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let r=fn(e),o=t===1||t===2&&n?{...r.metadata,...r.metadata.dependencies===void 0?{}:{dependencies:r.metadata.dependencies.map(s=>({...s,id:s.id.toLowerCase()}))},...r.metadata.tests===void 0?{}:{tests:r.metadata.tests.map(({workspace_context_mode:s,provenance:a,provenance_invalid:c,...d})=>d)},...r.metadata.test_runs===void 0?{}:{test_runs:r.metadata.test_runs.map(({executions:s,...a})=>a)}}:r.metadata,i=t===1&&o.tests?{...o,tests:[...o.tests].sort(tT)}:o;return{front_matter:A(i,ve),body:r.body}}function N_(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let t=fn(e);return{metadata:A(t.metadata,ve),body:t.body}}function WF(e){return j_(e,$t)}function j_(e,t,n){if(!Rr.some(r=>r===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return Ye(R(Li(e,t)),n)}function e_(e,t,n){let r=j_(e,t,n);return t===2?[r,Ye(R(Li(e,t,!0)),n)]:[r]}function GF(){return Vr(R(BI))}function Nr(e){let t=xf(e.op),n=Li(e.before,$t),r=Li(e.after,$t),o=N_(e.before),i=N_(e.after),s=P_.compare(o,i),a=oT(o,s),c=hm(e.author),d=c.harness?Object.fromEntries(Object.entries(_m().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??Hu,f={hash_algorithm:u,ts:e.nowIso,author:e.author,author_source:e.authorSource??ym(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:Ye(R(n),u),after_hash:Ye(R(r),u),item_hash_version:$t,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}};return Jc({...f,event_class:yn(f)})}function Ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kc(e){return new g(e,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function L_(e){let t=e.ts.trim();if(t.length===0)return Te();if(!Zt(t))throw Kc("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(t!==e.ts)throw Kc("History timestamp must not contain surrounding whitespace");return e.ts}function D_(e,t){let n=e.ts;if(typeof n=="string"&&n.trim().length>0){if(!Zt(n))throw Kc("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return e}return{...e,ts:t}}function Yc(e,t){let n=L_(t);if(typeof e=="string"){let r;try{r=JSON.parse(e)}catch{return e}return Ut(r)?JSON.stringify(D_(r,n)):e}return Ut(e)?JSON.stringify(D_(e,n)):JSON.stringify(e)}async function iT(e,t,n){if(n===!1)return!0;if(typeof n=="string"){let s=Yc(n,t);return await Xc(e,s),await $i(e),await Bc(e),!0}if(typeof n!="object"||n===null)return!1;let r=n;if(r.skip===!0)return!0;let o=typeof r.history_path=="string"?r.history_path:e,i=Yc(typeof r.line=="string"?r.line:r.entry??t,t);return await Xc(o,i),await $i(o),await Bc(o),!0}async function Xc(e,t){let n;try{n=JSON.parse(t)}catch{n=null}if(!Ut(n)||n.op!=="create"){await Cd(e,t);return}await R_.mkdir(VI.dirname(e),{recursive:!0});try{await R_.writeFile(e,`${t}
108
+ `,{encoding:"utf8",flag:"wx"})}catch(r){throw r.code!=="EEXIST"?r: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 Dr(e,t){let n=await cn("history_append",{history_path:e,entry:t});if(n.handled&&await iT(e,t,n.result))return;let r=t.ts.trim().length>0?t:{...t,ts:L_(t)},o=Jc({...r,hash_algorithm:kt(r.hash_algorithm),event_class:yn(r)});await O_(e,o,async()=>{await Xc(e,Yc(o,o))}),await $i(e)}import F_ from"node:fs/promises";import Cn 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 Ht(e){return Cn.join(e,"history",`${ct}.jsonl`)}function Zc(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 qt(e,t=e.length){let n=Si();for(let r of e.slice(0,t))n=Ai(n,r.patch).document;return Oi(n)}function Rn(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function xn(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 Fi(e,t){let n=Cn.resolve(t),r=Cn.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||Cn.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function sz(e){let t=await Rt(Ht(e),ct),n=jt(t);n.ok||xn(n.errors);let r=Rn(t.length===0?Pn:qt(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let d;try{let l=Fi(e,Cn.resolve(e,c));if(d=await Ae(l.absolutePath),d===null){s.push(c);continue}let u=JSON.parse(d);(R(u)===R(r[c])?o:i).push(c)}catch{a.push(c)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(r).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}async function z_(e){let t=Ht(e.pmRoot),n=await Rt(t,ct),r=jt(n);r.ok||xn(r.errors);let o=e.idempotencyKey===void 0?void 0:n.find(u=>u.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=Te(),s=n.length===0?Pn:qt(n),a=Rn(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=Zc({...a,[e.documentPath]:e.after},n.length===0?i:s.metadata.created_at),l=Nr({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 Dr(t,l),{entry:l,historyPath:t}}async function az(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await z_(e)}finally{await t()}}async function cz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=Ht(e.pmRoot),r=await Rt(n,ct),o=jt(r);o.ok||xn(o.errors);let i=r.length===0?Pn:qt(r),s=Nr({nowIso:Te(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Dr(n,s),{entry:s,historyPath:n}}finally{await t()}}async function U_(e,t){if(t===e.raw)return!1;let n=t===null?null:JSON.parse(t),r=JSON.parse(e.raw);await pt(e.filePath,e.raw);try{(t!==null||e.recordCreation!==!1)&&await z_({pmRoot:e.pmRoot,documentPath:Cn.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:n,after:r,op:e.op,idempotencyKey:e.idempotencyKey,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(o){throw t===null?await F_.rm(e.filePath,{force:!0}):await pt(e.filePath,t),o}return!0}async function H_(e){let{documentPath:t}=Fi(e.pmRoot,e.filePath),n=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let r=await Ae(e.filePath);if(e.dryRun===!0||e.idempotencyKey!==void 0){let i=await Rt(Ht(e.pmRoot),ct),s=jt(i);s.ok||xn(s.errors);let a=Rn(i.length===0?Pn:qt(i))[t];if(a!==void 0&&R(a)!==R(r===null?null:JSON.parse(r)))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(r);return JSON.parse(o.raw),e.dryRun===!0?{changed:r!==o.raw,result:o.result}:{changed:await U_({...e,raw:o.raw},r),result:o.result}}finally{await n()}}async function dz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await U_(e,await Ae(e.filePath))}finally{await t()}}async function lz(e){let t=e.authorizationDecision.trim();if(!t)throw new TypeError("Workspace history reconciliation requires an authorization decision");let n=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:r,absolutePath:o}=Fi(e.pmRoot,e.filePath),i=Ht(e.pmRoot),s=await Rt(i,ct),a=jt(s);a.ok||xn(a.errors);let c=qt(s),d=Rn(c);if(!Object.hasOwn(d,r))throw new TypeError(`Workspace history does not govern document ${r}`);let l=await Ae(o);if(l===null)throw new TypeError(`Workspace history document is missing: ${r}`);let u=JSON.parse(l);if(R(d[r])===R(u))return{changed:!1,historyPath:i};let f=Te(),m=Nr({nowIso:f,author:e.author,op:e.op,before:c,after:Zc({...d,[r]:u},c.metadata.created_at),message:e.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:r,authorization_decision:t}});return await Dr(i,m),{changed:!0,entry:m,historyPath:i}}finally{await n()}}async function uz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:n,absolutePath:r}=Fi(e.pmRoot,e.filePath),o=await Rt(Ht(e.pmRoot),ct),i=jt(o);if(i.ok||xn(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=Rn(qt(o,e.targetVersion))[n];if(s===void 0)throw new TypeError(`Workspace history version ${e.targetVersion} does not contain ${n}`);let a=await Ae(r),c=`${JSON.stringify(s,null,2)}
109
+ `;if(a===c)return{document_path:n,restored_from_version:e.targetVersion,changed:!1};let d=qt(o),l=Te(),u=Nr({nowIso:l,author:e.author,op:e.op,before:d,after:Zc({...Rn(d),[n]:s},d.metadata.created_at),message:e.message,context:{reason:"workspace_state_restore",document_path:n,restored_from_version:e.targetVersion,replaced_out_of_band_state:!0}});await pt(r,c);try{await Dr(Ht(e.pmRoot),u)}catch(f){throw a===null?await F_.rm(r,{force:!0}):await pt(r,a),f}return{document_path:n,restored_from_version:e.targetVersion,changed:!0}}finally{await 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]="33d6dc97-17d3-5db3-ab0d-6857be0e5827")}catch{}})();var Ne={ok:!1,path:[]};function ed(e,t){return{ok:!1,path:[e,...t.path]}}var b=e=>typeof e=="string"?{ok:!0,value:e}:Ne,x=e=>typeof e=="boolean"?{ok:!0,value:e}:Ne;function F(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?Ne:{ok:!0,value:t}}function N(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:Ne}function k(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return Ne;let r=[];for(let[o,i]of n.entries()){let s=e(i);if(!s.ok)return ed(String(o),s);r.push(s.value)}return{ok:!0,value:r}}}function td(e,t){return n=>typeof n=="string"&&n.length>0&&n.length<=e&&n===n.trim()&&(t===void 0||t.test(n))?{ok:!0,value:n}:Ne}function p(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function zi(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return Ne;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return ed(r,i);n[r]=i.value}return{ok:!0,value:n}}}function I(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return Ne;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return ed(o,s);s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var sT=I({key:b,values:k(b),required:p(x),aliases:p(k(b)),description:p(b)}),aT=I({command:N("create","update"),option:b,required:p(x),visible:p(x),enabled:p(x)}),cT=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(sT)),command_option_policies:p(k(aT))}),dT=I({id:b,aliases:p(k(b)),roles:p(k(N(...Kr))),description:p(b),order:p(F())}),lT=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(...Xt)),commands:p(k(N(...Yr))),repeatable:p(x),required:p(x),required_on_create:p(x),required_types:p(k(b)),allow_unset:p(x)}),uT=e=>{if(!Array.isArray(e)||e.length!==2)return Ne;let[t,n]=e;return typeof t!="string"||typeof n!="string"?Ne:{ok:!0,value:[t,n]}},fT=I({type:b,allowed_transitions:k(uT)}),mT=p(I({version:p(F({int:!0})),files:p(I({types:p(b),statuses:p(b),fields:p(b),workflows:p(b)})),statuses:p(k(dT)),fields:p(k(lT)),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(fT)),unknown_field_policy:p(N(...Xr))})),pT=p(I({preset:p(N(...jd)),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")),start_blocker_enforcement:p(N("off","warn","strict")),duplicate_detection_mode:p(N("off","advisory","strict")),duplicate_detection_threshold:p(F({min:0,max:1})),duplicate_detection_limit:p(F({int:!0,min:0,max:20}))})),_T=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))}),Qc=N("block","warn"),yT=e=>typeof e=="string"?Qc(e):I({global:p(Qc),project:p(Qc)})(e),hT=p(I({mode:p(N("off","warn","enforce")),trust_mode:p(N("off","warn","enforce")),pm_max_version_exceeded_mode:p(yT),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(_T))})),Vt=td(128),gT=I({harness:td(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:p(k(Vt,64)),model_environment_keys:p(k(Vt,64)),session_environment_keys:p(k(Vt,64)),provenance_environment_keys:p(zi(k(Vt,64))),provenance_resolvers:p(zi(N("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:p(k(Vt,64)),argv_markers:p(k(Vt,64)),client_names:p(k(Vt,64))}),q_={version:F({int:!0}),id_prefix:b,ids:p(I({token_length:p(F({int:!0,min:4,max:12}))})),author_default:b,agent_identity:p(I({probes_enabled:p(x),identity_vocabulary:p(I({version:F({int:!0,positive:!0}),aliases:zi(td(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:k(gT)})),mutation_guard:p(I({require_attributed_author:p(x),secret_guard:p(N("off","advise","block")),stale_in_progress_hours:p(F({int:!0,positive:!0}))})),item_format:p(N("toon","json_markdown")),locks:I({ttl_seconds:F({int:!0}),wait_ms:p(F({int:!0,min:0}))}),checkpoints:p(I({retention_days:p(F({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(F({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(zi(F({int:!0,positive:!0})))})),governance:pT,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(F({int:!0,positive:!0}))})),agent_guidance:p(I({prompt_completed:p(x),declined:p(x),declined_at:p(b),template_version:p(F({int:!0,positive:!0})),last_checked_files:p(k(b))})),item_types:p(I({definitions:k(cT)})),schema:mT,context:p(I({default_depth:p(N("brief","standard","deep")),activity_limit:p(F({int:!0,positive:!0})),stale_threshold_days:p(F({int:!0,positive:!0})),next_ranking_policy:p(N("priority_floor","weighted")),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:hT}),search:I({score_threshold:F(),hybrid_semantic_weight:p(F()),max_results:F({int:!0}),embedding_model:b,embedding_corpus_max_characters:p(F()),embedding_batch_size:F({int:!0}),embedding_timeout_ms:p(F({int:!0})),scanner_max_batch_retries:F({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(F({int:!0,positive:!0}))})),bm25:p(I({k1:p(F()),b:p(F())}))}),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})})},bT=I(q_),V_=Object.freeze(Object.keys(q_));function Ui(e){let t=bT(e);return t.ok?{success:!0,data:t.value}:{success:!1,path:t.path.join(".")}}import{AsyncLocalStorage as OT}from"node:async_hooks";import{lstat as AT,realpath as ty}from"node:fs/promises";import ny 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]="a0ca9902-540c-50fe-a4e2-9c234c4a01f3")}catch{}})();function Hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nd(e,t,n,r=[]){if(W(e,t)&&(r.length>0||Hi(n)))return n;if(W(e,n)||W(t,n))return t;if((e===void 0||Hi(e))&&Hi(t)&&Hi(n)){let o=e??{},i=new Set([...Object.keys(o),...Object.keys(t),...Object.keys(n)]);return Object.fromEntries([...i].flatMap(s=>{let a=nd(Object.hasOwn(o,s)?o[s]:void 0,Object.hasOwn(t,s)?t[s]:void 0,Object.hasOwn(n,s)?n[s]:void 0,[...r,s]);return a===void 0?[]:[[s,a]]}))}throw new g(`Settings changed concurrently at ${r.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 wT={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},B_=120;function rd(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function G_(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var vT=G_(wT),W_=new WeakMap;function ET(e){let t=W_.get(e);if(t)return t;let n=G_(e);return W_.set(e,n),n}function bz(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return B_;if(t){let o=ET(t).get(n);if(rd(o))return Math.floor(o)}let r=vT.get(n);return rd(r)?Math.floor(r):B_}function od(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!rd(r)||(t[o]=Math.floor(r))}return t}import{stat as kT}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 qi=new Map;function K_(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function ST(e){try{let t=await kT(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=K_(e),n=await Promise.all(t.map(r=>ST(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Pr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.path!==o.path||r.mtime_ms!==o.mtime_ms||r.size!==o.size)return!1}return!0}function Y_(e){return qi.get(e)}function Vi(e,t){let n=K_(t.tracked_paths),r=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));qi.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Bt(e){if(e){qi.delete(e);return}qi.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]="6e01cb2d-2ff0-54f2-abdb-2d16f36487c1")}catch{}})();var cd=new OT;async function Uz(e,t,n=()=>!0){let r=new Set([ny.resolve(e)]);try{r.add(await ty(e))}catch{}return cd.run([...cd.getStore()??[],[r,n]],t)}function IT(e){let t=ny.resolve(e);return cd.getStore()?.some(([n,r])=>n.has(t)&&r())??!1}var TT="settings:write",ry=Symbol("pm.settings.persist_source"),oy=Symbol("pm.settings.fallback_origin"),iy=Symbol("pm.settings.fallback_baseline"),CT=128,RT=new Set(["off","advisory","strict"]);function X_(e){return structuredClone(Id[e])}function xT(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:S.governance.preset}var NT=new Set(Ld);function sy(e){return NT.has(e)}function J_(e,t){let n=typeof t.create_default_type=="string"?t.create_default_type.trim():void 0;return n&&n.length>0&&(e.create_default_type=n),(t.workflow_enforcement==="off"||t.workflow_enforcement==="warn"||t.workflow_enforcement==="strict")&&(e.workflow_enforcement=t.workflow_enforcement),sy(t.start_blocker_enforcement)&&(e.start_blocker_enforcement=t.start_blocker_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 DT(e){return e.preset==="custom"?J_({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):J_({preset:e.preset},e)}function PT(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,n={};t&&t.length>0&&(n.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(n.workflow_enforcement=e.workflow_enforcement),sy(e.start_blocker_enforcement)&&(n.start_blocker_enforcement=e.start_blocker_enforcement),typeof e.require_close_reason=="boolean"&&(n.require_close_reason=e.require_close_reason),RT.has(String(e.duplicate_detection_mode))&&(n.duplicate_detection_mode=e.duplicate_detection_mode);let r=e.duplicate_detection_threshold;[typeof r=="number",Number.isFinite(r),Number(r)>=0,Number(r)<=1].every(Boolean)&&(n.duplicate_detection_threshold=r);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(n.duplicate_detection_limit=o),n}function ay(e){let t=e.governance??{},n=xT(t.preset),r=PT(t);if(n==="custom"){let s=X_("default"),a=r.require_close_reason??s.require_close_reason;return{preset:n,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,...r,require_close_reason:a,duplicate_detection_mode:r.duplicate_detection_mode??s.duplicate_detection_mode,duplicate_detection_threshold:r.duplicate_detection_threshold??s.duplicate_detection_threshold,duplicate_detection_limit:r.duplicate_detection_limit??s.duplicate_detection_limit}}let o=X_(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function ud(){return structuredClone(S)}function cy(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:S.search.mutation_refresh_policy}function dy(e){return e==="auto"||e==="keyword"||e==="semantic"||e==="hybrid"?e:"auto"}function ly(e){return typeof e=="boolean"?e:S.search.query_expansion.enabled}function uy(e){return typeof e!="string"?S.search.query_expansion.provider:e.trim()}function fy(e){return typeof e=="boolean"?e:S.search.rerank.enabled}function my(e){return typeof e!="string"?S.search.rerank.model:e.trim()}function py(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:S.search.rerank.top_k}function _y(e){if(typeof e!="string")return S.vector_store.collection_name;let t=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,CT);return t.length>0?t:S.vector_store.collection_name}function id(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function yy(e,t){let n=e.schema,r=id(n?.statuses),o=id(n?.fields),i=id(n?.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:Nn(e.item_types?.definitions),has_source_schema_statuses:r.present,source_schema_statuses:r.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:Nn(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 Gi(e,t){Object.defineProperty(e,ry,{value:t,writable:!0,configurable:!0,enumerable:!1})}function fd(e){let t=e[ry];if(!(!t||typeof t!="object"))return t}function Hz(e){let t=fd(e);if(t){let n=structuredClone(t);n.source_settings.item_format=e.item_format,Gi(e,n)}}function Bi(e){let t=structuredClone(e.settings),n=fd(e.settings);n&&Gi(t,n);let r=md(e.settings);return r!==void 0&&hy(t,r),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function MT(e,t,n){let r=Ce(t);return[n,ue(e,r.files.types,ie.types),ue(e,r.files.statuses,ie.statuses),ue(e,r.files.fields,ie.fields),ue(e,r.files.workflows,ie.workflows)]}async function $T(e,t,n){let r=await dt(t);Vi(e,{tracked_paths:t,signatures:r,value:Bi(n)})}async function jT(e,t,n){try{await $T(e,t,n)}catch{Bt(e)}}function Z_(e,t){return e.find(n=>n.path===t)}function LT(e,t,n){for(let r of n){let o=Z_(e,r),i=Z_(t,r);if(!o||!i||!Pr([o],[i]))return!1}return!0}async function sd(e,t,n,r,o){try{let i=await dt(t);if(!LT(r,i,o)){Bt(e);return}Vi(e,{tracked_paths:t,signatures:i,value:Bi(n)})}catch{Bt(e)}}function FT(e,t){let n=Ce(e.schema),r=Nn(e.item_types?.definitions);if(!t)return{item_type_definitions:r,schema_statuses:n.statuses,schema_fields:n.fields,schema_type_workflows:n.type_workflows};let o=n.type_workflows??[],i=W(r,t.runtime_item_type_definitions),s=W(n.statuses,t.runtime_schema_statuses),a=W(n.fields,t.runtime_schema_fields),c=W(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?Nn(t.source_item_type_definitions):[]:r,schema_statuses:s?t.has_source_schema_statuses?structuredClone(t.source_schema_statuses):[]:n.statuses,schema_fields:a?t.has_source_schema_fields?structuredClone(t.source_schema_fields):[]:n.fields,schema_type_workflows:c?t.has_source_schema_type_workflows?structuredClone(t.source_schema_type_workflows):void 0:n.type_workflows}}function hy(e,t){Object.defineProperty(e,oy,{value:t,writable:!0,configurable:!0,enumerable:!1})}function qz(e){return md(e)!==void 0}function md(e){let t=e[oy];return typeof t=="string"?t:void 0}function zT(e){return e[iy]}function UT(e,t){Object.defineProperty(e,iy,{value:t,writable:!0,configurable:!0,enumerable:!1})}function De(e){let t=ud();return e!==void 0&&hy(t,e),{settings:t,metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function gy(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function dd(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function by(e){let t=S.agent_guidance,n=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 n=="number"&&Number.isInteger(n)&&n>0?n:t.template_version,last_checked_files:dd(e?.last_checked_files??t.last_checked_files)}}function Oe(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function HT(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.mode}function qT(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.trust_mode}function wy(e){return e==="none"||e==="restricted"||e==="strict"?e:S.extensions.policy.default_sandbox_profile}function VT(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let n={name:t};e.disabled===!0&&(n.disabled=!0),e.require_trusted===!0&&(n.require_trusted=!0),e.require_provenance===!0&&(n.require_provenance=!0),e.sandbox_profile!==void 0&&(n.sandbox_profile=wy(e.sandbox_profile));let r=Oe(e.allowed_capabilities),o=Oe(e.blocked_capabilities),i=Oe(e.allowed_surfaces),s=Oe(e.blocked_surfaces),a=Oe(e.allowed_commands),c=Oe(e.blocked_commands),d=Oe(e.allowed_actions),l=Oe(e.blocked_actions),u=Oe(e.allowed_services),f=Oe(e.blocked_services);return r.length>0&&(n.allowed_capabilities=r),o.length>0&&(n.blocked_capabilities=o),i.length>0&&(n.allowed_surfaces=i),s.length>0&&(n.blocked_surfaces=s),a.length>0&&(n.allowed_commands=a),c.length>0&&(n.blocked_commands=c),d.length>0&&(n.allowed_actions=d),l.length>0&&(n.blocked_actions=l),u.length>0&&(n.allowed_services=u),f.length>0&&(n.blocked_services=f),n}function BT(e){let t=new Map;for(let n of e??[]){let r=VT(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function ad(e){return e==="block"||e==="warn"?e:void 0}function WT(e){if(typeof e=="string")return ad(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=ad(e.global),n=ad(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function he(e,t){return Oe(e?.[t]??S.extensions.policy[t])}function vy(e){let t=WT(e?.pm_max_version_exceeded_mode);return{mode:HT(e?.mode),trust_mode:qT(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:he(e,"trusted_extensions"),default_sandbox_profile:wy(e?.default_sandbox_profile),allowed_extensions:he(e,"allowed_extensions"),blocked_extensions:he(e,"blocked_extensions"),allowed_capabilities:he(e,"allowed_capabilities"),blocked_capabilities:he(e,"blocked_capabilities"),allowed_surfaces:he(e,"allowed_surfaces"),blocked_surfaces:he(e,"blocked_surfaces"),allowed_commands:he(e,"allowed_commands"),blocked_commands:he(e,"blocked_commands"),allowed_actions:he(e,"allowed_actions"),blocked_actions:he(e,"blocked_actions"),allowed_services:he(e,"allowed_services"),blocked_services:he(e,"blocked_services"),extension_overrides:BT(e?.extension_overrides??S.extensions.policy.extension_overrides)}}function Ey(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].filter(t=>t.length>0).sort((t,n)=>t.localeCompare(n)).filter(t=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(t))}function lt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function G(e,t){return e===void 0?t:e}function ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function ld(e){return Array.isArray(e)?e:[]}function GT(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:Ey(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:lt(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:lt(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:lt(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:lt(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:od(e.validation?.estimate_defaults_by_type)}}function KT(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 YT(e,t){return{...t.search,...e.search,default_mode:dy(e.search?.default_mode),mutation_refresh_policy:cy(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:ly(e.search?.query_expansion?.enabled),provider:uy(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:fy(e.search?.rerank?.enabled),model:my(e.search?.rerank?.model),top_k:py(e.search?.rerank?.top_k)}}}function XT(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:_y(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function JT(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function ZT(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,next_ranking_policy:e.context?.next_ranking_policy??t.context.next_ranking_policy,sections:{...t.context.sections,...e.context?.sections}}}function QT(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Nn(e){let t=(e??[]).map(r=>eo(r)).filter(r=>r!==null),n=new Map;for(let r of t)n.set(r.name.toLowerCase(),r);return[...n.values()].sort((r,o)=>r.name.localeCompare(o.name))}function Wi(e){let t=ud(),n=ay({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:JT(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:GT(e,t,n),governance:n,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:KT(e,t),agent_guidance:by(e.agent_guidance??t.agent_guidance),item_types:{definitions:Nn(e.item_types?.definitions)},schema:Ce(e.schema??t.schema),context:ZT(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:vy(e.extensions.policy??t.extensions.policy)},search:YT(e,t),providers:QT(e,t),vector_store:XT(e,t)}}function eC(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(ge(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=ld(e.agent_identity.harness_signals).map(n=>A(ge(n),["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(ge(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=A(ge(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","next_ranking_policy","sections"]),e.context.sections=A(ge(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=A(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=A(ge(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=ld(e.extensions.policy.extension_overrides).map(n=>A(ge(n),["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(ge(e.search.query_expansion),["enabled","provider"]),e.search.rerank=A(ge(e.search.rerank),["enabled","model","top_k"]),e.providers=A(e.providers,["openai","ollama"]),e.providers.openai=A(ge(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=A(ge(e.providers.ollama),["base_url","model"]),e.vector_store=A(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=A(ge(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=A(ge(e.vector_store.lancedb),["path"])}function tC(e){return{...e,locks:G(e.locks,S.locks),ids:G(e.ids,S.ids),agent_identity:G(e.agent_identity,S.agent_identity),mutation_guard:G(e.mutation_guard,S.mutation_guard),checkpoints:G(e.checkpoints,S.checkpoints),output:G(e.output,S.output),ux:G(e.ux,S.ux),history:G(e.history,S.history),validation:G(e.validation,S.validation),workflow:G(e.workflow,S.workflow),testing:G(e.testing,S.testing),telemetry:G(e.telemetry,S.telemetry),agent_guidance:G(e.agent_guidance,S.agent_guidance),item_types:G(e.item_types,S.item_types),schema:G(e.schema,S.schema),context:G(e.context,S.context),extensions:G(e.extensions,S.extensions),search:G(e.search,S.search),providers:G(e.providers,S.providers),vector_store:G(e.vector_store,S.vector_store)}}function nC(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:Ey(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:lt(e.validation?.lifecycle_stale_blocker_reason_patterns??S.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:lt(e.validation?.lifecycle_closure_like_blocked_reason_patterns??S.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:lt(e.validation?.lifecycle_closure_like_resolution_patterns??S.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:lt(e.validation?.lifecycle_closure_like_actual_result_patterns??S.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:od(e.validation?.estimate_defaults_by_type)}}function rC(e){return{...S.search,...e.search,default_mode:dy(e.search?.default_mode),mutation_refresh_policy:cy(e.search?.mutation_refresh_policy),query_expansion:{...S.search.query_expansion,...e.search?.query_expansion,enabled:ly(e.search?.query_expansion?.enabled),provider:uy(e.search?.query_expansion?.provider)},rerank:{...S.search.rerank,...e.search?.rerank,enabled:fy(e.search?.rerank?.enabled),model:my(e.search?.rerank?.model),top_k:py(e.search?.rerank?.top_k)}}}function oC(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,next_ranking_policy:e.context?.next_ranking_policy??S.context.next_ranking_policy,sections:{...S.context.sections,...e.context?.sections}}}function iC(e){return{...e.vector_store,adapter:e.vector_store?.adapter??S.vector_store.adapter,collection_name:_y(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function sC(e,t,n,r){return{...e,item_format:"toon",validation:nC(e,t),governance:t,agent_guidance:by(e.agent_guidance),item_types:{definitions:r.item_type_definitions},schema:{...n,statuses:r.schema_statuses,fields:r.schema_fields,type_workflows:r.schema_type_workflows},search:rC(e),context:oC(e),extensions:{enabled:dd(e.extensions?.enabled),disabled:dd(e.extensions?.disabled),policy:vy(e.extensions?.policy)},vector_store:iC(e)}}function ky(e,t){for(let n of Object.keys(t)){let r=Reflect.get(t,n),o=e[n];typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?ky(o,r):e[n]=structuredClone(r)}}function pd(e,t,n){let r=new Set([...Object.keys(t),...Object.keys(n)]);for(let o of r){let i=t[o],s=n[o];if(!W(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:{};pd(c,i,s),Object.keys(c).length>0?e[o]=c:delete e[o];continue}e[o]=structuredClone(s)}}}var Ki=["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 Q_(e,t){let n=tC(e),r=ay(n),o=Ce(n.schema),i=FT(n,t),s=sC(n,r,o,i),a=A({...s,governance:DT(r)},Ki);return eC(a),a}function Sy(e,t={}){let n=t.source===void 0?t.persist_source:yy(t.source.validated,Wi(t.source.validated)),r=Q_(e,n);if(n){let o=Wi(n.source_settings);o.item_types={definitions:structuredClone(n.runtime_item_type_definitions)},o.schema={...o.schema,statuses:structuredClone(n.runtime_schema_statuses),fields:structuredClone(n.runtime_schema_fields),type_workflows:structuredClone(n.runtime_schema_type_workflows)};let i=Q_(o,n);t.source!==void 0&&ky(i,t.source.validated);let s=structuredClone(t.source===void 0?n.source_settings:t.source.raw);return pd(s,i,r),`${JSON.stringify(A(s,Ki),null,2)}
110
110
  `}return`${JSON.stringify(r,null,2)}
111
- `}async function aC(e){let t;try{t=await ey(e)}catch(a){if(be(a))return De();throw a}let n=Ie(t),r;try{r=await AT(n)}catch(a){if(be(a))return De();throw a}if(!r.isFile())throw rs("settings.json");let o;try{o=await Id(n,rs("settings.json"))}catch(a){if(be(a))return De();throw a}let i;try{i=JSON.parse(o)}catch{return De("settings_read_invalid_json")}let s=Ui(i);return s.success?{settings:Wi(s.data),metadata:{has_explicit_item_format:hy(i)},warnings:s.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[]}:De("settings_read_invalid_schema")}async function Sy(e){if(IT(e))return aC(e);let t=Ie(e),n=[t];await an({path:t,scope:"project"});let r=K_(e);if(r){let d=await dt(r.tracked_paths);if(Pr(d,r.signatures))return Bi(r.value)}let o=await dt([t]),i;try{i=await Ae(t)}catch{return De("settings_read_fs_error")}if(i===null){let d=De();return await sd(e,[t],d,o,[t]),d}let s=await dt([t]);if(!Pr(o,s))return Bt(e),Sy(e);let a;try{a=JSON.parse(i)}catch{let d=De("settings_read_invalid_json");return await sd(e,[t],d,s,[t]),d}let c=Ui(a);if(!c.success){let d=De("settings_read_invalid_schema");return await sd(e,[t],d,s,[t]),d}try{let d=Wi(c.data),l=MT(e,d.schema,t);n=l;let u=await dt(l),f=await Zu(e,d.schema),m=await dt(l),_={...d,item_types:{definitions:Nn([...d.item_types.definitions,...ld(f.type_definitions_from_file)])},schema:f.schema};Gi(_,_y(c.data,_));let y={settings:_,metadata:{has_explicit_item_format:hy(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.warnings]};return Pr(u,m)?Vi(e,{tracked_paths:l,signatures:m,value:Bi(y)}):Bt(e),y}catch{let d=De("settings_read_merge_failed");return await jT(e,n,d),d}}var cC=/^[A-Za-z0-9_-]+$/u,dC=new Set(["__proto__","constructor","prototype"]);function Oy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function lC(e){for(let t of e)if(t.split(".").find(n=>!cC.test(n)||dC.has(n))!==void 0)throw new g(`Settings write assignedPaths entry "${t}" is not a dotted settings path.`,h.USAGE,{code:"settings_write_assigned_path_invalid",reason:"assigned_path_segment_invalid",field:t,why:"Assigned paths name settings keys; an empty, reserved or non-identifier segment cannot address one safely.",nextSteps:["Pass dotted settings keys such as context.next_ranking_policy in assignedPaths."]})}function Ay(e,t){return Oy(Object.hasOwn(e,t)?e[t]:void 0)}function Q_(e,t){let n=e;for(let r of t)if(n=Ay(n,r),n===void 0)return;return n}function uC(e,t){let n=e;for(let r of t){let o=Ay(n,r);o===void 0&&(o={},n[r]=o),n=o}return n}function fC(e,t,n){for(let r of n){let o=r.split("."),i=o.pop(),s=Q_(t,o);if(s===void 0)continue;if(Object.hasOwn(s,i)){uC(e,o)[i]=structuredClone(s[i]);continue}if(!q_.includes(o[0]??i))continue;let a=Q_(e,o);a!==void 0&&delete a[i]}}function mC(e,t,n,r,o){let i=o??JSON.parse(ky(ud())),s=structuredClone(Oy(e)??{});pd(s,i,t),fC(s,t,r);let a=Ui(s);if(!a.success){let c=a.path;throw new g(`Existing settings.json fails validation at ${c}; the settings write was refused and nothing was changed.`,h.USAGE,{code:"settings_write_invalid_existing_schema",reason:"existing_settings_schema_invalid",field:c,original_code:n,why:"The stored settings could not be read, so writing would either keep an invalid document or replace intended project configuration with defaults.",nextSteps:[`Fix or remove ${c} in settings.json, then retry the original command.`,"A configurable setting can also be repaired explicitly, even to its default value, with pm config <scope> set <dotted.key> <value>.","Run pm health to confirm the settings warning has cleared."]})}return`${JSON.stringify(A(s,Ki),null,2)}
112
- `}function pC(e){try{return JSON.parse(e)}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."]})}}async function qz(e){return(await Sy(e)).settings}async function Vz(e,t,n=TT,r={}){let o=r.assignedPaths??[];lC(o);let i=Ie(e),s=fd(t),a=s?void 0:md(t),c=ky(t,{persist_source:s}),d=JSON.parse(c);try{await U_({pmRoot:e,filePath:i,mutate:l=>{let u=l===null?null:pC(l);return a!==void 0&&l!==null?{raw:mC(u,d,a,o,zT(t)),result:void 0}:{raw:s?`${JSON.stringify(A(nd(s.persisted_settings,d,u),Ki),null,2)}
113
- `:c,result:void 0}},op:n,author:hm(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),s?Gi(t,{...s,persisted_settings:structuredClone(d)}):a!==void 0&&UT(t,structuredClone(d)),await Io({path:i,scope:"project",op:n})}finally{Bt(e)}}import Iy from"node:fs";import Mr from"node:path";import{createRequire as _C}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]="2b3d7667-1c63-565a-b314-3a74cc8d6b7d")}catch{}})();var $r="@unbrained/pm-cli",yC=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"]),Ty=new Set(["--author","--expect-hash","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),yd=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,Zi="2026.8.31";function ce(e,t){return e.some(n=>t.includes(n.split("=",1)[0]))}function _d(e,t){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(t[0]??"")||ce(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var hC={changelog:(e,t)=>{if(t[0]==="generate")return!ce(e,["--check"]);let n=e.indexOf("export");return t[0]==="export"&&(ce(e,["--output"])||n>=0&&e[n+1]!==void 0&&!e[n+1].startsWith("-"))},comments:e=>ce(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>ce(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:_d,files:(e,t)=>ce(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&ce(e,["--apply"]),health:e=>!ce(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>ce(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>ce(e,["--add","--delete","--edit","--file","--stdin"]),package:_d,packages:_d,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]??"")&&!(ce(e,["--infer"])&&!ce(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(n=>["clear","flush"].includes(n)),templates:(e,t)=>t[0]==="save",test:e=>ce(e,["--update","--update-index","--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>ce(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 Xi(e){let t=e.match(yd);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function ut(e,t){let n=Xi(e),r=Xi(t);if(!n||!r)return null;for(let o=0;o<n.length;o+=1){let i=n[o]-r[o];if(i!==0)return Math.sign(i)}return 0}function Yi(e){return ut(e,Zi)!==-1?3:2}function gC(e,t){if(t===3)return e.filter(n=>n.history_epoch_compatible===!1).map(n=>({...n,declaration:n.declaration??n.version})).sort((n,r)=>ut(n.version,r.version))[0]}function Ji(e){try{let t=JSON.parse(Iy.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function bC(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(r=>({inclusive:r[1]==="<=",version:r[2]})),n=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...t,{inclusive:!0,version:n[1]}]:t}function wC(e){let t=e.split("||").map(n=>bC(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(r=>{let o=ut(Zi,r.version);return o!==null&&(r.inclusive?o!==1:o===-1)}))}}function Cy(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let r=n[$r];return typeof r=="string"?[r.trim()]:[]})}function vC(e){return Cy(e).flatMap(t=>{let n=/^[<!]/u.test(t)?void 0:t.match(yd)?.[0];if(!n)return[];let r=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(t),o=wC(t);return[{version:n,constraint:r?"exact":o.bounded?"range":"minimum",...r?{}:{declaration:t},history_epoch_compatible:r?ut(n,Zi)!==-1:o.compatible}]})}function EC(e){let t=Ji(Mr.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let n=t["node_modules/@unbrained/pm-cli"];if(typeof n!="object"||n===null)return;let r=n.version;return typeof r=="string"?r:void 0}function kC(e,t){try{let n=Iy.readFileSync(Mr.join(e,t),"utf8").split(/\r?\n/u),r=n.findIndex(s=>s.includes($r));if(r<0)return;let o=n[r].match(/^\s*/u)[0].length,i=[n[r]];for(let s=r+1;s<n.length;s+=1){let a=n[s],c=a.trim(),d=a.match(/^\s*/u)[0].length;if(c.length>0&&d<=o)break;i.push(a)}return i.join(`
114
- `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match(yd)?.[0]}catch{return}}function Ry(e){let t=[],n=Ji(Mr.join(e,"package.json"));n&&t.push(...vC(n).map(i=>({...i,source:"package.json"})));let r=Ji(Mr.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof r=="string"&&Xi(r)&&t.push({version:r,source:"installed-package",constraint:"exact",history_epoch_compatible:Yi(r)===3});let o=EC(e);o&&Xi(o)&&t.push({version:o,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Yi(o)===3});for(let i of["pnpm-lock.yaml","yarn.lock"]){let s=kC(e,i);s&&t.push({version:s,source:i,constraint:"exact",history_epoch_compatible:Yi(s)===3})}return t}function Jz(e,t){if(t<=1)return;let{minVersion:n,lt:r}=_C(import.meta.url)("semver"),o=Cy(Ji(Mr.join(e,"package.json"))??{}).find(s=>{try{let a=n(s);return a!==null&&r(a,"2026.10.10")}catch{return!1}}),i=o===void 0?Ry(e).find(s=>ut(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 xy(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Ty.has(n)){t+=1;continue}if(!n.startsWith("-"))return{command:n.toLowerCase(),index:t}}}function SC(e){let t=xy(e);if(!t||ce(e,["--help","-h","--dry-run"]))return!1;let{command:n,index:r}=t,o=[];for(let s=r+1;s<e.length;s+=1){let a=e[s];if(Ty.has(a)){s+=1;continue}a.startsWith("-")||o.push(a.toLowerCase())}let i=hC[n];return i?i(e,o):yC.has(n)}function OC(e){let t=xy(e.argv)?.command,n=SC(e.argv),r=Ry(e.projectRoot).filter(l=>ut(l.version,e.executingVersion)!==null).sort((l,u)=>ut(u.version,l.version)),o=r[0],i=o!==void 0&&ut(e.executingVersion,o.version)===-1,s=Yi(e.executingVersion),a=gC(r,s),c=n&&a!==void 0,d=i&&!n?{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 ${$r} ${o.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!n||!i&&!c||e.allowStale===!0,executing_version:e.executingVersion,...o?{project_version:o.version,source:o.source}:{},...t?{command:t}:{},mutating:n,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:n&&(i||c)&&e.allowStale===!0}}function Zz(e){let t=OC(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 ${$r} pin to ${Zi} 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 ${$r} ${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."]})}import gd from"node:fs/promises";import Qi 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 ft(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Ny(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:Jt(t),suggested_retry_args:t}}function es(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 hd(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 AC(e){let t=Qi.resolve(e),n=Qi.parse(t).root,r=Qi.dirname(t);for(;r!==n;){let o;try{o=await gd.stat(r)}catch(i){if(ft(i,"ENOTDIR"))throw es(e);if(!ft(i,"ENOENT"))throw i;r=Qi.dirname(r);continue}if(!o.isDirectory())throw es(e);return}}async function IC(e){let t;try{t=await gd.stat(e)}catch(n){throw ft(n,"ENOENT")?(await AC(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:Ny(e)})):ft(n,"ENOTDIR")?es(e):ft(n,"EACCES")||ft(n,"EPERM")?hd(e):n}if(!t.isDirectory())throw es(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw hd(e);try{await(await gd.opendir(e)).close()}catch(n){throw ft(n,"EACCES")||ft(n,"EPERM")?hd(e):n}}async function aU(e){if(await IC(e),!await mt(Ie(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:Ny(e)})}export{R as a,W as b,Vr as c,By as d,Rd as e,os as f,Ky as g,Yy as h,Br as i,Nd as j,Jy as k,eh as l,PC as m,MC as n,oh as o,ih as p,sh as q,ah as r,is as s,jC as t,ch as u,$n as v,Wr as w,LC as x,FC as y,zC as z,dh as A,lh as B,uh as C,BC as D,WC as E,fh as F,Gr as G,GC as H,KC as I,mh as J,ph as K,_h as L,Pd as M,Kt as N,yh as O,YC as P,XC as Q,JC as R,ZC as S,QC as T,eR as U,tR as V,nR as W,nl as X,hg as Y,gg as Z,bg as _,no as $,GR as aa,hh as ba,Md as ca,Yt as da,Kr as ea,Xt as fa,Yr as ga,oR as ha,iR as ia,sR as ja,Jr as ka,Zr as la,aR as ma,cR as na,dR as oa,lR as pa,Qr as qa,jn as ra,ss as sa,uR as ta,Ld as ua,fR as va,mR as wa,pR as xa,_R as ya,kh as za,Hd as Aa,Gd as Ba,SR as Ca,ls as Da,Mh as Ea,OR as Fa,Yh as Ga,Xh as Ha,AR as Ia,IR as Ja,$R as Ka,us as La,jR as Ma,Jd as Na,Zd as Oa,Qd as Pa,Ie as Qa,LR as Ra,FR as Sa,zR as Ta,fs as Ua,ms as Va,to as Wa,mg as Xa,UR as Ya,pg as Za,_g as _a,HR as $a,qR as ab,yg as bb,VR as cb,zn as db,el as eb,tl as fb,Jt as gb,nx as hb,rx as ib,ox as jb,Sg as kb,ys as lb,cx as mb,il as nb,sl as ob,qu as pb,Ag as qb,lx as rb,ux as sb,fx as tb,cl as ub,mx as vb,px as wb,_x as xb,al as yb,dl as zb,yx as Ab,oo as Bb,Cg as Cb,Rg as Db,vx as Eb,Ex as Fb,Te as Gb,$e as Hb,Un as Ib,Zt as Jb,re as Kb,Tx as Lb,Cx as Mb,so as Nb,Nx as Ob,pl as Pb,Dx as Qb,ao as Rb,vs as Sb,Ss as Tb,Os as Ub,Fx as Vb,zx as Wb,Ux as Xb,ib as Yb,yl as Zb,Hx as _b,As as $b,hl as ac,fo as bc,mo as cc,Kx as dc,Yx as ec,po as fc,_o as gc,ht as hc,z as ic,yo as jc,eN as kc,gl as lc,Is as mc,wb as nc,vb as oc,Vn as pc,Ts as qc,Cs as rc,Rs as sc,xs as tc,Ns as uc,Ds as vc,Xs as wc,kb as xc,Sb as yc,Tb as zc,Cb as Ac,Ol as Bc,tu as Cc,gu as Dc,bu as Ec,uN as Fc,fN as Gc,Nb as Hc,Ps as Ic,Pb as Jc,Ms as Kc,$s as Lc,js as Mc,Ls as Nc,Fs as Oc,zs as Pc,Hs as Qc,qs as Rc,Vs as Sc,Ew as Tc,Sw as Uc,Ow as Vc,Dw as Wc,BD as Xc,WD as Yc,GD as Zc,JD as _c,QD as $c,Zw as ad,Qw as bd,ra as cd,nv as dd,rv as ed,aP as fd,Oo as gd,cP as hd,dP as id,lP as jd,uP as kd,fP as ld,mP as md,pP as nd,$u as od,_P as pd,yP as qd,ju as rd,hP as sd,Ao as td,gP as ud,bP as vd,wP as wd,vP as xd,EP as yd,Io as zd,kP as Ad,an as Bd,SP as Cd,OP as Dd,AP as Ed,IP as Fd,TP as Gd,cn as Hd,MP as Id,cv as Jd,Uu as Kd,kt as Ld,Ye as Md,Hu as Nd,Xe as Od,ie as Pd,aa as Qd,Ce as Rd,ue as Sd,YP as Td,XP as Ud,Zu as Vd,Qu as Wd,ca as Xd,ef as Yd,tf as Zd,JP as _d,o1 as $d,Hv as ae,i1 as be,df as ce,lf as de,cr as ee,s1 as fe,a1 as ge,da as he,la as ie,d1 as je,ua as ke,ff as le,Xv as me,l1 as ne,Po as oe,Zv as pe,p1 as qe,Mo as re,VE as se,Lo as te,d0 as ue,D1 as ve,P1 as we,fn as xe,Of as ye,Af as ze,If as Ae,Sa as Be,Tf as Ce,j1 as De,Cf as Ee,L1 as Fe,Rf as Ge,Ot as He,Aa as Ie,U1 as Je,H1 as Ke,Uo as Le,Ho as Me,H0 as Ne,Yo as Oe,K0 as Pe,fe as Qe,J0 as Re,Ma as Se,tm as Te,ja as Ue,vM as Ve,EM as We,kM as Xe,SM as Ye,OM as Ze,AM as _e,Wa as $e,Ga as af,dm as bf,$M as cf,jM as df,LM as ef,FM as ff,zM as gf,UM as hf,Ja as if,pm as jf,HM as kf,qM as lf,VM as mf,Tk as nf,BM as of,hm as pf,ei as qf,Rt as rf,e$ as sf,Rk as tf,xk as uf,yn as vf,i_ as wf,RI as xf,MI as yf,bF as zf,wF as Af,br as Bf,o$ as Cf,ti as Df,$k as Ef,jk as Ff,i$ as Gf,xe as Hf,s$ as If,Hk as Jf,Bk as Kf,Zk as Lf,vm as Mf,Dm as Nf,rc as Of,km as Pf,ri as Qf,eS as Rf,tt as Sf,hn as Tf,yr as Uf,oi as Vf,hr as Wf,Sm as Xf,c$ as Yf,gr as Zf,lc as _f,wr as $f,yS as ag,S$ as bg,Mm as cg,hS as dg,AS as eg,TS as fg,$m as gg,CS as hg,RS as ig,jm as jg,Nt as kg,Lm as lg,O$ as mg,A$ as ng,sc as og,I$ as pg,T$ as qg,C$ as rg,R$ as sg,x$ as tg,j$ as ug,ac as vg,cc as wg,li as xg,Hm as yg,dc as zg,qm as Ag,vr as Bg,F$ as Cg,Dt as Dg,rj as Eg,oj as Fg,BS as Gg,vn as Hg,ij as Ig,Qm as Jg,JS as Kg,sj as Lg,tp as Mg,pc as Ng,cp as Og,dp as Pg,lp as Qg,up as Rg,fi as Sg,_c as Tg,Sr as Ug,vj as Vg,Ej as Wg,Or as Xg,yc as Yg,bc as Zg,kj as _g,AO as $g,Sj as ah,Oj as bh,Ue as ch,Y as dh,jj as eh,kn as fh,jO as gh,Lj as hh,Fj as ih,LO as jh,zj as kh,Uj as lh,Hj as mh,HO as nh,Op as oh,qO as ph,eL as qh,BO as rh,Ip as sh,tL as th,Rp as uh,GO as vh,JO as wh,xp as xh,Pp as yh,Mp as zh,iL as Ah,cL as Bh,wi as Ch,dL as Dh,lL as Eh,mA as Fh,uL as Gh,fL as Hh,mL as Ih,pL as Jh,_L as Kh,Fp as Lh,Up as Mh,EL as Nh,kL as Oh,MA as Ph,Cr as Qh,vi as Rh,jL as Sh,LL as Th,qI as Uh,$i as Vh,$t as Wh,Rr as Xh,WI as Yh,GI as Zh,P_ as _h,Tn as $h,VF as ai,Jc as bi,ki as ci,Zp as di,Pc as ei,BF as fi,$_ as gi,Qp as hi,WF as ii,Nr as ji,Dr as ki,rI as li,Si as mi,ZL as ni,Dc as oi,Oi as pi,QL as qi,eF as ri,t_ as si,Ai as ti,Ii as ui,jt as vi,fI as wi,tF as xi,nF as yi,ct as zi,Ht as Ai,iz as Bi,sz as Ci,az as Di,U_ as Ei,cz as Fi,dz as Gi,lz as Hi,q_ as Ii,Ui as Ji,gz as Ki,Bt as Li,zz as Mi,IT as Ni,sy as Oi,Uz as Pi,Hz as Qi,Wi as Ri,ky as Si,Sy as Ti,qz as Ui,Vz as Vi,Zi as Wi,ut as Xi,Yi,Ry as Zi,Jz as _i,SC as $i,OC as aj,Zz as bj,Ny as cj,IC as dj,aU as ej};
115
- //# sourceMappingURL=chunk-3OXQGGRD.js.map
111
+ `}async function aC(e){let t;try{t=await ty(e)}catch(a){if(be(a))return De();throw a}let n=Ie(t),r;try{r=await AT(n)}catch(a){if(be(a))return De();throw a}if(!r.isFile())throw rs("settings.json");let o;try{o=await Td(n,rs("settings.json"))}catch(a){if(be(a))return De();throw a}let i;try{i=JSON.parse(o)}catch{return De("settings_read_invalid_json")}let s=Ui(i);return s.success?{settings:Wi(s.data),metadata:{has_explicit_item_format:gy(i)},warnings:s.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[]}:De("settings_read_invalid_schema")}async function Oy(e){if(IT(e))return aC(e);let t=Ie(e),n=[t];await an({path:t,scope:"project"});let r=Y_(e);if(r){let d=await dt(r.tracked_paths);if(Pr(d,r.signatures))return Bi(r.value)}let o=await dt([t]),i;try{i=await Ae(t)}catch{return De("settings_read_fs_error")}if(i===null){let d=De();return await sd(e,[t],d,o,[t]),d}let s=await dt([t]);if(!Pr(o,s))return Bt(e),Oy(e);let a;try{a=JSON.parse(i)}catch{let d=De("settings_read_invalid_json");return await sd(e,[t],d,s,[t]),d}let c=Ui(a);if(!c.success){let d=De("settings_read_invalid_schema");return await sd(e,[t],d,s,[t]),d}try{let d=Wi(c.data),l=MT(e,d.schema,t);n=l;let u=await dt(l),f=await Qu(e,d.schema),m=await dt(l),_={...d,item_types:{definitions:Nn([...d.item_types.definitions,...ld(f.type_definitions_from_file)])},schema:f.schema};Gi(_,yy(c.data,_));let y={settings:_,metadata:{has_explicit_item_format:gy(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.warnings]};return Pr(u,m)?Vi(e,{tracked_paths:l,signatures:m,value:Bi(y)}):Bt(e),y}catch{let d=De("settings_read_merge_failed");return await jT(e,n,d),d}}function cC(e,t=[],n=null){let r=_d(n)??{},o=t.filter(s=>!Object.hasOwn(r,s));if(o.length===0)return e;let i=JSON.parse(e);for(let s of o)Reflect.deleteProperty(i,s);return`${JSON.stringify(i,null,2)}
112
+ `}var dC=/^[A-Za-z0-9_-]+$/u,lC=new Set(["__proto__","constructor","prototype"]);function _d(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function uC(e){for(let t of e)if(t.split(".").find(n=>!dC.test(n)||lC.has(n))!==void 0)throw new g(`Settings write assignedPaths entry "${t}" is not a dotted settings path.`,h.USAGE,{code:"settings_write_assigned_path_invalid",reason:"assigned_path_segment_invalid",field:t,why:"Assigned paths name settings keys; an empty, reserved or non-identifier segment cannot address one safely.",nextSteps:["Pass dotted settings keys such as context.next_ranking_policy in assignedPaths."]})}function Ay(e,t){return _d(Object.hasOwn(e,t)?e[t]:void 0)}function ey(e,t){let n=e;for(let r of t)if(n=Ay(n,r),n===void 0)return;return n}function fC(e,t){let n=e;for(let r of t){let o=Ay(n,r);o===void 0&&(o={},n[r]=o),n=o}return n}function mC(e,t,n){for(let r of n){let o=r.split("."),i=o.pop(),s=ey(t,o);if(s===void 0)continue;if(Object.hasOwn(s,i)){fC(e,o)[i]=structuredClone(s[i]);continue}if(!V_.includes(o[0]??i))continue;let a=ey(e,o);a!==void 0&&delete a[i]}}function pC(e,t,n,r,o){let i=o??JSON.parse(Sy(ud())),s=structuredClone(_d(e)??{});pd(s,i,t),mC(s,t,r);let a=Ui(s);if(!a.success){let c=a.path;throw new g(`Existing settings.json fails validation at ${c}; the settings write was refused and nothing was changed.`,h.USAGE,{code:"settings_write_invalid_existing_schema",reason:"existing_settings_schema_invalid",field:c,original_code:n,why:"The stored settings could not be read, so writing would either keep an invalid document or replace intended project configuration with defaults.",nextSteps:[`Fix or remove ${c} in settings.json, then retry the original command.`,"A configurable setting can also be repaired explicitly, even to its default value, with pm config <scope> set <dotted.key> <value>.","Run pm health to confirm the settings warning has cleared."]})}return`${JSON.stringify(A(s,Ki),null,2)}
113
+ `}function _C(e){try{return JSON.parse(e)}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."]})}}async function Vz(e){return(await Oy(e)).settings}async function Bz(e,t,n=TT,r={}){let o=r.assignedPaths??[];uC(o);let i=Ie(e),s=fd(t),a=s?void 0:md(t),c=Sy(t,{persist_source:s}),d=JSON.parse(c),l=!1;try{if(await H_({pmRoot:e,filePath:i,mutate:u=>{let f=u===null?null:_C(u);return u!==null&&r.skipIfStored?.(f)===!0?(l=!0,{raw:u,result:void 0}):a!==void 0&&u!==null?{raw:pC(f,d,a,o,zT(t)),result:void 0}:{raw:s?`${JSON.stringify(A(nd(s.persisted_settings,d,f),Ki),null,2)}
114
+ `:cC(c,r.omitSections,f),result:void 0}},op:n,author:gm(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),l)return;s?Gi(t,{...s,persisted_settings:structuredClone(d)}):a!==void 0&&UT(t,structuredClone(d)),await Io({path:i,scope:"project",op:n})}finally{Bt(e)}}import Iy from"node:fs";import Mr from"node:path";import{createRequire as yC}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]="2b3d7667-1c63-565a-b314-3a74cc8d6b7d")}catch{}})();var $r="@unbrained/pm-cli",hC=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"]),Ty=new Set(["--author","--expect-hash","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),hd=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,Zi="2026.8.31";function ce(e,t){return e.some(n=>t.includes(n.split("=",1)[0]))}function yd(e,t){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(t[0]??"")||ce(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var gC={changelog:(e,t)=>{if(t[0]==="generate")return!ce(e,["--check"]);let n=e.indexOf("export");return t[0]==="export"&&(ce(e,["--output"])||n>=0&&e[n+1]!==void 0&&!e[n+1].startsWith("-"))},comments:e=>ce(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>ce(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:yd,files:(e,t)=>ce(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&ce(e,["--apply"]),health:e=>!ce(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>ce(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>ce(e,["--add","--delete","--edit","--file","--stdin"]),package:yd,packages:yd,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]??"")&&!(ce(e,["--infer"])&&!ce(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(n=>["clear","flush"].includes(n)),templates:(e,t)=>t[0]==="save",test:e=>ce(e,["--update","--update-index","--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>ce(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 Xi(e){let t=e.match(hd);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function ut(e,t){let n=Xi(e),r=Xi(t);if(!n||!r)return null;for(let o=0;o<n.length;o+=1){let i=n[o]-r[o];if(i!==0)return Math.sign(i)}return 0}function Yi(e){return ut(e,Zi)!==-1?3:2}function bC(e,t){if(t===3)return e.filter(n=>n.history_epoch_compatible===!1).map(n=>({...n,declaration:n.declaration??n.version})).sort((n,r)=>ut(n.version,r.version))[0]}function Ji(e){try{let t=JSON.parse(Iy.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function wC(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(r=>({inclusive:r[1]==="<=",version:r[2]})),n=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...t,{inclusive:!0,version:n[1]}]:t}function vC(e){let t=e.split("||").map(n=>wC(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(r=>{let o=ut(Zi,r.version);return o!==null&&(r.inclusive?o!==1:o===-1)}))}}function Cy(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let r=n[$r];return typeof r=="string"?[r.trim()]:[]})}function EC(e){return Cy(e).flatMap(t=>{let n=/^[<!]/u.test(t)?void 0:t.match(hd)?.[0];if(!n)return[];let r=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(t),o=vC(t);return[{version:n,constraint:r?"exact":o.bounded?"range":"minimum",...r?{}:{declaration:t},history_epoch_compatible:r?ut(n,Zi)!==-1:o.compatible}]})}function kC(e){let t=Ji(Mr.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let n=t["node_modules/@unbrained/pm-cli"];if(typeof n!="object"||n===null)return;let r=n.version;return typeof r=="string"?r:void 0}function SC(e,t){try{let n=Iy.readFileSync(Mr.join(e,t),"utf8").split(/\r?\n/u),r=n.findIndex(s=>s.includes($r));if(r<0)return;let o=n[r].match(/^\s*/u)[0].length,i=[n[r]];for(let s=r+1;s<n.length;s+=1){let a=n[s],c=a.trim(),d=a.match(/^\s*/u)[0].length;if(c.length>0&&d<=o)break;i.push(a)}return i.join(`
115
+ `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match(hd)?.[0]}catch{return}}function Ry(e){let t=[],n=Ji(Mr.join(e,"package.json"));n&&t.push(...EC(n).map(i=>({...i,source:"package.json"})));let r=Ji(Mr.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof r=="string"&&Xi(r)&&t.push({version:r,source:"installed-package",constraint:"exact",history_epoch_compatible:Yi(r)===3});let o=kC(e);o&&Xi(o)&&t.push({version:o,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Yi(o)===3});for(let i of["pnpm-lock.yaml","yarn.lock"]){let s=SC(e,i);s&&t.push({version:s,source:i,constraint:"exact",history_epoch_compatible:Yi(s)===3})}return t}function Zz(e,t){if(t<=1)return;let{minVersion:n,lt:r}=yC(import.meta.url)("semver"),o=Cy(Ji(Mr.join(e,"package.json"))??{}).find(s=>{try{let a=n(s);return a!==null&&r(a,"2026.10.10")}catch{return!1}}),i=o===void 0?Ry(e).find(s=>ut(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 xy(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Ty.has(n)){t+=1;continue}if(!n.startsWith("-"))return{command:n.toLowerCase(),index:t}}}function OC(e){let t=xy(e);if(!t||ce(e,["--help","-h","--dry-run"]))return!1;let{command:n,index:r}=t,o=[];for(let s=r+1;s<e.length;s+=1){let a=e[s];if(Ty.has(a)){s+=1;continue}a.startsWith("-")||o.push(a.toLowerCase())}let i=gC[n];return i?i(e,o):hC.has(n)}function AC(e){let t=xy(e.argv)?.command,n=OC(e.argv),r=Ry(e.projectRoot).filter(l=>ut(l.version,e.executingVersion)!==null).sort((l,u)=>ut(u.version,l.version)),o=r[0],i=o!==void 0&&ut(e.executingVersion,o.version)===-1,s=Yi(e.executingVersion),a=bC(r,s),c=n&&a!==void 0,d=i&&!n?{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 ${$r} ${o.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!n||!i&&!c||e.allowStale===!0,executing_version:e.executingVersion,...o?{project_version:o.version,source:o.source}:{},...t?{command:t}:{},mutating:n,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:n&&(i||c)&&e.allowStale===!0}}function Qz(e){let t=AC(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 ${$r} pin to ${Zi} 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 ${$r} ${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."]})}import bd from"node:fs/promises";import Qi 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 ft(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Ny(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:Jt(t),suggested_retry_args:t}}function es(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 gd(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 IC(e){let t=Qi.resolve(e),n=Qi.parse(t).root,r=Qi.dirname(t);for(;r!==n;){let o;try{o=await bd.stat(r)}catch(i){if(ft(i,"ENOTDIR"))throw es(e);if(!ft(i,"ENOENT"))throw i;r=Qi.dirname(r);continue}if(!o.isDirectory())throw es(e);return}}async function TC(e){let t;try{t=await bd.stat(e)}catch(n){throw ft(n,"ENOENT")?(await IC(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:Ny(e)})):ft(n,"ENOTDIR")?es(e):ft(n,"EACCES")||ft(n,"EPERM")?gd(e):n}if(!t.isDirectory())throw es(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw gd(e);try{await(await bd.opendir(e)).close()}catch(n){throw ft(n,"EACCES")||ft(n,"EPERM")?gd(e):n}}async function cU(e){if(await TC(e),!await mt(Ie(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:Ny(e)})}export{R as a,W as b,Vr as c,By as d,xd as e,os as f,Ky as g,Yy as h,Br as i,Dd as j,Jy as k,eh as l,MC as m,$C as n,oh as o,ih as p,sh as q,ah as r,is as s,LC as t,ch as u,$n as v,Wr as w,FC as x,zC as y,UC as z,dh as A,lh as B,uh as C,WC as D,GC as E,fh as F,Gr as G,KC as H,YC as I,mh as J,ph as K,_h as L,Md as M,Kt as N,yh as O,XC as P,JC as Q,ZC as R,QC as S,eR as T,tR as U,nR as V,rR as W,rl as X,hg as Y,gg as Z,bg as _,no as $,KR as aa,hh as ba,$d as ca,Yt as da,Kr as ea,Xt as fa,Yr as ga,iR as ha,sR as ia,aR as ja,Jr as ka,Zr as la,cR as ma,dR as na,lR as oa,uR as pa,Qr as qa,jn as ra,ss as sa,fR as ta,Fd as ua,mR as va,pR as wa,_R as xa,yR as ya,kh as za,qd as Aa,Kd as Ba,OR as Ca,ls as Da,Mh as Ea,AR as Fa,Yh as Ga,Xh as Ha,IR as Ia,TR as Ja,jR as Ka,us as La,LR as Ma,Zd as Na,Qd as Oa,el as Pa,Ie as Qa,FR as Ra,zR as Sa,UR as Ta,fs as Ua,ms as Va,to as Wa,mg as Xa,HR as Ya,pg as Za,_g as _a,qR as $a,VR as ab,yg as bb,BR as cb,zn as db,tl as eb,nl as fb,Jt as gb,rx as hb,ox as ib,ix as jb,Sg as kb,ys as lb,dx as mb,sl as nb,al as ob,Vu as pb,Ag as qb,ux as rb,fx as sb,mx as tb,dl as ub,px as vb,_x as wb,yx as xb,cl as yb,ll as zb,hx as Ab,oo as Bb,Cg as Cb,Rg as Db,Ex as Eb,kx as Fb,Te as Gb,$e as Hb,Un as Ib,Zt as Jb,re as Kb,Cx as Lb,Rx as Mb,so as Nb,Dx as Ob,_l as Pb,Px as Qb,ao as Rb,vs as Sb,Ss as Tb,Os as Ub,zx as Vb,Ux as Wb,Hx as Xb,ib as Yb,hl as Zb,qx as _b,As as $b,gl as ac,fo as bc,mo as cc,Yx as dc,Xx as ec,po as fc,_o as gc,ht as hc,z as ic,yo as jc,tN as kc,bl as lc,Is as mc,wb as nc,vb as oc,Vn as pc,Ts as qc,Cs as rc,Rs as sc,xs as tc,Ns as uc,Ds as vc,Xs as wc,kb as xc,Sb as yc,Tb as zc,Cb as Ac,Al as Bc,nu as Cc,bu as Dc,wu as Ec,Ee as Fc,fN as Gc,mN as Hc,Nb as Ic,Ps as Jc,Pb as Kc,Ms as Lc,$s as Mc,js as Nc,Ls as Oc,Fs as Pc,zs as Qc,Hs as Rc,qs as Sc,Vs as Tc,Ew as Uc,Sw as Vc,Ow as Wc,Dw as Xc,WD as Yc,GD as Zc,KD as _c,ZD as $c,eP as ad,Zw as bd,Qw as cd,ra as dd,nv as ed,rv as fd,cP as gd,Oo as hd,dP as id,lP as jd,uP as kd,fP as ld,mP as md,pP as nd,_P as od,ju as pd,yP as qd,hP as rd,Lu as sd,gP as td,Ao as ud,bP as vd,wP as wd,vP as xd,EP as yd,kP as zd,Io as Ad,SP as Bd,an as Cd,OP as Dd,AP as Ed,IP as Fd,TP as Gd,CP as Hd,cn as Id,$P as Jd,cv as Kd,Hu as Ld,kt as Md,Ye as Nd,qu as Od,Xe as Pd,ie as Qd,aa as Rd,Ce as Sd,ue as Td,XP as Ud,JP as Vd,Qu as Wd,ef as Xd,ca as Yd,tf as Zd,nf as _d,ZP as $d,i1 as ae,Hv as be,s1 as ce,lf as de,uf as ee,cr as fe,a1 as ge,c1 as he,da as ie,la as je,l1 as ke,ua as le,mf as me,Xv as ne,u1 as oe,Po as pe,Zv as qe,_1 as re,Mo as se,VE as te,Lo as ue,d0 as ve,P1 as we,M1 as xe,fn as ye,Af as ze,If as Ae,Tf as Be,Sa as Ce,Cf as De,L1 as Ee,Rf as Fe,F1 as Ge,xf as He,Ot as Ie,Aa as Je,H1 as Ke,q1 as Le,Uo as Me,Ho as Ne,H0 as Oe,Yo as Pe,K0 as Qe,fe as Re,J0 as Se,Ma as Te,nm as Ue,ja as Ve,EM as We,kM as Xe,SM as Ye,OM as Ze,AM as _e,IM as $e,Wa as af,Ga as bf,lm as cf,jM as df,LM as ef,FM as ff,zM as gf,UM as hf,HM as if,Ja as jf,_m as kf,qM as lf,VM as mf,BM as nf,Tk as of,WM as pf,gm as qf,ei as rf,Rt as sf,t$ as tf,Rk as uf,xk as vf,yn as wf,s_ as xf,RI as yf,MI as zf,wF as Af,vF as Bf,br as Cf,i$ as Df,ti as Ef,$k as Ff,jk as Gf,s$ as Hf,xe as If,a$ as Jf,Hk as Kf,Bk as Lf,Zk as Mf,Em as Nf,Pm as Of,rc as Pf,Sm as Qf,ri as Rf,eS as Sf,tt as Tf,hn as Uf,yr as Vf,oi as Wf,hr as Xf,Om as Yf,d$ as Zf,gr as _f,lc as $f,wr as ag,yS as bg,O$ as cg,$m as dg,hS as eg,AS as fg,TS as gg,jm as hg,CS as ig,RS as jg,Lm as kg,Nt as lg,Fm as mg,A$ as ng,I$ as og,sc as pg,T$ as qg,C$ as rg,R$ as sg,x$ as tg,N$ as ug,L$ as vg,ac as wg,cc as xg,li as yg,qm as zg,dc as Ag,Vm as Bg,vr as Cg,z$ as Dg,Dt as Eg,oj as Fg,ij as Gg,BS as Hg,vn as Ig,sj as Jg,ep as Kg,JS as Lg,aj as Mg,np as Ng,pc as Og,dp as Pg,lp as Qg,up as Rg,fp as Sg,fi as Tg,_c as Ug,Sr as Vg,Ej as Wg,kj as Xg,Or as Yg,yc as Zg,bc as _g,Sj as $g,AO as ah,Oj as bh,Aj as ch,Ue as dh,Y as eh,Lj as fh,kn as gh,jO as hh,Fj as ih,zj as jh,LO as kh,Uj as lh,Hj as mh,qj as nh,HO as oh,Ap as ph,qO as qh,tL as rh,BO as sh,Tp as th,nL as uh,xp as vh,GO as wh,JO as xh,Np as yh,Mp as zh,$p as Ah,sL as Bh,dL as Ch,wi as Dh,lL as Eh,uL as Fh,mA as Gh,fL as Hh,mL as Ih,pL as Jh,_L as Kh,yL as Lh,zp as Mh,Hp as Nh,kL as Oh,SL as Ph,MA as Qh,Cr as Rh,vi as Sh,LL as Th,FL as Uh,qI as Vh,$i as Wh,$t as Xh,Rr as Yh,WI as Zh,GI as _h,M_ as $h,Tn as ai,BF as bi,Jc as ci,ki as di,Qp as ei,Pc as fi,WF as gi,j_ as hi,e_ as ii,GF as ji,Nr as ki,Dr as li,rI as mi,Si as ni,QL as oi,Dc as pi,Oi as qi,eF as ri,tF as si,n_ as ti,Ai as ui,Ii as vi,jt as wi,fI as xi,nF as yi,rF as zi,ct as Ai,Ht as Bi,sz as Ci,az as Di,cz as Ei,H_ as Fi,dz as Gi,lz as Hi,uz as Ii,V_ as Ji,Ui as Ki,bz as Li,Bt as Mi,Uz as Ni,IT as Oi,ay as Pi,Hz as Qi,qz as Ri,Wi as Si,Sy as Ti,Oy as Ui,Vz as Vi,Bz as Wi,Zi as Xi,ut as Yi,Yi as Zi,Ry as _i,Zz as $i,OC as aj,AC as bj,Qz as cj,Ny as dj,TC as ej,cU as fj};
116
+ //# sourceMappingURL=chunk-7ZRCYESH.js.map