@unbrained/pm-cli 2026.10.17 → 2026.10.18

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 (188) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +25 -0
  3. package/dist/cli/register-list-query.js +2 -2
  4. package/dist/cli-bundle/bundle-manifest.json +1 -1
  5. package/dist/cli-bundle/chunks/{chunk-3QKI3XNX.js → chunk-4GA4MUTE.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-X2ONXFBP.js → chunk-4V6ONLI6.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-B5QVGCZX.js → chunk-6VZKYJW7.js} +2 -2
  8. package/dist/cli-bundle/chunks/chunk-7PATQWTH.js +20 -0
  9. package/dist/cli-bundle/chunks/{chunk-W3KZ22DW.js → chunk-7WIEAGDS.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-EA2CG7UM.js → chunk-AETP4JEM.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-6ZDKKOKM.js → chunk-FIJOSX2C.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-VMCSTFSO.js → chunk-LUKVNL72.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-J4LPQCET.js → chunk-OJ77ZQN3.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-O4YBC3OM.js → chunk-PYRREEUB.js} +30 -30
  15. package/dist/cli-bundle/chunks/chunk-RHQJ6VWC.js +237 -0
  16. package/dist/cli-bundle/chunks/{chunk-OZCSXX4D.js → chunk-RNABUEFB.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-HY7FQ7QX.js → chunk-TO6CIV4C.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-JS3B2M4D.js → chunk-ZZED447K.js} +2 -2
  19. package/dist/cli-bundle/chunks/{register-list-query-RU3QZSAQ.js → register-list-query-PUCVYYBD.js} +7 -7
  20. package/dist/cli-bundle/chunks/{register-mutation-EQYMT32A.js → register-mutation-GGGVBXD5.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-operations-VXBGE4XI.js → register-operations-NRZ6Q4QE.js} +2 -2
  22. package/dist/cli-bundle/chunks/{register-setup-UUDEGFRO.js → register-setup-MV3P3YSF.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-LDKX4KYJ.js → chunk-2MPQUMTF.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-MBQF6HT6.js → chunk-5UKCSZWT.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-FTUZ3JF2.js → chunk-A4ZHHTEX.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-JXR6UKFM.js → chunk-B4YLP5ZB.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-NZO7GOXD.js → chunk-BFEMT5U3.js} +16 -16
  28. package/dist/cli-bundle/focused-chunks/{chunk-QOSVJDOO.js → chunk-FW7CSSKL.js} +61 -61
  29. package/dist/cli-bundle/focused-chunks/{chunk-AH6NX6GM.js → chunk-HYPRPSYD.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-RBLSY6ML.js → chunk-IRVL4UXR.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-RHTH5ILM.js → chunk-L55KQ2KT.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-PYC7BF6Z.js → chunk-MASIOFPG.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-RJ3EIHDU.js +26 -0
  34. package/dist/cli-bundle/focused-chunks/chunk-SEL4Z2OO.js +167 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-2IOHHNRT.js → chunk-TB7F4FCR.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-UNTQE37U.js → chunk-TZUIBG3P.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-E33QA7PK.js → chunk-Z7YIFCNE.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-SIGIGZCG.js → chunk-ZDBS2DCT.js} +2 -2
  39. package/dist/cli-bundle/main.js +2 -2
  40. package/dist/cli-bundle/sdk-authoring.js +1 -1
  41. package/dist/cli-bundle/sdk-contracts.js +1 -1
  42. package/dist/cli-bundle/sdk-core.js +16 -16
  43. package/dist/cli-bundle/sdk-governance.js +1 -1
  44. package/dist/cli-bundle/sdk-graph.js +1 -1
  45. package/dist/cli-bundle/sdk-merge.js +50 -49
  46. package/dist/cli-bundle/sdk-query.js +1 -1
  47. package/dist/cli-bundle/sdk-runtime.js +1 -1
  48. package/dist/cli-bundle/sdk-testing.js +1 -1
  49. package/dist/cli-bundle/sdk.js +1 -1
  50. package/dist/core/history/event-index.d.ts +8 -1
  51. package/dist/core/history/event-index.js +19 -18
  52. package/dist/core/item/item-format.js +1 -1
  53. package/dist/core/lock/lock.d.ts +8 -1
  54. package/dist/core/lock/lock.js +3 -3
  55. package/dist/core/output/output.js +2 -2
  56. package/dist/core/store/paths.js +1 -1
  57. package/dist/core/telemetry/policy.d.ts +2 -0
  58. package/dist/core/telemetry/policy.js +1 -1
  59. package/dist/core/telemetry/runtime.d.ts +5 -3
  60. package/dist/core/telemetry/runtime.js +3 -3
  61. package/dist/sdk/governance/health/projection.d.ts +37 -0
  62. package/dist/sdk/governance/health/projection.js +2 -0
  63. package/dist/sdk/governance/health.d.ts +7 -18
  64. package/dist/sdk/governance/health.js +2 -2
  65. package/dist/sdk/mutation-events.js +1 -1
  66. package/dist/sdk/public-surface.json +1 -1
  67. package/dist/sdk/query/list.d.ts +2 -0
  68. package/dist/sdk/query/list.js +1 -1
  69. package/dist/types.d.ts +2 -2
  70. package/dist/types.js +1 -1
  71. package/docs/COMMANDS.md +26 -0
  72. package/docs/CONFIGURATION.md +22 -1
  73. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +22 -3
  74. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +10 -0
  75. package/docs/RELEASING.md +8 -1
  76. package/docs/SDK_CONTEXT_COORDINATION.md +71 -7
  77. package/docs/SDK_STORAGE_LIFECYCLE.md +24 -2
  78. package/docs/TESTING.md +8 -0
  79. package/docs/examples/ci/github-actions-pm-extension-gate.yml +1 -1
  80. package/docs/examples/ci/gitlab-ci-pm-extension-gate.yml +1 -1
  81. package/docs/examples/ci/jenkins-pm-extension-gate.Jenkinsfile +1 -1
  82. package/marketplace.json +1 -1
  83. package/node_modules/@opentelemetry/core/package.json +2 -1
  84. package/node_modules/@opentelemetry/instrumentation/package.json +2 -1
  85. package/node_modules/@opentelemetry/resources/package.json +2 -1
  86. package/node_modules/@opentelemetry/sdk-trace/package.json +2 -1
  87. package/node_modules/@opentelemetry/sdk-trace-base/package.json +2 -1
  88. package/node_modules/@sentry/core/build/cjs/client.js +5 -4
  89. package/node_modules/@sentry/core/build/cjs/tracing/ai/gen-ai-attributes.js +0 -4
  90. package/node_modules/@sentry/core/build/cjs/tracing/ai/utils.js +33 -23
  91. package/node_modules/@sentry/core/build/cjs/tracing/anthropic-ai/index.js +7 -6
  92. package/node_modules/@sentry/core/build/cjs/tracing/anthropic-ai/streaming.js +3 -1
  93. package/node_modules/@sentry/core/build/cjs/tracing/google-genai/index.js +13 -14
  94. package/node_modules/@sentry/core/build/cjs/tracing/google-genai/streaming.js +6 -1
  95. package/node_modules/@sentry/core/build/cjs/tracing/langchain/utils.js +71 -21
  96. package/node_modules/@sentry/core/build/cjs/tracing/langgraph/utils.js +23 -33
  97. package/node_modules/@sentry/core/build/cjs/tracing/openai/streaming.js +6 -0
  98. package/node_modules/@sentry/core/build/cjs/tracing/openai/utils.js +11 -0
  99. package/node_modules/@sentry/core/build/cjs/tracing/workers-ai/utils.js +1 -1
  100. package/node_modules/@sentry/core/build/cjs/utils/eventUtils.js +4 -0
  101. package/node_modules/@sentry/core/build/cjs/utils/prepareEvent.js +2 -2
  102. package/node_modules/@sentry/core/build/cjs/utils/version.js +1 -1
  103. package/node_modules/@sentry/core/build/esm/client.js +6 -5
  104. package/node_modules/@sentry/core/build/esm/package.json +1 -1
  105. package/node_modules/@sentry/core/build/esm/tracing/ai/gen-ai-attributes.js +1 -3
  106. package/node_modules/@sentry/core/build/esm/tracing/ai/utils.js +34 -24
  107. package/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/index.js +8 -7
  108. package/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/streaming.js +3 -1
  109. package/node_modules/@sentry/core/build/esm/tracing/google-genai/index.js +15 -16
  110. package/node_modules/@sentry/core/build/esm/tracing/google-genai/streaming.js +6 -1
  111. package/node_modules/@sentry/core/build/esm/tracing/langchain/utils.js +73 -24
  112. package/node_modules/@sentry/core/build/esm/tracing/langgraph/utils.js +24 -34
  113. package/node_modules/@sentry/core/build/esm/tracing/openai/streaming.js +6 -0
  114. package/node_modules/@sentry/core/build/esm/tracing/openai/utils.js +11 -0
  115. package/node_modules/@sentry/core/build/esm/tracing/workers-ai/utils.js +2 -2
  116. package/node_modules/@sentry/core/build/esm/utils/eventUtils.js +4 -1
  117. package/node_modules/@sentry/core/build/esm/utils/prepareEvent.js +2 -2
  118. package/node_modules/@sentry/core/build/esm/utils/version.js +1 -1
  119. package/node_modules/@sentry/core/build/types/tracing/ai/utils.d.ts +3 -7
  120. package/node_modules/@sentry/core/build/types/tracing/anthropic-ai/types.d.ts +2 -2
  121. package/node_modules/@sentry/core/build/types/tracing/langchain/types.d.ts +15 -0
  122. package/node_modules/@sentry/core/build/types/tracing/langchain/utils.d.ts +1 -0
  123. package/node_modules/@sentry/core/build/types/tracing/langgraph/utils.d.ts +2 -0
  124. package/node_modules/@sentry/core/build/types/tracing/openai/types.d.ts +2 -0
  125. package/node_modules/@sentry/core/build/types/utils/eventUtils.d.ts +2 -1
  126. package/node_modules/@sentry/core/build/types-ts3.8/tracing/ai/utils.d.ts +3 -7
  127. package/node_modules/@sentry/core/build/types-ts3.8/tracing/anthropic-ai/types.d.ts +2 -2
  128. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langchain/types.d.ts +15 -0
  129. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langchain/utils.d.ts +1 -0
  130. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langgraph/utils.d.ts +2 -0
  131. package/node_modules/@sentry/core/build/types-ts3.8/tracing/openai/types.d.ts +2 -0
  132. package/node_modules/@sentry/core/build/types-ts3.8/utils/eventUtils.d.ts +2 -1
  133. package/node_modules/@sentry/core/package.json +1 -1
  134. package/node_modules/@sentry/node/build/esm/package.json +1 -1
  135. package/node_modules/@sentry/node/package.json +5 -5
  136. package/node_modules/@sentry/node-core/build/cjs/integrations/anr/index.js +1 -1
  137. package/node_modules/@sentry/node-core/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
  138. package/node_modules/@sentry/node-core/build/esm/integrations/anr/index.js +1 -1
  139. package/node_modules/@sentry/node-core/build/esm/integrations/anr/worker-script.js +2 -2
  140. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/local-variables-async.js +1 -1
  141. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/worker-script.js +1 -1
  142. package/node_modules/@sentry/node-core/build/esm/package.json +1 -1
  143. package/node_modules/@sentry/node-core/package.json +10 -4
  144. package/node_modules/@sentry/opentelemetry/build/esm/package.json +1 -1
  145. package/node_modules/@sentry/opentelemetry/package.json +5 -2
  146. package/node_modules/@sentry/server-utils/build/THIRD-PARTY-LICENSES.txt +55 -55
  147. package/node_modules/@sentry/server-utils/build/esm/package.json +1 -1
  148. package/node_modules/@sentry/server-utils/package.json +2 -2
  149. package/node_modules/@toon-format/toon/README.md +10 -41
  150. package/node_modules/@toon-format/toon/dist/index.d.mts +12 -36
  151. package/node_modules/@toon-format/toon/dist/index.mjs +134 -202
  152. package/node_modules/@toon-format/toon/package.json +2 -2
  153. package/node_modules/debug/package.json +3 -0
  154. package/node_modules/fdir/package.json +3 -0
  155. package/node_modules/has-flag/index.d.ts +39 -0
  156. package/node_modules/has-flag/index.js +8 -0
  157. package/node_modules/has-flag/license +9 -0
  158. package/node_modules/has-flag/package.json +46 -0
  159. package/node_modules/has-flag/readme.md +89 -0
  160. package/node_modules/supports-color/browser.js +5 -0
  161. package/node_modules/supports-color/index.js +135 -0
  162. package/node_modules/supports-color/license +9 -0
  163. package/node_modules/supports-color/package.json +53 -0
  164. package/node_modules/supports-color/readme.md +76 -0
  165. package/package.json +4 -4
  166. package/packages/pm-beads/package.json +1 -1
  167. package/packages/pm-calendar/package.json +1 -1
  168. package/packages/pm-command-kit/package.json +1 -1
  169. package/packages/pm-digital-twin/package.json +1 -1
  170. package/packages/pm-governance-audit/package.json +1 -1
  171. package/packages/pm-guide-shell/package.json +1 -1
  172. package/packages/pm-kanban/package.json +1 -1
  173. package/packages/pm-lifecycle-hooks/package.json +1 -1
  174. package/packages/pm-linked-test-adapters/package.json +1 -1
  175. package/packages/pm-search-advanced/package.json +1 -1
  176. package/packages/pm-templates/package.json +1 -1
  177. package/packages/pm-todos/package.json +1 -1
  178. package/packages/pm-vcs/package.json +1 -1
  179. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  180. package/plugins/pm-claude/package.json +1 -1
  181. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  182. package/plugins/pm-codex/package.json +1 -1
  183. package/plugins/pm-codex/plugin.json +1 -1
  184. package/runtime-dependencies.json +1 -1
  185. package/dist/cli-bundle/chunks/chunk-4PNPDT2N.js +0 -236
  186. package/dist/cli-bundle/chunks/chunk-X53HM753.js +0 -20
  187. package/dist/cli-bundle/focused-chunks/chunk-5JEFDEL3.js +0 -166
  188. package/dist/cli-bundle/focused-chunks/chunk-TRFVAWF2.js +0 -26
@@ -1,75 +1,75 @@
1
- import{a as Za,c as Kr,d as Yr,e as Cd,g as Td,h as eo,i as $d,j as ln,k as un,l as Od,m as Dd,n as to,o as Ld,p as mn,q as pn,r as Md,s as jd,t as no}from"./chunk-RBLSY6ML.js";import{e as ii,f as io,h as ao}from"./chunk-2IOHHNRT.js";import{B as Vd,C as ti,D as Jd,E as ro,G as Kd,H as Yd,J as Xd,K as Zd,L as ni,O as ri,a as Ed,g as Xa,i as Sd}from"./chunk-JXR6UKFM.js";import{K as cu}from"./chunk-RHTH5ILM.js";import{D as mo,E as bi,Fa as Ql,Ga as eu,Ka as tu,La as nu,T as ki,U as Rl,V as po,W as Qn,Y as fo,aa as zl,ba as Hl,ca as Gl,da as Wl,ea as xi,f as yl,g as wl,ga as ql,h as vl,ha as Bl,i as bl,ia as Vl,ib as au,ja as Vt,k as vi,ka as Jl,kb as go,la as yn,lb as ou,ma as Kl,mb as su,na as ho,o as Xn,oa as wn,p as kl,pa as Yl,q as El,qa as Xl,r as Zn,ra as Zl,s as Sl,sa as _o,u as uo,ub as yo,v as xl,z as Al}from"./chunk-NZO7GOXD.js";import{a as xd,b as dn,c as Qa,d as Ad,e as Id,f as ct,g as Xr,h as Rd,i as It}from"./chunk-SIGIGZCG.js";import{$ as rl,$a as wi,Aa as pl,Ab as Ei,Ca as mi,Cb as jl,D as W,Da as pi,E as Qd,Ea as co,Eb as ne,Fa as Tt,Fb as ve,Ga as Yn,Gb as be,H as Ce,Ha as fl,Hb as Fl,I as oo,Ia as fi,Ib as Si,Ja as Bt,Jb as lt,Ka as ce,Kb as ut,La as hi,Ma as hl,N as ai,Na as lo,Nb as Ul,O as Kn,Oa as _i,Ob as mt,P as el,Pa as gn,Q as oi,Qa as gi,R as tl,Ra as _l,T as si,U as ci,Va as Te,W as nl,X as je,Ya as gl,Za as T,_ as Ct,_a as yi,aa as il,ac as er,ba as al,bb as Il,ca as dt,cc as Ai,da as ol,ia as sl,ib as Cl,ja as so,jb as Tl,jc as ru,ka as di,la as hn,lb as $l,mb as Ol,mc as iu,na as li,nb as $t,oa as cl,ob as Dl,pa as dl,pb as Pl,ra as ll,sb as Nl,ta as ul,ub as Ll,va as ml,vb as Ml,xa as ui,za as _n}from"./chunk-5JEFDEL3.js";import{b as sn,e as le,g as Le,i as Re,j as Ze,n as ge,o as Pd,p as Zr,r as Nd}from"./chunk-AH6NX6GM.js";import{$ as g,$a as Jn,Bc as Fd,Ca as fe,Da as Ne,Dc as Qr,Ea as ad,Ec as Ud,Fc as zd,Ga as ee,Hb as gd,Hc as Hd,Ja as od,Oa as sd,Pc as z,Qb as yd,S as Zc,Sc as X,T as Qc,Ua as cd,Uc as Ge,V as ed,Va as dd,Vc as Gd,Wa as G,Wc as ei,X as td,Y as Br,Z as nd,a as Wr,aa as y,ab as L,ae as $,bb as Ke,bd as Wd,be as Bd,cb as Vr,ce as fn,d as qr,db as Ht,de as Rt,ee as qt,fb as ld,fc as wd,gb as Gt,gc as vd,hd as qd,i as Kc,ia as rd,ib as ud,id as Me,jb as C,je as te,kb as md,l as Yc,la as id,lb as Ie,m as Xc,na as Ba,nb as Jr,ob as pd,oc as bd,pb as Va,pc as Wt,qb as Ja,rb as Ka,rc as Ya,sa as Vn,sc as kd,ta as O,tb as fd,tc as cn,ua as At,ub as hd,va as F,vc as Ye,w as qa,wa as V,xb as _d,xc as Xe,za as Z}from"./chunk-TRFVAWF2.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var M=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},$e=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Qe=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function vn(e){try{return await e()}catch(t){throw t instanceof M?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function du(e){try{return await e()}catch(t){throw t instanceof $e?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as ay}from"node:crypto";import oy from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var bn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="416aaf09-e4f6-5d10-aee0-eba374f1cd83")}catch{}})();var uu=1,Jt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],wo=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],sy=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],cy=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Ii=30,Ri=5e3,mu=4,dy=50;function pt(e,t){if(!cy.test(e))throw new M(`${t} must be a stable lowercase id`)}function ly(e,t){if(!Number.isFinite(e)||e<0)throw new M(`${t} must be a finite non-negative number`)}function tr(e){let t=sy.filter(i=>e[i]!==void 0);if(t.length!==1)throw new M(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function bo(e,t){return C(e)===C(t)}function pu(e,t){if(t.polarity==="equals")return bo(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function fu(e){let t=tr(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>pu(r.observed,t)===(r.expected==="pass"))}function uy(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!bo(e.value,t.value)}function my(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||C(e.scope)!==C(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return uy(tr(e),tr(t))||n[t.enforcement]<n[e.enforcement]||r}function py(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new M("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new M("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new M("items source equals/state requires field")}function fy(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new M("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new M("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new M("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new M("dependency_kind source source_kind_state must be present or missing")}function hy(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new M("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new M("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new M("prose_edge_gap exemption selectors must not be empty")}}function ko(e){pt(e.id,"measurement.id"),e.max_cost!==void 0&&ly(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new M(`measurement.source.kind must be one of ${wo.join(", ")}`);let n=Reflect.get(t,"kind");if(!wo.includes(n))throw new M(`measurement.source.kind must be one of ${wo.join(", ")}`);let r=t;if(r.kind==="items"&&py(r),r.kind==="dependency_kind"&&fy(r),r.kind==="prose_edge_gap"&&hy(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new M(`${r.kind} source requires field`);return r.kind==="provider"&&(pt(r.provider,"provider source provider"),pt(r.key,"provider source key")),e}function Eo(e){if(pt(e.id,"assertion.id"),pt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new M("assertion.owner_item_id is required");let t=tr(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new M(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new M("retired assertion requires retire_reason");e.scope.kind==="filter"&&pt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new M("assertion negative control requires pass and fail cases");if(!fu(e))throw new M(`assertion ${e.id} negative control does not prove its bound`);return e}function _y(e){if(!Array.isArray(e.allowed_providers))throw new M("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)pt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new M("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Jt.includes(t))throw new M(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new M(`gate provider policy trigger ${t} is invalid`)}}function hu(e){if(pt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new M("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new M("gate requires at least one assertion");for(let t of e.assertion_ids)pt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new M(`gate.triggers is required and must be an array of ${Jt.join(", ")}`);if(e.triggers.length===0)throw new M("gate requires at least one trigger");for(let t of e.triggers)if(!Jt.includes(t))throw new M(`gate trigger must be one of ${Jt.join(", ")}`);return e.provider_policy&&_y(e.provider_policy),e}function kn(e){if(e.version!==uu)throw new M(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(ko(r),t.has(`measurement:${r.id}`))throw new M(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(Eo(r),t.has(`assertion:${r.id}`))throw new M(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){hu(r);let i=r.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(i.length>0)throw new M(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new M(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of _u(e))if(!n.has(r))throw new M(`${i.join(", ")} references missing measurement ${r}`);return e}function So(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)So(n,t)}function _u(e){let t=new Map,n=(r,i)=>{let a=t.get(r)??[];a.push(i),t.set(r,a)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];So(r.source.expression,i);for(let a of i)n(a,`derived measurement ${r.id}`)}return t}function gy(e,t){let n=e.assertion_ids.flatMap(a=>{let o=t.assertions.find(s=>s.id===a);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let a=n.pop();if(r.has(a))continue;r.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?i.add(o.source.provider):o.source.kind==="derived"&&So(o.source.expression,n)}return i}function nr(){return{version:uu,measurements:[],assertions:[],gates:[]}}function yy(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let a=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?a:!a}return bo(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function wy(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function vy(e,t){let n=[],r=Ba(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let a of i.dependencies??[]){let o=Ba(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===r&&wy(e,s)&&n.push(`${i.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function by(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let a=Reflect.get(i,"text");typeof a=="string"&&t.push(a)}}}return t}function ky(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function vo(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Ey(e){let t=new Map,n=new Set,r=[],i=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,a=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let s of o.dependencies??[])n.add(vo(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(vo(o.id,s));for(let s of by(o)){let c=[...s.matchAll(i)].map(d=>d[0]);a+=c.length,r.push({holder_id:o.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:a}}function Sy(e,t){let n=Ey(t.items),r=new Map;for(let o of n.prose_mentions){let s=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(s)];for(let d of c){let l=vo(o.holder_id,d);if(n.linked_pairs.has(l)||ky(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],a=i.map(o=>o.contributor).sort();return{value:a.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:a.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(o=>o.explicit).length,implicit_subject:i.filter(o=>!o.explicit).length}}}function xy(e,t){return{value:t.history.filter(n=>(e.op===void 0||n.op===e.op)&&(e.author===void 0||n.author===e.author)&&(e.harness===void 0||n.agent_harness===e.harness)&&(e.model===void 0||n.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function Ay(e,t){let n=t.items.filter(r=>{let i=r[e.link],a=Array.isArray(i)&&i.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Iy(e,t){let n=e.source;return n.kind==="items"?yy(n,t):n.kind==="dependency_kind"?vy(n,t):n.kind==="prose_edge_gap"?Sy(n,t):n.kind==="history"?xy(n,t):n.kind==="links"?Ay(n,t):null}function gu(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function Ry(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function yu(e,t,n){let r=new Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o],o)}});return await Promise.all(a),r}async function wu(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await vu(o,t,n,r,i);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=i.charged.has(o.id)?[]:[s.cost];return i.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await yu(e.operands,mu,o=>wu(o,t,n,r,i));return{value:Ry(e.operator,a.map(o=>o.value)),costs:a.flatMap(o=>o.costs),population_size:Math.max(0,...a.map(o=>o.population_size)),contributors:[...new Set(a.flatMap(o=>o.contributors))]}}async function Cy(e,t,n,r,i){ko(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await wu(e.source.expression,t,n,[...r,e.id],i);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Iy(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let d={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-a},l=gu([...s,d],Date.now()-a);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new $e(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${ay("sha256").update(C(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function vu(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let a=i.cache.get(e.id);if(a)return a;let o=Cy(e,t,n,r,i).catch(s=>{if(s instanceof Qe&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new Qe(s.message,c);throw d.cause=s,d}throw s});return i.cache.set(e.id,o),o}async function xo(e,t,n=[e]){return vu(e,t,n,[],{cache:new Map,charged:new Set})}function Ty(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity,e-t.value)}function $y(e,t,n={}){Eo(e);let r=tr(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:Ty(t.value,r),verdict:i?"retired":pu(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:fu(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Oy(e,t,n,r){let i=gy(e,t);if(i.size===0)return;let a=e.provider_policy,o=a?.triggers[r];if(!a||!o)throw new $e(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!s.has(d))throw new $e(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new $e(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new $e(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!o.allow_network)throw new $e(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function lu(e,t,n,r,i){try{return await xo(n,r,i)}catch(a){if(a instanceof Qe){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new $e(`assurance gate ${e} assertion ${t} measurement ${s} source ${a.source_kind}${o} field ${a.field} could not resolve: ${a.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}});throw c.cause=a,c}throw a}}async function bu(e,t,n,r){kn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new $e(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new $e(`assurance gate ${e} does not declare trigger ${r.trigger}`);Oy(i,t,n,r.trigger);let a=await yu(i.assertion_ids,mu,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(v=>v.id===p),_=await lu(i.id,d.id,h,n,t.measurements),w=new Set(_.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return $y(d,await lu(i.id,d.id,l,u,t.measurements),{owner_terminal:f})}),o=a.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=a.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":s?"warn":"pass",exit_code:o?1:0,assertions:a,assertions_total:a.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:gu(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function Ci(e){return oy.join(e,"assurance.json")}async function ku(e){let t=await V(Ci(e));return t===null?nr():Ti(t)}function Ti(e){try{return kn(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function $i(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Dy(e,t){e==="measurement"?ko(t):e==="assertion"?Eo(t):hu(t)}async function rr(e,t){let n=structuredClone($i(await ku(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Ao(e,t,n){let r=$i(await ku(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Oi(e,t,n,r={}){Dy(t,n);let i=await T(e),a=W(r.author,i.author_default),o=await gn({pmRoot:e,filePath:Ci(e),op:`assurance:${t}:put`,author:a,message:r.message,lockTtlSeconds:Ii,lockWaitMs:Ri,mutate:s=>{let c=s===null?nr():Ti(s),d=$i(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&my(d[l],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new M(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),kn(c),{raw:`${JSON.stringify(c,null,2)}
2
- `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function Io(e,t,n={}){let r=nr();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),kn(r);let i=await T(e),a=W(n.author,i.author_default),o=await gn({pmRoot:e,filePath:Ci(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:Ii,lockWaitMs:Ri,mutate:s=>{let c=s===null?nr():Ti(s),d=[],l=[],u=(m,f,p)=>{for(let h of f){let _=m.find(w=>w.id===h.id);if(!_){m.push(structuredClone(h)),d.push(`${p}:${h.id}`);continue}if(C(_)!==C(h))throw new M(`assurance bundle refuses to replace divergent ${p} ${h.id}`);l.push(`${p}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),kn(c),{raw:`${JSON.stringify(c,null,2)}
3
- `,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function Eu(e,t,n,r={}){let i=await T(e),a=W(r.author,i.author_default),o=await gn({pmRoot:e,filePath:Ci(e),op:`assurance:${t}:remove`,author:a,message:r.message,lockTtlSeconds:Ii,lockWaitMs:Ri,mutate:s=>{let c=s===null?nr():Ti(s);if(t==="measurement"){let u=_u(c).get(n);if(u&&u.length>0)throw new M(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new M(`assurance assertion ${n} is referenced by gate`);let d=$i(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new M(`assurance ${t} ${n} not found`);return d.splice(l,1),kn(c),{raw:`${JSON.stringify(c,null,2)}
4
- `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function Su(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await T(e);await _i({pmRoot:e,op:"assurance:gate:verdict",author:W(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Ii,lockWaitMs:Ri})}async function xu(e,t={}){let n=t.limit??dy;if(!Number.isInteger(n)||n<1||n>bn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${bn}`);return(await dt(hi(e),ce)).reverse().filter(r=>r.op==="assurance:gate:verdict").map(r=>r.context?.assurance_verdict).filter(r=>typeof r=="object"&&r!==null&&"gate_id"in r).filter(r=>t.gate_id===void 0||r.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var ir={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Di={type:"array",minItems:1,maxItems:Va,items:ir},Au={...Di,items:{...ir,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},Py={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Di])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:ir,id:ir}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Au}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Di}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Au,authors:Di}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Va,items:{type:"array",minItems:2,maxItems:2,items:ir}}}}]}}},g$={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:pd,items:Py}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function Iu(e,t,n,r){let i=await $t(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Ru(i,t,n,r)}function Ny(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Ru(e,t,n=5,r=!1){let i=[],a=new Map,o=e.policies.filter(_=>_.rule.kind==="require_fields"),s=o.filter(_=>_.subject?.operations===void 0),c=new Set,d=0,l=0,u=0,m=0,f=0,p=_d(e);for(let _ of t){let w=p({operation:"",author:"",before:_,after:_,completeness_only:!0});d+=+(w.decisions.length>0),l+=w.decisions.length,w.decisions.forEach(k=>c.add(k.policy_id));let v=w.decisions.filter(k=>!k.satisfied);if(v.length===0)continue;m+=1;let E=a.get(_.type)??{items:0,violations:0,missing_fields:0};E.items+=1;for(let k of v)u+=1,E.violations+=1,E.missing_fields+=k.missing_fields.length,k.effect==="refuse"&&(f+=1),i.length<n&&i.push({id:_.id,type:_.type,status:_.status,decision:k});a.set(_.type,E)}let h=r||f>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:h,ok:h==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:l,governed_items:d,ungoverned_items:t.length-d,contract_status:Ny(o.length,t.length,d),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:u,refused_violations:f,missing_by_type:Object.fromEntries(a),violations:i,violations_truncated:i.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}import Ly from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function My(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function $u(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new y("Policy definition must be valid JSON.",g.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("Policy definition must be an object.",g.USAGE);return t}async function jy(e,t){let n=L(process.cwd(),e.path);await ne(n);let r=await T(n);return{pmRoot:n,settings:r,author:W(t,r.author_default)}}function Cu(e,t,n,r){if(e==="policy-mode")return Ka({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let a=Ja(r.definition),o=Ka({...n,policies:[...i,a].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
5
- `)>$l)throw new y("Policy registry exceeds its byte ceiling.",g.USAGE);return o}async function Tu(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:Cu(e,t,await $t(r.pmRoot),n)};let i=await gn({pmRoot:r.pmRoot,filePath:Ly.join(r.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:r.author,message:n.message,lockTtlSeconds:r.settings.locks.ttl_seconds,lockWaitMs:r.settings.locks.wait_ms,mutate(a){let o=Cu(e,t,Ol(a),n);return{raw:`${JSON.stringify(o,null,2)}
6
- `,result:o}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function Fy(e,t,n){let r,i=await Ul({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(a){let o=(await $t(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!o||o.rule.kind!=="approval")throw new y("--policy must name an approval rule.",g.USAGE);if(!o.rule.authors.includes(n.author))throw new y("This actor is not a declared approver.",g.CONFLICT);return await Dl(n.pmRoot,a.metadata.id),r={policy_id:o.id,policy_fingerprint:fd(o),content_fingerprint:hd(o,{...a.metadata,body:a.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...r,warnings:i.warnings}}}function Uy(e,t){let n=$u(t),r=Ja({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==r.id)throw new y("Policy id operand does not match definition.id.",g.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return r}async function M$(e,t,n={},r={}){if(!Jr.includes(e))throw new y("Unknown workflow policy action.",g.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:My()};let i=await jy(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await $t(i.pmRoot)};if(e==="policy-put"){let l=Uy(t,n.definition);return Tu(e,l.id,{...n,definition:l},i)}if(!t?.trim())throw new y(`schema ${e} requires an operand.`,g.USAGE);if(["policy-remove","policy-mode"].includes(e))return Tu(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new y("Use policy-check to preview; policy-approve records an approval.",g.USAGE);return Fy(t,n,i)}let a=G(i.settings,z()),o=await ve(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,a.type_to_folder);if(!o)throw new y(`Item ${t} not found.`,g.NOT_FOUND);let{document:s}=await be(o,{schema:i.settings.schema}),c={...s.metadata,body:s.body},d=n.definition===void 0?c:{...c,...$u(n.definition)};if(d.id!==c.id)throw new y("Policy preview cannot change the item id.",g.USAGE);return{policy_result:!0,action:e,changed:!1,result:await Pl(i.pmRoot,await $t(i.pmRoot),{operation:"update",author:i.author,before:c,after:d,completeness_only:n.definition===void 0})}}import{createHash as Gu}from"node:crypto";import ar from"node:fs/promises";import or from"node:path";import{Option as aO}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="201134b5-01e8-55ae-a099-137b9b6fae92")}catch{}})();function ft(e,t,n){if(typeof n!="string")return;let r=n.trim();r.length!==0&&e.push(t,r)}function Fe(e,t,n){n===!0&&e.push(t)}function Kt(e,t,n){if(Array.isArray(n))for(let r of n){if(typeof r!="string")continue;let i=r.trim();i.length!==0&&e.push(t,i)}}function zy(e,t){let n=["test",e,"--run","--json","--progress"];return Kt(n,"--add",t.add),Kt(n,"--add-json",t.addJson),Kt(n,"--remove",t.remove),Kt(n,"--remove-index",Array.isArray(t.removeIndex)?t.removeIndex.map(r=>typeof r=="number"?String(r):r):t.removeIndex),ft(n,"--match",t.match),ft(n,"--only-index",typeof t.onlyIndex=="number"?String(t.onlyIndex):t.onlyIndex),Fe(n,"--only-last",t.onlyLast),Kt(n,"--measure",t.measure),ft(n,"--metric-below",t.metricBelow),ft(n,"--metric-diff",t.metricDiff),Hy(n,t),ft(n,"--author",t.author),ft(n,"--message",t.message),Fe(n,"--force",t.force),n}function Hy(e,t){ft(e,"--timeout",t.timeout),Kt(e,"--env-set",t.envSet),Kt(e,"--env-clear",t.envClear),Fe(e,"--shared-host-safe",t.sharedHostSafe),ft(e,"--pm-context",t.pmContext),Fe(e,"--override-linked-pm-context",t.overrideLinkedPmContext),ft(e,"--workspace-context",t.workspaceContext),Fe(e,"--override-linked-workspace-context",t.overrideLinkedWorkspaceContext),Fe(e,"--allow-untrusted-linked-tests",t.allowUntrustedLinkedTests),Fe(e,"--fail-on-context-mismatch",t.failOnContextMismatch),Fe(e,"--fail-on-skipped",t.failOnSkipped),Fe(e,"--fail-on-empty-test-run",t.failOnEmptyTestRun),Fe(e,"--require-assertions-for-pm",t.requireAssertionsForPm),Fe(e,"--check-context",t.checkContext),Fe(e,"--auto-pm-context",t.autoPmContext)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f71d68b8-a4cd-5fda-83a0-0528ac44aed0")}catch{}})();function Gy(e,t){let n=[],r=new Set;for(let i of t.keys){if(!Object.hasOwn(e,i))continue;let a=e[i];if(a!=null){if(typeof a=="string"){n.push(a);continue}if(!Array.isArray(a)||!a.every(o=>typeof o=="string"))return;r.has(a)||(r.add(a),n.push(...a))}}return n.length>0?n.join("; "):void 0}function Pi(e,t){return e.find(n=>n.target===t)??{target:t,keys:[t]}}function U(e,t){return e[t]===!0?!0:void 0}function ht(e,t){return e[t]===!1?!0:void 0}function Ou(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Du(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function Pu(e){let t=i=>Xa(e,Pi(ii,i)),n=i=>Sd(e,Pi(io,i)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:Gy(e,Pi(io,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),allowUnresolvedDeps:Ou(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:U(e,"replaceDeps"),replaceTests:U(e,"replaceTests"),replaceFiles:U(e,"replaceFiles"),replaceDocs:U(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:U(e,"clearDeps"),clearComments:U(e,"clearComments"),clearNotes:U(e,"clearNotes"),clearLearnings:U(e,"clearLearnings"),clearFiles:U(e,"clearFiles"),clearTests:U(e,"clearTests"),clearDocs:U(e,"clearDocs"),clearReminders:U(e,"clearReminders"),clearEvents:U(e,"clearEvents"),clearTypeOptions:U(e,"clearTypeOptions")};return Du(r,e),r}function ie(e,t){let n=Pi(Ed,t),r=Xa(e,n);if(r!==void 0)return r;for(let i of n.keys){let a=e[i];if(Array.isArray(a)){let o=a.filter(s=>typeof s=="string");if(o.length>0)return o.join(",")}if(t==="ids"&&typeof a=="string")return a;if(typeof a=="number"&&Number.isFinite(a))return String(a)}}function Wy(e){let t=U(e,"filterFilesMissing"),n=U(e,"filterDocsMissing");return{filterReviewerMissing:U(e,"filterReviewerMissing"),filterRiskMissing:U(e,"filterRiskMissing"),filterConfidenceMissing:U(e,"filterConfidenceMissing"),filterSprintMissing:U(e,"filterSprintMissing"),filterReleaseMissing:U(e,"filterReleaseMissing"),hasNotes:U(e,"hasNotes"),hasLearnings:U(e,"hasLearnings"),hasFiles:U(e,"hasFiles"),hasDocs:U(e,"hasDocs"),hasTests:U(e,"hasTests"),hasComments:U(e,"hasComments"),hasDeps:U(e,"hasDeps"),hasBody:U(e,"hasBody"),hasLinkedCommand:U(e,"hasLinkedCommand"),noNotes:ht(e,"notes"),noLearnings:ht(e,"learnings"),noFiles:ht(e,"files")??t,filterFilesMissing:t,noDocs:ht(e,"docs")??n,filterDocsMissing:n,noTests:ht(e,"tests"),noComments:ht(e,"comments"),noDeps:ht(e,"deps"),emptyBody:U(e,"emptyBody"),noLinkedCommand:ht(e,"linkedCommand")}}function Nu(e){let t={status:ie(e,"status"),type:ie(e,"type"),tag:ie(e,"tag"),priority:ie(e,"priority"),deadlineBefore:ie(e,"deadlineBefore"),deadlineAfter:ie(e,"deadlineAfter"),updatedAfter:ie(e,"updatedAfter"),updatedBefore:ie(e,"updatedBefore"),createdAfter:ie(e,"createdAfter"),createdBefore:ie(e,"createdBefore"),today:U(e,"today"),recent:U(e,"recent"),ids:ie(e,"ids"),assignee:ie(e,"assignee"),assigneeFilter:ie(e,"assigneeFilter"),parent:ie(e,"parent"),sprint:ie(e,"sprint"),release:ie(e,"release"),limit:ie(e,"limit"),offset:ie(e,"offset"),noTruncate:ht(e,"truncate"),includeBody:U(e,"includeBody"),strictRead:U(e,"strictRead"),compact:U(e,"compact"),brief:U(e,"brief"),full:U(e,"full"),fields:ie(e,"fields"),sort:ie(e,"sort"),order:ie(e,"order"),tree:U(e,"tree"),treeDepth:ie(e,"treeDepth"),filterAcMissing:U(e,"filterAcMissing"),filterEstimatesMissing:Ou(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:U(e,"filterResolutionMissing"),filterMetadataMissing:U(e,"filterMetadataMissing"),...Wy(e)};return Du(t,e),t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f604cc2-c8cd-5c15-8fec-2243f64ef7d2")}catch{}})();var qy=Symbol("pm.mcp-mutation-transport"),By=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function Li(e){return qy in e}function Mi(e,t){return Li(e)?Sl(t):uo(e,t)}function yO(e,t,n=[]){let r=uo(e,{...e,...t});for(let i of n)Reflect.deleteProperty(r,i);return r}function P(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function oe(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function wO(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function En(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function To(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new y(`${t} must be a finite integer.`,g.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new y(`${t} must be a finite integer.`,g.USAGE);return n}}function vO(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:P(e,"limit")??P(t,"limit")}function bO(e){let t=P(e,"outputFormat");return{json:!0,quiet:!0,author:P(e,"author"),path:P(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:P(e,"outputInclude"),outputLimit:oe(e,"outputLimit"),outputBudget:oe(e,"outputBudget"),outputSession:P(e,"outputSession"),outputCursor:P(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Vy=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Mu=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),Jy=new Set([...Mu].filter(e=>e!=="file")),Ky=new Set(["files","files-discover","docs","test","test-all"]),ju=new Set(["comments","notes","learnings"]);function Yy(e,t){if(!(!ju.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new y(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,g.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var Xy=new Set(["claim","release","start-task","pause-task","close-task"]),Zy={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause","handoff"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun","offline"],package:["dryRun","offline"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Qy=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Fu(e,t=""){let n={},r=Ky.has(t),i=t==="files"||t==="files-discover"||t==="docs",a=ju.has(t)?Jy:Mu;for(let[o,s]of Object.entries(e)){if(Array.isArray(s)&&Vy.has(o)){n[o]=s.join(",");continue}if(o==="note"&&i){n[o]=s;continue}if(typeof s=="string"&&a.has(o)){n[o]=[s];continue}if(typeof s=="string"&&r&&(o==="add"||o==="remove")){n[o]=[s];continue}n[o]=s}return Object.assign(n,Object.fromEntries(Object.getOwnPropertySymbols(e).map(o=>[o,Reflect.get(e,o)]))),n}function ew(e,t,n){let r=P(e,"author");return r!==void 0?r:n!==void 0&&Xy.has(n)?P(e,"assignee")??P(t,"assignee"):void 0}function tw(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function kO(e,t){let n=En(e.options)?e.options:void 0,r=sd(e.options),i={},a=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of Zy[t??""]??[])a(c);for(let c of Qy)a(c);t!==void 0&&Li(e)&&Yy(t,r);let o=Fu({...i,...r},t);if(t==="history-attest"&&Li(e)&&(o.output!==void 0||typeof o.verify=="string"))throw new y("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",g.USAGE);let s=Li(e)?e:n??e;return Mi(s,tw(o,ew(e,o,t)))}function EO(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function SO(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function nw(e){let t=[],n=!0;for(let r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function xO(e){return!By.has(nw(e))}function AO(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function $o(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function IO(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[a,o]of Object.entries(e))n.has(a)||(r[a]=o);let i={...r,...t};return delete i.args,i}function RO(e,t){let n=Mi(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function Co(e){return{type:oe(e,"filterType"),tag:oe(e,"filterTag"),priority:oe(e,"filterPriority"),deadlineBefore:oe(e,"filterDeadlineBefore"),deadlineAfter:oe(e,"filterDeadlineAfter"),updatedAfter:oe(e,"filterUpdatedAfter"),updatedBefore:oe(e,"filterUpdatedBefore"),createdAfter:oe(e,"filterCreatedAfter"),createdBefore:oe(e,"filterCreatedBefore"),ids:mo(e.ids),assignee:oe(e,"filterAssignee"),assigneeFilter:oe(e,"filterAssigneeFilter")??oe(e,"filterAssignee_filter"),parent:oe(e,"filterParent"),sprint:oe(e,"filterSprint"),release:oe(e,"filterRelease"),limit:oe(e,"limit"),offset:oe(e,"offset")}}function Ro(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return $o(e)}function Ni(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function CO(e){let t=Ro(e.kind),n=Ro(e.exemptIsolate),r=Ro(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Ni(e.maxDepth),limit:Ni(e.limit),after:P(e,"after"),direction:P(e,"direction"),maxPaths:Ni(e.maxPaths),sample:Ni(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function Uu(e){let t=Nu(e);return e.ids!==void 0&&(t.ids=mo(e.ids)),t}function TO(e){return{status:P(e,"filterStatus"),list:En(e.list)?Uu(e.list):Co(e),reason:P(e,"reason"),resolution:P(e,"resolution"),expectedResult:P(e,"expectedResult")??P(e,"expected_result")??P(e,"expected"),actualResult:P(e,"actualResult")??P(e,"actual_result")??P(e,"actual"),validateClose:P(e,"validateClose")??P(e,"validate_close"),author:P(e,"author"),message:P(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:P(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var rw=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function Lu(e){let t={};for(let[n,r]of Object.entries(e))rw.has(n)||(t[n]=r);return zu(t)}function zu(e){let t=Fu(e,"update-many");for(let n of ii)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return Pu(t)}function $O(e){if(En(e.list)||En(e.update)){let t=En(e.update)?e.update:Lu(e),n=Mi(e,zu(t));return{status:oe(e,"filterStatus"),list:En(e.list)?Uu(e.list):Co(e),update:xl(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:P(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:oe(e,"filterStatus"),list:Co(e),update:Mi(e,Lu(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:P(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69bf315a-01aa-56d9-bd56-196d6792dea2")}catch{}})();function Ue(e,t){throw new y(e,g.USAGE,t)}var iw="2026-07-15T06:22:12.276Z",aw=Date.parse(iw),ow=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Hu=e=>typeof e=="string"?e:"",Wu=e=>{let t=e??{},n=Hu(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Hu(t.ts))>=aw);return ow[r][i]};function qu(e,t,n=20,r=new Set,i=!1){let a=[],o=[],s={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}d+=1;let h=Wu(p);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}s[h]+=1,i&&h==="actionable_unknown"&&o.push({item_id:e,line:m+1}),a.length<c&&a.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:s.legacy_unknown,actionable_unknown_event_count:s.actionable_unknown,acknowledged_actionable_event_count:u,samples:a,samples_truncated:s.legacy_unknown+s.actionable_unknown>a.length,actionable_events:o}}var zO=(e,t,n=20,r=new Set)=>qu(e,t,n,r);function Bu(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let a of i.events)typeof a=="object"&&a!==null&&typeof a.item_id=="string"&&Number.isSafeInteger(a.line)&&t.add(`${a.item_id}:${String(a.line)}`)}return t}var sr=async(e,t=20,n=!1)=>{let r=or.join(e,"history"),i;try{i=(await ar.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let a=new Set,o=[],s=[],c=0,d=0,l=0,u=0,m=0,f=0,p="_workspace.jsonl",h=new Set;if(i.includes(p))try{h=Bu(await ar.readFile(or.join(r,p),"utf8"))}catch{h=new Set}for(let w of i){let v;try{v=await ar.readFile(or.join(r,w),"utf8")}catch{continue}let E=w.slice(0,-6),k=qu(E,v,t-o.length,h,n);c+=1,d+=k.checked_events,l+=k.unknown_event_count,u+=k.legacy_unknown_event_count,m+=k.actionable_unknown_event_count,f+=k.acknowledged_actionable_event_count,k.unknown_event_count>0&&a.add(E),o.push(...k.samples),n&&s.push(...k.actionable_events)}let _=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...a].sort((w,v)=>w.localeCompare(v)),samples:o,samples_truncated:_>o.length,...n?{actionable_events:s}:{}}};function sw(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function cw(e){try{return Bu(await ar.readFile(or.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function dw(e){return(e.item_id===ce||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function lw(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Ue(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Wu(i)!=="actionable_unknown"&&Ue(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:Gu("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Vu(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Ue("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Ue("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Ue("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let a=sw(t.all_actionable===!0?(await sr(e,0,!0)).actionable_events:r),o=await cw(e),s=new Map;for(let m of a)if(dw(m)||Ue(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!s.has(m.item_id))try{s.set(m.item_id,(await ar.readFile(or.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Ue(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=a.map(m=>lw(m,o,s.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Gu("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function HO(e,t,n=50){return(await Vu(e,t,n)).plan}function uw(e,t){let n=e.length>0;return n&&t&&Ue("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&Ue("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:mw(e),all_actionable:t}}function mw(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),a=r===ce||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!a||!Number.isSafeInteger(i)||i<1)&&Ue(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function GO(e,t){let n=uw($o(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return pw(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:P(t,"planFingerprint")??P(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:P(t,"attributedAuthor")??P(t,"attributed_author")??void 0,reviewer:P(t,"reviewer"),reason:P(t,"reason")})}async function pw(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",a=await Vu(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:g.SUCCESS,plan:a.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Ue("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Ue("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==a.plan.plan_fingerprint)throw new y("Author acknowledgment selection changed after preview; no history was mutated.",g.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let o=a.completeCoordinates.filter(({disposition:l})=>a.plan.selection.kind==="events"||l==="actionable").map(({item_id:l,line:u})=>({item_id:l,line:u}));if(o.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:g.NO_EFFECT,plan:a.plan};let s=await T(e),c=await _i({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:o,attributed_author:r}},message:i,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms}),d=a.plan.actionable_count>0&&a.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:g.PARTIAL_EFFECT}:{outcome:"effect",exit_code:g.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:o.length,...d,plan:a.plan,history_path:c.historyPath}}import{execFile as fw}from"node:child_process";import Ju from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bb613e2-51f9-5947-8d92-d6207bb62cdc")}catch{}})();function Ku(e,t){return new Promise((n,r)=>{fw("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,a)=>{i?r(i):n(a)})})}function Yu(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function JO(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Yu(n),!n)throw new RangeError("Source line range must use start:end.");return n}function hw(e){let t=new Map;for(let n of e.split(`
7
- `)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function _w(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let a=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,s)=>o.localeCompare(s));n.set(i,a)}return n}async function gw(e){let t=Ju.relative(e.workspaceRoot,Ju.resolve(e.workspaceRoot,e.sourcePath)),n=await Ku(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Ku(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:hw(n),commitItems:_w(r),available:!0}}function yw(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let a=i.source===t,o=a?i.target:i.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let s=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,a?i.kind:s.inverse??i.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function ww(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let a=t.shift(),o=a.kinds.length;i!==void 0&&o>=i||o>=e.maxDepth||(i=yw({current:a,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((a,o)=>a.nodes.join("\0").localeCompare(o.nodes.join("\0"))),r}function vw(e,t,n){let r=iu(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=ww({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(s=>[s.id,s]))}),a=i[0];if(!a)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(i.map(s=>s.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:a.nodes,kinds:a.kinds,alternative_decision_ids:o.slice(1)}}async function bw(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await gw({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function kw(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function Ew(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Xu(e){Yu(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await bw(e),r=Ew(n),i=new Map;for(let a of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(a.item.id)),s=o.reduce((l,[,u])=>l+u,0),c=vw(a.item.id,e.corpus,t),d=kw({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:s,decisionStatus:c.status});i.set(a.item.id,{score:s*100+a.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(a.item.updated_at))/(720*60*60*1e3))),contribution_lines:s,evidence:[...a.files.map(l=>({kind:"linked_file",reference:l.path})),...o.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:a.item.value?.trim()||null,why_now:a.item.why_now?.trim()||null,outcome:a.item.outcome?.trim()||null,objective:a.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bee6d15d-ca4a-538c-bb70-fd3dc7e2a8ec")}catch{}})();var cr=["software-delivery","research","agent-evaluation","operations"];function Zu(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function ji(e,t,n,r,i){let a=`preset-${e}`,o=i.map(c=>({id:`${a}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),s=o.map(c=>Zu(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:s,gates:[{id:`${a}-readiness`,description:n,assertion_ids:s.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Fi(e,t){return e==="software-delivery"?ji(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?ji(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?ji(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):ji(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function Qu(e,t,n,r={}){return Io(e,Fi(t,n).declarations,r)}async function em(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(i=>!n.has(i.status))};return await Promise.all(["files","tests","docs"].map(async i=>{let a={id:`derived-active-missing-${i}`,description:`Observed active items missing ${i} evidence.`,source:{kind:"links",link:i,state:"missing"}},o=(await xo(a,r)).value,s=Zu(`${a.id}-ceiling`,a.id,t,o,"observe"),c=`active-missing-${i}`;return{id:c,population_size:r.items.length,scope:{kind:"active"},observed:o,declarations:{measurements:[a],assertions:[s],gates:[{id:`derived-${c}`,description:`Observe the accepted ${i} evidence baseline.`,assertion_ids:[s.id],triggers:["ci","scheduled"]}]}}}))}function tm(e,t,n={}){return Io(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function nm(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return Oi(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import am from"node:fs/promises";import{createRequire as Sw}from"node:module";import Oe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32adaa7c-f0aa-5aff-8d88-d7c0ccfbd971")}catch{}})();function rm(e,t){let n=Oe.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Oe.sep}`)&&!Oe.isAbsolute(n))return n.split(Oe.sep).join("/");let r=Oe.resolve(e),i=0xcbf29ce484222325n;for(let a=0;a<r.length;a+=1)i^=BigInt(r.charCodeAt(a)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Oe.basename(Oe.dirname(e))}/package.json`}function xw(e){return e.includes(`${Oe.sep}.pnpm${Oe.sep}`)?"pnpm":e.includes(`${Oe.sep}node_modules${Oe.sep}`)?"npm":"other"}async function im(e){try{let t=JSON.parse(await am.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function Oo(e){try{return await am.realpath(e)}catch{return Oe.resolve(e)}}async function om(e,t,n=Ne(import.meta.url,["../../.."])){let r=await Oo(t),i=await Oo(Oe.join(n,"package.json")),a=await im(i),o=new Map;a!==void 0&&o.set(i,{version:a,path:rm(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=Sw(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await Oo(l),m=await im(u);if(m===void 0)continue;let f=u,p=o.get(f);if(p){p.consumers.includes(d.name)||(p.consumers.push(d.name),p.consumers.sort((h,_)=>h.localeCompare(_)));continue}o.set(f,{version:m,path:rm(u,r),layout:xw(u),consumers:[d.name]})}catch{}let s=[...o.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=a===void 0?[]:s.filter(d=>d.version!==a);return{host_version:a??null,copies:s,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${a}:${d.version}:${d.consumers.join("+")}`)}}import Do from"node:fs/promises";import Po from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="069e2e60-11d9-5a37-a966-9073944d32a2")}catch{}})();var sm=8388608,Aw=new Set(["resolved","failed"]),Iw=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function No(e){return Iw.find(t=>t.matches(e))?.kind}function cm(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let a=et(i.agent_provenance)?i.agent_provenance:void 0;if(a===void 0||!cl(i).ok)return i;let o={},s=!1;for(let[d,l]of Object.entries(a)){let u=et(l)?No(l.value):void 0;if(u===void 0){o[d]=l;continue}s=!0,r+=1;let m=i.agent_harness??"unknown",f=`${m}\0${d}\0${u}`,p=t.get(f)??{harness:m,dimension:d,kind:u,count:0};p.count+=1,t.set(f,p)}if(!s)return i;n+=1;let c={...i};return Object.keys(o).length===0?delete c.agent_provenance:c.agent_provenance=o,dl(i,c,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((i,a)=>i.harness.localeCompare(a.harness)||i.dimension.localeCompare(a.dimension)||i.kind.localeCompare(a.kind))}}}async function dm(e){let t=[];for(let n of await lm(e)??[])try{let r=await Do.readFile(Po.join(e,"history",n),"utf8");for(let i of r.split(`
8
- `)){if(i.trim().length===0)continue;let a=um(i);if(!(a===null||!et(a.agent_provenance))&&Object.values(a.agent_provenance).some(o=>et(o)&&No(o.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function lm(e){try{return(await Do.readdir(Po.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function Rw(e,t,n){let r;try{r=await Do.open(Po.join(e,"history",t),"r");let i=(await r.stat()).size,a=Math.min(i,Math.max(0,n)),o=Buffer.alloc(a),{bytesRead:s}=await r.read(o,0,a,0),c=o.subarray(0,s).toString("utf8"),d=s>=i,l=c.lastIndexOf(`
9
- `),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:s,complete:d}}catch{return null}finally{await r?.close()}}function um(e){try{let t=JSON.parse(e);return et(t)?t:null}catch{return null}}function Cw(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=et(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([o,s])=>{if(!et(s))return;let c=No(s.value);if(!c)return;let d=`${r}\0${o}\0${c}`,l=n.get(d)??{harness:r,dimension:o,kind:c,count:0};l.count+=1,n.set(d,l)}),!et(e.context))return;let a=e.context.agent_provenance_outcomes;et(a)&&Object.entries(a).forEach(([o,s])=>{if(!et(s)||typeof s.resolver!="string"||!Aw.has(String(s.status)))return;let c=`${r}\0${o}\0${s.resolver}`,d=t.get(c)??{harness:r,dimension:o,resolver:s.resolver,attempts:0,successes:0};d.attempts+=1,s.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function Tw(e,t,n,r,i,a){let o=i;for(let s of e.split(`
10
- `)){if(s.trim().length===0)continue;if(o>=r)return{eventsRead:o,truncated:!0};o+=1;let c=um(s);if(c===null){a.malformed_events+=1;continue}if(typeof c.ts=="string"&&Rt(c.ts)){let d=new Date(c.ts).toISOString();(a.earliest_event_at===null||d<a.earliest_event_at)&&(a.earliest_event_at=d),(a.latest_event_at===null||d>a.latest_event_at)&&(a.latest_event_at=d)}Cw(c,t,n)}return{eventsRead:o,truncated:!1}}function $w(e,t,n){return n?[...e.filter(r=>r.attempts>0&&r.successes===0).map(r=>`provenance_resolver_zero_success:${r.harness}:${r.dimension}:${r.resolver}:${String(r.attempts)}`),...t.map(r=>`provenance_value_domain_invalid:${r.harness}:${r.dimension}:${r.kind}:${String(r.count)}`)]:[]}async function mm(e,t=1e4){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("Provenance event limit must be a non-negative safe integer.");let n={scope:"history_prefix",event_limit:t,byte_limit:sm,bytes_read:0,events_read:0,truncated:!1,unreadable_sources:0,malformed_events:0,earliest_event_at:null,latest_event_at:null,complete:!1},r=new Map,i=new Map,a=0,o=0,s=!1,c=await lm(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await Rw(e,u,Math.max(0,sm-o));if(m===null){n.unreadable_sources+=1;continue}o+=m.bytesRead;let f=Tw(m.content,r,i,t,a,n);if(a=f.eventsRead,f.truncated){s=!0;break}if(!m.complete){s=!0;break}}let d=[...r.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.resolver.localeCompare(m.resolver)),l=[...i.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.kind.localeCompare(m.kind));return n.bytes_read=o,n.events_read=a,n.truncated=s,n.complete=!s&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:d,sample:n,invalid_values:l,warnings:$w(d,l,n.complete),events_read:a,truncated:s}}import Ow from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eeaf2318-5964-5d98-ad90-9faa7fc69975")}catch{}})();function Lo(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Te(e.settings);if(n.ownership_enforcement==="strict")throw new y(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,g.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function Dw(e){let t=await V(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new y(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);let n=await ve(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?e.readItem?await e.readItem(n):await be(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new y(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function Ui(e){let t=e.writeHistoryRaw??Z;try{await t(e.historyPath,e.nextHistoryRaw),await so(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await Ow.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await so(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function pm(e){let t=[...Lo({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await te(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let r=await Dw({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(r),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await n()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6283ef18-f75e-5e8c-a65f-0ba05858bc2b")}catch{}})();async function fm(e){let{subject:t,settings:n,operation:r,options:i}=e,a=await al(t.historyPath,t.id);if(a.raw===null)throw new y(`No history stream exists for ${t.id}.`,g.NOT_FOUND);if(a.entries.length===0)throw new y(`No history entries exist for ${t.id}; nothing to ${r.slice(8)}.`,g.USAGE);let o=t.located?await be(t.located,{schema:n.schema}):null,s=W(i.author,n.author_default),c=await e.transform({raw:a.raw,entries:a.entries,verification:Yn(a.entries),loadedItem:o,author:s}),d=Yn(c.rewrittenEntries);if(!d.ok)throw new y(`${r} produced an invalid rewritten chain (${d.errors.join(", ")}).`,g.GENERIC_FAILURE);let l=c.changed&&!i.dryRun?await pm({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:a.raw,currentItemRawBeforeLock:o?.raw??null,operation:r,author:s,force:i.force,itemDocument:o?.document??null,applyRewrite:async u=>{await c.beforeWrite?.(),c.applyRewrite?await c.applyRewrite(u):await Ui({historyPath:t.historyPath,nextHistoryRaw:Bt(c.rewrittenEntries),historyRawUnderLock:u.historyRawUnderLock})},applyPostRewrite:c.afterWrite??(async()=>X({path:t.historyPath,scope:"project",op:`${r.replace("-","_")}:history`}))}):[];return c.report({verification:d,warnings: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]="d8f1968e-a030-5a3c-b766-60a409163745")}catch{}})();function zi(e,t,n=25){let r=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,s)=>o.localeCompare(s)),i=new Set(r),a=t.filter(o=>{let s=Pd(o.status,e);return s!==void 0&&i.has(s)}).map(o=>o.id).sort((o,s)=>o.localeCompare(s));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:a.length,affected_item_ids:a.slice(0,n),affected_item_ids_truncated:a.length>n}}function Hi(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}import jo from"node:fs/promises";import ue from"node:path";import Pw from"node:readline/promises";import{stdin as Nw,stdout as Gi}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a0706e-7162-5cde-9f48-c5de9b2fbd8e")}catch{}})();var PD=["ask","add","skip","status"],Lw=["AGENTS.md","CLAUDE.md"],Mw=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],jw=8,Fo=1,Fw="<!-- pm-cli:agent-guidance:start:",Uw=`<!-- pm-cli:agent-guidance:start:v${Fo} -->`,Mo="<!-- pm-cli:agent-guidance:end -->",lr="Add workflow guidance later: pm init --agent-guidance add";var zw=()=>Pw.createInterface({input:Nw,output:Gi});function Sn(e,t){let n=ue.relative(e,t);return n.length===0?ue.basename(t):n.split(ue.sep).join("/")}function hm(e){return e.endsWith(`
1
+ import{a as Ya,c as Vr,d as Kr,e as $d,g as Od,h as Za,i as Dd,j as dn,k as ln,l as Pd,m as Nd,n as Qa,o as jd,p as un,q as mn,r as Fd,s as Ud,t as eo}from"./chunk-IRVL4UXR.js";import{e as ri,f as no,h as ro}from"./chunk-TB7F4FCR.js";import{B as Kd,C as ei,D as Yd,E as to,G as Xd,H as Zd,J as Qd,K as el,L as ti,O as ni,a as xd,g as Ka,i as Ad}from"./chunk-B4YLP5ZB.js";import{K as lu}from"./chunk-L55KQ2KT.js";import{D as lo,E as vi,Fa as tu,Ga as nu,Ka as ru,La as iu,T as bi,U as Tl,V as uo,W as Xn,Y as mo,aa as Gl,ba as Wl,ca as ql,da as Bl,ea as Si,f as vl,g as bl,ga as Jl,h as kl,ha as Vl,i as El,ia as Kl,ib as su,ja as Jt,k as wi,ka as Yl,kb as ho,la as gn,lb as cu,ma as Xl,mb as du,na as po,o as Kn,oa as yn,p as Sl,pa as Zl,q as xl,qa as Ql,r as Yn,ra as eu,s as Al,sa as fo,u as co,ub as _o,v as Il,z as Rl}from"./chunk-BFEMT5U3.js";import{a as Id,b as cn,c as Xa,d as Rd,e as Cd,f as ct,g as Yr,h as Td,i as It}from"./chunk-ZDBS2DCT.js";import{$ as al,$a as yi,Aa as hl,Ab as ki,Ca as ui,Cb as Ul,D as W,Da as mi,E as tl,Ea as oo,Eb as ne,Fa as Tt,Fb as ve,Ga as Vn,Gb as be,H as Ce,Ha as _l,Hb as Hl,I as io,Ia as pi,Ib as Ei,Ja as Bt,Jb as lt,Ka as ce,Kb as ut,La as fi,Ma as gl,N as ii,Na as so,Nb as zl,O as Jn,Oa as hi,Ob as mt,P as nl,Pa as _n,Q as ai,Qa as _i,R as rl,Ra as yl,T as oi,U as si,Va as Te,W as il,X as je,Ya as wl,Za as T,_ as Ct,_a as gi,aa as ol,ac as Zn,ba as sl,bb as Cl,ca as dt,cc as xi,da as cl,ia as dl,ib as $l,ja as ao,jb as Ol,jc as au,ka as ci,la as fn,lb as Dl,mb as Pl,mc as ou,na as di,nb as $t,oa as ll,ob as Nl,pa as ul,pb as Ll,ra as ml,sb as Ml,ta as pl,ub as jl,va as fl,vb as Fl,xa as li,za as hn}from"./chunk-SEL4Z2OO.js";import{b as on,e as le,g as Le,i as Re,j as Qe,n as ge,o as Ld,p as Xr,r as Md}from"./chunk-HYPRPSYD.js";import{$ as g,$a as Bn,Bc as Hd,Ca as fe,Da as Ne,Dc as Zr,Ea as sd,Ec as zd,Fc as Gd,Ga as ee,Hb as wd,Hc as Wd,Ja as cd,Oa as dd,Pc as H,Qb as vd,S as ed,Sc as X,T as td,Ua as ld,Uc as Ge,V as nd,Va as ud,Vc as qd,Wa as G,Wc as Qr,X as rd,Y as qr,Z as id,a as Gr,aa as y,ab as L,ae as $,bb as Ye,bd as Bd,be as Vd,cb as Br,ce as pn,d as Wr,db as zt,de as Rt,ee as qt,fb as md,fc as bd,gb as Gt,gc as kd,hd as Jd,i as Xc,ia as ad,ib as pd,id as Me,jb as C,kb as fd,ke as te,l as Zc,la as od,lb as Ie,m as Qc,na as Wa,nb as Jr,ob as hd,oc as Ed,pb as qa,pc as Wt,qb as Ba,rb as Ja,rc as Va,sa as qn,sc as Sd,ta as O,tb as _d,tc as sn,ua as At,ub as gd,va as F,vc as Xe,w as Ga,wa as J,xb as yd,xc as Ze,za as Z}from"./chunk-RJ3EIHDU.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var M=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},$e=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},et=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function wn(e){try{return await e()}catch(t){throw t instanceof M?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function uu(e){try{return await e()}catch(t){throw t instanceof $e?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as cy}from"node:crypto";import dy from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var vn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="416aaf09-e4f6-5d10-aee0-eba374f1cd83")}catch{}})();var pu=1,Vt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],go=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],ly=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],uy=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Ai=30,Ii=5e3,fu=4,my=50;function pt(e,t){if(!uy.test(e))throw new M(`${t} must be a stable lowercase id`)}function py(e,t){if(!Number.isFinite(e)||e<0)throw new M(`${t} must be a finite non-negative number`)}function Qn(e){let t=ly.filter(i=>e[i]!==void 0);if(t.length!==1)throw new M(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function wo(e,t){return C(e)===C(t)}function hu(e,t){if(t.polarity==="equals")return wo(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function _u(e){let t=Qn(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>hu(r.observed,t)===(r.expected==="pass"))}function fy(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!wo(e.value,t.value)}function hy(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||C(e.scope)!==C(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return fy(Qn(e),Qn(t))||n[t.enforcement]<n[e.enforcement]||r}function _y(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new M("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new M("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new M("items source equals/state requires field")}function gy(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new M("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new M("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new M("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new M("dependency_kind source source_kind_state must be present or missing")}function yy(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new M("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new M("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new M("prose_edge_gap exemption selectors must not be empty")}}function vo(e){pt(e.id,"measurement.id"),e.max_cost!==void 0&&py(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new M(`measurement.source.kind must be one of ${go.join(", ")}`);let n=Reflect.get(t,"kind");if(!go.includes(n))throw new M(`measurement.source.kind must be one of ${go.join(", ")}`);let r=t;if(r.kind==="items"&&_y(r),r.kind==="dependency_kind"&&gy(r),r.kind==="prose_edge_gap"&&yy(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new M(`${r.kind} source requires field`);return r.kind==="provider"&&(pt(r.provider,"provider source provider"),pt(r.key,"provider source key")),e}function bo(e){if(pt(e.id,"assertion.id"),pt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new M("assertion.owner_item_id is required");let t=Qn(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new M(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new M("retired assertion requires retire_reason");e.scope.kind==="filter"&&pt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new M("assertion negative control requires pass and fail cases");if(!_u(e))throw new M(`assertion ${e.id} negative control does not prove its bound`);return e}function wy(e){if(!Array.isArray(e.allowed_providers))throw new M("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)pt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new M("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Vt.includes(t))throw new M(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new M(`gate provider policy trigger ${t} is invalid`)}}function gu(e){if(pt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new M("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new M("gate requires at least one assertion");for(let t of e.assertion_ids)pt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new M(`gate.triggers is required and must be an array of ${Vt.join(", ")}`);if(e.triggers.length===0)throw new M("gate requires at least one trigger");for(let t of e.triggers)if(!Vt.includes(t))throw new M(`gate trigger must be one of ${Vt.join(", ")}`);return e.provider_policy&&wy(e.provider_policy),e}function bn(e){if(e.version!==pu)throw new M(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(vo(r),t.has(`measurement:${r.id}`))throw new M(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(bo(r),t.has(`assertion:${r.id}`))throw new M(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){gu(r);let i=r.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(i.length>0)throw new M(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new M(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of yu(e))if(!n.has(r))throw new M(`${i.join(", ")} references missing measurement ${r}`);return e}function ko(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)ko(n,t)}function yu(e){let t=new Map,n=(r,i)=>{let a=t.get(r)??[];a.push(i),t.set(r,a)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];ko(r.source.expression,i);for(let a of i)n(a,`derived measurement ${r.id}`)}return t}function vy(e,t){let n=e.assertion_ids.flatMap(a=>{let o=t.assertions.find(s=>s.id===a);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let a=n.pop();if(r.has(a))continue;r.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?i.add(o.source.provider):o.source.kind==="derived"&&ko(o.source.expression,n)}return i}function er(){return{version:pu,measurements:[],assertions:[],gates:[]}}function by(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let a=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?a:!a}return wo(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function ky(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function Ey(e,t){let n=[],r=Wa(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let a of i.dependencies??[]){let o=Wa(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===r&&ky(e,s)&&n.push(`${i.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Sy(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let a=Reflect.get(i,"text");typeof a=="string"&&t.push(a)}}}return t}function xy(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function yo(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Ay(e){let t=new Map,n=new Set,r=[],i=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,a=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let s of o.dependencies??[])n.add(yo(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(yo(o.id,s));for(let s of Sy(o)){let c=[...s.matchAll(i)].map(d=>d[0]);a+=c.length,r.push({holder_id:o.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:a}}function Iy(e,t){let n=Ay(t.items),r=new Map;for(let o of n.prose_mentions){let s=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(s)];for(let d of c){let l=yo(o.holder_id,d);if(n.linked_pairs.has(l)||xy(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],a=i.map(o=>o.contributor).sort();return{value:a.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:a.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(o=>o.explicit).length,implicit_subject:i.filter(o=>!o.explicit).length}}}function Ry(e,t){return{value:t.history.filter(n=>(e.op===void 0||n.op===e.op)&&(e.author===void 0||n.author===e.author)&&(e.harness===void 0||n.agent_harness===e.harness)&&(e.model===void 0||n.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function Cy(e,t){let n=t.items.filter(r=>{let i=r[e.link],a=Array.isArray(i)&&i.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Ty(e,t){let n=e.source;return n.kind==="items"?by(n,t):n.kind==="dependency_kind"?Ey(n,t):n.kind==="prose_edge_gap"?Iy(n,t):n.kind==="history"?Ry(n,t):n.kind==="links"?Cy(n,t):null}function wu(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function $y(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function vu(e,t,n){let r=new Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o],o)}});return await Promise.all(a),r}async function bu(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await ku(o,t,n,r,i);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=i.charged.has(o.id)?[]:[s.cost];return i.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await vu(e.operands,fu,o=>bu(o,t,n,r,i));return{value:$y(e.operator,a.map(o=>o.value)),costs:a.flatMap(o=>o.costs),population_size:Math.max(0,...a.map(o=>o.population_size)),contributors:[...new Set(a.flatMap(o=>o.contributors))]}}async function Oy(e,t,n,r,i){vo(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await bu(e.source.expression,t,n,[...r,e.id],i);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Ty(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let d={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-a},l=wu([...s,d],Date.now()-a);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new $e(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${cy("sha256").update(C(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function ku(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let a=i.cache.get(e.id);if(a)return a;let o=Oy(e,t,n,r,i).catch(s=>{if(s instanceof et&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new et(s.message,c);throw d.cause=s,d}throw s});return i.cache.set(e.id,o),o}async function Eo(e,t,n=[e]){return ku(e,t,n,[],{cache:new Map,charged:new Set})}function Dy(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity,e-t.value)}function Py(e,t,n={}){bo(e);let r=Qn(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:Dy(t.value,r),verdict:i?"retired":hu(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:_u(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Ny(e,t,n,r){let i=vy(e,t);if(i.size===0)return;let a=e.provider_policy,o=a?.triggers[r];if(!a||!o)throw new $e(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!s.has(d))throw new $e(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new $e(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new $e(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!o.allow_network)throw new $e(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function mu(e,t,n,r,i){try{return await Eo(n,r,i)}catch(a){if(a instanceof et){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new $e(`assurance gate ${e} assertion ${t} measurement ${s} source ${a.source_kind}${o} field ${a.field} could not resolve: ${a.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}});throw c.cause=a,c}throw a}}async function Eu(e,t,n,r){bn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new $e(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new $e(`assurance gate ${e} does not declare trigger ${r.trigger}`);Ny(i,t,n,r.trigger);let a=await vu(i.assertion_ids,fu,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(v=>v.id===p),_=await mu(i.id,d.id,h,n,t.measurements),w=new Set(_.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return Py(d,await mu(i.id,d.id,l,u,t.measurements),{owner_terminal:f})}),o=a.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=a.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":s?"warn":"pass",exit_code:o?1:0,assertions:a,assertions_total:a.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:wu(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function Ri(e){return dy.join(e,"assurance.json")}async function Su(e){let t=await J(Ri(e));return t===null?er():Ci(t)}function Ci(e){try{return bn(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function Ti(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Ly(e,t){e==="measurement"?vo(t):e==="assertion"?bo(t):gu(t)}async function tr(e,t){let n=structuredClone(Ti(await Su(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function So(e,t,n){let r=Ti(await Su(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function $i(e,t,n,r={}){Ly(t,n);let i=await T(e),a=W(r.author,i.author_default),o=await _n({pmRoot:e,filePath:Ri(e),op:`assurance:${t}:put`,author:a,message:r.message,lockTtlSeconds:Ai,lockWaitMs:Ii,mutate:s=>{let c=s===null?er():Ci(s),d=Ti(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&hy(d[l],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new M(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),bn(c),{raw:`${JSON.stringify(c,null,2)}
2
+ `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function xo(e,t,n={}){let r=er();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),bn(r);let i=await T(e),a=W(n.author,i.author_default),o=await _n({pmRoot:e,filePath:Ri(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:Ai,lockWaitMs:Ii,mutate:s=>{let c=s===null?er():Ci(s),d=[],l=[],u=(m,f,p)=>{for(let h of f){let _=m.find(w=>w.id===h.id);if(!_){m.push(structuredClone(h)),d.push(`${p}:${h.id}`);continue}if(C(_)!==C(h))throw new M(`assurance bundle refuses to replace divergent ${p} ${h.id}`);l.push(`${p}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),bn(c),{raw:`${JSON.stringify(c,null,2)}
3
+ `,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function xu(e,t,n,r={}){let i=await T(e),a=W(r.author,i.author_default),o=await _n({pmRoot:e,filePath:Ri(e),op:`assurance:${t}:remove`,author:a,message:r.message,lockTtlSeconds:Ai,lockWaitMs:Ii,mutate:s=>{let c=s===null?er():Ci(s);if(t==="measurement"){let u=yu(c).get(n);if(u&&u.length>0)throw new M(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new M(`assurance assertion ${n} is referenced by gate`);let d=Ti(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new M(`assurance ${t} ${n} not found`);return d.splice(l,1),bn(c),{raw:`${JSON.stringify(c,null,2)}
4
+ `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function Au(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await T(e);await hi({pmRoot:e,op:"assurance:gate:verdict",author:W(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Ai,lockWaitMs:Ii})}async function Iu(e,t={}){let n=t.limit??my;if(!Number.isInteger(n)||n<1||n>vn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${vn}`);return(await dt(fi(e),ce)).reverse().filter(r=>r.op==="assurance:gate:verdict").map(r=>r.context?.assurance_verdict).filter(r=>typeof r=="object"&&r!==null&&"gate_id"in r).filter(r=>t.gate_id===void 0||r.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var nr={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Oi={type:"array",minItems:1,maxItems:qa,items:nr},Ru={...Oi,items:{...nr,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},My={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Oi])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:nr,id:nr}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Ru}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Oi}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Ru,authors:Oi}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:qa,items:{type:"array",minItems:2,maxItems:2,items:nr}}}}]}}},b$={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:hd,items:My}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function Cu(e,t,n,r){let i=await $t(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Tu(i,t,n,r)}function jy(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Tu(e,t,n=5,r=!1){let i=[],a=new Map,o=e.policies.filter(_=>_.rule.kind==="require_fields"),s=o.filter(_=>_.subject?.operations===void 0),c=new Set,d=0,l=0,u=0,m=0,f=0,p=yd(e);for(let _ of t){let w=p({operation:"",author:"",before:_,after:_,completeness_only:!0});d+=+(w.decisions.length>0),l+=w.decisions.length,w.decisions.forEach(k=>c.add(k.policy_id));let v=w.decisions.filter(k=>!k.satisfied);if(v.length===0)continue;m+=1;let E=a.get(_.type)??{items:0,violations:0,missing_fields:0};E.items+=1;for(let k of v)u+=1,E.violations+=1,E.missing_fields+=k.missing_fields.length,k.effect==="refuse"&&(f+=1),i.length<n&&i.push({id:_.id,type:_.type,status:_.status,decision:k});a.set(_.type,E)}let h=r||f>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:h,ok:h==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:l,governed_items:d,ungoverned_items:t.length-d,contract_status:jy(o.length,t.length,d),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:u,refused_violations:f,missing_by_type:Object.fromEntries(a),violations:i,violations_truncated:i.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}import Fy from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function Uy(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function Du(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new y("Policy definition must be valid JSON.",g.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("Policy definition must be an object.",g.USAGE);return t}async function Hy(e,t){let n=L(process.cwd(),e.path);await ne(n);let r=await T(n);return{pmRoot:n,settings:r,author:W(t,r.author_default)}}function $u(e,t,n,r){if(e==="policy-mode")return Ja({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let a=Ba(r.definition),o=Ja({...n,policies:[...i,a].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
5
+ `)>Dl)throw new y("Policy registry exceeds its byte ceiling.",g.USAGE);return o}async function Ou(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:$u(e,t,await $t(r.pmRoot),n)};let i=await _n({pmRoot:r.pmRoot,filePath:Fy.join(r.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:r.author,message:n.message,lockTtlSeconds:r.settings.locks.ttl_seconds,lockWaitMs:r.settings.locks.wait_ms,mutate(a){let o=$u(e,t,Pl(a),n);return{raw:`${JSON.stringify(o,null,2)}
6
+ `,result:o}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function zy(e,t,n){let r,i=await zl({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(a){let o=(await $t(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!o||o.rule.kind!=="approval")throw new y("--policy must name an approval rule.",g.USAGE);if(!o.rule.authors.includes(n.author))throw new y("This actor is not a declared approver.",g.CONFLICT);return await Nl(n.pmRoot,a.metadata.id),r={policy_id:o.id,policy_fingerprint:_d(o),content_fingerprint:gd(o,{...a.metadata,body:a.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...r,warnings:i.warnings}}}function Gy(e,t){let n=Du(t),r=Ba({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==r.id)throw new y("Policy id operand does not match definition.id.",g.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return r}async function H$(e,t,n={},r={}){if(!Jr.includes(e))throw new y("Unknown workflow policy action.",g.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:Uy()};let i=await Hy(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await $t(i.pmRoot)};if(e==="policy-put"){let l=Gy(t,n.definition);return Ou(e,l.id,{...n,definition:l},i)}if(!t?.trim())throw new y(`schema ${e} requires an operand.`,g.USAGE);if(["policy-remove","policy-mode"].includes(e))return Ou(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new y("Use policy-check to preview; policy-approve records an approval.",g.USAGE);return zy(t,n,i)}let a=G(i.settings,H()),o=await ve(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,a.type_to_folder);if(!o)throw new y(`Item ${t} not found.`,g.NOT_FOUND);let{document:s}=await be(o,{schema:i.settings.schema}),c={...s.metadata,body:s.body},d=n.definition===void 0?c:{...c,...Du(n.definition)};if(d.id!==c.id)throw new y("Policy preview cannot change the item id.",g.USAGE);return{policy_result:!0,action:e,changed:!1,result:await Ll(i.pmRoot,await $t(i.pmRoot),{operation:"update",author:i.author,before:c,after:d,completeness_only:n.definition===void 0})}}import{createHash as qu}from"node:crypto";import rr from"node:fs/promises";import ir from"node:path";import{Option as dO}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="201134b5-01e8-55ae-a099-137b9b6fae92")}catch{}})();function ft(e,t,n){if(typeof n!="string")return;let r=n.trim();r.length!==0&&e.push(t,r)}function Fe(e,t,n){n===!0&&e.push(t)}function Kt(e,t,n){if(Array.isArray(n))for(let r of n){if(typeof r!="string")continue;let i=r.trim();i.length!==0&&e.push(t,i)}}function Wy(e,t){let n=["test",e,"--run","--json","--progress"];return Kt(n,"--add",t.add),Kt(n,"--add-json",t.addJson),Kt(n,"--remove",t.remove),Kt(n,"--remove-index",Array.isArray(t.removeIndex)?t.removeIndex.map(r=>typeof r=="number"?String(r):r):t.removeIndex),ft(n,"--match",t.match),ft(n,"--only-index",typeof t.onlyIndex=="number"?String(t.onlyIndex):t.onlyIndex),Fe(n,"--only-last",t.onlyLast),Kt(n,"--measure",t.measure),ft(n,"--metric-below",t.metricBelow),ft(n,"--metric-diff",t.metricDiff),qy(n,t),ft(n,"--author",t.author),ft(n,"--message",t.message),Fe(n,"--force",t.force),n}function qy(e,t){ft(e,"--timeout",t.timeout),Kt(e,"--env-set",t.envSet),Kt(e,"--env-clear",t.envClear),Fe(e,"--shared-host-safe",t.sharedHostSafe),ft(e,"--pm-context",t.pmContext),Fe(e,"--override-linked-pm-context",t.overrideLinkedPmContext),ft(e,"--workspace-context",t.workspaceContext),Fe(e,"--override-linked-workspace-context",t.overrideLinkedWorkspaceContext),Fe(e,"--allow-untrusted-linked-tests",t.allowUntrustedLinkedTests),Fe(e,"--fail-on-context-mismatch",t.failOnContextMismatch),Fe(e,"--fail-on-skipped",t.failOnSkipped),Fe(e,"--fail-on-empty-test-run",t.failOnEmptyTestRun),Fe(e,"--require-assertions-for-pm",t.requireAssertionsForPm),Fe(e,"--check-context",t.checkContext),Fe(e,"--auto-pm-context",t.autoPmContext)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f71d68b8-a4cd-5fda-83a0-0528ac44aed0")}catch{}})();function By(e,t){let n=[],r=new Set;for(let i of t.keys){if(!Object.hasOwn(e,i))continue;let a=e[i];if(a!=null){if(typeof a=="string"){n.push(a);continue}if(!Array.isArray(a)||!a.every(o=>typeof o=="string"))return;r.has(a)||(r.add(a),n.push(...a))}}return n.length>0?n.join("; "):void 0}function Di(e,t){return e.find(n=>n.target===t)??{target:t,keys:[t]}}function U(e,t){return e[t]===!0?!0:void 0}function ht(e,t){return e[t]===!1?!0:void 0}function Pu(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Nu(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function Lu(e){let t=i=>Ka(e,Di(ri,i)),n=i=>Ad(e,Di(no,i)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:By(e,Di(no,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),allowUnresolvedDeps:Pu(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:U(e,"replaceDeps"),replaceTests:U(e,"replaceTests"),replaceFiles:U(e,"replaceFiles"),replaceDocs:U(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:U(e,"clearDeps"),clearComments:U(e,"clearComments"),clearNotes:U(e,"clearNotes"),clearLearnings:U(e,"clearLearnings"),clearFiles:U(e,"clearFiles"),clearTests:U(e,"clearTests"),clearDocs:U(e,"clearDocs"),clearReminders:U(e,"clearReminders"),clearEvents:U(e,"clearEvents"),clearTypeOptions:U(e,"clearTypeOptions")};return Nu(r,e),r}function ie(e,t){let n=Di(xd,t),r=Ka(e,n);if(r!==void 0)return r;for(let i of n.keys){let a=e[i];if(Array.isArray(a)){let o=a.filter(s=>typeof s=="string");if(o.length>0)return o.join(",")}if(t==="ids"&&typeof a=="string")return a;if(typeof a=="number"&&Number.isFinite(a))return String(a)}}function Jy(e){let t=U(e,"filterFilesMissing"),n=U(e,"filterDocsMissing");return{filterReviewerMissing:U(e,"filterReviewerMissing"),filterRiskMissing:U(e,"filterRiskMissing"),filterConfidenceMissing:U(e,"filterConfidenceMissing"),filterSprintMissing:U(e,"filterSprintMissing"),filterReleaseMissing:U(e,"filterReleaseMissing"),hasNotes:U(e,"hasNotes"),hasLearnings:U(e,"hasLearnings"),hasFiles:U(e,"hasFiles"),hasDocs:U(e,"hasDocs"),hasTests:U(e,"hasTests"),hasComments:U(e,"hasComments"),hasDeps:U(e,"hasDeps"),hasBody:U(e,"hasBody"),hasLinkedCommand:U(e,"hasLinkedCommand"),noNotes:ht(e,"notes"),noLearnings:ht(e,"learnings"),noFiles:ht(e,"files")??t,filterFilesMissing:t,noDocs:ht(e,"docs")??n,filterDocsMissing:n,noTests:ht(e,"tests"),noComments:ht(e,"comments"),noDeps:ht(e,"deps"),emptyBody:U(e,"emptyBody"),noLinkedCommand:ht(e,"linkedCommand")}}function Mu(e){let t={status:ie(e,"status"),type:ie(e,"type"),tag:ie(e,"tag"),priority:ie(e,"priority"),deadlineBefore:ie(e,"deadlineBefore"),deadlineAfter:ie(e,"deadlineAfter"),updatedAfter:ie(e,"updatedAfter"),updatedBefore:ie(e,"updatedBefore"),createdAfter:ie(e,"createdAfter"),createdBefore:ie(e,"createdBefore"),today:U(e,"today"),recent:U(e,"recent"),ids:ie(e,"ids"),assignee:ie(e,"assignee"),assigneeFilter:ie(e,"assigneeFilter"),parent:ie(e,"parent"),sprint:ie(e,"sprint"),release:ie(e,"release"),limit:ie(e,"limit"),offset:ie(e,"offset"),noTruncate:ht(e,"truncate"),includeBody:U(e,"includeBody"),strictRead:U(e,"strictRead"),compact:U(e,"compact"),brief:U(e,"brief"),full:U(e,"full"),fields:ie(e,"fields"),sort:ie(e,"sort"),order:ie(e,"order"),tree:U(e,"tree"),treeDepth:ie(e,"treeDepth"),filterAcMissing:U(e,"filterAcMissing"),filterEstimatesMissing:Pu(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:U(e,"filterResolutionMissing"),filterMetadataMissing:U(e,"filterMetadataMissing"),...Jy(e)};return Nu(t,e),t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f604cc2-c8cd-5c15-8fec-2243f64ef7d2")}catch{}})();var Vy=Symbol("pm.mcp-mutation-transport"),Ky=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function Ni(e){return Vy in e}function Li(e,t){return Ni(e)?Al(t):co(e,t)}function kO(e,t,n=[]){let r=co(e,{...e,...t});for(let i of n)Reflect.deleteProperty(r,i);return r}function P(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function oe(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function EO(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function kn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ro(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new y(`${t} must be a finite integer.`,g.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new y(`${t} must be a finite integer.`,g.USAGE);return n}}function SO(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:P(e,"limit")??P(t,"limit")}function xO(e){let t=P(e,"outputFormat");return{json:!0,quiet:!0,author:P(e,"author"),path:P(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:P(e,"outputInclude"),outputLimit:oe(e,"outputLimit"),outputBudget:oe(e,"outputBudget"),outputSession:P(e,"outputSession"),outputCursor:P(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Yy=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Fu=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),Xy=new Set([...Fu].filter(e=>e!=="file")),Zy=new Set(["files","files-discover","docs","test","test-all"]),Uu=new Set(["comments","notes","learnings"]);function Qy(e,t){if(!(!Uu.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new y(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,g.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var ew=new Set(["claim","release","start-task","pause-task","close-task"]),tw={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause","handoff"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun","offline"],package:["dryRun","offline"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},nw=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Hu(e,t=""){let n={},r=Zy.has(t),i=t==="files"||t==="files-discover"||t==="docs",a=Uu.has(t)?Xy:Fu;for(let[o,s]of Object.entries(e)){if(Array.isArray(s)&&Yy.has(o)){n[o]=s.join(",");continue}if(o==="note"&&i){n[o]=s;continue}if(typeof s=="string"&&a.has(o)){n[o]=[s];continue}if(typeof s=="string"&&r&&(o==="add"||o==="remove")){n[o]=[s];continue}n[o]=s}return Object.assign(n,Object.fromEntries(Object.getOwnPropertySymbols(e).map(o=>[o,Reflect.get(e,o)]))),n}function rw(e,t,n){let r=P(e,"author");return r!==void 0?r:n!==void 0&&ew.has(n)?P(e,"assignee")??P(t,"assignee"):void 0}function iw(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function AO(e,t){let n=kn(e.options)?e.options:void 0,r=dd(e.options),i={},a=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of tw[t??""]??[])a(c);for(let c of nw)a(c);t!==void 0&&Ni(e)&&Qy(t,r);let o=Hu({...i,...r},t);if(t==="history-attest"&&Ni(e)&&(o.output!==void 0||typeof o.verify=="string"))throw new y("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",g.USAGE);let s=Ni(e)?e:n??e;return Li(s,iw(o,rw(e,o,t)))}function IO(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function RO(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function aw(e){let t=[],n=!0;for(let r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function CO(e){return!Ky.has(aw(e))}function TO(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function Co(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function $O(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[a,o]of Object.entries(e))n.has(a)||(r[a]=o);let i={...r,...t};return delete i.args,i}function OO(e,t){let n=Li(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function Io(e){return{type:oe(e,"filterType"),tag:oe(e,"filterTag"),priority:oe(e,"filterPriority"),deadlineBefore:oe(e,"filterDeadlineBefore"),deadlineAfter:oe(e,"filterDeadlineAfter"),updatedAfter:oe(e,"filterUpdatedAfter"),updatedBefore:oe(e,"filterUpdatedBefore"),createdAfter:oe(e,"filterCreatedAfter"),createdBefore:oe(e,"filterCreatedBefore"),ids:lo(e.ids),assignee:oe(e,"filterAssignee"),assigneeFilter:oe(e,"filterAssigneeFilter")??oe(e,"filterAssignee_filter"),parent:oe(e,"filterParent"),sprint:oe(e,"filterSprint"),release:oe(e,"filterRelease"),limit:oe(e,"limit"),offset:oe(e,"offset")}}function Ao(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return Co(e)}function Pi(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function DO(e){let t=Ao(e.kind),n=Ao(e.exemptIsolate),r=Ao(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Pi(e.maxDepth),limit:Pi(e.limit),after:P(e,"after"),direction:P(e,"direction"),maxPaths:Pi(e.maxPaths),sample:Pi(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function zu(e){let t=Mu(e);return e.ids!==void 0&&(t.ids=lo(e.ids)),t}function PO(e){return{status:P(e,"filterStatus"),list:kn(e.list)?zu(e.list):Io(e),reason:P(e,"reason"),resolution:P(e,"resolution"),expectedResult:P(e,"expectedResult")??P(e,"expected_result")??P(e,"expected"),actualResult:P(e,"actualResult")??P(e,"actual_result")??P(e,"actual"),validateClose:P(e,"validateClose")??P(e,"validate_close"),author:P(e,"author"),message:P(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:P(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var ow=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function ju(e){let t={};for(let[n,r]of Object.entries(e))ow.has(n)||(t[n]=r);return Gu(t)}function Gu(e){let t=Hu(e,"update-many");for(let n of ri)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return Lu(t)}function NO(e){if(kn(e.list)||kn(e.update)){let t=kn(e.update)?e.update:ju(e),n=Li(e,Gu(t));return{status:oe(e,"filterStatus"),list:kn(e.list)?zu(e.list):Io(e),update:Il(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:P(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:oe(e,"filterStatus"),list:Io(e),update:Li(e,ju(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:P(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69bf315a-01aa-56d9-bd56-196d6792dea2")}catch{}})();function Ue(e,t){throw new y(e,g.USAGE,t)}var sw="2026-07-15T06:22:12.276Z",cw=Date.parse(sw),dw=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Wu=e=>typeof e=="string"?e:"",Bu=e=>{let t=e??{},n=Wu(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Wu(t.ts))>=cw);return dw[r][i]};function Ju(e,t,n=20,r=new Set,i=!1){let a=[],o=[],s={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}d+=1;let h=Bu(p);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}s[h]+=1,i&&h==="actionable_unknown"&&o.push({item_id:e,line:m+1}),a.length<c&&a.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:s.legacy_unknown,actionable_unknown_event_count:s.actionable_unknown,acknowledged_actionable_event_count:u,samples:a,samples_truncated:s.legacy_unknown+s.actionable_unknown>a.length,actionable_events:o}}var qO=(e,t,n=20,r=new Set)=>Ju(e,t,n,r);function Vu(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let a of i.events)typeof a=="object"&&a!==null&&typeof a.item_id=="string"&&Number.isSafeInteger(a.line)&&t.add(`${a.item_id}:${String(a.line)}`)}return t}var ar=async(e,t=20,n=!1)=>{let r=ir.join(e,"history"),i;try{i=(await rr.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let a=new Set,o=[],s=[],c=0,d=0,l=0,u=0,m=0,f=0,p="_workspace.jsonl",h=new Set;if(i.includes(p))try{h=Vu(await rr.readFile(ir.join(r,p),"utf8"))}catch{h=new Set}for(let w of i){let v;try{v=await rr.readFile(ir.join(r,w),"utf8")}catch{continue}let E=w.slice(0,-6),k=Ju(E,v,t-o.length,h,n);c+=1,d+=k.checked_events,l+=k.unknown_event_count,u+=k.legacy_unknown_event_count,m+=k.actionable_unknown_event_count,f+=k.acknowledged_actionable_event_count,k.unknown_event_count>0&&a.add(E),o.push(...k.samples),n&&s.push(...k.actionable_events)}let _=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...a].sort((w,v)=>w.localeCompare(v)),samples:o,samples_truncated:_>o.length,...n?{actionable_events:s}:{}}};function lw(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function uw(e){try{return Vu(await rr.readFile(ir.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function mw(e){return(e.item_id===ce||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function pw(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Ue(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Bu(i)!=="actionable_unknown"&&Ue(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:qu("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Ku(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Ue("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Ue("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Ue("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let a=lw(t.all_actionable===!0?(await ar(e,0,!0)).actionable_events:r),o=await uw(e),s=new Map;for(let m of a)if(mw(m)||Ue(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!s.has(m.item_id))try{s.set(m.item_id,(await rr.readFile(ir.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Ue(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=a.map(m=>pw(m,o,s.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=qu("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function BO(e,t,n=50){return(await Ku(e,t,n)).plan}function fw(e,t){let n=e.length>0;return n&&t&&Ue("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&Ue("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:hw(e),all_actionable:t}}function hw(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),a=r===ce||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!a||!Number.isSafeInteger(i)||i<1)&&Ue(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function JO(e,t){let n=fw(Co(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return _w(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:P(t,"planFingerprint")??P(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:P(t,"attributedAuthor")??P(t,"attributed_author")??void 0,reviewer:P(t,"reviewer"),reason:P(t,"reason")})}async function _w(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",a=await Ku(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:g.SUCCESS,plan:a.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Ue("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Ue("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==a.plan.plan_fingerprint)throw new y("Author acknowledgment selection changed after preview; no history was mutated.",g.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let o=a.completeCoordinates.filter(({disposition:l})=>a.plan.selection.kind==="events"||l==="actionable").map(({item_id:l,line:u})=>({item_id:l,line:u}));if(o.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:g.NO_EFFECT,plan:a.plan};let s=await T(e),c=await hi({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:o,attributed_author:r}},message:i,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms}),d=a.plan.actionable_count>0&&a.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:g.PARTIAL_EFFECT}:{outcome:"effect",exit_code:g.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:o.length,...d,plan:a.plan,history_path:c.historyPath}}import{execFile as gw}from"node:child_process";import Yu from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bb613e2-51f9-5947-8d92-d6207bb62cdc")}catch{}})();function Xu(e,t){return new Promise((n,r)=>{gw("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,a)=>{i?r(i):n(a)})})}function Zu(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function ZO(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Zu(n),!n)throw new RangeError("Source line range must use start:end.");return n}function yw(e){let t=new Map;for(let n of e.split(`
7
+ `)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function ww(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let a=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,s)=>o.localeCompare(s));n.set(i,a)}return n}async function vw(e){let t=Yu.relative(e.workspaceRoot,Yu.resolve(e.workspaceRoot,e.sourcePath)),n=await Xu(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Xu(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:yw(n),commitItems:ww(r),available:!0}}function bw(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let a=i.source===t,o=a?i.target:i.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let s=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,a?i.kind:s.inverse??i.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function kw(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let a=t.shift(),o=a.kinds.length;i!==void 0&&o>=i||o>=e.maxDepth||(i=bw({current:a,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((a,o)=>a.nodes.join("\0").localeCompare(o.nodes.join("\0"))),r}function Ew(e,t,n){let r=ou(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=kw({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(s=>[s.id,s]))}),a=i[0];if(!a)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(i.map(s=>s.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:a.nodes,kinds:a.kinds,alternative_decision_ids:o.slice(1)}}async function Sw(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await vw({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function xw(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function Aw(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Qu(e){Zu(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await Sw(e),r=Aw(n),i=new Map;for(let a of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(a.item.id)),s=o.reduce((l,[,u])=>l+u,0),c=Ew(a.item.id,e.corpus,t),d=xw({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:s,decisionStatus:c.status});i.set(a.item.id,{score:s*100+a.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(a.item.updated_at))/(720*60*60*1e3))),contribution_lines:s,evidence:[...a.files.map(l=>({kind:"linked_file",reference:l.path})),...o.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:a.item.value?.trim()||null,why_now:a.item.why_now?.trim()||null,outcome:a.item.outcome?.trim()||null,objective:a.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bee6d15d-ca4a-538c-bb70-fd3dc7e2a8ec")}catch{}})();var or=["software-delivery","research","agent-evaluation","operations"];function em(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function Mi(e,t,n,r,i){let a=`preset-${e}`,o=i.map(c=>({id:`${a}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),s=o.map(c=>em(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:s,gates:[{id:`${a}-readiness`,description:n,assertion_ids:s.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function ji(e,t){return e==="software-delivery"?Mi(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Mi(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Mi(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Mi(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function tm(e,t,n,r={}){return xo(e,ji(t,n).declarations,r)}async function nm(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(i=>!n.has(i.status))};return await Promise.all(["files","tests","docs"].map(async i=>{let a={id:`derived-active-missing-${i}`,description:`Observed active items missing ${i} evidence.`,source:{kind:"links",link:i,state:"missing"}},o=(await Eo(a,r)).value,s=em(`${a.id}-ceiling`,a.id,t,o,"observe"),c=`active-missing-${i}`;return{id:c,population_size:r.items.length,scope:{kind:"active"},observed:o,declarations:{measurements:[a],assertions:[s],gates:[{id:`derived-${c}`,description:`Observe the accepted ${i} evidence baseline.`,assertion_ids:[s.id],triggers:["ci","scheduled"]}]}}}))}function rm(e,t,n={}){return xo(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function im(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return $i(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import sm from"node:fs/promises";import{createRequire as Iw}from"node:module";import Oe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32adaa7c-f0aa-5aff-8d88-d7c0ccfbd971")}catch{}})();function am(e,t){let n=Oe.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Oe.sep}`)&&!Oe.isAbsolute(n))return n.split(Oe.sep).join("/");let r=Oe.resolve(e),i=0xcbf29ce484222325n;for(let a=0;a<r.length;a+=1)i^=BigInt(r.charCodeAt(a)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Oe.basename(Oe.dirname(e))}/package.json`}function Rw(e){return e.includes(`${Oe.sep}.pnpm${Oe.sep}`)?"pnpm":e.includes(`${Oe.sep}node_modules${Oe.sep}`)?"npm":"other"}async function om(e){try{let t=JSON.parse(await sm.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function To(e){try{return await sm.realpath(e)}catch{return Oe.resolve(e)}}async function cm(e,t,n=Ne(import.meta.url,["../../.."])){let r=await To(t),i=await To(Oe.join(n,"package.json")),a=await om(i),o=new Map;a!==void 0&&o.set(i,{version:a,path:am(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=Iw(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await To(l),m=await om(u);if(m===void 0)continue;let f=u,p=o.get(f);if(p){p.consumers.includes(d.name)||(p.consumers.push(d.name),p.consumers.sort((h,_)=>h.localeCompare(_)));continue}o.set(f,{version:m,path:am(u,r),layout:Rw(u),consumers:[d.name]})}catch{}let s=[...o.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=a===void 0?[]:s.filter(d=>d.version!==a);return{host_version:a??null,copies:s,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${a}:${d.version}:${d.consumers.join("+")}`)}}import $o from"node:fs/promises";import Oo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="069e2e60-11d9-5a37-a966-9073944d32a2")}catch{}})();var dm=8388608,Cw=new Set(["resolved","failed"]),Tw=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Do(e){return Tw.find(t=>t.matches(e))?.kind}function lm(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let a=tt(i.agent_provenance)?i.agent_provenance:void 0;if(a===void 0||!ll(i).ok)return i;let o={},s=!1;for(let[d,l]of Object.entries(a)){let u=tt(l)?Do(l.value):void 0;if(u===void 0){o[d]=l;continue}s=!0,r+=1;let m=i.agent_harness??"unknown",f=`${m}\0${d}\0${u}`,p=t.get(f)??{harness:m,dimension:d,kind:u,count:0};p.count+=1,t.set(f,p)}if(!s)return i;n+=1;let c={...i};return Object.keys(o).length===0?delete c.agent_provenance:c.agent_provenance=o,ul(i,c,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((i,a)=>i.harness.localeCompare(a.harness)||i.dimension.localeCompare(a.dimension)||i.kind.localeCompare(a.kind))}}}async function um(e){let t=[];for(let n of await mm(e)??[])try{let r=await $o.readFile(Oo.join(e,"history",n),"utf8");for(let i of r.split(`
8
+ `)){if(i.trim().length===0)continue;let a=pm(i);if(!(a===null||!tt(a.agent_provenance))&&Object.values(a.agent_provenance).some(o=>tt(o)&&Do(o.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function mm(e){try{return(await $o.readdir(Oo.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function $w(e,t,n){let r;try{r=await $o.open(Oo.join(e,"history",t),"r");let i=(await r.stat()).size,a=Math.min(i,Math.max(0,n)),o=Buffer.alloc(a),{bytesRead:s}=await r.read(o,0,a,0),c=o.subarray(0,s).toString("utf8"),d=s>=i,l=c.lastIndexOf(`
9
+ `),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:s,complete:d}}catch{return null}finally{await r?.close()}}function pm(e){try{let t=JSON.parse(e);return tt(t)?t:null}catch{return null}}function Ow(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=tt(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([o,s])=>{if(!tt(s))return;let c=Do(s.value);if(!c)return;let d=`${r}\0${o}\0${c}`,l=n.get(d)??{harness:r,dimension:o,kind:c,count:0};l.count+=1,n.set(d,l)}),!tt(e.context))return;let a=e.context.agent_provenance_outcomes;tt(a)&&Object.entries(a).forEach(([o,s])=>{if(!tt(s)||typeof s.resolver!="string"||!Cw.has(String(s.status)))return;let c=`${r}\0${o}\0${s.resolver}`,d=t.get(c)??{harness:r,dimension:o,resolver:s.resolver,attempts:0,successes:0};d.attempts+=1,s.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function Dw(e,t,n,r,i,a){let o=i;for(let s of e.split(`
10
+ `)){if(s.trim().length===0)continue;if(o>=r)return{eventsRead:o,truncated:!0};o+=1;let c=pm(s);if(c===null){a.malformed_events+=1;continue}if(typeof c.ts=="string"&&Rt(c.ts)){let d=new Date(c.ts).toISOString();(a.earliest_event_at===null||d<a.earliest_event_at)&&(a.earliest_event_at=d),(a.latest_event_at===null||d>a.latest_event_at)&&(a.latest_event_at=d)}Ow(c,t,n)}return{eventsRead:o,truncated:!1}}function Pw(e,t,n){return n?[...e.filter(r=>r.attempts>0&&r.successes===0).map(r=>`provenance_resolver_zero_success:${r.harness}:${r.dimension}:${r.resolver}:${String(r.attempts)}`),...t.map(r=>`provenance_value_domain_invalid:${r.harness}:${r.dimension}:${r.kind}:${String(r.count)}`)]:[]}async function fm(e,t=1e4){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("Provenance event limit must be a non-negative safe integer.");let n={scope:"history_prefix",event_limit:t,byte_limit:dm,bytes_read:0,events_read:0,truncated:!1,unreadable_sources:0,malformed_events:0,earliest_event_at:null,latest_event_at:null,complete:!1},r=new Map,i=new Map,a=0,o=0,s=!1,c=await mm(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await $w(e,u,Math.max(0,dm-o));if(m===null){n.unreadable_sources+=1;continue}o+=m.bytesRead;let f=Dw(m.content,r,i,t,a,n);if(a=f.eventsRead,f.truncated){s=!0;break}if(!m.complete){s=!0;break}}let d=[...r.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.resolver.localeCompare(m.resolver)),l=[...i.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.kind.localeCompare(m.kind));return n.bytes_read=o,n.events_read=a,n.truncated=s,n.complete=!s&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:d,sample:n,invalid_values:l,warnings:Pw(d,l,n.complete),events_read:a,truncated:s}}import Nw from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eeaf2318-5964-5d98-ad90-9faa7fc69975")}catch{}})();function Po(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Te(e.settings);if(n.ownership_enforcement==="strict")throw new y(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,g.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function Lw(e){let t=await J(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new y(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);let n=await ve(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?e.readItem?await e.readItem(n):await be(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new y(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function Fi(e){let t=e.writeHistoryRaw??Z;try{await t(e.historyPath,e.nextHistoryRaw),await ao(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await Nw.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await ao(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function hm(e){let t=[...Po({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await te(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let r=await Lw({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(r),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await n()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6283ef18-f75e-5e8c-a65f-0ba05858bc2b")}catch{}})();async function _m(e){let{subject:t,settings:n,operation:r,options:i}=e,a=await sl(t.historyPath,t.id);if(a.raw===null)throw new y(`No history stream exists for ${t.id}.`,g.NOT_FOUND);if(a.entries.length===0)throw new y(`No history entries exist for ${t.id}; nothing to ${r.slice(8)}.`,g.USAGE);let o=t.located?await be(t.located,{schema:n.schema}):null,s=W(i.author,n.author_default),c=await e.transform({raw:a.raw,entries:a.entries,verification:Vn(a.entries),loadedItem:o,author:s}),d=Vn(c.rewrittenEntries);if(!d.ok)throw new y(`${r} produced an invalid rewritten chain (${d.errors.join(", ")}).`,g.GENERIC_FAILURE);let l=c.changed&&!i.dryRun?await hm({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:a.raw,currentItemRawBeforeLock:o?.raw??null,operation:r,author:s,force:i.force,itemDocument:o?.document??null,applyRewrite:async u=>{await c.beforeWrite?.(),c.applyRewrite?await c.applyRewrite(u):await Fi({historyPath:t.historyPath,nextHistoryRaw:Bt(c.rewrittenEntries),historyRawUnderLock:u.historyRawUnderLock})},applyPostRewrite:c.afterWrite??(async()=>X({path:t.historyPath,scope:"project",op:`${r.replace("-","_")}:history`}))}):[];return c.report({verification:d,warnings: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]="d8f1968e-a030-5a3c-b766-60a409163745")}catch{}})();function Ui(e,t,n=25){let r=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,s)=>o.localeCompare(s)),i=new Set(r),a=t.filter(o=>{let s=Ld(o.status,e);return s!==void 0&&i.has(s)}).map(o=>o.id).sort((o,s)=>o.localeCompare(s));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:a.length,affected_item_ids:a.slice(0,n),affected_item_ids_truncated:a.length>n}}function Hi(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="717434ef-3c62-50a8-8887-e2bbc3851eff")}catch{}})();var ym=8,No=100;function wm(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function We(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function Mw(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function sr(e,t){let n=We(e,t);return{...n,sample:n.sample.map(r=>Mw(r))}}function q(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function jw(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var Fw={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:q(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:q(e.missing_required,t),missing_optional:q(e.missing_optional,t),missing:q(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:q(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:sr(e.discovered,t),effective:sr(e.effective,t),loaded:sr(e.loaded,t),failed:We(e.failed,t),warnings:q(e.warnings,t),activation:{failed:We(n.failed,t),warnings:q(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:jw(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:We(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:q(n.affected_item_ids,t),samples:We(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:q(e.item_unreadable,t),item_conflict_markers:We(e.item_conflict_markers,t),item_parse_failures:q(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:q(n.tracked_paths,t)},history_unreadable:q(e.history_unreadable,t),history_conflict_markers:We(e.history_conflict_markers,t),history_invalid_json:We(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:q(n.candidate_items,t),confirmed_items:q(n.confirmed_items,t),resolved_false_positive_items:q(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:q(e.drifted_items,t),merge_receipt_attributed_items:q(e.merge_receipt_attributed_items,t),missing_streams:q(e.missing_streams,t),unreadable_streams:q(e.unreadable_streams,t),hash_mismatches:q(e.hash_mismatches,t),chain_mismatches:q(e.chain_mismatches,t),version_skews:q(e.version_skews,t),workspace_state_mismatches:q(e.workspace_state_mismatches,t),workspace_state_missing:q(e.workspace_state_missing,t),workspace_state_unreadable:q(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:q(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:q(e.stale_items_after,t),skipped:e.skipped})};function Lo(e,t){let n=Fw[e.name];return n?n(e.details,t):e.details}function vm(e){return{disabled_by_flag:e.details.disabled_by_flag,loaded_count:Array.isArray(e.details.loaded)?e.details.loaded.length:0,failed_count:0,warning_count:0,restore_with:"pm health --full"}}function Uw(e){if(e.name==="extensions"&&e.status==="ok")return vm(e);let t=Lo(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function Mo(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(r=>n.has(r.warning))}function Hw(e){let t=q(e.warnings,8);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:Uw(n)})),warnings:t.sample,findings:Mo(e,t.sample),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8},generated_at:e.generated_at}}function gm(e){return e.details.skipped===!0}function zw(e){let t=q(e.warnings,8),n=e.checks.filter(gm).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!gm(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:Mo(e,t.sample),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8,omitted_checks:n},generated_at:e.generated_at}}function Gw(e,t,n){return t.full===!0?e:n?zw(e):t.brief===!0?Hw(e):{...e,checks:e.checks.map(r=>r.name==="extensions"&&r.status==="ok"?{...r,details:vm(r)}:r),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function jo(e,t,n){let r=e.warning_count??e.warnings.length,i=e.warnings.slice(0,100),a={...e,warning_count:r,warning_limit:100,warnings_truncated:r>100,warnings:i,findings:Mo(e,i)},o=Gw(a,t,n);return{...o,warning_count:r,warning_limit:100,warnings_truncated:r>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:r,warnings_truncated:r>o.warnings.length}}:{}}}import Uo from"node:fs/promises";import ue from"node:path";import Ww from"node:readline/promises";import{stdin as qw,stdout as zi}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a0706e-7162-5cde-9f48-c5de9b2fbd8e")}catch{}})();var FD=["ask","add","skip","status"],Bw=["AGENTS.md","CLAUDE.md"],Jw=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Vw=8,Ho=1,Kw="<!-- pm-cli:agent-guidance:start:",Yw=`<!-- pm-cli:agent-guidance:start:v${Ho} -->`,Fo="<!-- pm-cli:agent-guidance:end -->",dr="Add workflow guidance later: pm init --agent-guidance add";var Xw=()=>Ww.createInterface({input:qw,output:zi});function En(e,t){let n=ue.relative(e,t);return n.length===0?ue.basename(t):n.split(ue.sep).join("/")}function bm(e){return e.endsWith(`
11
11
  `)?e:`${e}
12
- `}function Hw(e){return e.includes(`\r
12
+ `}function Zw(e){return e.includes(`\r
13
13
  `)?`\r
14
14
  `:`
15
- `}function _m(e){let t=e.indexOf(Fw);if(t===-1)return null;let n=e.indexOf(Mo,t);return n===-1?null:{start_index:t,end_index:n+Mo.length}}function Gw(e){return _m(e)!==null}function Ww(e,t="<your project test command>"){return[Uw,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and start atomically: `pm claim <id> --start`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Mo,""].join(e)}function gm(e,t="<your project test command>"){let n=Hw(e),r=Ww(n,t),i=_m(e);if(i){let s=e.slice(i.end_index),c=s.startsWith(`\r
15
+ `}function km(e){let t=e.indexOf(Kw);if(t===-1)return null;let n=e.indexOf(Fo,t);return n===-1?null:{start_index:t,end_index:n+Fo.length}}function Qw(e){return km(e)!==null}function ev(e,t="<your project test command>"){return[Yw,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and start atomically: `pm claim <id> --start`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Fo,""].join(e)}function Em(e,t="<your project test command>"){let n=Zw(e),r=ev(n,t),i=km(e);if(i){let s=e.slice(i.end_index),c=s.startsWith(`\r
16
16
  `)?s.slice(2):s.startsWith(`
17
- `)?s.slice(1):s,d=hm(`${e.slice(0,i.start_index)}${r}${c}`);return{next_content:d,changed:d!==e}}let a=e.length===0?"":e.endsWith(`
17
+ `)?s.slice(1):s,d=bm(`${e.slice(0,i.start_index)}${r}${c}`);return{next_content:d,changed:d!==e}}let a=e.length===0?"":e.endsWith(`
18
18
  `)?`
19
19
  `:`
20
20
 
21
- `,o=hm(`${e}${a}${r}`);return{next_content:o,changed:o!==e}}async function ym(e){if(await O(ue.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await jo.readFile(ue.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=qw(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await O(ue.join(e,"pnpm-lock.yaml"))?"pnpm test":await O(ue.join(e,"bun.lock"))||await O(ue.join(e,"bun.lockb"))?"bun run test":await O(ue.join(e,"yarn.lock"))?"yarn test":"npm test"}function qw(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function Bw(e,t){let n=ue.dirname(e);return ue.basename(e)==="pm"&&ue.basename(n)===".agents"?ue.dirname(n):ue.resolve(t,e)}function Vw(e,t){let n=e.find(i=>ue.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let r=e.find(i=>i.exists);return r?r.file_path:ue.join(t,"AGENTS.md")}function Jw(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function Kw(e){let t=zw();try{Gi.write(`
21
+ `,o=bm(`${e}${a}${r}`);return{next_content:o,changed:o!==e}}async function Sm(e){if(await O(ue.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Uo.readFile(ue.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=tv(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await O(ue.join(e,"pnpm-lock.yaml"))?"pnpm test":await O(ue.join(e,"bun.lock"))||await O(ue.join(e,"bun.lockb"))?"bun run test":await O(ue.join(e,"yarn.lock"))?"yarn test":"npm test"}function tv(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function nv(e,t){let n=ue.dirname(e);return ue.basename(e)==="pm"&&ue.basename(n)===".agents"?ue.dirname(n):ue.resolve(t,e)}function rv(e,t){let n=e.find(i=>ue.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let r=e.find(i=>i.exists);return r?r.file_path:ue.join(t,"AGENTS.md")}function iv(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function av(e){let t=Xw();try{zi.write(`
22
22
  Agent guidance check
23
- `),Gi.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
24
- `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return Gi.write(`
25
- `),Jw(n,!0)}finally{t.close()}}function wm(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:Fo,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function vm(e){let t=[],n=await ym(e);for(let r of Lw){let i=ue.join(e,r),a=await O(i);if(!a){t.push({file_path:i,exists:a,has_guidance:!1,has_marker:!1});continue}let o=await jo.readFile(i,"utf8"),s=o.toLowerCase(),c=Mw.filter(l=>s.includes(l)),d=Gw(o);t.push({file_path:i,exists:a,has_guidance:d||c.length>=jw,has_marker:d,outdated:d&&gm(o,n).changed})}return t}function Yt(e,t){e.includes(t)||e.push(t)}function Yw(e,t){let n=wm(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function bm(e,t=ue.dirname(e)){let n=await O(e)?await jo.readFile(e,"utf8"):"",r=gm(n,await ym(t));return r.changed?(await Z(e,r.next_content),{changed:!0,warnings:await X({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function Xw(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Sn(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Sn(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Sn(e.projectRoot,t.file_path))}}async function Zw(e,t,n){return e?await vm(n):t}function dr(e,t,n){e.state={...e.state,...n,template_version:Fo,last_checked_files:t}}async function km(e,t){if(t.presentBefore)return;let n=await bm(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Qw(e,t){t||(e.warnings.push("agent_guidance:missing"),Yt(e.nextSteps,lr))}function ev(e,t){e.skipped=!0,dr(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Yt(e.nextSteps,lr)}async function tv(e,t){await km(e,t),dr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function nv(e,t){e.state.declined&&dr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function rv(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Yt(e.nextSteps,lr)}async function iv(e,t){if(e.prompted=!0,await Kw(t.targetRelativePath)){await km(e,t),dr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,dr(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Yt(e.nextSteps,lr)}function av(e){e.warnings.push("agent_guidance:missing_non_interactive"),Yt(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Yt(e.nextSteps,lr)}async function ov(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Qw(n,t.presentBefore),n):t.mode==="skip"?(ev(n,t.checkedFiles),n):t.mode==="add"?(await tv(n,t),n):t.presentBefore?(nv(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(rv(n),n):t.interactive?(await iv(n,t),n):(av(n),n)}async function Em(e){let t=Bw(e.pm_root,e.cwd),n=await vm(t),r=Vw(n,t),i=Sn(t,r),a=n.map(l=>Sn(t,l.file_path)),o=n.some(l=>l.has_guidance),s=await ov(wm(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:i,checkedFiles:a,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let l of n.filter(u=>u.outdated)){let u=await bm(l.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=Yw(e.settings,s.state);n=await Zw(s.applied,n,t);let d=n.filter(l=>l.outdated).map(l=>Sn(t,l.file_path));return d.length>0&&(s.warnings.push(`agent_guidance_outdated:${d.join(",")}`),Yt(s.nextSteps,"pm init --agent-guidance add")),{summary:Xw({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import St from"node:fs/promises";import Ee from"node:path";import ur from"node:fs/promises";import{createHash as sv}from"node:crypto";import xm from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="97537e2a-b8cb-559e-82bc-3c98b0c51db1")}catch{}})();var Uo=new Set([void 0,...Qd]),Am=11,cv="history-drift-cache.json";function Im(e){return xm.join(e,"runtime",cv)}async function dv(e){try{let t=await ur.readFile(Im(e),"utf8"),n=JSON.parse(t);return n.version!==Am||n.history_item_hash_version!==di||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!Uo.has(r.hash_algorithm)||!hn.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&hn.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}function Rm(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function Cm(e){let t=[...new Set([...e.missingStreams,...e.unreadableStreams,...e.hashMismatches,...e.chainMismatches,...e.versionSkews,...e.workspaceStateMismatches.length>0||e.workspaceStateMissing.length>0||e.workspaceStateUnreadable.length>0?[ce]:[]])].sort((n,r)=>n.localeCompare(r));return{...e,driftedItems:t}}async function lv(e,t,n,r,i){let a=hi(e),o;try{o=await ur.stat(a)}catch(d){return F(d)||i.unreadableStreams.push(ce),!1}let s=i.missingStreams.length,c=await Tm({itemId:ce,historyPath:a,stat:o,cached:t[ce],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(ce),c.verification.chainOk||i.chainMismatches.push(ce),n[ce]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion,hash_algorithm:c.verification.hashAlgorithm},c.cacheDirty):(i.missingStreams.splice(s),c.cacheDirty)}function uv(e){return!Uo.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!hn.includes(e.item_hash_version)}async function mv(e){let t=await ur.readFile(e,"utf8"),n=sv("sha256").update(t).digest("hex");if(t.trim().length===0)return null;let r=[],i=null;for(let m of t.split(/\r?\n/)){let f=m.trim();if(f.length===0)continue;let p=JSON.parse(f);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(p),i=p.after_hash}if(!i)return null;let a=Tt(r),o=r.some(uv),s=r[r.length-1],c=Uo.has(s.hash_algorithm),d=s.item_hash_version,l=d!==void 0&&hn.includes(d),u=l?d:a.item_hash_version;return{latestAfterHash:i,hashAlgorithm:c?Ce(s.hash_algorithm):void 0,identityDiscontinuities:ml(r),chainOk:a.ok,versionSkew:o,latestHashComparable:c&&u!==void 0&&(!o||l||d===void 0),contentHash:n,itemHashVersion:u??di}}function pv(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Sm(e,t,n){try{return await mv(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function fv(e,t){return e!==null&&e.contentHash===t.content_hash&&e.latestAfterHash===t.latest_after_hash&&e.chainOk===t.chain_ok&&e.versionSkew===(t.version_skew===!0)&&e.latestHashComparable===t.latest_hash_comparable&&e.itemHashVersion===t.item_hash_version&&e.hashAlgorithm===t.hash_algorithm}async function Tm(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(pv(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await Sm(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await Sm(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!fv(n,e.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&hn.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function $m(e,t,n,r){let i,a;try{i=Gt(e,t.id),a=await ur.stat(i)}catch(d){return(F(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let o=await Tm({itemId:t.id,historyPath:i,stat:a,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!o.verification)return o.cacheDirty;o.verification.identityDiscontinuities.length>0&&(r.identityDiscontinuities??=[]).push(...o.verification.identityDiscontinuities.map(d=>({...d,item_id:t.id}))),o.verification.versionSkew&&r.versionSkews.push(t.id),o.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:o.verification.contentHash,latest_after_hash:o.verification.latestAfterHash,chain_ok:o.verification.chainOk,version_skew:o.verification.versionSkew,latest_hash_comparable:o.verification.latestHashComparable,item_hash_version:o.verification.itemHashVersion,hash_algorithm:o.verification.hashAlgorithm};let{body:s,...c}=t;return o.verification.latestHashComparable&&(ll({metadata:c,body:s},o.verification.itemHashVersion,o.verification.hashAlgorithm).includes(o.verification.latestAfterHash)||r.hashMismatches.push(t.id)),o.cacheDirty}async function hv(e,t){if(!(t.unreadableStreams.includes(ce)||t.chainMismatches.includes(ce)||t.versionSkews.includes(ce)))try{let n=await hl(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(ce)}}async function Om(e,t){let n=Rm();return await $m(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),Cm(n)}async function Xt(e,t,n={}){let r=Rm(),i=(await dv(e))?.entries??{},a={},o=!1,s=n.cacheHitVerification!=="metadata",c={previousEntries:i,nextEntries:a,verifyCacheHitByContent:s};for(let l of t)await $m(e,l,c,r)&&(o=!0);let d=await lv(e,i,a,s,r);if(o||=d,await hv(e,r),o||Object.keys(i).length!==Object.keys(a).length){let l=Im(e);try{await ur.mkdir(xm.dirname(l),{recursive:!0}),await Z(l,JSON.stringify({version:Am,history_item_hash_version:di,entries:a}))}catch{}}return Cm(r)}import mr from"node:fs/promises";import Wi from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5974276-3b45-5ad6-a7aa-e05a33807ee7")}catch{}})();function _v(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:a,ttl_seconds:o}=n;return typeof r!="string"||typeof i!="string"||typeof a!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:r,owner:i,created_at:a,ttl_seconds:o}}function Dm(e,t,n){let r=_v(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let a=n-i,o=Math.floor(a/1e3),s=a>r.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:o,stale:s,reason:s?"expired":"active"}}}async function Pm(e,t){let n=t??Date.now(),r=Wi.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},a;try{a=(await mr.readdir(r)).filter(o=>o.endsWith(".lock")).sort()}catch(o){if(F(o))return i;throw o}for(let o of a){let s;try{s=await mr.readFile(Wi.join(r,o),"utf8")}catch(d){if(F(d))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=Dm(o,s,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function Nm(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Wi.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await mr.readdir(a)).filter(c=>c.endsWith(".lock")).sort()}catch(c){if(F(c))return o;throw c}for(let c of s){o.scanned+=1;let d=Wi.join(a,c),l=`locks/${c}`;if(r?.onRead){let f=await r.onRead(d);o.warnings.push(...f)}let u;try{u=await mr.readFile(d,"utf8")}catch(f){if(F(f)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${c}`),o.retained.push(l),o.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=Dm(c,u,i);if(m.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="active"){o.retained.push(l),o.entries.push(m.entry);continue}if(!n){try{await mr.unlink(d)}catch(f){if(!F(f)){o.warnings.push(`lock_remove_failed:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}}if(r?.onWrite){let f=await r.onWrite(d);o.warnings.push(...f)}}o.removed.push(l),o.entries.push(m.entry)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="270d544f-ac42-559f-ba6a-82f3d3b6c187")}catch{}})();var gv=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function zo(e){if(typeof e!="string")return;let t=e.trim();for(let n of gv)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Ho(e){let t={};for(let n of e){let r=zo(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Lm(e){return Object.values(Ho(e))}import jt from"node:fs/promises";import Pe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var yv=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function xn(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Qr(t.extensionName));for(let _ of t.extensionNames??[])n.add(Qr(_));let r=_=>n.size===0||n.has(Qr(_)),i=(_,w)=>Mm(_.filter(v=>r(v.name)).map(w)),a=(_,w)=>Mm(_.filter(v=>r(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:c,preflight:d,services:l,renderers:u,hooks:m}=e,f=a(o.relationship_kinds??[],_=>_.definitions.map(w=>w.kind)),p=u.overrides.filter(_=>r(_.name)&&((_.commands?.length??0)>0||_.resultDiscriminator!==void 0)).map(_=>({format:_.format,commands:[..._.commands??[]],result_discriminator:_.resultDiscriminator!==void 0})).sort((_,w)=>_.format.localeCompare(w.format)),h=i(o.assurance_providers??[],_=>_.definition.id);return{capabilities:Ud(e,t),commands:i(o.commands,_=>_.command),command_overrides:i(s.overrides,_=>_.command),command_handlers:i(s.handlers,_=>_.command),hooks:yv.filter(([_])=>m[_].some(w=>r(w.name))).map(([,_])=>_),flag_commands:i(o.flags,_=>_.target_command),item_types:a(o.item_types,_=>_.types.map(w=>w.name)),item_fields:a(o.item_fields,_=>_.fields.map(w=>w.name)),...f.length>0?{relationship_kinds:f}:{},migrations:a(o.migrations,_=>typeof _.definition.id=="string"?[_.definition.id]:[]),profiles:i(o.profiles,_=>_.profile.name),importers:i(o.importers,_=>_.importer),exporters:i(o.exporters,_=>_.exporter),search_providers:i(o.search_providers,_=>_.definition.name),vector_store_adapters:i(o.vector_store_adapters,_=>_.definition.name),...h.length>0?{assurance_providers:h}:{},parser_overrides:i(c.overrides,_=>_.command),service_overrides:i(l.overrides,_=>_.service),renderer_overrides:i(u.overrides,_=>_.format),...p.length>0?{renderer_ownership:p}:{},preflight_overrides:d.overrides.filter(_=>r(_.name)).length,preflight_ownership:d.overrides.filter(_=>r(_.name)).map(_=>({commands:[..._.commands??[]]}))}}function Mm(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import Ob from"node:path";import{mkdir as Db}from"node:fs/promises";import{access as Cv,readFile as Jo,realpath as Ot}from"node:fs/promises";import{constants as Tv}from"node:fs";import{execFile as $v}from"node:child_process";import J from"node:path";import{promisify as Ov}from"node:util";import{readFile as wv,writeFile as vv}from"node:fs/promises";import pr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1de99e25-e132-5071-833e-37361b4cc7e6")}catch{}})();var Fm="# pm-cli:runtime-cache:start",Go="# pm-cli:runtime-cache:end",Um=".agents/pm",Wo=["runtime/","search/","locks/","transactions/","checkpoints/"],bv=["search/eval-queries.json"];async function jm(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new y("The workspace .gitignore is not writable.",g.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function zm(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function qo(e){let t=e.replaceAll("\\","/");return pr.isAbsolute(e)||t===".."||t.startsWith("../")}function kv(e=Um){let t=zm(e);return[Fm,...Wo.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...bv.map(n=>`!${t}/${n}`),Go].join(`
26
- `)}async function aP(e,t={}){let n=pr.join(e,".gitignore"),r=Um;if(t.pmRoot!==void 0){let d=zm(pr.relative(pr.resolve(e),pr.resolve(t.pmRoot)));if(qo(d))return{path:n,changed:!1};d.length>0&&(r=d)}let i="";try{i=await jm(()=>wv(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&F(d)))throw d}let a=i.indexOf(Fm),o=i.indexOf(Go),s=(a>=0&&o>=a?`${i.slice(0,a)}${i.slice(o+Go.length)}`:i).trimEnd(),c=`${s.length>0?`${s}
23
+ `),zi.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
24
+ `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return zi.write(`
25
+ `),iv(n,!0)}finally{t.close()}}function xm(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:Ho,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function Am(e){let t=[],n=await Sm(e);for(let r of Bw){let i=ue.join(e,r),a=await O(i);if(!a){t.push({file_path:i,exists:a,has_guidance:!1,has_marker:!1});continue}let o=await Uo.readFile(i,"utf8"),s=o.toLowerCase(),c=Jw.filter(l=>s.includes(l)),d=Qw(o);t.push({file_path:i,exists:a,has_guidance:d||c.length>=Vw,has_marker:d,outdated:d&&Em(o,n).changed})}return t}function Yt(e,t){e.includes(t)||e.push(t)}function ov(e,t){let n=xm(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function Im(e,t=ue.dirname(e)){let n=await O(e)?await Uo.readFile(e,"utf8"):"",r=Em(n,await Sm(t));return r.changed?(await Z(e,r.next_content),{changed:!0,warnings:await X({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function sv(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>En(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>En(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>En(e.projectRoot,t.file_path))}}async function cv(e,t,n){return e?await Am(n):t}function cr(e,t,n){e.state={...e.state,...n,template_version:Ho,last_checked_files:t}}async function Rm(e,t){if(t.presentBefore)return;let n=await Im(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function dv(e,t){t||(e.warnings.push("agent_guidance:missing"),Yt(e.nextSteps,dr))}function lv(e,t){e.skipped=!0,cr(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Yt(e.nextSteps,dr)}async function uv(e,t){await Rm(e,t),cr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function mv(e,t){e.state.declined&&cr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function pv(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Yt(e.nextSteps,dr)}async function fv(e,t){if(e.prompted=!0,await av(t.targetRelativePath)){await Rm(e,t),cr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,cr(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Yt(e.nextSteps,dr)}function hv(e){e.warnings.push("agent_guidance:missing_non_interactive"),Yt(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Yt(e.nextSteps,dr)}async function _v(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(dv(n,t.presentBefore),n):t.mode==="skip"?(lv(n,t.checkedFiles),n):t.mode==="add"?(await uv(n,t),n):t.presentBefore?(mv(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(pv(n),n):t.interactive?(await fv(n,t),n):(hv(n),n)}async function Cm(e){let t=nv(e.pm_root,e.cwd),n=await Am(t),r=rv(n,t),i=En(t,r),a=n.map(l=>En(t,l.file_path)),o=n.some(l=>l.has_guidance),s=await _v(xm(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:i,checkedFiles:a,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let l of n.filter(u=>u.outdated)){let u=await Im(l.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=ov(e.settings,s.state);n=await cv(s.applied,n,t);let d=n.filter(l=>l.outdated).map(l=>En(t,l.file_path));return d.length>0&&(s.warnings.push(`agent_guidance_outdated:${d.join(",")}`),Yt(s.nextSteps,"pm init --agent-guidance add")),{summary:sv({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import St from"node:fs/promises";import Ee from"node:path";import lr from"node:fs/promises";import{createHash as gv}from"node:crypto";import $m from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="97537e2a-b8cb-559e-82bc-3c98b0c51db1")}catch{}})();var zo=new Set([void 0,...tl]),Om=11,yv="history-drift-cache.json";function Dm(e){return $m.join(e,"runtime",yv)}async function wv(e){try{let t=await lr.readFile(Dm(e),"utf8"),n=JSON.parse(t);return n.version!==Om||n.history_item_hash_version!==ci||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!zo.has(r.hash_algorithm)||!fn.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&fn.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}function Pm(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function Nm(e){let t=[...new Set([...e.missingStreams,...e.unreadableStreams,...e.hashMismatches,...e.chainMismatches,...e.versionSkews,...e.workspaceStateMismatches.length>0||e.workspaceStateMissing.length>0||e.workspaceStateUnreadable.length>0?[ce]:[]])].sort((n,r)=>n.localeCompare(r));return{...e,driftedItems:t}}async function vv(e,t,n,r,i){let a=fi(e),o;try{o=await lr.stat(a)}catch(d){return F(d)||i.unreadableStreams.push(ce),!1}let s=i.missingStreams.length,c=await Lm({itemId:ce,historyPath:a,stat:o,cached:t[ce],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(ce),c.verification.chainOk||i.chainMismatches.push(ce),n[ce]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion,hash_algorithm:c.verification.hashAlgorithm},c.cacheDirty):(i.missingStreams.splice(s),c.cacheDirty)}function bv(e){return!zo.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!fn.includes(e.item_hash_version)}async function kv(e){let t=await lr.readFile(e,"utf8"),n=gv("sha256").update(t).digest("hex");if(t.trim().length===0)return null;let r=[],i=null;for(let m of t.split(/\r?\n/)){let f=m.trim();if(f.length===0)continue;let p=JSON.parse(f);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(p),i=p.after_hash}if(!i)return null;let a=Tt(r),o=r.some(bv),s=r[r.length-1],c=zo.has(s.hash_algorithm),d=s.item_hash_version,l=d!==void 0&&fn.includes(d),u=l?d:a.item_hash_version;return{latestAfterHash:i,hashAlgorithm:c?Ce(s.hash_algorithm):void 0,identityDiscontinuities:fl(r),chainOk:a.ok,versionSkew:o,latestHashComparable:c&&u!==void 0&&(!o||l||d===void 0),contentHash:n,itemHashVersion:u??ci}}function Ev(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Tm(e,t,n){try{return await kv(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function Sv(e,t){return e!==null&&e.contentHash===t.content_hash&&e.latestAfterHash===t.latest_after_hash&&e.chainOk===t.chain_ok&&e.versionSkew===(t.version_skew===!0)&&e.latestHashComparable===t.latest_hash_comparable&&e.itemHashVersion===t.item_hash_version&&e.hashAlgorithm===t.hash_algorithm}async function Lm(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Ev(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await Tm(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await Tm(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!Sv(n,e.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&fn.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function Mm(e,t,n,r){let i,a;try{i=Gt(e,t.id),a=await lr.stat(i)}catch(d){return(F(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let o=await Lm({itemId:t.id,historyPath:i,stat:a,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!o.verification)return o.cacheDirty;o.verification.identityDiscontinuities.length>0&&(r.identityDiscontinuities??=[]).push(...o.verification.identityDiscontinuities.map(d=>({...d,item_id:t.id}))),o.verification.versionSkew&&r.versionSkews.push(t.id),o.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:o.verification.contentHash,latest_after_hash:o.verification.latestAfterHash,chain_ok:o.verification.chainOk,version_skew:o.verification.versionSkew,latest_hash_comparable:o.verification.latestHashComparable,item_hash_version:o.verification.itemHashVersion,hash_algorithm:o.verification.hashAlgorithm};let{body:s,...c}=t;return o.verification.latestHashComparable&&(ml({metadata:c,body:s},o.verification.itemHashVersion,o.verification.hashAlgorithm).includes(o.verification.latestAfterHash)||r.hashMismatches.push(t.id)),o.cacheDirty}async function xv(e,t){if(!(t.unreadableStreams.includes(ce)||t.chainMismatches.includes(ce)||t.versionSkews.includes(ce)))try{let n=await gl(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(ce)}}async function jm(e,t){let n=Pm();return await Mm(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),Nm(n)}async function Xt(e,t,n={}){let r=Pm(),i=(await wv(e))?.entries??{},a={},o=!1,s=n.cacheHitVerification!=="metadata",c={previousEntries:i,nextEntries:a,verifyCacheHitByContent:s};for(let l of t)await Mm(e,l,c,r)&&(o=!0);let d=await vv(e,i,a,s,r);if(o||=d,await xv(e,r),o||Object.keys(i).length!==Object.keys(a).length){let l=Dm(e);try{await lr.mkdir($m.dirname(l),{recursive:!0}),await Z(l,JSON.stringify({version:Om,history_item_hash_version:ci,entries:a}))}catch{}}return Nm(r)}import ur from"node:fs/promises";import Gi from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5974276-3b45-5ad6-a7aa-e05a33807ee7")}catch{}})();function Av(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:a,ttl_seconds:o}=n;return typeof r!="string"||typeof i!="string"||typeof a!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:r,owner:i,created_at:a,ttl_seconds:o}}function Fm(e,t,n){let r=Av(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let a=n-i,o=Math.floor(a/1e3),s=a>r.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:o,stale:s,reason:s?"expired":"active"}}}async function Um(e,t){let n=t??Date.now(),r=Gi.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},a;try{a=(await ur.readdir(r)).filter(o=>o.endsWith(".lock")).sort()}catch(o){if(F(o))return i;throw o}for(let o of a){let s;try{s=await ur.readFile(Gi.join(r,o),"utf8")}catch(d){if(F(d))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=Fm(o,s,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function Hm(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Gi.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await ur.readdir(a)).filter(c=>c.endsWith(".lock")).sort()}catch(c){if(F(c))return o;throw c}for(let c of s){o.scanned+=1;let d=Gi.join(a,c),l=`locks/${c}`;if(r?.onRead){let f=await r.onRead(d);o.warnings.push(...f)}let u;try{u=await ur.readFile(d,"utf8")}catch(f){if(F(f)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${c}`),o.retained.push(l),o.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=Fm(c,u,i);if(m.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="active"){o.retained.push(l),o.entries.push(m.entry);continue}if(!n){try{await ur.unlink(d)}catch(f){if(!F(f)){o.warnings.push(`lock_remove_failed:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}}if(r?.onWrite){let f=await r.onWrite(d);o.warnings.push(...f)}}o.removed.push(l),o.entries.push(m.entry)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="270d544f-ac42-559f-ba6a-82f3d3b6c187")}catch{}})();var Iv=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Go(e){if(typeof e!="string")return;let t=e.trim();for(let n of Iv)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Wo(e){let t={};for(let n of e){let r=Go(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function zm(e){return Object.values(Wo(e))}import jt from"node:fs/promises";import Pe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var Rv=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Sn(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Zr(t.extensionName));for(let _ of t.extensionNames??[])n.add(Zr(_));let r=_=>n.size===0||n.has(Zr(_)),i=(_,w)=>Gm(_.filter(v=>r(v.name)).map(w)),a=(_,w)=>Gm(_.filter(v=>r(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:c,preflight:d,services:l,renderers:u,hooks:m}=e,f=a(o.relationship_kinds??[],_=>_.definitions.map(w=>w.kind)),p=u.overrides.filter(_=>r(_.name)&&((_.commands?.length??0)>0||_.resultDiscriminator!==void 0)).map(_=>({format:_.format,commands:[..._.commands??[]],result_discriminator:_.resultDiscriminator!==void 0})).sort((_,w)=>_.format.localeCompare(w.format)),h=i(o.assurance_providers??[],_=>_.definition.id);return{capabilities:zd(e,t),commands:i(o.commands,_=>_.command),command_overrides:i(s.overrides,_=>_.command),command_handlers:i(s.handlers,_=>_.command),hooks:Rv.filter(([_])=>m[_].some(w=>r(w.name))).map(([,_])=>_),flag_commands:i(o.flags,_=>_.target_command),item_types:a(o.item_types,_=>_.types.map(w=>w.name)),item_fields:a(o.item_fields,_=>_.fields.map(w=>w.name)),...f.length>0?{relationship_kinds:f}:{},migrations:a(o.migrations,_=>typeof _.definition.id=="string"?[_.definition.id]:[]),profiles:i(o.profiles,_=>_.profile.name),importers:i(o.importers,_=>_.importer),exporters:i(o.exporters,_=>_.exporter),search_providers:i(o.search_providers,_=>_.definition.name),vector_store_adapters:i(o.vector_store_adapters,_=>_.definition.name),...h.length>0?{assurance_providers:h}:{},parser_overrides:i(c.overrides,_=>_.command),service_overrides:i(l.overrides,_=>_.service),renderer_overrides:i(u.overrides,_=>_.format),...p.length>0?{renderer_ownership:p}:{},preflight_overrides:d.overrides.filter(_=>r(_.name)).length,preflight_ownership:d.overrides.filter(_=>r(_.name)).map(_=>({commands:[..._.commands??[]]}))}}function Gm(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import zb from"node:path";import{mkdir as Gb}from"node:fs/promises";import{access as Fv,readFile as Yo,realpath as Ot}from"node:fs/promises";import{constants as Uv}from"node:fs";import{execFile as Hv}from"node:child_process";import V from"node:path";import{promisify as zv}from"node:util";import{readFile as Cv,writeFile as Tv}from"node:fs/promises";import mr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1de99e25-e132-5071-833e-37361b4cc7e6")}catch{}})();var qm="# pm-cli:runtime-cache:start",qo="# pm-cli:runtime-cache:end",Bm=".agents/pm",Bo=["runtime/","search/","locks/","transactions/","checkpoints/"],$v=["search/eval-queries.json"];async function Wm(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new y("The workspace .gitignore is not writable.",g.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function Jm(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function Jo(e){let t=e.replaceAll("\\","/");return mr.isAbsolute(e)||t===".."||t.startsWith("../")}function Ov(e=Bm){let t=Jm(e);return[qm,...Bo.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...$v.map(n=>`!${t}/${n}`),qo].join(`
26
+ `)}async function lP(e,t={}){let n=mr.join(e,".gitignore"),r=Bm;if(t.pmRoot!==void 0){let d=Jm(mr.relative(mr.resolve(e),mr.resolve(t.pmRoot)));if(Jo(d))return{path:n,changed:!1};d.length>0&&(r=d)}let i="";try{i=await Wm(()=>Cv(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&F(d)))throw d}let a=i.indexOf(qm),o=i.indexOf(qo),s=(a>=0&&o>=a?`${i.slice(0,a)}${i.slice(o+qo.length)}`:i).trimEnd(),c=`${s.length>0?`${s}
27
27
 
28
- `:""}${kv(r)}
29
- `;return c===i?{path:n,changed:!1}:(await jm(()=>vv(n,c,"utf8")),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d1f8e03-97b4-5d83-b85c-e47f39c07d48")}catch{}})();var Ev="PM_SOURCE_CONTEXT_ACCESS",Sv="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Hm(e){let t=e[Ev],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[Sv]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}import{execFile as xv}from"node:child_process";import Av from"node:path";import{promisify as Iv}from"node:util";import{setTimeout as Rv}from"node:timers/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f8f33f3d-854e-5cb4-b0bf-8d2d89da27e8")}catch{}})();var Vo=Iv(xv);async function An(e,t){let n=performance.now()+5e3,r=25;for(;;)try{await Vo("git",["config",...t],{cwd:e,env:{...tt(),LC_ALL:"C"},timeout:1e4});return}catch(i){let a=n-performance.now();if(typeof i!="object"||i===null||!("stderr"in i)||typeof i.stderr!="string"||!/could not lock config file [^\r\n]+: File exists/u.test(i.stderr)||a<=0)throw i;await Rv(Math.min(r,a)),r=Math.min(r*2,200)}}function tt(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"])delete e[t];return e}async function Bo(e,t){try{return(await Vo("git",["config","--local",...t==="core.bare"||t==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",t],{cwd:e,env:tt(),timeout:1e4})).stdout.trim()}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code===1)return;throw n}}async function Gm(e){if(await Bo(e,"extensions.worktreeConfig")==="true")return"--worktree";let{stdout:t}=await Vo("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"],{cwd:e,env:tt(),timeout:1e4}),[n,r]=t.trim().split(/\r?\n/);if(n===r)return"--local";let i=Av.join(r,"config.worktree");for(let a of["core.bare","core.worktree"]){let o=await Bo(e,a);o===void 0||a==="core.bare"&&o!=="true"||(await An(e,["--file",i,a,o]),await An(e,["--local","--unset-all",a]))}for(let a of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(let o of["name","driver"]){let s=`merge.${a}.${o}`,c=await Bo(e,s);c!==void 0&&await An(e,["--file",i,s,c])}return await An(e,["--local","extensions.worktreeConfig","true"]),"--worktree"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="98a35fdb-bff9-5556-9c1d-1c345cb39171")}catch{}})();var Zt=Ov($v),qi="# pm-cli:merge-drivers:start",Dv="# pm-cli:merge-drivers:end",fr="# pm-cli:merge-drivers:v2:start",Bm="# pm-cli:merge-drivers:v2:end",Pv="merge-fence",Nv="merge-attributes";function Wm(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function Lv(e,t){let n=await Ot(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(n))return;let{stdout:r}=await Zt(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return r.trim()===t?n:void 0}async function Mv(){let e=Ne(import.meta.url,["../../.."]),t=process.execPath,n=!1,r=await Ot(process.execPath),i=process.versions.bun,a=(process.env.PATH??"").split(J.delimiter).filter(s=>J.isAbsolute(s)).map(s=>J.join(s,i===void 0?J.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),o=i===void 0?a:[process.env.npm_execpath??"",...a,r].filter(s=>J.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(J.basename(s)));for(let s of o)try{if(await Cv(s,Tv.X_OK),i!==void 0){let c=await Lv(s,i);if(c!==void 0){t=c,n=!0;break}continue}if(s!==r&&await Ot(s)===r){t=s;break}}catch{}if(i!==void 0&&!n)throw new y("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",g.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${Wm(t)} ${Wm(J.join(e,"dist","cli.js"))}`}var Vm=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function jv(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=Hm(e.environment),a=!!(n&&r),o=t===void 0&&a&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let s=L(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}return o?{pm_root:J.resolve(r),workspace_start:J.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:a?L(e.cwd,".agents/pm"):L(e.cwd),workspace_start:e.cwd,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}async function nt(e){try{let{stdout:t}=await Zt("git",["rev-parse","--show-toplevel"],{cwd:e,env:tt(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await Ot(t.trim())}catch{return null}}async function Jm(e){let t=await nt(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function Ko(e,t){return J.relative(e,t).replaceAll("\\","/")}function We(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function qm(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function Fv(e,t,n){if(Nl(t).filter(i=>i.constraint==="exact").some(i=>i.version!==n))return!1;let r=await nt(e);if(r!==null&&r!==await Ot(t)){let i=await Promise.all([r,t].map(async a=>{let o=await Zt("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:a,env:tt(),timeout:1e4});return Ot(o.stdout.trim())}));if(i[0]===i[1])return!1}return!0}async function Uv(e,t,n){let r=qm(e,0);if(r===null||e[r.nextOffset]!==" ")return!1;let i=qm(e,r.nextOffset+1);if(i===null||e.slice(i.nextOffset)!==t||!/^(?:node|bun)(?:\.exe)?$/iu.test(J.basename(r.value))||J.basename(i.value)!=="cli.js"||J.basename(J.dirname(i.value))!=="dist"||!await O(r.value)||!await O(i.value))return!1;try{let a=J.dirname(J.dirname(i.value)),o=JSON.parse(await Jo(J.join(a,"package.json"),"utf8")),s=typeof o.bin=="string"?o.bin:o.bin?.pm;return await Fv(a,n,o.version)?o.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function Yo(e,t){let n=e.length>0?`${e}/`:"",r=[`${We(`${n}**/*.toon`)} merge=pm-item-toon`,`${We(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${We(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${We(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${We(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${We(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${We(`${n}settings.json`)} merge=pm-json`),r.push(`${We(`${n}**/*.json`)} merge=pm-json`),r.push(`${We(`${n}extensions/**`)} merge=text`),r.push(`${We(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function Km(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(qi,n),i=e.indexOf(fr,n),a=r===-1?i:i===-1?r:Math.min(r,i);if(a===-1)break;let o=a===i,s=o?fr:qi,c=o?Bm:Dv,d=e.indexOf(c,a+s.length),l=d===-1?e.length:d+c.length;t.push({start:a,end:l,closed:d!==-1,lines:e.slice(a+s.length,d===-1?l:d).split(`
30
- `).map(u=>u.trim()).filter(Boolean)}),n=l}return t}function Ym(e,t,n){let r=new Set(t),i=We(n.length>0?`${n}/`:"").slice(0,-1);return e.some(a=>r.has(a)||a.startsWith(i)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(a.slice(i.length)))}async function Xm(e,t,n,r){let i=J.join(e,".gitattributes"),a=r?null:(await Zt("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:tt(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),o=a===null?null:await te(a,Nv,120,"merge-fence",!1,!0,5e3);try{let s=await V(i)??"",c=[fr,...n,Bm].join(`
31
- `),d=Km(s),l=d.filter(m=>Ym(m.lines,n,t));l.length===0&&t===".agents/pm"&&d.length===1&&d[0].lines.every(m=>!m.includes(".agents/pm/"))&&l.push(d[0]);let u;if(l.length>0){let m=l[0];u=s;for(let f of l.slice(1).reverse())u=`${u.slice(0,f.start)}${u.slice(f.end)}`;u=`${u.slice(0,m.start)}${c}${u.slice(m.end)}`}else{let m=s.trimEnd();u=`${m.length>0?`${m}
28
+ `:""}${Ov(r)}
29
+ `;return c===i?{path:n,changed:!1}:(await Wm(()=>Tv(n,c,"utf8")),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d1f8e03-97b4-5d83-b85c-e47f39c07d48")}catch{}})();var Dv="PM_SOURCE_CONTEXT_ACCESS",Pv="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Vm(e){let t=e[Dv],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[Pv]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}import{execFile as Nv}from"node:child_process";import Lv from"node:path";import{promisify as Mv}from"node:util";import{setTimeout as jv}from"node:timers/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f8f33f3d-854e-5cb4-b0bf-8d2d89da27e8")}catch{}})();var Ko=Mv(Nv);async function xn(e,t){let n=performance.now()+5e3,r=25;for(;;)try{await Ko("git",["config",...t],{cwd:e,env:{...nt(),LC_ALL:"C"},timeout:1e4});return}catch(i){let a=n-performance.now();if(typeof i!="object"||i===null||!("stderr"in i)||typeof i.stderr!="string"||!/could not lock config file [^\r\n]+: File exists/u.test(i.stderr)||a<=0)throw i;await jv(Math.min(r,a)),r=Math.min(r*2,200)}}function nt(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"])delete e[t];return e}async function Vo(e,t){try{return(await Ko("git",["config","--local",...t==="core.bare"||t==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",t],{cwd:e,env:nt(),timeout:1e4})).stdout.trim()}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code===1)return;throw n}}async function Km(e){if(await Vo(e,"extensions.worktreeConfig")==="true")return"--worktree";let{stdout:t}=await Ko("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"],{cwd:e,env:nt(),timeout:1e4}),[n,r]=t.trim().split(/\r?\n/);if(n===r)return"--local";let i=Lv.join(r,"config.worktree");for(let a of["core.bare","core.worktree"]){let o=await Vo(e,a);o===void 0||a==="core.bare"&&o!=="true"||(await xn(e,["--file",i,a,o]),await xn(e,["--local","--unset-all",a]))}for(let a of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(let o of["name","driver"]){let s=`merge.${a}.${o}`,c=await Vo(e,s);c!==void 0&&await xn(e,["--file",i,s,c])}return await xn(e,["--local","extensions.worktreeConfig","true"]),"--worktree"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="98a35fdb-bff9-5556-9c1d-1c345cb39171")}catch{}})();var Zt=zv(Hv),Wi="# pm-cli:merge-drivers:start",Gv="# pm-cli:merge-drivers:end",pr="# pm-cli:merge-drivers:v2:start",Zm="# pm-cli:merge-drivers:v2:end",Wv="merge-fence",qv="merge-attributes";function Ym(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function Bv(e,t){let n=await Ot(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(n))return;let{stdout:r}=await Zt(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return r.trim()===t?n:void 0}async function Jv(){let e=Ne(import.meta.url,["../../.."]),t=process.execPath,n=!1,r=await Ot(process.execPath),i=process.versions.bun,a=(process.env.PATH??"").split(V.delimiter).filter(s=>V.isAbsolute(s)).map(s=>V.join(s,i===void 0?V.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),o=i===void 0?a:[process.env.npm_execpath??"",...a,r].filter(s=>V.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(V.basename(s)));for(let s of o)try{if(await Fv(s,Uv.X_OK),i!==void 0){let c=await Bv(s,i);if(c!==void 0){t=c,n=!0;break}continue}if(s!==r&&await Ot(s)===r){t=s;break}}catch{}if(i!==void 0&&!n)throw new y("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",g.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${Ym(t)} ${Ym(V.join(e,"dist","cli.js"))}`}var Qm=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function Vv(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=Vm(e.environment),a=!!(n&&r),o=t===void 0&&a&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let s=L(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}return o?{pm_root:V.resolve(r),workspace_start:V.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:a?L(e.cwd,".agents/pm"):L(e.cwd),workspace_start:e.cwd,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}async function rt(e){try{let{stdout:t}=await Zt("git",["rev-parse","--show-toplevel"],{cwd:e,env:nt(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await Ot(t.trim())}catch{return null}}async function ep(e){let t=await rt(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function Xo(e,t){return V.relative(e,t).replaceAll("\\","/")}function qe(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Xm(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function Kv(e,t,n){if(Ml(t).filter(i=>i.constraint==="exact").some(i=>i.version!==n))return!1;let r=await rt(e);if(r!==null&&r!==await Ot(t)){let i=await Promise.all([r,t].map(async a=>{let o=await Zt("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:a,env:nt(),timeout:1e4});return Ot(o.stdout.trim())}));if(i[0]===i[1])return!1}return!0}async function Yv(e,t,n){let r=Xm(e,0);if(r===null||e[r.nextOffset]!==" ")return!1;let i=Xm(e,r.nextOffset+1);if(i===null||e.slice(i.nextOffset)!==t||!/^(?:node|bun)(?:\.exe)?$/iu.test(V.basename(r.value))||V.basename(i.value)!=="cli.js"||V.basename(V.dirname(i.value))!=="dist"||!await O(r.value)||!await O(i.value))return!1;try{let a=V.dirname(V.dirname(i.value)),o=JSON.parse(await Yo(V.join(a,"package.json"),"utf8")),s=typeof o.bin=="string"?o.bin:o.bin?.pm;return await Kv(a,n,o.version)?o.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function Zo(e,t){let n=e.length>0?`${e}/`:"",r=[`${qe(`${n}**/*.toon`)} merge=pm-item-toon`,`${qe(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${qe(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${qe(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${qe(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${qe(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${qe(`${n}settings.json`)} merge=pm-json`),r.push(`${qe(`${n}**/*.json`)} merge=pm-json`),r.push(`${qe(`${n}extensions/**`)} merge=text`),r.push(`${qe(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function tp(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(Wi,n),i=e.indexOf(pr,n),a=r===-1?i:i===-1?r:Math.min(r,i);if(a===-1)break;let o=a===i,s=o?pr:Wi,c=o?Zm:Gv,d=e.indexOf(c,a+s.length),l=d===-1?e.length:d+c.length;t.push({start:a,end:l,closed:d!==-1,lines:e.slice(a+s.length,d===-1?l:d).split(`
30
+ `).map(u=>u.trim()).filter(Boolean)}),n=l}return t}function np(e,t,n){let r=new Set(t),i=qe(n.length>0?`${n}/`:"").slice(0,-1);return e.some(a=>r.has(a)||a.startsWith(i)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(a.slice(i.length)))}async function rp(e,t,n,r){let i=V.join(e,".gitattributes"),a=r?null:(await Zt("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:nt(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),o=a===null?null:await te(a,qv,120,"merge-fence",!1,!0,5e3);try{let s=await J(i)??"",c=[pr,...n,Zm].join(`
31
+ `),d=tp(s),l=d.filter(m=>np(m.lines,n,t));l.length===0&&t===".agents/pm"&&d.length===1&&d[0].lines.every(m=>!m.includes(".agents/pm/"))&&l.push(d[0]);let u;if(l.length>0){let m=l[0];u=s;for(let f of l.slice(1).reverse())u=`${u.slice(0,f.start)}${u.slice(f.end)}`;u=`${u.slice(0,m.start)}${c}${u.slice(m.end)}`}else{let m=s.trimEnd();u=`${m.length>0?`${m}
32
32
 
33
33
  `:""}${c}
34
- `}return u===s?{path:i,changed:!1}:(r||await Z(i,u),{path:i,changed:!0})}finally{await o?.()}}function Dt(e){let t=G(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function In(e,t){let n=J.resolve(e),r=null,i="",a=n;for(let _=0;_<8;_+=1){let w=J.join(a,".gitattributes");try{let E=await Jo(w,"utf8");if(E.includes(fr)||E.includes(qi)){r=a,i=E;break}}catch{}let v=J.dirname(a);if(v===a)break;a=v}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=J.join(r,".gitattributes"),s=Ko(r,n),c=Km(i),d=Yo(s,t),l=c.filter(_=>Ym(_.lines,d,s)),u=l.flatMap(_=>_.closed?_.lines:[]),m=new Set(u),f=new Set(d),p=d.filter(_=>!m.has(_)),h=u.filter(_=>!f.has(_));return{status:l.length!==1||!l[0].closed||p.length>0||h.length>0?"drift":"ok",path:o,missing_patterns:p,stale_patterns:h,schema_scope:"project"}}async function Rn(e){let t=[],n=[];for(let r of Vm){let i=`merge.${r.key}.driver`,a=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`;try{let{stdout:o}=await Zt("git",["config","--get",i],{cwd:e,env:tt(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=o.trim();await Uv(s,a,e)||n.push(i)}catch{t.push(i)}}return{status:t.length>0?"missing":n.length>0?"drift":"ok",missing_keys:t,drifted_keys:n}}async function Zm(e){let t;try{t=await Jm(J.resolve(e))}catch{return{status:"no_git"}}let n=Ko(t,J.resolve(e)),r=await T(e),i=W(void 0,r.author_default),a=await te(e,Pv,r.locks.ttl_seconds,i,!1,Te(r).force_required_for_stale_lock,r.locks.wait_ms);try{let o=J.join(t,".gitattributes"),s;try{s=await Jo(o,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&F(u))return{status:"not_installed",path:o};throw u}if(!s.includes(fr)&&!s.includes(qi))return{status:"not_installed",path:o};let c=await T(e),d=Dt(c),l=await Xm(t,n,Yo(n,d),!1);return{status:l.changed?"refreshed":"unchanged",path:l.path}}finally{await a()}}async function PP(e,t){let n=jv({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await ne(r);let i=await Jm(n.workspace_start);return Hv({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function zv(e,t){let n=(await Zt("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:e,env:tt(),timeout:1e4})).stdout.trim(),r=await te(n,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{let i=await Gm(e),a;try{a=(await Zt("git",["config",i,"--null","--get-regexp","."],{cwd:e,env:tt(),timeout:1e4})).stdout}catch(s){if(typeof s!="object"||s===null||!("code"in s)||s.code!==1)throw s;a=""}let o=new Map(a.split("\0").filter(Boolean).map(s=>{let c=s.indexOf(`
35
- `);return[s.slice(0,c),s.slice(c+1)]}));for(let s of t)o.get(s.key)!==s.value&&await An(e,[i,s.key,s.value])}finally{await r()}}async function Hv(e){let t=J.resolve(e.pmRoot),n=J.resolve(e.workspaceRoot),r=e.dryRun===!0,i,a;try{[i,a]=await Promise.all([Ot(t),Ot(n)])}catch(f){throw new y(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,g.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let o=Ko(a,i);if(qo(o))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let s=await T(i),c=Dt(s),d=Yo(o,c),l=[],u=await Mv();for(let f of Vm)l.push({key:`merge.${f.key}.name`,value:f.name}),l.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!r)try{await zv(a,l)}catch{throw new y(`Cannot install repository-local merge drivers in ${a}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,g.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await Xm(a,o,d,r);return{ok:!0,dry_run:r,workspace_root:a,pm_root:i,gitattributes:{path:m.path,changed:m.changed,patterns:d,schema_scope:"project"},git_config:l,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:$()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var Gv=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Wv(e){let t=Gv.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function qv(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Qm(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let c=Wv(s);if(c===void 0)continue;let d=i.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(s),i.set(c,d)}let a=[];for(let[o,s]of i.entries()){if(s.count<n)continue;let c=qv(o);a.push({name:c,prefix:o,count:s.count,examples:s.examples,shadows_builtin:xd(c)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}import{createHash as lp}from"node:crypto";import en from"node:fs/promises";import Tn from"node:path";import{mkdir as Bv,readFile as Vv}from"node:fs/promises";import rp 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]="1fae5539-4eb8-5eba-bfd6-a191c89448ec")}catch{}})();var Xo=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Jv="sdk-workspace-transaction",Kv=/^[a-zA-Z0-9._-]+$/,Yv=30,Xv=3e3;function ip(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Kv.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function ep(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function Zv(e){return{pmRoot:ep(e.pmRoot,"Transaction pmRoot"),transactionId:ip(e.transactionId,"Transaction id"),author:ep(e.author,"Transaction author")}}function tp(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function ap(e,t){return rp.join(e,"transactions","sdk",`${t}.json`)}async function Pt(e,t){t.updatedAt=$();let n=ap(e,t.transactionId);await Bv(rp.dirname(n),{recursive:!0}),await Z(n,`${JSON.stringify(t,null,2)}
36
- `)}function Qv(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Qt(e){return Object.assign(Object.create(null),e)}function eb(e,t){try{let n=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function Zo(e,t){return e===void 0?void 0:eb(e,t)}function Qo(e,t,n,r){let i=Zo(n,r);i===void 0?delete e[t]:e[t]=i}function np(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function es(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function tb(e,t){if(!es(e.startedStepIds,t)||!es(e.completedStepIds,t)||!np(e.results)||!np(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,a=new Set(i);return Object.keys(e.compensationData).some(o=>!r.has(o))||Object.keys(e.results).some(o=>!a.has(o))?!1:e.status==="committed"?t.every(o=>a.has(o)):e.status!=="compensated"||a.size===0&&r.size===0}function Bi(e,t){return new y(`Workspace transaction ${e} journal is invalid (${t})`,g.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function nb(e){return new y(`Workspace transaction ${e} journal does not match the supplied plan`,g.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the exact plan that started this transaction, or start a new transaction with a different id.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","Pass --transaction-id <new-id> (or a new transactionId over MCP) to commit the changed plan as its own transaction.","Run pm ops gc --scope transactions --dry-run to inspect abandoned journals before pruning them."]})}function rb(e,t,n){let r;try{r=JSON.parse(e)}catch{throw Bi(t,"invalid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw Bi(t,"expected an object");let i=r;if(!(i.schemaVersion===1&&i.transactionId===t))throw Bi(t,"schema version or transaction id does not match the journal file");let a=i.stepIds;if(!Array.isArray(a)||!es(a,a)||!tb(i,a)||!Qv(i)||typeof i.status!="string"||!["applying","compensating","compensated","committed"].includes(i.status))throw Bi(t,"invalid lifecycle, metadata, status or step ids");if(!(i.status==="compensated"||a.length===n.length&&a.every((o,s)=>o===n[s])))throw nb(t);return{...i,results:Qt(i.results),compensationData:Qt(i.compensationData)}}async function ib(e,t,n,r,i){let a=i,o=a!==void 0;if(a?.status==="compensating"&&await op(e,a),a===void 0||a.status==="compensated"){let s=$();a={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(a?.attempt??0)+1,createdAt:a?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:Qt(),compensationData:Qt()},await Pt(e.pmRoot,a),await _t(e,a,"prepared")}return{journal:a,recovered:o}}async function ab(e,t,n){try{await sb(t,e.steps),await Pt(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let a of e.steps){if(r.has(a.id))continue;let o=await a.inspect(),s=Zo(o.result,`Step ${a.id} result`);if(o.state!=="applied"){let c=await a.prepareCompensation?.();Qo(t.compensationData,a.id,c,`Step ${a.id} compensation data`),i.add(a.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await Pt(e.pmRoot,t);let d=await a.apply();s=Zo(d,`Step ${a.id} result`)}await _t(e,t,"step_applied",a.id),r.add(a.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),Qo(t.results,a.id,s,`Step ${a.id} result`),await Pt(e.pmRoot,t),await _t(e,t,"step_recorded",a.id)}return await _t(e,t,"committing"),t.status="committed",await Pt(e.pmRoot,t),await _t(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Qt(t.results)}}catch(r){if(r instanceof Xo||t.status==="committed")throw r;try{await op(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function ob(e,t,n){try{return rb(await Vv(ap(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&F(r))return;throw r}}async function _t(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function sb(e,t){let n=new Set,r=Qt();for(let i of t){let a=await i.inspect();a.state==="applied"&&(n.add(i.id),Qo(r,i.id,a.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function op(e,t){t.status="compensating",await Pt(e.pmRoot,t),await _t(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!r.has(i.id)&&!n.has(i.id))continue;let a;try{a=r.has(i.id)&&(await i.inspect()).state==="applied"}catch{a=r.has(i.id)}a&&(await _t(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),r.delete(i.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>r.has(o)),delete t.results[i.id],delete t.compensationData[i.id],await Pt(e.pmRoot,t),await _t(e,t,"step_compensated",i.id)}t.status="compensated",await Pt(e.pmRoot,t),await _t(e,t,"compensated")}async function sp(e){let{pmRoot:t,transactionId:n,author:r}=Zv(e),i=tp(e.lockTtlSeconds,Yv,"Transaction lock TTL"),a=tp(e.lockWaitMs,Xv,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(l=>{let u=ip(l.id,"Transaction step id");if(u!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return u});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:o,lockTtlSeconds:i,lockWaitMs:a},d=await te(t,Jv,i,r,!1,!1,a);try{let l=await ob(t,n,s),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Qt(l.results)};let m=await ib(c,n,r,s,l);return await ab(c,m.journal,u||m.recovered)}finally{await d()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d04c087-62e4-51d3-8832-6cbcfd3ed993")}catch{}})();function gt(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function up(e){let t=gt(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function mp(e,t){let n=ns(e),r=gt(t,"migrationScope");return`auto-${lp("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function ns(e){let t=e.kind==="rename-type"?{kind:e.kind,from:gt(e.from,"source"),to:gt(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:le(gt(e.from,"source")),to:le(gt(e.to,"target")),...e.type===void 0?{}:{type:gt(e.type,"type")}}:{kind:e.kind,from:le(gt(e.from,"source")),to:le(gt(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function cb(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function db(e,t,n){let r=Re(t.schema),i=cb(n);return Ze(e,r.files[i],Le[i])}function pp(e,t){return Tn.join(e,"transactions","schema",`${t}-plan.json`)}function Vi(e){return e.length===0?null:JSON.parse(e)}async function Cn(e){let t=await V(e);return{exists:t!==null,raw:t??""}}async function fp(e,t){t.exists?await Z(e,t.raw):await en.rm(e,{force:!0})}function lb(e,t,n){let r=ct(e),i=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),a=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(a>=0)return It(r);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[i],name:t.to})}else i>=0&&r.definitions.splice(i,1);return It(r)}function ub(e,t,n){let r=ln(e),i=r.fields.findIndex(o=>o.key===t.from),a=r.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(a>=0)return un(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=r.fields[i];r.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&r.fields.splice(i,1);return un(r)}function mb(e,t,n){let r=mn(e),i=r.statuses.findIndex(o=>o.id===t.from),a=r.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(a>=0)return pn(r);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[i],id:t.to})}else i>=0&&r.statuses.splice(i,1);return pn(r)}function pb(e,t,n){return t.kind==="rename-type"?lb(e,t,n):t.kind==="rename-field"?ub(e,t,n):mb(e,t,n)}function Nt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function rs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function $n(e){return Array.isArray(e)?e.map(t=>rs(t)).filter(t=>t!==void 0):[]}function fb(e,t){for(let n of $n(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>Nt(r,t)));for(let n of $n(e.type_workflows))n.type=Nt(n.type,t)}function hb(e,t){for(let r of $n(e.definitions))r.default_status=Nt(r.default_status,t);let n=rs(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=Nt(i,t);for(let r of $n(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(a=>Nt(a,t)):i))}function _b(e,t){for(let n of $n(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>Nt(i,t)));for(let r of["options","command_option_policies"])for(let i of $n(n[r])){let a=r==="options"?"key":"option";i[a]=Nt(i[a],t)}}}function gb(e,t){let n=rs(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=Nt(n[r],t)}function ts(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?fb(r,t):t.kind==="rename-field"?_b(r,t):hb(r,t),gb(r,t),`${JSON.stringify(r,null,2)}
37
- `}function hp(e,t){if(t.kind==="rename-type"){let r=ct(e).definitions;return{source:r.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=ln(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=mn(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function yb(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function wb(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function _p(e,t){let n=ns(t.request),r=t.migrationId===void 0?mp(n,t.migrationScope??"plan"):up(t.migrationId),i=e.map(c=>wb(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),a=lp("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!o.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:a,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function vb(e){let t=G(e.settings,z()),n=[...new Set(Object.values(t.type_to_folder))],r=await Ei(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},a=r?await Ll({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:i}):null;return a?{items:a.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await lt(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function bb(e,t){let n=await V(pp(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new y(`Stored schema migration plan "${t}" is invalid: ${od(r)}`,g.GENERIC_FAILURE)}}async function kb(e,t){let n=pp(e,t.migration_id);await en.mkdir(Tn.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await Z(n,`${JSON.stringify(r,null,2)}
38
- `)}function Eb(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Sb(e){let t=await ve(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new y(`Schema migration item "${e.id}" no longer exists.`,g.NOT_FOUND);return(await be(t,{schema:e.settings.schema})).document.metadata}function cp(e,t,n){let r=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let a=e.metadata;if(Object.prototype.hasOwnProperty.call(a,i)&&!Object.prototype.hasOwnProperty.call(a,r))return[];if(!Object.prototype.hasOwnProperty.call(a,r)||Object.prototype.hasOwnProperty.call(a,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return a[i]=a[r],delete a[r],[r,i]}function dp(e){return{id:e.id,inspect:async()=>{let t=await Cn(e.filePath),n=hp(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Cn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Cn(e.filePath);return await Z(e.filePath,pb(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await fp(e.filePath,{exists:t.exists,raw:t.raw})}}}function xb(e){return{id:e.stepId,inspect:async()=>{let t=await Cn(e.filePath);return{state:ts(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Cn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Cn(e.filePath);return await Z(e.filePath,ts(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await fp(e.filePath,{exists:t.exists,raw:t.raw})}}}function Ab(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await T(e.pmRoot),n=G(t,z()).type_to_folder,r=await Sb({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=yb(r,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await T(e.pmRoot),n=G(t,z()).type_to_folder,r=await mt({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:cp(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await T(e.pmRoot),n=G(t,z()).type_to_folder;await mt({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:cp(r,e.request,"reverse")}}})}}}async function Ib(e){let t=await bb(e.pmRoot,e.migrationId);if(t){if(!Eb(t.request,e.request))throw new y(`Schema migration id "${e.migrationId}" already belongs to a different request.`,g.CONFLICT);return{plan:t,stored:!0}}let n=await vb({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{..._p(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Rb(e){let t=hp(await V(e.schemaPath)??"",e.request);if(!t.source)throw new y(`Schema migration source "${e.request.from}" is not a custom definition.`,g.NOT_FOUND);if(t.target)throw new y(`Schema migration target "${e.request.to}" already exists.`,g.CONFLICT);await kb(e.pmRoot,e.plan)}async function Cb(e){let t=Re(e.settings.schema),n=[...new Set([["types",Le.types],["fields",Le.fields],["workflows",Le.workflows]].map(([i,a])=>Ze(e.pmRoot,t.files[i],a)).filter(i=>i!==e.schemaPath))];try{let i=Tn.join(e.pmRoot,"templates"),a=await en.readdir(i,{withFileTypes:!0});n.push(...a.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>Tn.join(i,o.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!F(i))throw i}n.sort((i,a)=>i.localeCompare(a));let r=[];for(let i of n){let a=await V(i);a!==null&&ts(a,e.request)!==a&&r.push({filePath:i,beforeRaw:a})}return{paths:n,snapshots:r}}async function Tb(e){for(let t of e.snapshots){let n=await en.readFile(t.filePath,"utf8"),r=Tn.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await lo({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Vi(t.beforeRaw),after:Vi(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function $b(e,t,n){let r=ns(e),i=L(process.cwd(),n.path);await ne(i);let a=t.migrationId===void 0?mp(r,await en.realpath(i)):up(t.migrationId),o=await T(i),s=W(t.author,o.author_default),c=await Ib({pmRoot:i,settings:o,migrationId:a,request:r}),d=c.plan;if(t.dryRun===!0)return{...d,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=db(i,o,r),u=await en.readFile(l,"utf8");c.stored||await Rb({pmRoot:i,schemaPath:l,request:r,plan:d});let m=await Cb({pmRoot:i,schemaPath:l,settings:o,request:r}),f=[dp({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...m.paths.map((w,v)=>xb({filePath:w,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>Ab({pmRoot:i,id:w.id,request:r,author:s,force:t.force===!0})),dp({id:"retire-source",filePath:l,request:r,phase:"retire"})],p=await sp({pmRoot:i,transactionId:`schema-${a}`,author:s,steps:f,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),h=await en.readFile(l,"utf8"),{historyPath:_}=await lo({pmRoot:i,author:s,documentPath:Tn.relative(i,l).replaceAll("\\","/"),before:Vi(u),after:Vi(h),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await Tb({pmRoot:i,author:s,settings:o,request:r,plan:d,snapshots:m.snapshots}),{...d,action:r.kind,applied:!0,recovered:p.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:_}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var UN=[...Jr,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Ji="schema-types",gp="schema-statuses",yp="schema-fields";function Lt(e){return gi({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function GN(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i;try{i=Qa({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(f){throw new y(f instanceof Error?f.message:String(f),g.USAGE)}let a=await T(r),o=Re(a.schema),s=Ze(r,o.files.types,Le.types),c=[],d=W(t.author,a.author_default),l=Te(a),u=await te(r,Ji,a.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms),m;try{let f=await V(s),p;try{p=ct(f)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.GENERIC_FAILURE)}try{Ad(i,p);let h=new Map,_=G(a,z());for(let[w,v]of Object.entries(_.type_to_folder)){let E=v.trim().toLowerCase();E.length>0&&!h.has(E)&&h.set(E,w)}Id(i,p,h)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}m=Xr(p,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await Lt({pmRoot:r,filePath:s,raw:It(m.file),op:"schema:add-type",author:d,settings:a}),await hr(r,[m.definition],c,"schema:add-type-folder"),c.push(...await X({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await wp(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Mt(c),generated_at:$()}}async function yt(e){await ne(e)}async function wp(e,t){try{let n=await Zm(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Mt(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Pb(e,t,n,r){let i=G(t,z()),a=r.trim().toLowerCase();return(await lt(e,t.item_format,i.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===a).length}async function Nb(e,t,n,r){let i=G(t,z()),a=ge(n),o=le(r);return(await lt(e,t.item_format,i.type_to_folder,[],n)).filter(s=>{let c=typeof s.status=="string"?s.status:"";return(a.alias_to_id.get(le(c))??le(c))===o}).length}async function Lb(e,t,n,r,i){if(i.length===0||to.has(i))return;let a=await Nb(t,n,r,i);a>0&&e.push(`items_using_status:${a}`);let o=Mb(r.workflow,i);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function Mb(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&le(n)===t).map(([n])=>n)}async function WN(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i=await T(r),a=Re(i.schema),o=Ze(r,a.files.types,Le.types),s=[],c=W(t.author,i.author_default),d=Te(i),l=await te(r,Ji,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await V(o),f;try{f=ct(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=Rd(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=(u.definition?.name??e??"").trim();if(p.length>0){let h=await Pb(r,i,a,p);h>0&&s.push(`items_using_type:${h}`)}await Lt({pmRoot:r,filePath:o,raw:It(u.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await X({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await wp(r,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:o,definitions:u.file.definitions.length},warnings:Mt(s),generated_at:$()}}function is(e,t){return Ze(e,t.files.statuses,Le.statuses)}function Ki(e,t){return Ze(e,t.files.fields,Le.fields)}function vp(e,t){return Ze(e,t.files.types,Le.types)}async function hr(e,t,n,r){for(let i of t){let a=dd(i.folder??cd(i.name)),o=Ob.join(e,a);await O(o)||(await Db(o,{recursive:!0}),n.push(...await X({path:o,scope:"project",op:r})))}}function as(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function jb(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Fb(e){let t=new Map;for(let n of e){let r=le(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let a=le(i);a.length>0&&!t.has(a)&&t.set(a,r)}}}return t}async function qN(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i;try{i=Ld({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}let a=await T(r),o=Re(a.schema),s=is(r,o),c=ge(o);try{no(i,c.alias_to_id)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}let d=jb(c.by_id.get(i.id));if((i.roles??d?.roles??[]).length===0)throw new y(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,g.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${dn(i.id)}" --role active`,`pm schema add-status "${dn(i.id)}" --role blocked`]});let l=[],u=W(t.author,a.author_default),m=Te(a),f=await te(r,gp,a.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,a.locks.wait_ms),p;try{let h=await V(s),_;try{_=mn(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=Fb(_.statuses);try{no(i,w)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.USAGE)}p=Md(_,i,d),await Lt({pmRoot:r,filePath:s,raw:pn(p.file),op:"schema:add-status",author:u,settings:a}),l.push(...await X({path:s,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:p.replaced,status:p.definition,file:{path:s,statuses:p.file.statuses.length},warnings:Mt(l),generated_at:$()}}async function BN(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i=await T(r),a=Re(i.schema),o=is(r,a),s=[],c=W(t.author,i.author_default),d=Te(i),l=await te(r,gp,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await V(o),f;try{f=mn(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=jd(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=le(u.definition?.id??e);await Lb(s,r,i,a,p),await Lt({pmRoot:r,filePath:o,raw:pn(u.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await X({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:o,statuses:u.file.statuses.length},warnings:Mt(s),generated_at:$()}}function bp(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function Ub(e,t,n){return{...bp(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function kp(e){return{id:e.id,source:to.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Ep(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function zb(){let e=new Map,t=z();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let i of r){if(typeof i!="object"||i===null||Array.isArray(i))continue;let a=i.name;typeof a=="string"&&a.trim().length>0&&e.set(a.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function Hb(e){let t=ge(e),n=[],r=[];for(let i of t.definitions){let a=kp(i);a.source==="builtin"?n.push(a):r.push(a)}return{builtin:n,custom:r}}async function _r(e){let t=L(process.cwd(),e.path);await yt(t);let n=await T(t),r=Re(n.schema),i=Ze(t,r.files.types,Le.types),a=is(t,r),o=G(n,z()),s=zb(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:i,statusesPath:a,byType:o.by_type,customNames:c,extensionProvenance:s,schema:r}}async function VN(e){let t=await _r(e),n=[],r=[],i=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Ep(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=bp(s);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let a=Hb(t.schema),o=Zr(t.schema).definitions.map(as);return{action:"list",builtin:n,custom:r,extension:i,counts:{builtin:n.length,custom:r.length,extension:i.length,total:n.length+r.length+i.length},statuses:{builtin:a.builtin,custom:a.custom,counts:{builtin:a.builtin.length,custom:a.custom.length,total:a.builtin.length+a.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:$()}}async function JN(e,t){let n=(e??"").trim();if(n.length===0)throw new y("Type name must not be empty.",g.USAGE);let r=await _r(t),i=Object.values(r.byType).find(a=>a.name.toLowerCase()===n.toLowerCase()||a.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!i)throw new y(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${dn(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Ub(i,Ep(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:$()}}async function KN(e,t){let n=le(e);if(n.length===0)throw new y("Status id must not be empty.",g.USAGE);let r=await _r(t),i=ge(r.schema),a=i.alias_to_id.get(n)??n,o=i.by_id.get(a);if(!o)throw new y(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${dn(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:kp(o),file:{path:r.statusesPath},generated_at:$()}}async function YN(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i;try{i=$d({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}let a=await T(r),o=Re(a.schema),s=Ki(r,o),c=[],d=ri(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=W(t.author,a.author_default),u=Te(a),m=await te(r,yp,a.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,a.locks.wait_ms),f;try{let p=await V(s),h;try{h=ln(p)}catch(_){throw new y(_ instanceof Error?_.message:String(_),g.GENERIC_FAILURE)}f=Od(h,i),await Lt({pmRoot:r,filePath:s,raw:un(f.file),op:"schema:add-field",author:l,settings:a}),c.push(...await X({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:s,fields:f.file.fields.length},warnings:Mt(c),generated_at:$()}}async function Gb(e,t,n,r){let i=G(t,z());return(await lt(e,t.item_format,i.type_to_folder,[],n)).filter(a=>{let o=a[r];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function XN(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i=await T(r),a=Re(i.schema),o=Ki(r,a),s=[],c=W(t.author,i.author_default),d=Te(i),l=await te(r,yp,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await V(o),f;try{f=ln(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=Dd(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=le(u.definition?.key??e),h=le(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(h.length>0){let _=await Gb(r,i,a,h);_>0&&s.push(`items_using_field:${_}`)}await Lt({pmRoot:r,filePath:o,raw:un(u.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await X({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:o,fields:u.file.fields.length},warnings:Mt(s),generated_at:$()}}async function ZN(e){let t=await _r(e),n=Zr(t.schema).definitions.map(as);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Ki(t.pmRoot,t.schema)},generated_at:$()}}async function QN(e,t){let n=le(e);if(n.length===0)throw new y("Field key must not be empty.",g.USAGE);let r=await _r(t),i=Zr(r.schema).by_key.get(n);if(!i)throw new y(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${dn(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:as(i),file:{path:Ki(r.pmRoot,r.schema)},generated_at:$()}}async function eL(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i;try{let h=Td(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${Cd.join(", ")}.`);i=h}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}let a=await T(r),o=Re(a.schema),s=vp(r,o),c=[],d=W(t.author,a.author_default),l=Te(a),u=[],m=[],f,p=await te(r,Ji,a.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms);try{let h=await V(s),_;try{_=ct(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=_;for(let v of eo(i)){let E=Xr(w,v);w=E.file,(E.replaced?m:u).push(E.definition.name)}f=w.definitions.length,await Lt({pmRoot:r,filePath:s,raw:It(w),op:"schema:apply-preset",author:d,settings:a}),await hr(r,eo(i),c,"schema:apply-preset-folder"),c.push(...await X({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await p()}return{action:"apply-preset",preset:i,registered:u,replaced:m,file:{path:s,definitions:f},warnings:Mt(c),generated_at:$()}}function Wb(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new y("--min-count must be a positive integer (>= 1).",g.USAGE);return e}async function tL(e,t){let n=L(process.cwd(),t.path);await yt(n);let r=await T(n),i=Re(r.schema),a=vp(n,i),o=Wb(e.minCount),s=G(r,z()),c=(await lt(n,r.item_format,s.type_to_folder,[],i)).map(v=>typeof v.title=="string"?v.title:""),d=Qm(c,{minCount:o}),l=[],u=[],m=[],f=[],p;if(!e.apply){let v;try{v=ct(await V(a))}catch(E){throw new y(E instanceof Error?E.message:String(E),g.GENERIC_FAILURE)}return p=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:d,registered:u,replaced:m,skipped:f,file:{path:a,definitions:p},warnings:l,generated_at:$()}}let h=W(e.author,r.author_default),_=Te(r),w=await te(n,Ji,r.locks.ttl_seconds,h,!!e.force,_.force_required_for_stale_lock,r.locks.wait_ms);try{let v=await V(a),E;try{E=ct(v)}catch(x){throw new y(x instanceof Error?x.message:String(x),g.GENERIC_FAILURE)}let k=E;for(let x of d){if(x.shadows_builtin){f.push({name:x.name,reason:"shadows_builtin"});continue}let D;try{D=Qa({name:x.name})}catch{f.push({name:x.name,reason:"invalid_type_token"});continue}let S=Xr(k,D);k=S.file,(S.replaced?m:u).push(S.definition.name)}p=k.definitions.length,await Lt({pmRoot:n,filePath:a,raw:It(k),op:"schema:infer-types",author:h,settings:r}),await hr(n,k.definitions.filter(x=>u.includes(x.name)||m.includes(x.name)),l,"schema:infer-types-folder"),l.push(...await X({path:a,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:o,candidates:d,registered:u,replaced:m,skipped:f,file:{path:a,definitions:p},warnings:Mt(l),generated_at:$()}}import Sp from"node:fs/promises";import os from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cf1403b0-7b07-5f00-9523-87bc727dd7fa")}catch{}})();function De(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function I(e){return e.trim().toLowerCase()}function Yi(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let i=t.slice(n,r);if(i.length===0)throw new y("Extension manifest name must resolve to a non-empty directory name.",g.USAGE);if(i==="."||i==="..")throw new y('Extension manifest name must not resolve to "." or "..".',g.USAGE);return i}function ss(e){return bd(e)}async function qb(e){try{let t=JSON.parse(await Sp.readFile(os.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(r=>typeof t.scripts?.[r]=="string")}}catch{return{has_build_script:!1}}}async function Bb(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new y(`Extension entry file is missing at "${t}".`,g.USAGE);let r=await qb(n.source_root),i=r.package_name?`pm install npm:${r.package_name}`:void 0,a=n.source_input??n.source_root;return new y(`Extension entry "${e.entry}" is absent from GitHub source "${a}". pm install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,g.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${a}`,normalized_args:["install",a],...i?{next_best_command:i}:{}}})}async function On(e,t={}){let n=os.join(e,"manifest.json");if(!await O(n))throw new y(`Extension manifest is missing at "${n}".`,g.USAGE);let r;try{r=JSON.parse(await Sp.readFile(n,"utf8"))}catch(o){throw new y(`Failed to parse extension manifest at "${n}": ${Vb(o)}`,g.USAGE)}let i=ss(r);if(!i)throw new y(`Extension manifest at "${n}" is invalid.`,g.USAGE);let a=os.resolve(e,i.entry);if(!fe(e,a))throw new y(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await O(a))throw await Bb(i,a,t);if(!await kd(e,a))throw new y(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:a,manifest:i}}function Vb(e){return e instanceof Error?e.message:String(e)}import cs from"node:fs/promises";import Jb 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]="5181479f-469f-525b-add2-914a9934afbd")}catch{}})();var Kb=".managed-extensions.json",Xi=1;function gr(e){return Jb.join(e,Kb)}function Yb(){return{version:Xi,updated_at:$(),entries:[]}}function yr(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function xp(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function ke(e){return typeof e=="string"?e:void 0}function Xb(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function Zb(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:ke(t.name),package:ke(t.package),version:ke(t.version),repository:ke(t.repository),owner:ke(t.owner),repo:ke(t.repo),ref:ke(t.ref),subpath:ke(t.subpath),commit:ke(t.commit)}}function Qb(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Xb(t))return null;let n=Zb(t.source);if(!n)return null;let r=wd(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:De(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:ke(t.last_update_check_at),last_update_remote_commit:ke(t.last_update_remote_commit),last_update_remote_version:ke(t.last_update_remote_version),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:ke(t.update_error)}}function ek(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Xi||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=Qb(r);i&&n.push(i)}return{version:Xi,updated_at:ke(t.updated_at)??$(),entries:yr(n)}}async function ye(e){let t=gr(e),n=Yb();try{let r=await cs.readFile(t,"utf8"),i=JSON.parse(r),a=ek(i);if(!a)throw new y(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE);return{path:t,state:a,warnings:[]}}catch(r){if(r instanceof y)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&F(r))return{path:t,state:n,warnings:[]};throw new y(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE)}}async function Dn(e,t){let n=gr(e),r={version:Xi,updated_at:$(),entries:yr(t.entries)};await cs.mkdir(e,{recursive:!0}),await cs.writeFile(n,`${JSON.stringify(r,null,2)}
39
- `,"utf8")}function wr(e,t){let n=e.entries.filter(r=>I(r.name)!==I(t.name)&&I(r.directory)!==I(t.directory));return n.push(t),{...e,updated_at:$(),entries:yr(n)}}async function Ap(e,t,n,r){let i=t.entries.find(o=>I(o.name)===I(n));if(!i)return t;let a=wr(t,{...i,contributions:r});return await Dn(e,a),a}import{execFile as uk}from"node:child_process";import K from"node:fs/promises";import fs from"node:os";import j from"node:path";import{fileURLToPath as mk}from"node:url";import{promisify as pk}from"node:util";import fk from"npm-package-arg";import{extract as hk,list as _k}from"tar";import tk from"node:fs/promises";import qe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var nk="PM_CLI_PACKAGE_ROOT",Ip={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},rk=new Set(["*","all"]);function ds(){let e=[],t=process.env[nk];return typeof t=="string"&&t.trim().length>0&&e.push(qe.resolve(t.trim())),e.push(Ne(import.meta.url,["../../.."])),[...new Set(e)]}async function vr(e){let t=e.trim().toLowerCase(),n=await Cp(t);if(n)return n;let r=Ip[t];if(!r)return null;for(let i of ds()){let a=qe.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await O(qe.join(a,"manifest.json")))return a}return null}function Rp(e){return rk.has(e.trim().toLowerCase())}function ik(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function ak(e,t){let n=await tk.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=qe.join(e,r.name);if(!await O(qe.join(i,"package.json")))continue;let a=await Kr(i),o=a.aliases&&a.aliases.length>0?a.aliases:[ik(r.name)];for(let s of o){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:i,package_name:a.package_name??null})}}}async function ls(){let e=new Map;for(let t of ds()){let n=qe.join(t,"packages");await O(n)&&await ak(n,e)}for(let[t,n]of Object.entries(Ip))if(!e.has(t))for(let r of ds()){let i=qe.join(r,"packages",n.package_directory);if(await O(qe.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Zi(){return(await ls()).map(e=>e.alias)}async function Cp(e){let t=e.trim().toLowerCase();return(await ls()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function Tp(e){let t=await Cp(e);return t?(await Kr(t)).package_name??null:null}async function $p(e){let t=await vr(e);if(!t)return null;try{let n=await Yr(t);return n.length!==1?null:(await On(n[0])).manifest.name}catch{return null}}function ok(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function sk(e,t,n,r,i,a){let o=r==="global"?"--global":"--project",s=Object.fromEntries(Za.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||a.has(qe.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:ok(e),media:e.catalog?.media}}}async function Op(e,t,n={}){let r=cn(L(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,a=await ye(i),o=new Set(a.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>qe.resolve(m.source.location))),s=new Set(a.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),c=[],d=new Map;for(let m of await ls()){let f=qe.resolve(m.package_root),p=d.get(f)??[];p.push(m),d.set(f,p)}for(let m of d.values()){let f=m[0],p=m.map(_=>_.alias).sort((_,w)=>_.localeCompare(w)),h=await Kr(f.package_root);c.push(sk(h,f,p,e,s,o))}let l=dk(n.fields),u=l?c.map(m=>lk(m,l)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Za.filter(m=>m!=="extensions"),packages:u}}var ck=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function dk(e){if(e===void 0)return;let t=eu(e);if(t.length===0)throw new y("Package catalog --fields requires a comma-separated list of field names",g.USAGE);let n=t.filter(r=>!ck.has(r));if(n.length>0)throw new y(`Unknown package catalog --fields value(s): ${n.join(", ")}`,g.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function lk(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="db10bb85-f21c-58b1-8b78-8ce1024b3e08")}catch{}})();var Pp=pk(uk),ea="@unbrained/pm-cli",gk={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},us;async function Np(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=j.resolve(t);for(;;){let i=j.join(r,"node_modules",...n.split("/")),a=j.join(i,"package.json");if(await O(a))try{let s=JSON.parse(await K.readFile(a,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let o=j.dirname(r);if(o===r)return null;r=o}}function ms(e,t,n){let r=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(r.length<2)return null;let i=r[0],a=r[1].replace(/\.git$/i,"");if(i.length===0||a.length===0)return null;let o=r.slice(2),s,c;return o[0]==="tree"&&o.length>=2?(s=o[1],c=o.slice(2).join("/")):o.length>0&&(c=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:a,repository:`https://github.com/${i}/${a}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function yk(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new y('npm package source must include a package spec after "npm:".',g.USAGE);if(t)throw new y('Options "--gh/--github" cannot be combined with npm: package sources.',g.USAGE);if(n)throw new y('Option "--ref" cannot be combined with npm: package sources.',g.USAGE);return{kind:"npm",input:e,spec:r}}function br(e,t={}){let n=e.trim();if(n.length===0)throw new y("Extension source is required for --install.",g.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return yk(n,t.forceGithub===!0,r);let i=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return ms(s,n,r)}catch{return null}})();if(i)return i;let a=n.startsWith("github.com/")?n.slice(11):null;if(a){let o=ms(a,n,r);if(!o)throw new y(`Invalid GitHub source "${n}".`,g.USAGE);return o}if(t.forceGithub){let o=ms(n,n,r);if(!o)throw new y(`Invalid GitHub shorthand "${n}".`,g.USAGE);return o}if(/^https?:\/\//i.test(n))throw new y(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,g.USAGE);return{kind:"local",input:n,absolute_path:j.resolve(process.cwd(),n)}}async function Qi(e,t=Pp,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",a=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new y(`Git command failed: git ${e.join(" ")}
40
- ${a}`,g.GENERIC_FAILURE)}}function hs(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function _s(e=process.platform){return e==="win32"}async function Lp(e,t,n=Pp,r=process.platform,i=process.env){let a=hs(r),o=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));o.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(a,e,{cwd:t,encoding:"utf8",env:o,shell:_s(r)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",d=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new y(`npm command failed: ${a} ${e.join(" ")}
41
- ${d}`,g.GENERIC_FAILURE)}}function Mp(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function jp(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function wk(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("npm err! code e404")||t.includes("404 not found")||t.includes("is not in this registry")}function vk(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return wk(e)||t.includes("not found")}function bk(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function kk(e){let t=Mp(e),n=bk(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,a=i?`pm install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:a?[a,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:a?[`Try ${a} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&a?{fallback_candidates:[{source:i,command:a,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:a}:{}}}}}function Ek(e,t){if(!vk(t))return null;let n=kk(e);return new y(n.message,g.NOT_FOUND,n.context)}async function Fp(e){if(j.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=j.resolve(process.cwd(),e);return await O(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=mk(t);return await O(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=j.resolve(process.cwd(),e);if(await O(t))return t}return null}async function Sk(e){let t=await Fp(e);if(t)return t;let n=xk(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function xk(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!jp(e))return e;let i=e.slice(0,r),a=e.slice(r+n.length);if(a.startsWith("//")&&!a.startsWith("///"))return e;if(!a.startsWith("/"))return`${i}@${j.resolve(t,a)}`;let o;try{o=decodeURIComponent(new URL(`file:${a}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${i}@${s}`}function Dp(e,t){let n=j.resolve(e,t),r=j.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${j.sep}`)||j.isAbsolute(r))throw new y("npm pack reported a package archive outside its isolated destination.",g.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function Ak(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function Ik(e){return(Array.isArray(e)?e.map(t=>({value:t})):typeof e=="object"&&e!==null?Object.entries(e).map(([t,n])=>({key:t,value:n})):[]).flatMap(({key:t,value:n})=>{let r=Ak(n,t);return r?[r]:[]})}function Rk(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(o=>{let s=o.name?.trim().toLowerCase();return s!==void 0?s===n:o.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let i=e[0],a=i.name??i.key;return n&&a!==void 0&&a.trim().toLowerCase()!==n?void 0:i}function Ck(e,t,n){let r;try{r=JSON.parse(e)}catch{let o=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!o)throw new y("npm pack did not report a tarball filename.",g.GENERIC_FAILURE);return{tarball:Dp(t,o)}}let i=Ik(r),a=Rk(i,n);if(!a)throw new y("npm pack --json returned an unsupported or ambiguous package receipt.",g.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Dp(t,a.filename),package:a.name??a.key,version:a.version}}async function Tk(e){return $k(e,Lp)}async function $k(e,t){let n=await Fp(e.spec);if(n){if((await K.stat(n)).isFile()&&Up(n))return ps(n);let a=j.join(n,"package.json"),o=await O(a)?JSON.parse(await K.readFile(a,"utf8")):{};return{directory:await ta(n,e.input),package:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,cleanup:async()=>{}}}let r=await K.mkdtemp(j.join(fs.tmpdir(),"pm-npm-package-source-")),i=j.join(r,"pack");await K.mkdir(i,{recursive:!0});try{let a=await Sk(e.spec),o=await t(["pack",a,"--json","--pack-destination",i]),s=Ck(o,i,jp(e.spec)?void 0:Mp(e.spec));if(!await O(s.tarball))throw new y("npm pack did not create its reported package archive.",g.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await ps(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await K.rm(r,{recursive:!0,force:!0})}}}}catch(a){throw await K.rm(r,{recursive:!0,force:!0}),Ek(e.spec,a)||a}}function Up(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function wt(e){throw new y(e,g.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function Ok(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&wt(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,i=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||i.some(a=>a===".."))&&wt(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&wt(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&wt(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&wt(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&wt(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&wt(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function ps(e,t=gk){(await K.stat(e)).size>t.maxArchiveBytes&&wt(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await K.mkdtemp(j.join(fs.tmpdir(),"pm-local-package-archive-")),r=j.join(n,"extract");await K.mkdir(r,{recursive:!0});let i={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await _k({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(a===void 0)try{Ok(d,t,i)}catch(l){a=l}}}),a!==void 0)throw a;i.packageJsonEntries!==1&&wt(`Local package archive must contain exactly one package/package.json entry; found ${i.packageJsonEntries}.`),await hk({file:e,cwd:r,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let o=j.join(r,"package"),s=j.join(o,"package.json"),c=JSON.parse(await K.readFile(s,"utf8"));return await Dk(o),{directory:await ta(o,e),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{await K.rm(n,{recursive:!0,force:!0})}}}catch(o){throw await K.rm(n,{recursive:!0,force:!0}),o}}async function Dk(e,t=Lp){let n=j.join(e,"package.json");if(!await O(n))return;let r;try{r=JSON.parse(await K.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,a=Fk(i),o=Pk(i);if(a.length===0&&!o)return;let s={...r};delete s.devDependencies;let c={...s};Nk(c),await K.writeFile(n,`${JSON.stringify(c,null,2)}
42
- `,"utf8");try{await Promise.all([K.rm(j.join(e,"package-lock.json"),{force:!0}),K.rm(j.join(e,"npm-shrinkwrap.json"),{force:!0})]),a.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await Lk(e)}finally{await K.writeFile(n,`${JSON.stringify(s,null,2)}
43
- `,"utf8")}}function Pk(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&ea in t)return!0;return!1}function Nk(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[ea],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function Lk(e){let t=Ne(import.meta.url,["../../.."]),[n,r]=ea.split("/"),i=j.join(e,"node_modules",n),a=j.join(i,r);await K.mkdir(i,{recursive:!0}),await K.rm(a,{recursive:!0,force:!0}),await K.symlink(t,a,Mk(process.platform))}function Mk(e){return e==="win32"?"junction":"dir"}function jk(e,t){if(e.startsWith("-"))throw new y(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,g.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(n=>{let r=n.charCodeAt(0);return r<=31||r===127||"&|;()`\"'".includes(n)}))throw new y(`Extension runtime dependency "${e}" has an unsafe version specifier.`,g.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{fk.resolve(e,t)}catch{throw new y(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,g.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function Fk(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===ea||typeof i!="string"||i.trim().length===0||t.has(r))continue;let a=i.trim();t.set(r,jk(r,a))}return[...t.values()]}async function ta(e,t){let n=await Yr(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>j.relative(e,i).replaceAll(j.sep,"/")).sort((i,a)=>i.localeCompare(a));throw new y(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,g.USAGE)}throw new y(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,g.USAGE)}async function Uk(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(j.posix.join(".agents/pm/extensions",t.subpath)),n.push(j.posix.join(".custom/pm-extensions",t.subpath)),n.push(j.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let a=j.resolve(e,i);if(fe(e,a)&&await O(j.join(a,"manifest.json")))return{directory:a,resolved_subpath:i}}if(await O(j.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await ta(e,t.input);return{directory:r,resolved_subpath:j.relative(e,r).replaceAll(j.sep,"/")}}function zk(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function Hk(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!zk(n))return new y(t,g.NOT_FOUND);let r=[];try{let a=process.env.PM_CLI_PACKAGE_ROOT,o=typeof a=="string"&&a.trim().length>0?j.resolve(a.trim()):"";us?.key!==o&&(us={key:o,aliases:await Zi()}),r=us.aliases}catch{}let i=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${r.join(", ")}`];return new y(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,g.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function zp(e){if(e.kind==="local"){let r;try{r=await K.stat(e.absolute_path)}catch{throw await Hk(e)}if(r.isFile()&&Up(e.absolute_path)){let a=await ps(e.absolute_path);return{source:e,directory:a.directory,source_root:j.dirname(a.directory),resolved_subpath:j.relative(j.dirname(a.directory),a.directory).replaceAll(j.sep,"/"),npm_package:a.package,npm_version:a.version,cleanup:a.cleanup}}if(!r.isDirectory())throw new y(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,g.USAGE);let i=await ta(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await Tk(e);return{source:e,directory:r.directory,source_root:j.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:j.relative(j.dirname(r.directory),r.directory).replaceAll(j.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await K.mkdtemp(j.join(fs.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Qi(n);let r=await Qi(["-C",t,"rev-parse","HEAD"]),i=await Uk(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await K.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await K.rm(t,{recursive:!0,force:!0}),r}}async function na(e,t){if(!await O(e)||!await O(t))return!1;let[n,r]=await Promise.all([K.realpath(e),K.realpath(t)]);return n===r}import kr from"node:fs/promises";import Er from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var gs=1,tn="2026.6.24",Gk=">=22.18.0",Wk={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Hp=new Set([...yd.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(gd).map(e=>e.toLowerCase()),"scaffold"]),qk="^6.0.0",Bk="^22.0.0",qp=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],rt=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Gp(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Bp(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function Vp(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var Vk={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Wp=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Jp={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},Jk={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},Kk={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},Yk={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},Kp="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Xk={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},Zk={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},Qk={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},eE={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function Yp(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function Xp(e,t){return e==="schema"?Qk[t]:e==="profile"?eE[t]:Zk[t]}function tE(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(o=>o.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),a=r>0&&(r===t.length||i!==void 0&&Hp.has(i));return`${(Hp.has(n)||a?["starter",...t]:t).join(" ")} ping`}function Zp(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],a=`${e.replace(/-/g,"_")}_owner`,o="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(a)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function nE(e,t,n){let r=`${e}-search`,i=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,o=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...Zp(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(a)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(a)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...o,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...o,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function rE(e,t,n){let r=n==="hooks",i=n==="search",a=n==="importers",o=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",m=Jk[n],f=e,p=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,_=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...rt,"});",""]:[],E=i?ys(e,t,"search",m):[],k=a?ys(e,t,"importers",m):[],x=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Gp(Bp({extensionName:e,itemTypeName:f,itemTypeFolder:p,fieldName:h,migrationId:_,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...rt,"});",""]:[],D=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Gp(Vp(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...rt,"});",""]:[],S=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...rt,"});",""]:[],b=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...rt,"});",""]:[],N=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...rt,"});",""]:[],A=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...rt,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...qp,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...rt,"});","",...v,...E,...k,...x,...D,...S,...b,...N,...A,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
44
- `)}function iE(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var aE={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},oE={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function sE(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function cE(e,t,n){let r=[],i=[...sE(e,t,n)],a=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),m=u===d?[]:[u],f=`${e.replace(/-/g,"_")}_note`,p=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),a.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),a.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),a.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(f)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(p)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),a.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...Zp(e),"});"),a.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),a.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),a.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),a.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),a.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:a}}function dE(e,t,n){let r=cE(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((i,a)=>i.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
45
- `)}function ys(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,a=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],m=f=>[...u," let deactivated = false;"," try {",...f.map(p=>p===""?p:` ${p}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...rt];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(a)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(Bp({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Vp(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function lE(e,t,n){let r=n==="parser",i=JSON.stringify([...Jp[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...qp,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(tn)},`," },",` target: { pmVersion: ${JSON.stringify(tn)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...rt,"});","",...ys(e,t,n,i)].join(`
46
- `)}function uE(e,t,n){let r=Yp(n,"package"),i=Xp(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${aE[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",Kp,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${oE[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${gs}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${tn}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
47
- `)}function mE(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function pE(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function fE(e,t,n,r){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function hE(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function _E(e,t,n,r="commands",i=!1){let a=`pm-${e}`,o=Jp[r],s=iE(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:gs,pm_min_version:tn,trusted:!0,sandbox_profile:"strict",permissions:{...Wk},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
48
- `,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...nE(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
49
- `),l=`${JSON.stringify(Vk,null,2)}
50
- `,u=Kk[r],m=Yp(r,"package"),f=`${JSON.stringify({name:a,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Gk},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${tn}`},devDependencies:{"@types/node":Bk,typescript:qk},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
51
- `,p=rE(e,t,r),h=Yk[r],_=["node_modules/","*.log","*.tsbuildinfo",""].join(`
52
- `),w=mE(e),v=["```ts",`import { ${pE(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...fE(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...hE(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],E=[`# ${a}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,h,Kp,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...v,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Xk[r],...Xp(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${tn}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${gs}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${tn}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
53
- `);return{"package.json":f,"manifest.json":c,"index.ts":i?dE(e,t,r):d,"index.test.ts":i?lE(e,t,r):p,"tsconfig.json":l,".gitignore":_,"README.md":i?uE(a,t,r):E}}async function Qp(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!Wp.includes(i))throw new y(`Unknown scaffold capability "${n}". Supported capabilities: ${Wp.join(", ")}.`,g.USAGE);let a=i;if(r&&t!=="package")throw new y("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",g.USAGE);let o=r?"declarative":"imperative",s=e.trim(),c=Er.resolve(process.cwd(),s),d=Yi(Er.basename(c)).replace(/^(?:pm-)+/u,""),l=tE(d),u=_E(d,l,t,a,r),m=!1;if(await O(c)){if(!(await kr.stat(c)).isDirectory())throw new y(`Scaffold target "${c}" exists and is not a directory.`,g.CONFLICT)}else await kr.mkdir(c,{recursive:!0}),m=!0;for(let[p,h]of Object.entries(u)){let _=Er.join(c,p);if(await O(_)&&await kr.readFile(_,"utf8")!==h)throw new y(`Scaffold file "${p}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,g.CONFLICT)}let f=[];for(let[p,h]of Object.entries(u)){let _=Er.join(c,p);if(await O(_)){f.push({path:p,status:"unchanged"});continue}await kr.mkdir(Er.dirname(_),{recursive:!0}),await kr.writeFile(_,h,"utf8"),f.push({path:p,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:a,style:o,target_path:c,created_directory:m,files:f}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function ef(e,t){return`${e}:${I(t)}`}function gE(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let a=new Map;for(let o of i){let s=a.get(o.command)??[];a.set(o.command,[...s,o])}for(let[o,s]of a){if(t!==null&&!s.some(d=>t.has(I(d.name))))continue;let c=s.at(-1);n.push({command:o,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function tf(e,t,n){let r=new Set(n.failed.map(d=>ef(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(ef(d.layer,d.name))?"failed":"ok",surfaces:xn(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:xn(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),a=typeof e=="string"?I(e):null,o=a===null?null:new Set(t.loaded.filter(d=>I(d.name)===a||typeof d.source_package=="string"&&I(d.source_package)===a||(d.source_aliases??[]).some(l=>I(l)===a)).map(d=>I(d.name)).concat(a)),s=o===null?i:i.filter(d=>o.has(I(d.name))),c=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:xn(n,c),command_ownership:gE(n,o)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e6087f2-01b5-59c3-a471-433c722316b0")}catch{}})();function ws(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function ra(e,t,n){let r=I(t),i=n.trim();if(r.length===0||i.length===0)return;let a=e.get(r)??new Set;a.add(i),e.set(r,a)}function yE(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)ra(t,r.name,r.command),ra(n,r.name,r.action);for(let r of e.commands.handlers)ra(t,r.name,r.command);for(let r of e.commands.overrides)ra(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function nf(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function wE(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:a}=e;return t?i.has(n)||a.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function ia(e,t,n){let r=new Set(t.loaded.map(c=>I(c.name))),i=new Set(t.failed.map(c=>I(c.name))),a=new Set(n.failed.map(c=>I(c.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=yE(n);return e.map(c=>{let d=I(c.name),l=nf(o.get(d)),u=nf(s.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},f=wE({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:i,activationFailedNames:a});return{...c,...f,...m}})}function vE(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function me(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var of=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function bE(e){return of.has(mf(e))}function rf(e){return e==="project"||e==="global"}function sf(e){let t=e.split(":"),n=t[0];if(!n||!of.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!rf(r)||!rf(a)||!i||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:a,name:o}}}function kE(e){let t=new Set;for(let n of e){let r=sf(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function vs(e,t){let n=e.filter(bE);if(n.length===0)return null;let r=kE(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function EE(e,t,n,r){let i=t.map(u=>sf(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let a=e==="global"?"--global":"--project",o=me(r,"deactivate"),s=`${me(r,"doctor")} ${a} --detail deep --trace`,c=new Map(n.map(u=>[I(u.name),u])),d=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let f=I(m);d.set(f,(d.get(f)??0)+1)}let l=[...d.entries()].map(([u,m])=>{let f=c.get(u),p=f?.name??u,h=f?.command_paths??[],_=f?.action_paths??[];return{action:"deactivate",extension:p,command:`${o} ${p} ${a}`,affected_collisions:m,feature_loss:{command_paths:[...h].sort((w,v)=>w.localeCompare(v)),action_paths:[..._].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let f=m.affected_collisions-u.affected_collisions;if(f!==0)return f;let p=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,h=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return p!==h?p-h:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:d.size,next_best_command:s,collisions:i,remediation_candidates:l}}function cf(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function df(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function lf(e,t){let n=[];for(let r of zd(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var SE=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${me(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${Wr.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${me(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${me(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${me(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function xE(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=[],m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o};if(t.length>0){let f=vs(t,{deactivate:`${me(n,"deactivate")} <name> ${i}`,doctor:`${me(n,"doctor")} ${i} --detail deep --trace`});f&&u.push(f);for(let p of SE)p.matches(t,m)&&u.push(p.build(m))}return s>0&&u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${me(n,"manage")} ${i} --fix-managed-state (or ${me(n,"adopt-all")} ${i}, ${me(n,"adopt")} <name> ${i}, or reinstall via ${me(n,"install")} ${i} <source>).`),d>0&&u.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&u.push(`Update-check coverage is partial: some sources have no completed check. Run ${me(n,"manage")} ${i} to request update checks.`),l>0&&u.push(`Update available managed extensions via ${me(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${me(n,"manage")} ${i} after extension changes.`),u}function aa(e,t,n,r={}){let i=[...new Set(t)].sort((b,N)=>b.localeCompare(N)),a=n.filter(b=>b.managed).length,o=n.filter(b=>b.enabled).length,s=n.filter(b=>b.active).length,c=n.filter(b=>b.update_check_status==="checked"&&b.update_available===!0).length,d=n.filter(b=>b.managed===!1),l=d.filter(b=>af(b)).map(b=>b.name).sort((b,N)=>b.localeCompare(N)),u=d.filter(b=>!af(b)).map(b=>b.name).sort((b,N)=>b.localeCompare(N)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let b of n)m[b.update_check_status]+=1;let f=m.failed,p=n.filter(b=>b.update_check_status==="skipped_non_github"&&b.source?.kind!=="builtin").length,h=Object.entries({skipped_unmanaged:u.length,skipped_non_github:p,failed:f,not_checked:m.not_checked}).filter(([,b])=>b>0).map(([b,N])=>`extension_update_health_partial_coverage:${b}:${N}`),_=h.length>0,w=_?"partial":"full",v=[...new Set([...i,...h])].sort((b,N)=>b.localeCompare(N)),E=[...new Set(v.map(b=>mf(b)))].sort((b,N)=>b.localeCompare(N)),k=vE(v),x=e==="global"?"--global":"--project",D=EE(e,i,n,r),S=xE({normalizedWarnings:v,options:r,scope:e,scopeFlag:x,updateCheckFailedTotal:f,policyWarningCount:k.warning_count,unmanagedActionRequiredTotal:u.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:p,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:E,warnings:v,policy_warning_count:k.warning_count,policy_violation_count:k.violation_count,policy_blocked_count:k.blocked_count,total_extensions:n.length,managed_total:a,enabled_total:o,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:_,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(b=>b.name).sort((b,N)=>b.localeCompare(N)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:f,top_warnings:v.slice(0,8),remediation:S,...D?{collision_plan:D}:{}}}function uf(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new y(`Invalid --detail value "${e}". Expected summary or deep.`,g.USAGE)}function mf(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Sr(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let a=Yc(r);return a?[a]:Xc(r)})();for(let a of i){let o=`${a.layer}:${a.name}:${a.capability}`;t.has(o)||(t.add(o),n.push(a))}}return n}function xr(){return{version:qr.version,capabilities:[...qr.capabilities],legacy_aliases:{...qr.legacy_aliases}}}function af(e){let t=I(e.name),n=I(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function pf(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let a=[...new Set(t.filter(d=>d.active).map(d=>I(d.name)))].sort((d,l)=>d.localeCompare(l)),o=[...new Set(n.filter(d=>d.layer==="project").map(d=>I(d.name)))].sort((d,l)=>d.localeCompare(l)),s=new Set(r.map(d=>I(d.name))),c=a.filter(d=>!o.includes(d)&&!s.has(d)).sort((d,l)=>d.localeCompare(l));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:a.length,loaded_project_count:o.length,active_project_names:a,loaded_project_names:o,missing_active_project_names:c}}}import ff from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function Ar(e,t,n,r){let i=ff.relative(e,n);if(i!==""&&!fe(e,n)||n===t||fe(t,n))return!1;let a=i.split(ff.sep);return a.includes(".git")?!1:r?!a.some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as AE}from"node:crypto";import se from"node:fs/promises";import IE from"node:os";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]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var hf=3,RE=120,_f=250,CE=12e4,TE=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),gf=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,yf=e=>TE.has(String(gf(e))),oa=(e,t)=>gf(e)===t,wf=e=>new Promise(t=>{setTimeout(t,e)}),vf=async e=>{let t=re.join(e,"package.json");await O(t)||await se.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
54
- `,"utf8")},bf=async e=>{let t=Ne(import.meta.url,["../../.."]),n=re.join(e,"node_modules","@unbrained"),r=re.join(n,"pm-cli");await se.mkdir(n,{recursive:!0}),await se.rm(r,{recursive:!0,force:!0}),await se.symlink(t,r,process.platform==="win32"?"junction":"dir")},Ir=async e=>{let t=re.resolve(e),n=re.dirname(t),r=re.parse(n).root,i=await se.realpath(r).catch(()=>r),a=re.relative(r,n),o=a===""?[]:a.split(re.sep);for(let[s,c]of o.entries()){let d=re.join(i,c);try{i=await se.realpath(d)}catch{i=re.join(i,...o.slice(s));break}}return re.join(i,re.basename(t))},kf=async(e,t,n,r=IE.tmpdir())=>Wt("extension_install_copy",async()=>{let i=re.resolve(e),a=await se.realpath(i).catch(()=>i),o=await Ir(t);if(a===o)return;if(!fe(a,o)){await n(a,t,{recursive:!0,force:!0,filter:u=>Ar(a,o,re.resolve(u),!1)});return}let s=await se.realpath(re.resolve(r)).catch(()=>Ir(r)),c=fe(a,s)?re.dirname(a):s;if(fe(a,c))throw new y(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,g.USAGE,{code:"extension_install_source_contains_destination"});let d=await se.mkdtemp(re.join(c,"pm-extension-copy-")),l=re.join(d,"extension");try{await n(a,l,{recursive:!0,force:!0,filter:u=>Ar(a,o,re.resolve(u),!0)}),await n(l,t,{recursive:!0,force:!0})}finally{await se.rm(d,{recursive:!0,force:!0})}}),Ef=async(e,t,n=se.cp)=>{for(let r=1;r<=hf;r+=1)try{await Wt("extension_install_copy",async()=>{await se.rm(t,{recursive:!0,force:!0}),await kf(e,t,n)});return}catch(i){if(!yf(i)||r===hf)throw i;await wf(_f)}},bs=async e=>{let t;try{t=await se.readFile(re.join(e,"owner.json"),"utf8")}catch(i){if(!At(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},Sf=async(e,t)=>await bs(e)!==t?!1:(await se.rm(e,{recursive:!0,force:!0}),!0),$E=async(e,t)=>{let n;try{n=await se.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await bs(e);return r===null?(await se.rm(e,{recursive:!0,force:!0}),!0):Sf(e,r)},OE=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await bs(e)!==t)return;let a=new Date;await se.utimes(e,a,a)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},DE=async(e,t)=>{await se.mkdir(e);try{await se.writeFile(re.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
55
- `,"utf8")}catch(n){throw await se.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},PE=async(e,t,n,r,i)=>{for(let a=1;a<=n;a+=1)try{return await DE(e,t),!0}catch(o){if(!oa(o,"EEXIST"))throw o;await $E(e,i)?a-=1:await wf(r)}return!1},ks=async(e,t,n,r)=>Wt("extension_install",async()=>{let i=re.join(e,"runtime","extension-install-locks"),a=re.join(i,"scope.lock");await se.mkdir(i,{recursive:!0});let{attempts:o=RE,delay_ms:s=_f,stale_ms:c=CE,heartbeat_ms:d}=r??{};if(![o,s,c,d].filter(w=>w!==void 0).every(Number.isFinite))throw new y("Extension install lock timings must be finite numbers.",g.USAGE);let l=Math.max(1,Math.floor(o)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),f=Math.floor(d??m/3);if(m<=0||f<=0||f>=m)throw new y("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",g.USAGE);let p={pid:process.pid,token:AE(),created_at:$(),destination:t};if(!await PE(a,p,l,u,m))throw new y(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let h=OE(a,p.token,f),_=!1;try{let w=await n();return _=!0,w}finally{await h(),await Sf(a,p.token).catch(w=>{if(_)throw w})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var Es=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o])}});return await Promise.all(a),r};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function xf(e,t){let n=I(e),r=t.find(i=>I(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,a)=>i.localeCompare(a)),action_paths:[...r?.action_paths??[]].sort((i,a)=>i.localeCompare(a))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function Af(e,t){let n=new Set((t?.loaded??[]).flatMap(a=>(a.activation?.commands?.length??0)>0?[`${a.layer}:${I(a.name)}`]:[])),r=e.services.overrides.filter(a=>a.service==="output_format").filter(a=>a.passThrough!==!0).filter(a=>!n.has(`${a.layer}:${I(a.name)}`)).map(a=>`extension_output_service_override_global:${a.service}:${a.layer}:${a.name}`),i=e.renderers.overrides.filter(a=>(a.commands?.length??0)===0&&a.resultDiscriminator===void 0).map(a=>`extension_output_renderer_override_global:${a.format}:${a.layer}:${a.name}`);return[...new Set([...r,...i])].sort((a,o)=>a.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var If=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=ri(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{execFile as NE}from"node:child_process";import{promisify as LE}from"node:util";import ME from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b67e46f9-51ff-501b-98da-74353b4c66d9")}catch{}})();var jE=LE(NE),Cf=1e4;function Rf(e,t,n){if(typeof t=="string")try{let r=ME.resolve(e,t);if(r.type==="version")return r.fetchSpec}catch{}throw new Error(n)}async function FE(e,t){try{return(await jE(hs(),e,{encoding:"utf8",timeout:t,maxBuffer:65536,shell:_s(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function Tf(e,t=FE){let n=$();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let r=Rf(e.package,e.version,"missing_or_invalid_installed_npm_version"),i=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],Cf),a;try{a=JSON.parse(i)}catch{throw new Error("invalid_npm_registry_metadata")}let o=Array.isArray(a)&&a.length===1?a[0]:a,s=Rf(e.package,o,"invalid_npm_registry_version");return{checked_at:n,available:s!==r,remote_version:s}}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}}var UE=(e,t,n)=>{let r=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c=""]=o.split(/\s+/);return{commit:s,ref:c}}),i=r.find(o=>o.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let a=t?.trim();return a?{checked_at:n,remote_commit:i.commit,available:i.commit!==a}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},Ss=async(e,t=Qi)=>{let n=$();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let r=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,Cf);return UE(i,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(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]="d34e2cc0-5e58-5534-8480-a9ab47ec4a88")}catch{}})();var zE=4;async function $f(e,t=!1){let n=await Es(e.entries,zE,async r=>{if(!["github","npm"].includes(r.source.kind))return r;if(t)return{...r,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0};let i=r.source.kind==="github"?await Ss(r.source):await Tf(r.source);return{...r,last_update_check_at:i.checked_at,last_update_remote_commit:"remote_commit"in i?i.remote_commit:void 0,last_update_remote_version:"remote_version"in i?i.remote_version:void 0,update_available:i.available,update_error:i.error}});return{...e,entries:yr(n)}}import HE from"node:fs/promises";import GE from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function xs(e){return GE.join(e,"extension-migrations.json")}function Of(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Df(e,t){return`${e.layer}:${e.name}:${t}`}async function WE(e){let t=xs(e);if(!await O(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await HE.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function As(e,t){let n=await WE(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,a)=>{let o=Of(i,a),s=r.get(Df(i,o));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function qE(e){let t=await As(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),r=[],i=!1,a=e.migrations.map((l,u)=>({migration:l,index:u})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:u}of a){let m=Of(l,u),f=Df(l,m),p=n.get(f),h=String(l.definition.status??"pending").toLowerCase(),_=p?.status??(h==="applied"||h==="failed"?h:"pending");if(_==="applied"){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:_}));let E={key:f,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(f,E),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"applied"}),i=!0}catch(E){let k=E instanceof Error?E.message:String(E),x={key:f,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:k};n.set(f,x),l.definition.status="failed",l.definition.reason=k,r.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"failed",error:k}),i=!0}}if(i){let l=await T(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,f)=>m.key.localeCompare(f.key))};await gi({pmRoot:e.pmRoot,filePath:xs(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
56
- `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let o=r.filter(l=>l.outcome==="pending").length,s=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:xs(e.pmRoot),total:r.length,pending_count:o,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function Pf(e){let t=await T(e.resolvedRoots.settings_root),n=await Ye({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Xe(n);e.warnings.push(...n.warnings,...r.warnings);let i=await qE({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fcf7df06-e3b8-5476-a76a-cd391839c13d")}catch{}})();function Nf(e,t){let n=e.filter(r=>r.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:r,result:i})=>{let a=i.details;return{alias:r,ok:i.ok,extension:a.extension,source:a.source,source_resolution:a.source_resolution,install_plan:a.install_plan,dry_run:a.dry_run,destination_path:a.destination_path,activated:a.activated,settings_changed:a.settings_changed,command_paths:a.command_paths,action_paths:a.action_paths,command_discovery:a.command_discovery,verification:a.verification,runtime_activation_status:a.runtime_activation_status,activation_diagnostics:a.activation_diagnostics,warnings:i.warnings}})}}import ca from"node:fs/promises";import sa from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var BE=new Set(["node_modules",".git","dist","build","coverage"]);async function Lf(e,t,n,r){let i=e.source.kind==="local"?await ca.stat(e.source.absolute_path):void 0,a=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,o=await VE(e.directory,t,r),s={source_mode:a,...a==="archive"?{archive_bytes:i.size}:{},copy:o},c=e.source_root??e.directory;if(a==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await O(sa.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),a==="directory"&&!o.complete){let d=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new y(`Local extension source scan stopped at ${d}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,g.USAGE,{code:"extension_install_incomplete_source_scan",reason:o.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function VE(e,t,n={}){let{maxEntries:r=1e4,maxDepth:i=64,signal:a}=n;if(![r,i].every(u=>Number.isSafeInteger(u)&&u>0))throw new y("maxEntries and maxDepth must be positive safe integers.",g.USAGE);a?.throwIfAborted();let o=await ca.realpath(e),s=await Ir(t),c=await na(o,s);a?.throwIfAborted();let d=c?"in_place":fe(o,s)?"nested_filtered_snapshot":"directory_snapshot",l={copy_scope:d,source_directory:o,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:r,max_depth:i};return d==="in_place"||await Mf(o,0,l,a),l}async function Mf(e,t,n,r){r?.throwIfAborted();let i=await ca.opendir(e);for await(let a of i){if(r?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=sa.join(e,a.name);if(!Ar(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(sa.relative(n.source_directory,o).split(sa.sep).some(s=>BE.has(s))&&(n.development_entries+=1),await JE(o,t,n,r),!n.complete)return}}async function JE(e,t,n,r){let i=await ca.lstat(e);if(r?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await Mf(e,t+1,n,r)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import KE from"node:fs/promises";import YE from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function XE(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function ZE(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function Is(e){let t=YE.join(e,"manifest.json"),n;try{n=await KE.readFile(t,"utf8")}catch(s){if(At(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=r,a=rd(i),o=XE(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:a.findings,warnings:a.findings.map(s=>ZE(o,s)),remediation:a.findings.map(s=>s.message)}}function jf(e){return Is(Ke(e))}import QE from"node:fs/promises";import eS from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bef4424-f5b8-511b-91f7-0b39cf11f515")}catch{}})();async function tS(e,t){if(e.kind!=="local"||e.input.startsWith(".")||e.input.includes("\\")||e.input.includes("/")&&!/^@[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/u.test(e.input))return e;try{return await QE.lstat(e.absolute_path),e}catch(a){if(!F(a))throw a}let n=e.input.trim(),r=t.filter(a=>a.source.kind==="npm"),i=(r.find(a=>a.name===n)??r.find(a=>a.directory===n)??r.find(a=>a.source.package===n))?.source.package;if(i===void 0)return e;try{let a=eS(i);if(!a.registry||a.name!==i)return e}catch{return e}return br(`npm:${i}`,{})}async function Ff(e,t,n,r=[]){let i=typeof t=="string"?null:await vr(e),a=i===null?null:e.trim().toLowerCase(),o=a===null?null:await Tp(a),s=await tS(br(i??e,{forceGithub:typeof t=="string",ref:n}),r),c=a===null?null:await Np(e);return{bundledAliasName:a,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:a===null?s.kind:"builtin",input:a??s.input,...o===null?{}:{package:o}},ambiguous:c!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...a===null?[]:[{kind:"builtin",input:a,...o===null?{}:{package:o},command:`pm install ${a}`}],...c===null?[]:[{kind:"npm",input:`npm:${c.package}`,package:c.package,...c.version===void 0?{}:{version:c.version},directory:c.directory,command:`pm install npm:${c.package}`}]]}}}import nn from"node:fs/promises";import nS from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="776854e4-6df4-507e-b21b-a4d320946642")}catch{}})();var Rs=async e=>nn.readFile(e).catch(t=>{if(oa(t,"ENOENT"))return null;throw t}),Uf=async(e,t,n,r,i)=>Wt("extension_install_backup",async()=>{let a=gr(e),o=Ht(t),[s,c]=await Promise.all([Rs(a),Rs(o)]);return r&&await nn.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:a,managedStateContents:s,settingsPath:o,settingsContents:c}}),zf=async e=>Wt("extension_install_rollback",async()=>{await nn.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await nn.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await nn.rm(t,{force:!0}):(await nn.mkdir(nS.dirname(t),{recursive:!0}),await nn.writeFile(t,n))});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="549164da-d760-52bc-9950-25dacf286775")}catch{}})();var qf=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],rS=qf.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),iS={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},aS="__pm_native_output",oS=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Bf=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],sS=["disabled","require_trusted","require_provenance"],Vf={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},cS=e=>{let t=e??Vf,n={};for(let r of oS)n[r]=De(t[r]??[]);return n},dS=(e,t)=>{for(let n of Bf)t[n].length>0&&(e[n]=t[n]);return e},lS=(e,t)=>{for(let n of sS)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},uS=e=>{let t={};for(let n of Bf)t[n]=De(e[n]??[]);return t},mS=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:dS(lS({name:t},e),uS(e))},pS=e=>(e??[]).map(t=>mS(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),fS=e=>{let t=Object.assign({},Vf,e??{}),n=cS(e),r=pS(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},Jf=async(e,t)=>{let n=[t],r=await $p(t);r&&n.push(r);let i=[...new Set(n.map(a=>I(a)).filter(a=>a.length>0))];for(let a of i){let o=e.find(c=>I(c.name)===a);if(o)return o;let s=e.find(c=>I(c.directory)===a);if(s)return s}},Kf=(e,t)=>{let n=t.trim(),r=new Set(De(e.extensions.enabled));return new Set(De(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},Yf=(e,t)=>{let n=t.trim(),r=new Set(De(e.extensions.enabled)),i=new Set(De(e.extensions.disabled)),a=[...r],o=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},hS=(e,t)=>{let n=t.trim(),r=new Set(De(e.extensions.enabled)),i=new Set(De(e.extensions.disabled)),a=[...r],o=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},_S=(e,t)=>{let n=t.trim(),r=new Set(De(e.extensions.enabled)),i=new Set(De(e.extensions.disabled)),a=[...r],o=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},gS=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=qf.map(([i,a,o])=>({action:a,flag:o,distance:Kc(t,i,n)})).filter(i=>i.distance!==null).sort((i,a)=>i.distance-a.distance)[0];return r?{action:r.action,flag:r.flag}:null},yS=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=gS(e);if(!r)return new y(`One action flag is required. Use one of: ${rS}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let i=`pm ${n} ${r.flag}`;return wi({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(Xf),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},wS=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],Xf={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},vS=e=>Xf[e]??null,bS=(e,t)=>{let n=[...new Set(wS.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=vS(e.trim().toLowerCase());if(r)return r;throw yS(e,t)}if(n.length>1)throw new y("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},kS=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new y('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"},ES=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],Zf=e=>{for(let t of ES){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Qf=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,last_update_remote_version:i.last_update_remote_version,update_error:i.update_error,update_check_status:r.status,update_check_reason:r.reason}},SS=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),a=r?Kf(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Qf({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:a},t,r,Zf(r))}},xS=async(e,t,n,r,i,a)=>{let o=Pe.join(e,t),s=Pe.join(o,"manifest.json"),c=a.get(I(t));if(!await O(s))return SS(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await jt.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=ss(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(I(u.name))??a.get(I(t));return{summary:Qf({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:Kf(r,u.name)},n,m,Zf(m))}},it=async(e,t,n,r)=>{if(!await O(e))return{extensions:[],warnings:[]};let i=(await jt.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,l)=>d.localeCompare(l)),a=new Map(r.entries.map(d=>[I(d.name),d])),o=new Map(r.entries.map(d=>[I(d.directory),d])),s=[],c=[];for(let d of i){let l=await xS(e,d,t,n,a,o);l.warning&&s.push(l.warning),l.summary&&c.push(l.summary)}return{extensions:c.sort((d,l)=>d.name.localeCompare(l.name)),warnings:s.sort((d,l)=>d.localeCompare(l))}},AS=Fd(),IS=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,RS=(e,t,n,r)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),a=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return a&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:IS(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:o,...a?{sdk_dependency_status:"missing"}:{}}},CS=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},eh=e=>e.map(t=>CS(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),th=(e,t,n)=>{let r=I(e);return t.find(i=>(n===void 0||i.layer===n)&&I(i.name)===r)},TS=(e,t,n,r)=>n.find(i=>i.scope===t&&I(i.name)===I(e))?.activation_status??(r?"failed":"unknown"),nh=(e,t,n,r,i)=>AS.enqueue(async()=>{let a=process.env.PM_CLI_PACKAGE_ROOT,o=await jt.mkdtemp(Pe.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Ne(import.meta.url,["../.."]);try{let s=await Ye({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:Ya(),cache_bust:!0,module_graph_snapshot_root:o}),c=await Xe({...s}),d=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...eh(c.failed)],l=Object.fromEntries(s.loaded.map(u=>[I(u.name),vd(xn(c,{extensionName:u.name}))]));return{installed:ia(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await jt.rm(o,{recursive:!0,force:!0}),a===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=a}}),Ts=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),a=[...i].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),o=r,s=[];for(let c of a){let d=Pe.join(e,c.directory),l=await On(d),u=$(),m={kind:"local",input:c.name,location:d};o=wr(o,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:u,updated_at:u,source:m}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return s.length>0&&await Dn(e,o),{state:o,adopted_entries:s,unmanaged_candidates:a,already_managed_count:n.length-i.length}},$S=(e,t)=>{let n=L(process.cwd(),t.path),r=cn(n,process.cwd()),i=e==="global"?Vr(process.cwd()):n,a=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:a,roots:r}},da=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new y('Options "--gh" and "--github" must match when both are provided.',g.USAGE);return n[0]},OS=e=>iS[e],DS=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,a=OS(e),o=`<${r}>`,s=`pm ${n} ${a} ${o}`;throw new y(`Action "${e}" requires ${i} input.`,g.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},la=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new y('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',g.USAGE);return DS(t,n)},PS=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${I(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${I(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,i,a)=>a.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},NS=(e,t)=>{let n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(r=>r.triggered&&!r.allowed);if(n)throw new y(n.message,g.USAGE)},LS=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},MS=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},jS=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:MS(e),warnings:[...new Set(e.warnings)].sort((i,a)=>i.localeCompare(a)),details:t};return e.action==="doctor"&&Object.defineProperty(r,aS,{value:!0,enumerable:!1,configurable:!1}),r},$s=async(e,t,n)=>{let r=bS(e,t);NS(r,t);let i=LS(e,r,t),a=kS(t),o=$S(a,n),s={action:r,normalizedTarget:i,scope:a,resolvedRoots:o,warnings:[],options:t,global:n},c={...s,withResult:(d,l=!0)=>jS(s,d,l)};return await g0(c)},FS=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=qd(r),a={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[a[n],...s,`Install the scaffold: ${Me(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},US=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([da(r),r.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new y('Action "init" does not accept --gh/--github/--ref options.',g.USAGE);let a=la(n,t,r),o=await Qp(a,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:FS(o,r)})},zS=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:a,withResult:o}=e;if(t!==void 0)throw new y('Action "reload" does not accept a target argument.',g.USAGE);let s=await T(n.settings_root),c=Ya(),d=await Ye({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:a.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await Xe(d);r.push(...l.warnings);let u={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(u)},HS=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:a}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new y('Action "catalog" does not accept a package target.',g.USAGE);return a(await Op(n,i,r))},GS=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),WS=e=>({kind:"local",input:e.input,location:e.absolute_path}),qS=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),BS=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),VS=(e,t,n,r)=>e?GS(e,t):n.kind==="local"?WS(n):n.kind==="npm"?qS(n,r):BS(n,r),JS=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:xp(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},KS=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:a,destinationDirectoryName:o}=t,s=await T(r.settings_root),c=await ye(r.selected_root);i.push(...c.warnings);let d=Pe.join(r.selected_root,o),l=await O(d),u=await na(a.directory,d);await jt.mkdir(r.selected_root,{recursive:!0});let m=await jt.mkdtemp(Pe.join(r.selected_root,".pm-extension-install-backup-")),f=Pe.join(m,"destination");try{let p=await Uf(r.selected_root,r.settings_root,d,l,f),h=VS(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),_=c.state.entries.find(k=>I(k.name)===I(a.manifest.name)),w=JS(_,a.manifest.version,h,$()),v=wr(c.state,{name:a.manifest.name,directory:o,scope:n,manifest_version:a.manifest.version,manifest_entry:a.manifest.entry,capabilities:[...a.manifest.capabilities],contributions:a.manifest.contributions,...w,source:h}),E=Yf(s,a.manifest.name);try{u||await Ef(a.directory,d),await vf(d),await bf(d),await Dn(r.selected_root,v),E&&await yi(r.settings_root,s,"settings:write")}catch(k){try{await zf(p)}catch(x){throw new AggregateError([k,x],`Extension install failed: ${String(k)}; rollback failed: ${String(x)}`,{cause:x})}throw k}return{settings:s,managedState:v,sourceRecord:h,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:E}}finally{await jt.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},YS=async(e,t,n)=>{let r=n.filter(i=>I(i.name)===I(t)).flatMap(i=>i.types.map(a=>({name:a.name,folder:a.folder})));return e.scope==="project"&&r.length>0&&await hr(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},XS=(e,t,n,r,i)=>{let a=th(t,n.activation_failures,e.scope),o=TS(t,e.scope,n.installed,a),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:a,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},ZS=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:a,withResult:o}=e,{validated:s,destinationDirectoryName:c}=t,d=await KS(e,t),l=await it(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let u=await nh(r.pm_root,Pe.dirname(r.selected_root),d.settings,l.extensions,a);i.push(...u.warnings);let m=await YS(e,s.manifest.name,u.item_type_registrations),f=xf(s.manifest.name,u.installed),p=XS(e,s.manifest.name,u,f,m),h=u.contribution_inventories[I(s.manifest.name)];return h&&(d.managedState=await Ap(r.selected_root,d.managedState,s.manifest.name,h)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:p.activated,settings_changed:d.activationChanged,runtime_activation_status:p.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:h,command_discovery:RS(s.manifest.name,d.sourceRecord,f,p.failure),verification:p.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:p.failure??null}},p.activated)},QS=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new y('Action "install all" does not accept --ref.',g.USAGE);let a=[],o=new Map;for(let s of await Zi()){let c=await vr(s),d=Pe.resolve(c),l=o.get(d);l===void 0&&(l=await $s(s,{...t,install:!0},n),o.set(d,l)),a.push({alias:s,result:l})}return r.push(...a.flatMap(s=>s.result.warnings)),i(Nf(a,t.dryRun===!0),a.every(s=>s.result.ok))},e0=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:a,installSource:o,sourceResolution:s}=await Ff(t,n,e.options.ref,(await ye(r.selected_root)).state.entries);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${d.package}`)}let c=await zp(o);try{let d=await On(c.directory,{source_kind:o.kind,source_input:o.input,source_root:c.source_root}),l=Yi(d.manifest.name),u=e.options.dryRun===!0||o.kind==="local"&&i===null?await Lf(c,Pe.join(r.selected_root,l),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:d.manifest.name,version:d.manifest.version},source_resolution:s,install_plan:u}):await ks(r.settings_root,l,()=>ZS(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:a,sourceResolution:s,installSource:o,resolvedSource:c,installPlan:u}))}finally{c.cleanup&&await c.cleanup()}},t0=async e=>{let t=da(e.options),n=t??la(e.normalizedTarget,e.action,e.options);return[t===void 0,Rp(n)].every(Boolean)?QS(e):e0(e,n,t)},n0=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e;if(t!==void 0)throw new y('Action "adopt-all" does not accept a target argument.',g.USAGE);if(da(a)!==void 0||typeof a.ref=="string"&&a.ref.trim().length>0)throw new y('Action "adopt-all" does not accept --gh/--github/--ref options.',g.USAGE);let s=await T(r.settings_root),c=await ye(r.selected_root);i.push(...c.warnings);let d=await it(r.selected_root,n,s,c.state);i.push(...d.warnings);let l=await Ts(r.selected_root,n,d.extensions,c.state),u=await it(r.selected_root,n,s,l.state);i.push(...u.warnings);let m=aa(n,i,u.extensions,a);i.push(...m.warnings);let f=new Map(u.extensions.map(_=>[`${I(_.name)}:${I(_.directory)}`,_])),p=new Map(u.extensions.map(_=>[I(_.directory),_])),h=l.adopted_entries.map(_=>{let w=I(_.directory),v=f.get(`${I(_.name)}:${w}`)??p.get(w);return{..._,...rh(v)}});return o({adopted_all:h.length>0,adopted_count:h.length,already_managed_count:l.already_managed_count,extensions:h,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},rh=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),r0=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=br(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new y(`Invalid GitHub shorthand "${e}".`,g.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},i0=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o,withResult:s}=e,c=la(n,t,o),d=da(o),l=await T(i.settings_root),u=await ye(i.selected_root);a.push(...u.warnings);let m=await it(i.selected_root,r,l,u.state);a.push(...m.warnings);let f=await Jf(m.extensions,c);if(!f)throw new y(`Installed extension "${c}" was not found in ${r} scope.`,g.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let p=Pe.join(i.selected_root,f.directory),h=await On(p),_=$(),w=r0(d,c,p,o.ref),v=wr(u.state,{name:h.manifest.name,directory:f.directory,scope:r,manifest_version:h.manifest.version,manifest_entry:h.manifest.entry,capabilities:[...h.manifest.capabilities],contributions:h.manifest.contributions,installed_at:_,updated_at:_,source:w});await Dn(i.selected_root,v);let E=await it(i.selected_root,r,l,v);a.push(...E.warnings);let k=E.extensions.find(x=>I(x.name)===I(h.manifest.name))??E.extensions.find(x=>I(x.directory)===I(f.directory));return s({adopted:!0,extension:{name:h.manifest.name,directory:f.directory,version:h.manifest.version,entry:h.manifest.entry},source:w,...rh(k)})},ih=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o}=e,s=la(n,t,o),c=await T(i.settings_root),d=await ye(i.selected_root);a.push(...d.warnings);let l=await it(i.selected_root,r,c,d.state);a.push(...l.warnings);let u=await Jf(l.extensions,s);if(!u)throw new y(`Installed extension "${s}" was not found in ${r} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},a0=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:a}=await ih(e),o=Pe.join(t.selected_root,a.directory);await jt.rm(o,{recursive:!0,force:!0});let s={...i.state,updated_at:$(),entries:i.state.entries.filter(d=>I(d.name)!==I(a.name)&&I(d.directory)!==I(a.directory))};await Dn(t.selected_root,s);let c=_S(r,a.name);return c&&await yi(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:a.name,directory:a.directory},destination_path:o,settings_changed:c})},Hf=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:a}=e,{settings:o,candidate:s}=await ih(e),c=t==="activate"?Yf(o,s.name):hS(o,s.name);c&&await yi(n.settings_root,o,"settings:write");let d=t==="activate"?await nh(n.pm_root,Pe.dirname(n.selected_root),o,[s],i).then(l=>(r.push(...l.warnings),th(s.name,l.activation_failures,e.scope))):void 0;return d&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),a({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},d===void 0)},o0=(e,t,n,r,i,a)=>{let o=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],c=i?.adopted_entries.length??0,d=[[a!==null,a??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},Cs=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),s0=(e,t,n,r)=>{if(e!=="project"||t||!Cs(r))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},c0=(e,t,n)=>{if(String(e??"").trim().length>0)throw new y('Action "doctor" does not accept a target argument.',g.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new y("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",g.USAGE);let i=uf(n.detail),a=n.trace===!0;if([a,i!=="deep"].every(Boolean))throw new y("--trace requires --detail deep with --doctor.",g.USAGE);return{isolated:r,detailMode:i,includeTrace:a}},d0=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await Ts(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},l0=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:Cs(r),rerun_command:null,pm_global_path_recipe:null};let a=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:Cs(r),rerun_command:t?null:a,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},u0=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,global:o,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=c0(t,n,a),u=await T(r.settings_root),m=await ye(r.selected_root);i.push(...m.warnings);let f=await it(r.selected_root,n,u,m.state);i.push(...f.warnings);let{state:p,fix:h}=await d0(e,f.extensions,m.state),_=await it(r.selected_root,n,u,p);i.push(..._.warnings);let w=await Ye({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Xe({...w,loaded:w.loaded}),E=await jf(r.pm_root);i.push(...E.warnings,...w.warnings),i.push(...cf(w.failed)),i.push(...v.warnings),i.push(...df(v.failed)),i.push(...lf(w,v)),i.push(...Af(v,w)),i.push(...PS(w,v)),i.push(...If(v));let k=ia(_.extensions,w,v),x=pf(n,k,w.loaded.map(H=>({layer:H.layer,name:H.name})),w.failed.map(H=>({name:H.name})),w.disabled_by_flag);i.push(...x.warnings);let D=k.filter(H=>H.update_check_status==="failed").map(H=>`extension_update_check_failed:${H.name}`);i.push(...D);let S=aa(n,i,k,a);i.push(...S.warnings);let b=[...S.warnings],N={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},A=Sr(b),R=xr(),Q=S.warning_codes,Ae=s0(n,c,a.vocabulary,w),we=o0(S.remediation,w.failed.length,v.failed.length,a.vocabulary,h,Ae),_e=l0(n,c,a.vocabulary,w),He={status:S.status,scope:n,warning_count:S.warning_count,warning_codes:Q,total_extensions:k.length,managed_total:k.filter(H=>H.managed).length,enabled_total:k.filter(H=>H.enabled).length,active_total:k.filter(H=>H.active).length,unmanaged_loaded_extension_count:S.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:S.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:S.unmanaged_expected_extension_count,runtime_active_total:k.filter(H=>H.runtime_active===!0).length,activation_status_totals:{ok:k.filter(H=>H.activation_status==="ok").length,failed:k.filter(H=>H.activation_status==="failed").length,not_loaded:k.filter(H=>H.activation_status==="not_loaded").length,unknown:k.filter(H=>H.activation_status==="unknown").length},unknown_capability_count:A.length,capability_contract_version:R.version,update_available_total:S.update_available_total,update_check_status_totals:S.update_check_status_totals,update_health_coverage:S.update_health_coverage,update_health_partial:S.update_health_partial,update_check_failed_total:k.filter(H=>H.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:ws(w.failed),activation_failures:ws(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:x.warnings.length,trace_enabled:l,isolation:_e,policy:N,remediation:we},zr=h?{requested:!0,applied:h.adopted_entries.length>0,adopted_count:h.adopted_entries.length,already_managed_count:h.already_managed_count,adopted_extensions:h.adopted_entries.map(H=>H.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:_.extensions.filter(H=>H.managed).length,adopted_extensions:[]},Bn={mode:d,summary:He,triage:S,trace_enabled:l,capability_contract:R,capability_guidance:A,managed_state_fix:zr,author_manifest:E,isolation:_e,policy:w.policy};if(d==="deep"){let H=l?v.failed:v.failed.map(B=>{let{trace:Hr,...Gr}=B;return Gr});Bn.deep={warnings:b,warning_codes:Q,capability_contract:R,capability_guidance:A,trace_enabled:l,managed_state:{path:m.path,count:p.entries.length,entries:p.entries},installed_extensions:k,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(B=>({layer:B.layer,directory:B.directory,name:B.name,version:B.version,entry:B.entry,priority:B.priority}))},activation:{failed:H,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:x.summary},l&&(Bn.deep.trace={activation_failures:v.failed.filter(B=>B.trace!==void 0).map(B=>({layer:B.layer,name:B.name,entry_path:B.entry_path,error:B.error,method:B.trace.method,command:B.trace.command,capability:B.trace.capability,missing_capability:B.trace.missing_capability,registration_index:B.trace.registration_index,expected_schema:B.trace.expected_schema,hint:B.trace.hint,received:B.trace.received}))})}return s(Bn)},m0=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,global:o,withResult:s}=e,c=await T(r.settings_root),d=await Ye({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),l=await Xe(d);i.push(...d.warnings),i.push(...l.warnings);let u=tf(t,d,l);if(t!==void 0&&u.extensions.length===0){let m=a.vocabulary==="package"?"package":"extension",f=[...new Set(d.loaded.map(h=>a.vocabulary==="package"&&typeof h.source_package=="string"&&h.source_package.trim().length>0?h.source_package.trim():h.name))].sort((h,_)=>h.localeCompare(_)),p=f.length>0?` Loaded ${m} names: ${f.join(", ")}.`:"";throw new y(`No loaded ${m} named "${t}" was found in ${n} scope.${p} Run pm ${m} explore to list discovered ${m}s.`,g.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},p0=async(e,t,n)=>{let r=n,i=null;return[e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await Ts(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"&&(r=await $f(r,e.options.offline)),{state:r,fix:i}},f0=async(e,t,n)=>{let r=await Ye({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Xe({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:ia(n,r,i),failures:eh(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...r.warnings,...i.warnings])].length,policy:r.policy}}},h0=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},Gf=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e,s=await T(r.settings_root),c=fS(s.extensions.policy),d=await ye(r.selected_root);i.push(...d.warnings);let l=await it(r.selected_root,n,s,d.state);i.push(...l.warnings);let{state:u,fix:m}=await p0(e,l.extensions,d.state),f=await it(r.selected_root,n,s,u);if(i.push(...f.warnings),t==="manage"&&a.offline===!0)for(let v of f.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=f.extensions.filter(E=>E.update_check_status==="failed").map(E=>`extension_update_check_failed:${E.name}`);i.push(...v)}let p=await f0(e,s,f.extensions),h=p.installed,_=aa(n,i,h,a);i.push(..._.warnings);let w={total:h.length,managed_total:h.filter(v=>v.managed).length,enabled_total:h.filter(v=>v.enabled).length,active_total:h.filter(v=>v.active).length,extensions:h,triage:_,policy:c};return p.failures!==void 0&&(w.activation_diagnostics={failed_count:p.failures.length,failed:p.failures}),t==="explore"&&(w.runtime_probe=p.summary),t==="manage"&&(w.runtime_probe=p.summary,w.managed_state_fix=h0(m,h)),o(w)},Wf={init:US,install:t0,uninstall:a0,explore:Gf,manage:Gf,describe:m0,reload:zS,doctor:u0,catalog:HS,adopt:i0,"adopt-all":n0,activate:Hf,deactivate:Hf,migrate:Pf},_0=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),g0=e=>_0(e)?ks(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Wf[e.action](e)):Wf[e.action](e);import{execFile as y0}from"node:child_process";import{realpath as w0}from"node:fs/promises";import ah from"node:path";import{promisify as v0}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9af87d55-dbe2-561b-9f3f-6f12c0416147")}catch{}})();var b0=v0(y0),k0=32*1024*1024,E0=1e4,S0=["search/eval-queries.json"];function Os(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function x0(e){return`'${e.replaceAll("'","'\\''")}'`}async function A0(e,t=w0){return t(e).catch(()=>ah.resolve(e))}async function ua(e){let t=await nt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await A0(e),r=Os(ah.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=Wo.map(a=>`${r}/${Os(a)}`);try{let{stdout:a}=await b0("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:k0,windowsHide:!0,timeout:E0}),o=new Set(S0.map(d=>`${r}/${d}`)),s=[...new Set(a.split("\0").filter(d=>d.length>0&&!o.has(Os(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>s.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:s,tracked_path_count:s.length,remediation_command:s.length===0?null:`git rm --cached -r -- ${c.map(d=>x0(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2e510b32-f27f-5ba5-94b2-8268343359dc")}catch{}})();async function oh(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await In(e,Dt(n));if(i.status==="ok")return{audit:i,count:0,warnings:[]};let a=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:a,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${a}`]:[]}}function sh(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}import{execFile as px}from"node:child_process";import{randomUUID as fx}from"node:crypto";import{readdir as hx,stat as _x}from"node:fs/promises";import he from"node:path";import{promisify as gx}from"node:util";import I0 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]="f6def6d2-fbf3-55ce-8654-0c4e76d78a2a")}catch{}})();var R0=Object.freeze({pm_item_scalar_missing:!0});function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function Y(e){return e===void 0?R0:e}function Ft(e){return Ie(C(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function Ds(e,t){let n=je(e);if(n)throw new y(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(o)try{let s=JSON.parse(o);if(typeof s!="object"||s===null||Array.isArray(s))throw new TypeError("history entry must be an object");r.push(s)}catch{throw new y(`History merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}}return r}function Be(e){return C({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function C0(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Be(e[r])===Be(t[r]);)r+=1;return r}function T0(e,t,n,r){let i=[...e,...n],a=new Map(i.map((u,m)=>[u,m])),o=new Map(i.map((u,m)=>[Be(u),m])),s=i.map(()=>new Set);for(let u of[e,t]){let m=u.map(f=>a.get(f)??o.get(Be(f)));for(let f=1;f<m.length;f+=1)m[f-1]!==m[f]&&s[m[f-1]].add(m[f])}let c=i.map(()=>0);for(let u of s)for(let m of u)c[m]+=1;let d=i.map((u,m)=>m).filter(u=>c[u]===0),l=[];for(;d.length>0;){d.sort((m,f)=>{let p=i[m],h=i[f],_=qt(p.ts,h.ts),w=Be(p),v=Be(h);return _||Number(r.has(v))-Number(r.has(w))});let u=d.shift();l.push(i[u]);for(let m of s[u])c[m]-=1,c[m]===0&&d.push(m)}if(l.length!==i.length)throw new y("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",g.GENERIC_FAILURE);return l}function ch(e){return{entries:e,positions:new Map(e.map((t,n)=>[Be(t),n])),index:-1,document:ui()}}function Fs(e,t){let n=t??e.index;for(;e.index<n;){let r=co(e.document,e.entries[e.index+1].patch);if(!r.ok)throw new y("History union cannot preserve a patch that does not apply in its original branch.",g.GENERIC_FAILURE);e.document=r.document,e.index+=1}return e.document}function dh(e,t){if(t!==void 0&&t>e.index+1)throw new y("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",g.GENERIC_FAILURE);return Fs(e,t)}function $0(e,t,n){if(n===0)return;let r=ch(e),i=ch(t),a=Fs(r,n-1);Fs(i,n-1);let o=0,s=new Set([...uh,...mh]);return(c,d)=>{if(o++<n)return c.patch;let l=Be(c),u=dh(r,r.positions.get(l)),m=dh(i,i.positions.get(l)),f=pi(c.patch).filter(v=>{let[E,k]=v.path.slice(1).split("/");return E!=="metadata"||!s.has(k)}),p=co(d,f);if(!p.ok)throw new y("History union cannot rebase a scalar patch onto the merged replay position; leave the file unresolved for manual recovery.",g.GENERIC_FAILURE);let h=hh(a.metadata,u.metadata,m.metadata,"ours","latest_document_update",String(u.metadata.updated_at),String(m.metadata.updated_at)),_=p.document;for(let v of s)Object.hasOwn(h.merged,v)?_.metadata[v]=h.merged[v]:delete _.metadata[v];let w=mi({metadata:_.metadata,body:_.body});return I0.compare(d,w)}}function PF(e,t,n){let r=Ds(e,"base"),i=Ds(t,"ours"),a=Ds(n,"theirs"),o=[r,i,a].map(f=>f.filter(p=>p.op==="create"));if(o[0].length===0&&o.slice(1).every(f=>f.length>0)||o.some(f=>f.length>1)||new Set(o.flat().map(Be)).size>1)throw new y("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict"});let s=C0(i,a);if(s===i.length&&s===a.length)return{merged:Bt(i),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(s===a.length)return{merged:Bt(i),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:i.length-s,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(s===i.length)return{merged:Bt(a),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:a.length-s,entries_total:a.length,reanchored:!1};let c=i.slice(s),d=new Set(c.map(Be)),l=a.slice(s).filter(f=>!d.has(Be(f))),u=T0(c,a.slice(s),l,d),m=fi([...i.slice(0,s),...u],void 0,{continuousHashSurface:!0,projectPatch:$0(i,a,s)});if(m.skippedOps>0)throw new y(`History union cannot preserve ${m.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,g.GENERIC_FAILURE);return{merged:Bt(m.entries),strategy:"union_reanchor",common_entries:s,entries_from_ours:c.length,entries_from_theirs:l.length,entries_total:m.entries.length,reanchored:!0}}function Ps(e,t){let n=je(e);if(n)throw new y(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(!o)continue;let s;try{s=JSON.parse(o)}catch{throw new y(`Relationship merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}if(typeof s!="object"||s===null||Array.isArray(s)||typeof s.eventId!="string"||typeof s.sequence!="number")throw new y(`Relationship merge input (${t}) line ${i+1} is not a relationship event (eventId + sequence required).`,g.GENERIC_FAILURE);r.push(s)}return r}function ma(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
34
+ `}return u===s?{path:i,changed:!1}:(r||await Z(i,u),{path:i,changed:!0})}finally{await o?.()}}function Dt(e){let t=G(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function An(e,t){let n=V.resolve(e),r=null,i="",a=n;for(let _=0;_<8;_+=1){let w=V.join(a,".gitattributes");try{let E=await Yo(w,"utf8");if(E.includes(pr)||E.includes(Wi)){r=a,i=E;break}}catch{}let v=V.dirname(a);if(v===a)break;a=v}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=V.join(r,".gitattributes"),s=Xo(r,n),c=tp(i),d=Zo(s,t),l=c.filter(_=>np(_.lines,d,s)),u=l.flatMap(_=>_.closed?_.lines:[]),m=new Set(u),f=new Set(d),p=d.filter(_=>!m.has(_)),h=u.filter(_=>!f.has(_));return{status:l.length!==1||!l[0].closed||p.length>0||h.length>0?"drift":"ok",path:o,missing_patterns:p,stale_patterns:h,schema_scope:"project"}}async function In(e){let t=[],n=[];for(let r of Qm){let i=`merge.${r.key}.driver`,a=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`;try{let{stdout:o}=await Zt("git",["config","--get",i],{cwd:e,env:nt(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=o.trim();await Yv(s,a,e)||n.push(i)}catch{t.push(i)}}return{status:t.length>0?"missing":n.length>0?"drift":"ok",missing_keys:t,drifted_keys:n}}async function ip(e){let t;try{t=await ep(V.resolve(e))}catch{return{status:"no_git"}}let n=Xo(t,V.resolve(e)),r=await T(e),i=W(void 0,r.author_default),a=await te(e,Wv,r.locks.ttl_seconds,i,!1,Te(r).force_required_for_stale_lock,r.locks.wait_ms);try{let o=V.join(t,".gitattributes"),s;try{s=await Yo(o,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&F(u))return{status:"not_installed",path:o};throw u}if(!s.includes(pr)&&!s.includes(Wi))return{status:"not_installed",path:o};let c=await T(e),d=Dt(c),l=await rp(t,n,Zo(n,d),!1);return{status:l.changed?"refreshed":"unchanged",path:l.path}}finally{await a()}}async function FP(e,t){let n=Vv({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await ne(r);let i=await ep(n.workspace_start);return Zv({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function Xv(e,t){let n=(await Zt("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:e,env:nt(),timeout:1e4})).stdout.trim(),r=await te(n,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{let i=await Km(e),a;try{a=(await Zt("git",["config",i,"--null","--get-regexp","."],{cwd:e,env:nt(),timeout:1e4})).stdout}catch(s){if(typeof s!="object"||s===null||!("code"in s)||s.code!==1)throw s;a=""}let o=new Map(a.split("\0").filter(Boolean).map(s=>{let c=s.indexOf(`
35
+ `);return[s.slice(0,c),s.slice(c+1)]}));for(let s of t)o.get(s.key)!==s.value&&await xn(e,[i,s.key,s.value])}finally{await r()}}async function Zv(e){let t=V.resolve(e.pmRoot),n=V.resolve(e.workspaceRoot),r=e.dryRun===!0,i,a;try{[i,a]=await Promise.all([Ot(t),Ot(n)])}catch(f){throw new y(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,g.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let o=Xo(a,i);if(Jo(o))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let s=await T(i),c=Dt(s),d=Zo(o,c),l=[],u=await Jv();for(let f of Qm)l.push({key:`merge.${f.key}.name`,value:f.name}),l.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!r)try{await Xv(a,l)}catch{throw new y(`Cannot install repository-local merge drivers in ${a}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,g.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await rp(a,o,d,r);return{ok:!0,dry_run:r,workspace_root:a,pm_root:i,gitattributes:{path:m.path,changed:m.changed,patterns:d,schema_scope:"project"},git_config:l,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:$()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var Qv=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function eb(e){let t=Qv.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function tb(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function ap(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let c=eb(s);if(c===void 0)continue;let d=i.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(s),i.set(c,d)}let a=[];for(let[o,s]of i.entries()){if(s.count<n)continue;let c=tb(o);a.push({name:c,prefix:o,count:s.count,examples:s.examples,shadows_builtin:Id(c)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}import{createHash as _p}from"node:crypto";import en from"node:fs/promises";import Cn from"node:path";import{mkdir as nb,readFile as rb}from"node:fs/promises";import dp 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]="1fae5539-4eb8-5eba-bfd6-a191c89448ec")}catch{}})();var Qo=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},ib="sdk-workspace-transaction",ab=/^[a-zA-Z0-9._-]+$/,ob=30,sb=3e3;function lp(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!ab.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function op(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function cb(e){return{pmRoot:op(e.pmRoot,"Transaction pmRoot"),transactionId:lp(e.transactionId,"Transaction id"),author:op(e.author,"Transaction author")}}function sp(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function up(e,t){return dp.join(e,"transactions","sdk",`${t}.json`)}async function Pt(e,t){t.updatedAt=$();let n=up(e,t.transactionId);await nb(dp.dirname(n),{recursive:!0}),await Z(n,`${JSON.stringify(t,null,2)}
36
+ `)}function db(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Qt(e){return Object.assign(Object.create(null),e)}function lb(e,t){try{let n=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function es(e,t){return e===void 0?void 0:lb(e,t)}function ts(e,t,n,r){let i=es(n,r);i===void 0?delete e[t]:e[t]=i}function cp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ns(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function ub(e,t){if(!ns(e.startedStepIds,t)||!ns(e.completedStepIds,t)||!cp(e.results)||!cp(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,a=new Set(i);return Object.keys(e.compensationData).some(o=>!r.has(o))||Object.keys(e.results).some(o=>!a.has(o))?!1:e.status==="committed"?t.every(o=>a.has(o)):e.status!=="compensated"||a.size===0&&r.size===0}function qi(e,t){return new y(`Workspace transaction ${e} journal is invalid (${t})`,g.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function mb(e){return new y(`Workspace transaction ${e} journal does not match the supplied plan`,g.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the exact plan that started this transaction, or start a new transaction with a different id.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","Pass --transaction-id <new-id> (or a new transactionId over MCP) to commit the changed plan as its own transaction.","Run pm ops gc --scope transactions --dry-run to inspect abandoned journals before pruning them."]})}function pb(e,t,n){let r;try{r=JSON.parse(e)}catch{throw qi(t,"invalid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw qi(t,"expected an object");let i=r;if(!(i.schemaVersion===1&&i.transactionId===t))throw qi(t,"schema version or transaction id does not match the journal file");let a=i.stepIds;if(!Array.isArray(a)||!ns(a,a)||!ub(i,a)||!db(i)||typeof i.status!="string"||!["applying","compensating","compensated","committed"].includes(i.status))throw qi(t,"invalid lifecycle, metadata, status or step ids");if(!(i.status==="compensated"||a.length===n.length&&a.every((o,s)=>o===n[s])))throw mb(t);return{...i,results:Qt(i.results),compensationData:Qt(i.compensationData)}}async function fb(e,t,n,r,i){let a=i,o=a!==void 0;if(a?.status==="compensating"&&await mp(e,a),a===void 0||a.status==="compensated"){let s=$();a={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(a?.attempt??0)+1,createdAt:a?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:Qt(),compensationData:Qt()},await Pt(e.pmRoot,a),await _t(e,a,"prepared")}return{journal:a,recovered:o}}async function hb(e,t,n){try{await gb(t,e.steps),await Pt(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let a of e.steps){if(r.has(a.id))continue;let o=await a.inspect(),s=es(o.result,`Step ${a.id} result`);if(o.state!=="applied"){let c=await a.prepareCompensation?.();ts(t.compensationData,a.id,c,`Step ${a.id} compensation data`),i.add(a.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await Pt(e.pmRoot,t);let d=await a.apply();s=es(d,`Step ${a.id} result`)}await _t(e,t,"step_applied",a.id),r.add(a.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),ts(t.results,a.id,s,`Step ${a.id} result`),await Pt(e.pmRoot,t),await _t(e,t,"step_recorded",a.id)}return await _t(e,t,"committing"),t.status="committed",await Pt(e.pmRoot,t),await _t(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Qt(t.results)}}catch(r){if(r instanceof Qo||t.status==="committed")throw r;try{await mp(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function _b(e,t,n){try{return pb(await rb(up(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&F(r))return;throw r}}async function _t(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function gb(e,t){let n=new Set,r=Qt();for(let i of t){let a=await i.inspect();a.state==="applied"&&(n.add(i.id),ts(r,i.id,a.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function mp(e,t){t.status="compensating",await Pt(e.pmRoot,t),await _t(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!r.has(i.id)&&!n.has(i.id))continue;let a;try{a=r.has(i.id)&&(await i.inspect()).state==="applied"}catch{a=r.has(i.id)}a&&(await _t(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),r.delete(i.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>r.has(o)),delete t.results[i.id],delete t.compensationData[i.id],await Pt(e.pmRoot,t),await _t(e,t,"step_compensated",i.id)}t.status="compensated",await Pt(e.pmRoot,t),await _t(e,t,"compensated")}async function pp(e){let{pmRoot:t,transactionId:n,author:r}=cb(e),i=sp(e.lockTtlSeconds,ob,"Transaction lock TTL"),a=sp(e.lockWaitMs,sb,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(l=>{let u=lp(l.id,"Transaction step id");if(u!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return u});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:o,lockTtlSeconds:i,lockWaitMs:a},d=await te(t,ib,i,r,!1,!1,a);try{let l=await _b(t,n,s),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Qt(l.results)};let m=await fb(c,n,r,s,l);return await hb(c,m.journal,u||m.recovered)}finally{await d()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d04c087-62e4-51d3-8832-6cbcfd3ed993")}catch{}})();function gt(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function gp(e){let t=gt(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function yp(e,t){let n=is(e),r=gt(t,"migrationScope");return`auto-${_p("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function is(e){let t=e.kind==="rename-type"?{kind:e.kind,from:gt(e.from,"source"),to:gt(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:le(gt(e.from,"source")),to:le(gt(e.to,"target")),...e.type===void 0?{}:{type:gt(e.type,"type")}}:{kind:e.kind,from:le(gt(e.from,"source")),to:le(gt(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function yb(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function wb(e,t,n){let r=Re(t.schema),i=yb(n);return Qe(e,r.files[i],Le[i])}function wp(e,t){return Cn.join(e,"transactions","schema",`${t}-plan.json`)}function Bi(e){return e.length===0?null:JSON.parse(e)}async function Rn(e){let t=await J(e);return{exists:t!==null,raw:t??""}}async function vp(e,t){t.exists?await Z(e,t.raw):await en.rm(e,{force:!0})}function vb(e,t,n){let r=ct(e),i=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),a=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(a>=0)return It(r);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[i],name:t.to})}else i>=0&&r.definitions.splice(i,1);return It(r)}function bb(e,t,n){let r=dn(e),i=r.fields.findIndex(o=>o.key===t.from),a=r.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(a>=0)return ln(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=r.fields[i];r.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&r.fields.splice(i,1);return ln(r)}function kb(e,t,n){let r=un(e),i=r.statuses.findIndex(o=>o.id===t.from),a=r.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(a>=0)return mn(r);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[i],id:t.to})}else i>=0&&r.statuses.splice(i,1);return mn(r)}function Eb(e,t,n){return t.kind==="rename-type"?vb(e,t,n):t.kind==="rename-field"?bb(e,t,n):kb(e,t,n)}function Nt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function as(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Tn(e){return Array.isArray(e)?e.map(t=>as(t)).filter(t=>t!==void 0):[]}function Sb(e,t){for(let n of Tn(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>Nt(r,t)));for(let n of Tn(e.type_workflows))n.type=Nt(n.type,t)}function xb(e,t){for(let r of Tn(e.definitions))r.default_status=Nt(r.default_status,t);let n=as(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=Nt(i,t);for(let r of Tn(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(a=>Nt(a,t)):i))}function Ab(e,t){for(let n of Tn(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>Nt(i,t)));for(let r of["options","command_option_policies"])for(let i of Tn(n[r])){let a=r==="options"?"key":"option";i[a]=Nt(i[a],t)}}}function Ib(e,t){let n=as(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=Nt(n[r],t)}function rs(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?Sb(r,t):t.kind==="rename-field"?Ab(r,t):xb(r,t),Ib(r,t),`${JSON.stringify(r,null,2)}
37
+ `}function bp(e,t){if(t.kind==="rename-type"){let r=ct(e).definitions;return{source:r.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=dn(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=un(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function Rb(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function Cb(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function kp(e,t){let n=is(t.request),r=t.migrationId===void 0?yp(n,t.migrationScope??"plan"):gp(t.migrationId),i=e.map(c=>Cb(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),a=_p("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!o.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:a,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function Tb(e){let t=G(e.settings,H()),n=[...new Set(Object.values(t.type_to_folder))],r=await ki(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},a=r?await jl({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:i}):null;return a?{items:a.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await lt(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function $b(e,t){let n=await J(wp(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new y(`Stored schema migration plan "${t}" is invalid: ${cd(r)}`,g.GENERIC_FAILURE)}}async function Ob(e,t){let n=wp(e,t.migration_id);await en.mkdir(Cn.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await Z(n,`${JSON.stringify(r,null,2)}
38
+ `)}function Db(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Pb(e){let t=await ve(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new y(`Schema migration item "${e.id}" no longer exists.`,g.NOT_FOUND);return(await be(t,{schema:e.settings.schema})).document.metadata}function fp(e,t,n){let r=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let a=e.metadata;if(Object.prototype.hasOwnProperty.call(a,i)&&!Object.prototype.hasOwnProperty.call(a,r))return[];if(!Object.prototype.hasOwnProperty.call(a,r)||Object.prototype.hasOwnProperty.call(a,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return a[i]=a[r],delete a[r],[r,i]}function hp(e){return{id:e.id,inspect:async()=>{let t=await Rn(e.filePath),n=bp(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Rn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Rn(e.filePath);return await Z(e.filePath,Eb(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await vp(e.filePath,{exists:t.exists,raw:t.raw})}}}function Nb(e){return{id:e.stepId,inspect:async()=>{let t=await Rn(e.filePath);return{state:rs(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Rn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Rn(e.filePath);return await Z(e.filePath,rs(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await vp(e.filePath,{exists:t.exists,raw:t.raw})}}}function Lb(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await T(e.pmRoot),n=G(t,H()).type_to_folder,r=await Pb({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=Rb(r,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await T(e.pmRoot),n=G(t,H()).type_to_folder,r=await mt({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:fp(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await T(e.pmRoot),n=G(t,H()).type_to_folder;await mt({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:fp(r,e.request,"reverse")}}})}}}async function Mb(e){let t=await $b(e.pmRoot,e.migrationId);if(t){if(!Db(t.request,e.request))throw new y(`Schema migration id "${e.migrationId}" already belongs to a different request.`,g.CONFLICT);return{plan:t,stored:!0}}let n=await Tb({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...kp(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function jb(e){let t=bp(await J(e.schemaPath)??"",e.request);if(!t.source)throw new y(`Schema migration source "${e.request.from}" is not a custom definition.`,g.NOT_FOUND);if(t.target)throw new y(`Schema migration target "${e.request.to}" already exists.`,g.CONFLICT);await Ob(e.pmRoot,e.plan)}async function Fb(e){let t=Re(e.settings.schema),n=[...new Set([["types",Le.types],["fields",Le.fields],["workflows",Le.workflows]].map(([i,a])=>Qe(e.pmRoot,t.files[i],a)).filter(i=>i!==e.schemaPath))];try{let i=Cn.join(e.pmRoot,"templates"),a=await en.readdir(i,{withFileTypes:!0});n.push(...a.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>Cn.join(i,o.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!F(i))throw i}n.sort((i,a)=>i.localeCompare(a));let r=[];for(let i of n){let a=await J(i);a!==null&&rs(a,e.request)!==a&&r.push({filePath:i,beforeRaw:a})}return{paths:n,snapshots:r}}async function Ub(e){for(let t of e.snapshots){let n=await en.readFile(t.filePath,"utf8"),r=Cn.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await so({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Bi(t.beforeRaw),after:Bi(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function Hb(e,t,n){let r=is(e),i=L(process.cwd(),n.path);await ne(i);let a=t.migrationId===void 0?yp(r,await en.realpath(i)):gp(t.migrationId),o=await T(i),s=W(t.author,o.author_default),c=await Mb({pmRoot:i,settings:o,migrationId:a,request:r}),d=c.plan;if(t.dryRun===!0)return{...d,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=wb(i,o,r),u=await en.readFile(l,"utf8");c.stored||await jb({pmRoot:i,schemaPath:l,request:r,plan:d});let m=await Fb({pmRoot:i,schemaPath:l,settings:o,request:r}),f=[hp({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...m.paths.map((w,v)=>Nb({filePath:w,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>Lb({pmRoot:i,id:w.id,request:r,author:s,force:t.force===!0})),hp({id:"retire-source",filePath:l,request:r,phase:"retire"})],p=await pp({pmRoot:i,transactionId:`schema-${a}`,author:s,steps:f,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),h=await en.readFile(l,"utf8"),{historyPath:_}=await so({pmRoot:i,author:s,documentPath:Cn.relative(i,l).replaceAll("\\","/"),before:Bi(u),after:Bi(h),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await Ub({pmRoot:i,author:s,settings:o,request:r,plan:d,snapshots:m.snapshots}),{...d,action:r.kind,applied:!0,recovered:p.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:_}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var qN=[...Jr,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Ji="schema-types",Ep="schema-statuses",Sp="schema-fields";function Lt(e){return _i({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function VN(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i;try{i=Xa({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(f){throw new y(f instanceof Error?f.message:String(f),g.USAGE)}let a=await T(r),o=Re(a.schema),s=Qe(r,o.files.types,Le.types),c=[],d=W(t.author,a.author_default),l=Te(a),u=await te(r,Ji,a.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms),m;try{let f=await J(s),p;try{p=ct(f)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.GENERIC_FAILURE)}try{Rd(i,p);let h=new Map,_=G(a,H());for(let[w,v]of Object.entries(_.type_to_folder)){let E=v.trim().toLowerCase();E.length>0&&!h.has(E)&&h.set(E,w)}Cd(i,p,h)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}m=Yr(p,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await Lt({pmRoot:r,filePath:s,raw:It(m.file),op:"schema:add-type",author:d,settings:a}),await fr(r,[m.definition],c,"schema:add-type-folder"),c.push(...await X({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await xp(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Mt(c),generated_at:$()}}async function yt(e){await ne(e)}async function xp(e,t){try{let n=await ip(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Mt(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Wb(e,t,n,r){let i=G(t,H()),a=r.trim().toLowerCase();return(await lt(e,t.item_format,i.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===a).length}async function qb(e,t,n,r){let i=G(t,H()),a=ge(n),o=le(r);return(await lt(e,t.item_format,i.type_to_folder,[],n)).filter(s=>{let c=typeof s.status=="string"?s.status:"";return(a.alias_to_id.get(le(c))??le(c))===o}).length}async function Bb(e,t,n,r,i){if(i.length===0||Qa.has(i))return;let a=await qb(t,n,r,i);a>0&&e.push(`items_using_status:${a}`);let o=Jb(r.workflow,i);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function Jb(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&le(n)===t).map(([n])=>n)}async function KN(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i=await T(r),a=Re(i.schema),o=Qe(r,a.files.types,Le.types),s=[],c=W(t.author,i.author_default),d=Te(i),l=await te(r,Ji,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await J(o),f;try{f=ct(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=Td(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=(u.definition?.name??e??"").trim();if(p.length>0){let h=await Wb(r,i,a,p);h>0&&s.push(`items_using_type:${h}`)}await Lt({pmRoot:r,filePath:o,raw:It(u.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await X({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await xp(r,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:o,definitions:u.file.definitions.length},warnings:Mt(s),generated_at:$()}}function os(e,t){return Qe(e,t.files.statuses,Le.statuses)}function Vi(e,t){return Qe(e,t.files.fields,Le.fields)}function Ap(e,t){return Qe(e,t.files.types,Le.types)}async function fr(e,t,n,r){for(let i of t){let a=ud(i.folder??ld(i.name)),o=zb.join(e,a);await O(o)||(await Gb(o,{recursive:!0}),n.push(...await X({path:o,scope:"project",op:r})))}}function ss(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function Vb(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Kb(e){let t=new Map;for(let n of e){let r=le(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let a=le(i);a.length>0&&!t.has(a)&&t.set(a,r)}}}return t}async function YN(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i;try{i=jd({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}let a=await T(r),o=Re(a.schema),s=os(r,o),c=ge(o);try{eo(i,c.alias_to_id)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}let d=Vb(c.by_id.get(i.id));if((i.roles??d?.roles??[]).length===0)throw new y(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,g.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${cn(i.id)}" --role active`,`pm schema add-status "${cn(i.id)}" --role blocked`]});let l=[],u=W(t.author,a.author_default),m=Te(a),f=await te(r,Ep,a.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,a.locks.wait_ms),p;try{let h=await J(s),_;try{_=un(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=Kb(_.statuses);try{eo(i,w)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.USAGE)}p=Fd(_,i,d),await Lt({pmRoot:r,filePath:s,raw:mn(p.file),op:"schema:add-status",author:u,settings:a}),l.push(...await X({path:s,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:p.replaced,status:p.definition,file:{path:s,statuses:p.file.statuses.length},warnings:Mt(l),generated_at:$()}}async function XN(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i=await T(r),a=Re(i.schema),o=os(r,a),s=[],c=W(t.author,i.author_default),d=Te(i),l=await te(r,Ep,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await J(o),f;try{f=un(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=Ud(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=le(u.definition?.id??e);await Bb(s,r,i,a,p),await Lt({pmRoot:r,filePath:o,raw:mn(u.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await X({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:o,statuses:u.file.statuses.length},warnings:Mt(s),generated_at:$()}}function Ip(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function Yb(e,t,n){return{...Ip(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function Rp(e){return{id:e.id,source:Qa.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Cp(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function Xb(){let e=new Map,t=H();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let i of r){if(typeof i!="object"||i===null||Array.isArray(i))continue;let a=i.name;typeof a=="string"&&a.trim().length>0&&e.set(a.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function Zb(e){let t=ge(e),n=[],r=[];for(let i of t.definitions){let a=Rp(i);a.source==="builtin"?n.push(a):r.push(a)}return{builtin:n,custom:r}}async function hr(e){let t=L(process.cwd(),e.path);await yt(t);let n=await T(t),r=Re(n.schema),i=Qe(t,r.files.types,Le.types),a=os(t,r),o=G(n,H()),s=Xb(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:i,statusesPath:a,byType:o.by_type,customNames:c,extensionProvenance:s,schema:r}}async function ZN(e){let t=await hr(e),n=[],r=[],i=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Cp(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=Ip(s);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let a=Zb(t.schema),o=Xr(t.schema).definitions.map(ss);return{action:"list",builtin:n,custom:r,extension:i,counts:{builtin:n.length,custom:r.length,extension:i.length,total:n.length+r.length+i.length},statuses:{builtin:a.builtin,custom:a.custom,counts:{builtin:a.builtin.length,custom:a.custom.length,total:a.builtin.length+a.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:$()}}async function QN(e,t){let n=(e??"").trim();if(n.length===0)throw new y("Type name must not be empty.",g.USAGE);let r=await hr(t),i=Object.values(r.byType).find(a=>a.name.toLowerCase()===n.toLowerCase()||a.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!i)throw new y(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${cn(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Yb(i,Cp(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:$()}}async function eL(e,t){let n=le(e);if(n.length===0)throw new y("Status id must not be empty.",g.USAGE);let r=await hr(t),i=ge(r.schema),a=i.alias_to_id.get(n)??n,o=i.by_id.get(a);if(!o)throw new y(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${cn(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Rp(o),file:{path:r.statusesPath},generated_at:$()}}async function tL(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i;try{i=Dd({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}let a=await T(r),o=Re(a.schema),s=Vi(r,o),c=[],d=ni(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=W(t.author,a.author_default),u=Te(a),m=await te(r,Sp,a.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,a.locks.wait_ms),f;try{let p=await J(s),h;try{h=dn(p)}catch(_){throw new y(_ instanceof Error?_.message:String(_),g.GENERIC_FAILURE)}f=Pd(h,i),await Lt({pmRoot:r,filePath:s,raw:ln(f.file),op:"schema:add-field",author:l,settings:a}),c.push(...await X({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:s,fields:f.file.fields.length},warnings:Mt(c),generated_at:$()}}async function Qb(e,t,n,r){let i=G(t,H());return(await lt(e,t.item_format,i.type_to_folder,[],n)).filter(a=>{let o=a[r];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function nL(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i=await T(r),a=Re(i.schema),o=Vi(r,a),s=[],c=W(t.author,i.author_default),d=Te(i),l=await te(r,Sp,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await J(o),f;try{f=dn(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=Nd(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=le(u.definition?.key??e),h=le(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(h.length>0){let _=await Qb(r,i,a,h);_>0&&s.push(`items_using_field:${_}`)}await Lt({pmRoot:r,filePath:o,raw:ln(u.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await X({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:o,fields:u.file.fields.length},warnings:Mt(s),generated_at:$()}}async function rL(e){let t=await hr(e),n=Xr(t.schema).definitions.map(ss);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Vi(t.pmRoot,t.schema)},generated_at:$()}}async function iL(e,t){let n=le(e);if(n.length===0)throw new y("Field key must not be empty.",g.USAGE);let r=await hr(t),i=Xr(r.schema).by_key.get(n);if(!i)throw new y(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${cn(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:ss(i),file:{path:Vi(r.pmRoot,r.schema)},generated_at:$()}}async function aL(e,t,n){let r=L(process.cwd(),n.path);await yt(r);let i;try{let h=Od(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${$d.join(", ")}.`);i=h}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}let a=await T(r),o=Re(a.schema),s=Ap(r,o),c=[],d=W(t.author,a.author_default),l=Te(a),u=[],m=[],f,p=await te(r,Ji,a.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms);try{let h=await J(s),_;try{_=ct(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=_;for(let v of Za(i)){let E=Yr(w,v);w=E.file,(E.replaced?m:u).push(E.definition.name)}f=w.definitions.length,await Lt({pmRoot:r,filePath:s,raw:It(w),op:"schema:apply-preset",author:d,settings:a}),await fr(r,Za(i),c,"schema:apply-preset-folder"),c.push(...await X({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await p()}return{action:"apply-preset",preset:i,registered:u,replaced:m,file:{path:s,definitions:f},warnings:Mt(c),generated_at:$()}}function ek(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new y("--min-count must be a positive integer (>= 1).",g.USAGE);return e}async function oL(e,t){let n=L(process.cwd(),t.path);await yt(n);let r=await T(n),i=Re(r.schema),a=Ap(n,i),o=ek(e.minCount),s=G(r,H()),c=(await lt(n,r.item_format,s.type_to_folder,[],i)).map(v=>typeof v.title=="string"?v.title:""),d=ap(c,{minCount:o}),l=[],u=[],m=[],f=[],p;if(!e.apply){let v;try{v=ct(await J(a))}catch(E){throw new y(E instanceof Error?E.message:String(E),g.GENERIC_FAILURE)}return p=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:d,registered:u,replaced:m,skipped:f,file:{path:a,definitions:p},warnings:l,generated_at:$()}}let h=W(e.author,r.author_default),_=Te(r),w=await te(n,Ji,r.locks.ttl_seconds,h,!!e.force,_.force_required_for_stale_lock,r.locks.wait_ms);try{let v=await J(a),E;try{E=ct(v)}catch(x){throw new y(x instanceof Error?x.message:String(x),g.GENERIC_FAILURE)}let k=E;for(let x of d){if(x.shadows_builtin){f.push({name:x.name,reason:"shadows_builtin"});continue}let D;try{D=Xa({name:x.name})}catch{f.push({name:x.name,reason:"invalid_type_token"});continue}let S=Yr(k,D);k=S.file,(S.replaced?m:u).push(S.definition.name)}p=k.definitions.length,await Lt({pmRoot:n,filePath:a,raw:It(k),op:"schema:infer-types",author:h,settings:r}),await fr(n,k.definitions.filter(x=>u.includes(x.name)||m.includes(x.name)),l,"schema:infer-types-folder"),l.push(...await X({path:a,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:o,candidates:d,registered:u,replaced:m,skipped:f,file:{path:a,definitions:p},warnings:Mt(l),generated_at:$()}}import Tp from"node:fs/promises";import cs from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cf1403b0-7b07-5f00-9523-87bc727dd7fa")}catch{}})();function De(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function I(e){return e.trim().toLowerCase()}function Ki(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let i=t.slice(n,r);if(i.length===0)throw new y("Extension manifest name must resolve to a non-empty directory name.",g.USAGE);if(i==="."||i==="..")throw new y('Extension manifest name must not resolve to "." or "..".',g.USAGE);return i}function ds(e){return Ed(e)}async function tk(e){try{let t=JSON.parse(await Tp.readFile(cs.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(r=>typeof t.scripts?.[r]=="string")}}catch{return{has_build_script:!1}}}async function nk(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new y(`Extension entry file is missing at "${t}".`,g.USAGE);let r=await tk(n.source_root),i=r.package_name?`pm install npm:${r.package_name}`:void 0,a=n.source_input??n.source_root;return new y(`Extension entry "${e.entry}" is absent from GitHub source "${a}". pm install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,g.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${a}`,normalized_args:["install",a],...i?{next_best_command:i}:{}}})}async function $n(e,t={}){let n=cs.join(e,"manifest.json");if(!await O(n))throw new y(`Extension manifest is missing at "${n}".`,g.USAGE);let r;try{r=JSON.parse(await Tp.readFile(n,"utf8"))}catch(o){throw new y(`Failed to parse extension manifest at "${n}": ${rk(o)}`,g.USAGE)}let i=ds(r);if(!i)throw new y(`Extension manifest at "${n}" is invalid.`,g.USAGE);let a=cs.resolve(e,i.entry);if(!fe(e,a))throw new y(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await O(a))throw await nk(i,a,t);if(!await Sd(e,a))throw new y(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:a,manifest:i}}function rk(e){return e instanceof Error?e.message:String(e)}import ls from"node:fs/promises";import ik 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]="5181479f-469f-525b-add2-914a9934afbd")}catch{}})();var ak=".managed-extensions.json",Yi=1;function _r(e){return ik.join(e,ak)}function ok(){return{version:Yi,updated_at:$(),entries:[]}}function gr(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function $p(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function ke(e){return typeof e=="string"?e:void 0}function sk(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function ck(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:ke(t.name),package:ke(t.package),version:ke(t.version),repository:ke(t.repository),owner:ke(t.owner),repo:ke(t.repo),ref:ke(t.ref),subpath:ke(t.subpath),commit:ke(t.commit)}}function dk(e){if(typeof e!="object"||e===null)return null;let t=e;if(!sk(t))return null;let n=ck(t.source);if(!n)return null;let r=bd(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:De(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:ke(t.last_update_check_at),last_update_remote_commit:ke(t.last_update_remote_commit),last_update_remote_version:ke(t.last_update_remote_version),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:ke(t.update_error)}}function lk(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Yi||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=dk(r);i&&n.push(i)}return{version:Yi,updated_at:ke(t.updated_at)??$(),entries:gr(n)}}async function ye(e){let t=_r(e),n=ok();try{let r=await ls.readFile(t,"utf8"),i=JSON.parse(r),a=lk(i);if(!a)throw new y(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE);return{path:t,state:a,warnings:[]}}catch(r){if(r instanceof y)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&F(r))return{path:t,state:n,warnings:[]};throw new y(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE)}}async function On(e,t){let n=_r(e),r={version:Yi,updated_at:$(),entries:gr(t.entries)};await ls.mkdir(e,{recursive:!0}),await ls.writeFile(n,`${JSON.stringify(r,null,2)}
39
+ `,"utf8")}function yr(e,t){let n=e.entries.filter(r=>I(r.name)!==I(t.name)&&I(r.directory)!==I(t.directory));return n.push(t),{...e,updated_at:$(),entries:gr(n)}}async function Op(e,t,n,r){let i=t.entries.find(o=>I(o.name)===I(n));if(!i)return t;let a=yr(t,{...i,contributions:r});return await On(e,a),a}import{execFile as bk}from"node:child_process";import K from"node:fs/promises";import _s from"node:os";import j from"node:path";import{fileURLToPath as kk}from"node:url";import{promisify as Ek}from"node:util";import Sk from"npm-package-arg";import{extract as xk,list as Ak}from"tar";import uk from"node:fs/promises";import Be from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var mk="PM_CLI_PACKAGE_ROOT",Dp={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},pk=new Set(["*","all"]);function us(){let e=[],t=process.env[mk];return typeof t=="string"&&t.trim().length>0&&e.push(Be.resolve(t.trim())),e.push(Ne(import.meta.url,["../../.."])),[...new Set(e)]}async function wr(e){let t=e.trim().toLowerCase(),n=await Np(t);if(n)return n;let r=Dp[t];if(!r)return null;for(let i of us()){let a=Be.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await O(Be.join(a,"manifest.json")))return a}return null}function Pp(e){return pk.has(e.trim().toLowerCase())}function fk(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function hk(e,t){let n=await uk.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=Be.join(e,r.name);if(!await O(Be.join(i,"package.json")))continue;let a=await Vr(i),o=a.aliases&&a.aliases.length>0?a.aliases:[fk(r.name)];for(let s of o){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:i,package_name:a.package_name??null})}}}async function ms(){let e=new Map;for(let t of us()){let n=Be.join(t,"packages");await O(n)&&await hk(n,e)}for(let[t,n]of Object.entries(Dp))if(!e.has(t))for(let r of us()){let i=Be.join(r,"packages",n.package_directory);if(await O(Be.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Xi(){return(await ms()).map(e=>e.alias)}async function Np(e){let t=e.trim().toLowerCase();return(await ms()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function Lp(e){let t=await Np(e);return t?(await Vr(t)).package_name??null:null}async function Mp(e){let t=await wr(e);if(!t)return null;try{let n=await Kr(t);return n.length!==1?null:(await $n(n[0])).manifest.name}catch{return null}}function _k(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function gk(e,t,n,r,i,a){let o=r==="global"?"--global":"--project",s=Object.fromEntries(Ya.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||a.has(Be.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:_k(e),media:e.catalog?.media}}}async function jp(e,t,n={}){let r=sn(L(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,a=await ye(i),o=new Set(a.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>Be.resolve(m.source.location))),s=new Set(a.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),c=[],d=new Map;for(let m of await ms()){let f=Be.resolve(m.package_root),p=d.get(f)??[];p.push(m),d.set(f,p)}for(let m of d.values()){let f=m[0],p=m.map(_=>_.alias).sort((_,w)=>_.localeCompare(w)),h=await Vr(f.package_root);c.push(gk(h,f,p,e,s,o))}let l=wk(n.fields),u=l?c.map(m=>vk(m,l)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Ya.filter(m=>m!=="extensions"),packages:u}}var yk=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function wk(e){if(e===void 0)return;let t=nu(e);if(t.length===0)throw new y("Package catalog --fields requires a comma-separated list of field names",g.USAGE);let n=t.filter(r=>!yk.has(r));if(n.length>0)throw new y(`Unknown package catalog --fields value(s): ${n.join(", ")}`,g.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function vk(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="db10bb85-f21c-58b1-8b78-8ce1024b3e08")}catch{}})();var Up=Ek(bk),Qi="@unbrained/pm-cli",Ik={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},ps;async function Hp(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=j.resolve(t);for(;;){let i=j.join(r,"node_modules",...n.split("/")),a=j.join(i,"package.json");if(await O(a))try{let s=JSON.parse(await K.readFile(a,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let o=j.dirname(r);if(o===r)return null;r=o}}function fs(e,t,n){let r=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(r.length<2)return null;let i=r[0],a=r[1].replace(/\.git$/i,"");if(i.length===0||a.length===0)return null;let o=r.slice(2),s,c;return o[0]==="tree"&&o.length>=2?(s=o[1],c=o.slice(2).join("/")):o.length>0&&(c=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:a,repository:`https://github.com/${i}/${a}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function Rk(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new y('npm package source must include a package spec after "npm:".',g.USAGE);if(t)throw new y('Options "--gh/--github" cannot be combined with npm: package sources.',g.USAGE);if(n)throw new y('Option "--ref" cannot be combined with npm: package sources.',g.USAGE);return{kind:"npm",input:e,spec:r}}function vr(e,t={}){let n=e.trim();if(n.length===0)throw new y("Extension source is required for --install.",g.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Rk(n,t.forceGithub===!0,r);let i=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return fs(s,n,r)}catch{return null}})();if(i)return i;let a=n.startsWith("github.com/")?n.slice(11):null;if(a){let o=fs(a,n,r);if(!o)throw new y(`Invalid GitHub source "${n}".`,g.USAGE);return o}if(t.forceGithub){let o=fs(n,n,r);if(!o)throw new y(`Invalid GitHub shorthand "${n}".`,g.USAGE);return o}if(/^https?:\/\//i.test(n))throw new y(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,g.USAGE);return{kind:"local",input:n,absolute_path:j.resolve(process.cwd(),n)}}async function Zi(e,t=Up,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",a=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new y(`Git command failed: git ${e.join(" ")}
40
+ ${a}`,g.GENERIC_FAILURE)}}function gs(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function ys(e=process.platform){return e==="win32"}async function zp(e,t,n=Up,r=process.platform,i=process.env){let a=gs(r),o=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));o.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(a,e,{cwd:t,encoding:"utf8",env:o,shell:ys(r)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",d=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new y(`npm command failed: ${a} ${e.join(" ")}
41
+ ${d}`,g.GENERIC_FAILURE)}}function Gp(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function Wp(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function Ck(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("npm err! code e404")||t.includes("404 not found")||t.includes("is not in this registry")}function Tk(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return Ck(e)||t.includes("not found")}function $k(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Ok(e){let t=Gp(e),n=$k(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,a=i?`pm install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:a?[a,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:a?[`Try ${a} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&a?{fallback_candidates:[{source:i,command:a,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:a}:{}}}}}function Dk(e,t){if(!Tk(t))return null;let n=Ok(e);return new y(n.message,g.NOT_FOUND,n.context)}async function qp(e){if(j.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=j.resolve(process.cwd(),e);return await O(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=kk(t);return await O(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=j.resolve(process.cwd(),e);if(await O(t))return t}return null}async function Pk(e){let t=await qp(e);if(t)return t;let n=Nk(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Nk(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!Wp(e))return e;let i=e.slice(0,r),a=e.slice(r+n.length);if(a.startsWith("//")&&!a.startsWith("///"))return e;if(!a.startsWith("/"))return`${i}@${j.resolve(t,a)}`;let o;try{o=decodeURIComponent(new URL(`file:${a}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${i}@${s}`}function Fp(e,t){let n=j.resolve(e,t),r=j.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${j.sep}`)||j.isAbsolute(r))throw new y("npm pack reported a package archive outside its isolated destination.",g.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function Lk(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function Mk(e){return(Array.isArray(e)?e.map(t=>({value:t})):typeof e=="object"&&e!==null?Object.entries(e).map(([t,n])=>({key:t,value:n})):[]).flatMap(({key:t,value:n})=>{let r=Lk(n,t);return r?[r]:[]})}function jk(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(o=>{let s=o.name?.trim().toLowerCase();return s!==void 0?s===n:o.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let i=e[0],a=i.name??i.key;return n&&a!==void 0&&a.trim().toLowerCase()!==n?void 0:i}function Fk(e,t,n){let r;try{r=JSON.parse(e)}catch{let o=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!o)throw new y("npm pack did not report a tarball filename.",g.GENERIC_FAILURE);return{tarball:Fp(t,o)}}let i=Mk(r),a=jk(i,n);if(!a)throw new y("npm pack --json returned an unsupported or ambiguous package receipt.",g.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Fp(t,a.filename),package:a.name??a.key,version:a.version}}async function Uk(e){return Hk(e,zp)}async function Hk(e,t){let n=await qp(e.spec);if(n){if((await K.stat(n)).isFile()&&Bp(n))return hs(n);let a=j.join(n,"package.json"),o=await O(a)?JSON.parse(await K.readFile(a,"utf8")):{};return{directory:await ea(n,e.input),package:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,cleanup:async()=>{}}}let r=await K.mkdtemp(j.join(_s.tmpdir(),"pm-npm-package-source-")),i=j.join(r,"pack");await K.mkdir(i,{recursive:!0});try{let a=await Pk(e.spec),o=await t(["pack",a,"--json","--pack-destination",i]),s=Fk(o,i,Wp(e.spec)?void 0:Gp(e.spec));if(!await O(s.tarball))throw new y("npm pack did not create its reported package archive.",g.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await hs(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await K.rm(r,{recursive:!0,force:!0})}}}}catch(a){throw await K.rm(r,{recursive:!0,force:!0}),Dk(e.spec,a)||a}}function Bp(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function wt(e){throw new y(e,g.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function zk(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&wt(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,i=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||i.some(a=>a===".."))&&wt(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&wt(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&wt(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&wt(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&wt(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&wt(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function hs(e,t=Ik){(await K.stat(e)).size>t.maxArchiveBytes&&wt(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await K.mkdtemp(j.join(_s.tmpdir(),"pm-local-package-archive-")),r=j.join(n,"extract");await K.mkdir(r,{recursive:!0});let i={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await Ak({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(a===void 0)try{zk(d,t,i)}catch(l){a=l}}}),a!==void 0)throw a;i.packageJsonEntries!==1&&wt(`Local package archive must contain exactly one package/package.json entry; found ${i.packageJsonEntries}.`),await xk({file:e,cwd:r,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let o=j.join(r,"package"),s=j.join(o,"package.json"),c=JSON.parse(await K.readFile(s,"utf8"));return await Gk(o),{directory:await ea(o,e),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{await K.rm(n,{recursive:!0,force:!0})}}}catch(o){throw await K.rm(n,{recursive:!0,force:!0}),o}}async function Gk(e,t=zp){let n=j.join(e,"package.json");if(!await O(n))return;let r;try{r=JSON.parse(await K.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,a=Kk(i),o=Wk(i);if(a.length===0&&!o)return;let s={...r};delete s.devDependencies;let c={...s};qk(c),await K.writeFile(n,`${JSON.stringify(c,null,2)}
42
+ `,"utf8");try{await Promise.all([K.rm(j.join(e,"package-lock.json"),{force:!0}),K.rm(j.join(e,"npm-shrinkwrap.json"),{force:!0})]),a.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await Bk(e)}finally{await K.writeFile(n,`${JSON.stringify(s,null,2)}
43
+ `,"utf8")}}function Wk(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Qi in t)return!0;return!1}function qk(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Qi],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function Bk(e){let t=Ne(import.meta.url,["../../.."]),[n,r]=Qi.split("/"),i=j.join(e,"node_modules",n),a=j.join(i,r);await K.mkdir(i,{recursive:!0}),await K.rm(a,{recursive:!0,force:!0}),await K.symlink(t,a,Jk(process.platform))}function Jk(e){return e==="win32"?"junction":"dir"}function Vk(e,t){if(e.startsWith("-"))throw new y(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,g.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(n=>{let r=n.charCodeAt(0);return r<=31||r===127||"&|;()`\"'".includes(n)}))throw new y(`Extension runtime dependency "${e}" has an unsafe version specifier.`,g.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Sk.resolve(e,t)}catch{throw new y(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,g.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function Kk(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===Qi||typeof i!="string"||i.trim().length===0||t.has(r))continue;let a=i.trim();t.set(r,Vk(r,a))}return[...t.values()]}async function ea(e,t){let n=await Kr(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>j.relative(e,i).replaceAll(j.sep,"/")).sort((i,a)=>i.localeCompare(a));throw new y(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,g.USAGE)}throw new y(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,g.USAGE)}async function Yk(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(j.posix.join(".agents/pm/extensions",t.subpath)),n.push(j.posix.join(".custom/pm-extensions",t.subpath)),n.push(j.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let a=j.resolve(e,i);if(fe(e,a)&&await O(j.join(a,"manifest.json")))return{directory:a,resolved_subpath:i}}if(await O(j.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await ea(e,t.input);return{directory:r,resolved_subpath:j.relative(e,r).replaceAll(j.sep,"/")}}function Xk(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function Zk(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Xk(n))return new y(t,g.NOT_FOUND);let r=[];try{let a=process.env.PM_CLI_PACKAGE_ROOT,o=typeof a=="string"&&a.trim().length>0?j.resolve(a.trim()):"";ps?.key!==o&&(ps={key:o,aliases:await Xi()}),r=ps.aliases}catch{}let i=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${r.join(", ")}`];return new y(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,g.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Jp(e){if(e.kind==="local"){let r;try{r=await K.stat(e.absolute_path)}catch{throw await Zk(e)}if(r.isFile()&&Bp(e.absolute_path)){let a=await hs(e.absolute_path);return{source:e,directory:a.directory,source_root:j.dirname(a.directory),resolved_subpath:j.relative(j.dirname(a.directory),a.directory).replaceAll(j.sep,"/"),npm_package:a.package,npm_version:a.version,cleanup:a.cleanup}}if(!r.isDirectory())throw new y(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,g.USAGE);let i=await ea(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await Uk(e);return{source:e,directory:r.directory,source_root:j.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:j.relative(j.dirname(r.directory),r.directory).replaceAll(j.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await K.mkdtemp(j.join(_s.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Zi(n);let r=await Zi(["-C",t,"rev-parse","HEAD"]),i=await Yk(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await K.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await K.rm(t,{recursive:!0,force:!0}),r}}async function ta(e,t){if(!await O(e)||!await O(t))return!1;let[n,r]=await Promise.all([K.realpath(e),K.realpath(t)]);return n===r}import br from"node:fs/promises";import kr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var ws=1,tn="2026.6.24",Qk=">=22.18.0",eE={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Vp=new Set([...vd.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(wd).map(e=>e.toLowerCase()),"scaffold"]),tE="^6.0.0",nE="^22.0.0",Xp=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],it=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Kp(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Zp(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function Qp(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var rE={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Yp=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],ef={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},iE={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},aE={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},oE={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},tf="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",sE={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},cE={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},dE={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},lE={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function nf(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function rf(e,t){return e==="schema"?dE[t]:e==="profile"?lE[t]:cE[t]}function uE(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(o=>o.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),a=r>0&&(r===t.length||i!==void 0&&Vp.has(i));return`${(Vp.has(n)||a?["starter",...t]:t).join(" ")} ping`}function af(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],a=`${e.replace(/-/g,"_")}_owner`,o="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(a)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function mE(e,t,n){let r=`${e}-search`,i=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,o=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...af(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(a)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(a)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...o,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...o,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function pE(e,t,n){let r=n==="hooks",i=n==="search",a=n==="importers",o=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",m=iE[n],f=e,p=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,_=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...it,"});",""]:[],E=i?vs(e,t,"search",m):[],k=a?vs(e,t,"importers",m):[],x=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Kp(Zp({extensionName:e,itemTypeName:f,itemTypeFolder:p,fieldName:h,migrationId:_,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...it,"});",""]:[],D=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Kp(Qp(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...it,"});",""]:[],S=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...it,"});",""]:[],b=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...it,"});",""]:[],N=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...it,"});",""]:[],A=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...it,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Xp,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...it,"});","",...v,...E,...k,...x,...D,...S,...b,...N,...A,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
44
+ `)}function fE(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var hE={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},_E={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function gE(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function yE(e,t,n){let r=[],i=[...gE(e,t,n)],a=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),m=u===d?[]:[u],f=`${e.replace(/-/g,"_")}_note`,p=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),a.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),a.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),a.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(f)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(p)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),a.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...af(e),"});"),a.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),a.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),a.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),a.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),a.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:a}}function wE(e,t,n){let r=yE(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((i,a)=>i.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
45
+ `)}function vs(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,a=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],m=f=>[...u," let deactivated = false;"," try {",...f.map(p=>p===""?p:` ${p}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...it];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(a)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(Zp({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Qp(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function vE(e,t,n){let r=n==="parser",i=JSON.stringify([...ef[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...Xp,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(tn)},`," },",` target: { pmVersion: ${JSON.stringify(tn)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...it,"});","",...vs(e,t,n,i)].join(`
46
+ `)}function bE(e,t,n){let r=nf(n,"package"),i=rf(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${hE[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",tf,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${_E[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${ws}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${tn}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
47
+ `)}function kE(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function EE(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function SE(e,t,n,r){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function xE(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function AE(e,t,n,r="commands",i=!1){let a=`pm-${e}`,o=ef[r],s=fE(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:ws,pm_min_version:tn,trusted:!0,sandbox_profile:"strict",permissions:{...eE},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
48
+ `,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...mE(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
49
+ `),l=`${JSON.stringify(rE,null,2)}
50
+ `,u=aE[r],m=nf(r,"package"),f=`${JSON.stringify({name:a,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Qk},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${tn}`},devDependencies:{"@types/node":nE,typescript:tE},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
51
+ `,p=pE(e,t,r),h=oE[r],_=["node_modules/","*.log","*.tsbuildinfo",""].join(`
52
+ `),w=kE(e),v=["```ts",`import { ${EE(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...SE(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...xE(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],E=[`# ${a}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,h,tf,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...v,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...sE[r],...rf(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${tn}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${ws}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${tn}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
53
+ `);return{"package.json":f,"manifest.json":c,"index.ts":i?wE(e,t,r):d,"index.test.ts":i?vE(e,t,r):p,"tsconfig.json":l,".gitignore":_,"README.md":i?bE(a,t,r):E}}async function of(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!Yp.includes(i))throw new y(`Unknown scaffold capability "${n}". Supported capabilities: ${Yp.join(", ")}.`,g.USAGE);let a=i;if(r&&t!=="package")throw new y("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",g.USAGE);let o=r?"declarative":"imperative",s=e.trim(),c=kr.resolve(process.cwd(),s),d=Ki(kr.basename(c)).replace(/^(?:pm-)+/u,""),l=uE(d),u=AE(d,l,t,a,r),m=!1;if(await O(c)){if(!(await br.stat(c)).isDirectory())throw new y(`Scaffold target "${c}" exists and is not a directory.`,g.CONFLICT)}else await br.mkdir(c,{recursive:!0}),m=!0;for(let[p,h]of Object.entries(u)){let _=kr.join(c,p);if(await O(_)&&await br.readFile(_,"utf8")!==h)throw new y(`Scaffold file "${p}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,g.CONFLICT)}let f=[];for(let[p,h]of Object.entries(u)){let _=kr.join(c,p);if(await O(_)){f.push({path:p,status:"unchanged"});continue}await br.mkdir(kr.dirname(_),{recursive:!0}),await br.writeFile(_,h,"utf8"),f.push({path:p,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:a,style:o,target_path:c,created_directory:m,files:f}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function sf(e,t){return`${e}:${I(t)}`}function IE(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let a=new Map;for(let o of i){let s=a.get(o.command)??[];a.set(o.command,[...s,o])}for(let[o,s]of a){if(t!==null&&!s.some(d=>t.has(I(d.name))))continue;let c=s.at(-1);n.push({command:o,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function cf(e,t,n){let r=new Set(n.failed.map(d=>sf(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(sf(d.layer,d.name))?"failed":"ok",surfaces:Sn(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:Sn(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),a=typeof e=="string"?I(e):null,o=a===null?null:new Set(t.loaded.filter(d=>I(d.name)===a||typeof d.source_package=="string"&&I(d.source_package)===a||(d.source_aliases??[]).some(l=>I(l)===a)).map(d=>I(d.name)).concat(a)),s=o===null?i:i.filter(d=>o.has(I(d.name))),c=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Sn(n,c),command_ownership:IE(n,o)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e6087f2-01b5-59c3-a471-433c722316b0")}catch{}})();function bs(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function na(e,t,n){let r=I(t),i=n.trim();if(r.length===0||i.length===0)return;let a=e.get(r)??new Set;a.add(i),e.set(r,a)}function RE(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)na(t,r.name,r.command),na(n,r.name,r.action);for(let r of e.commands.handlers)na(t,r.name,r.command);for(let r of e.commands.overrides)na(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function df(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function CE(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:a}=e;return t?i.has(n)||a.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function ra(e,t,n){let r=new Set(t.loaded.map(c=>I(c.name))),i=new Set(t.failed.map(c=>I(c.name))),a=new Set(n.failed.map(c=>I(c.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=RE(n);return e.map(c=>{let d=I(c.name),l=df(o.get(d)),u=df(s.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},f=CE({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:i,activationFailedNames:a});return{...c,...f,...m}})}function TE(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function me(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var mf=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function $E(e){return mf.has(yf(e))}function lf(e){return e==="project"||e==="global"}function pf(e){let t=e.split(":"),n=t[0];if(!n||!mf.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!lf(r)||!lf(a)||!i||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:a,name:o}}}function OE(e){let t=new Set;for(let n of e){let r=pf(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function ks(e,t){let n=e.filter($E);if(n.length===0)return null;let r=OE(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function DE(e,t,n,r){let i=t.map(u=>pf(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let a=e==="global"?"--global":"--project",o=me(r,"deactivate"),s=`${me(r,"doctor")} ${a} --detail deep --trace`,c=new Map(n.map(u=>[I(u.name),u])),d=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let f=I(m);d.set(f,(d.get(f)??0)+1)}let l=[...d.entries()].map(([u,m])=>{let f=c.get(u),p=f?.name??u,h=f?.command_paths??[],_=f?.action_paths??[];return{action:"deactivate",extension:p,command:`${o} ${p} ${a}`,affected_collisions:m,feature_loss:{command_paths:[...h].sort((w,v)=>w.localeCompare(v)),action_paths:[..._].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let f=m.affected_collisions-u.affected_collisions;if(f!==0)return f;let p=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,h=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return p!==h?p-h:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:d.size,next_best_command:s,collisions:i,remediation_candidates:l}}function ff(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function hf(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function _f(e,t){let n=[];for(let r of Gd(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var PE=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${me(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${Gr.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${me(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${me(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${me(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function NE(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=[],m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o};if(t.length>0){let f=ks(t,{deactivate:`${me(n,"deactivate")} <name> ${i}`,doctor:`${me(n,"doctor")} ${i} --detail deep --trace`});f&&u.push(f);for(let p of PE)p.matches(t,m)&&u.push(p.build(m))}return s>0&&u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${me(n,"manage")} ${i} --fix-managed-state (or ${me(n,"adopt-all")} ${i}, ${me(n,"adopt")} <name> ${i}, or reinstall via ${me(n,"install")} ${i} <source>).`),d>0&&u.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&u.push(`Update-check coverage is partial: some sources have no completed check. Run ${me(n,"manage")} ${i} to request update checks.`),l>0&&u.push(`Update available managed extensions via ${me(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${me(n,"manage")} ${i} after extension changes.`),u}function ia(e,t,n,r={}){let i=[...new Set(t)].sort((b,N)=>b.localeCompare(N)),a=n.filter(b=>b.managed).length,o=n.filter(b=>b.enabled).length,s=n.filter(b=>b.active).length,c=n.filter(b=>b.update_check_status==="checked"&&b.update_available===!0).length,d=n.filter(b=>b.managed===!1),l=d.filter(b=>uf(b)).map(b=>b.name).sort((b,N)=>b.localeCompare(N)),u=d.filter(b=>!uf(b)).map(b=>b.name).sort((b,N)=>b.localeCompare(N)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let b of n)m[b.update_check_status]+=1;let f=m.failed,p=n.filter(b=>b.update_check_status==="skipped_non_github"&&b.source?.kind!=="builtin").length,h=Object.entries({skipped_unmanaged:u.length,skipped_non_github:p,failed:f,not_checked:m.not_checked}).filter(([,b])=>b>0).map(([b,N])=>`extension_update_health_partial_coverage:${b}:${N}`),_=h.length>0,w=_?"partial":"full",v=[...new Set([...i,...h])].sort((b,N)=>b.localeCompare(N)),E=[...new Set(v.map(b=>yf(b)))].sort((b,N)=>b.localeCompare(N)),k=TE(v),x=e==="global"?"--global":"--project",D=DE(e,i,n,r),S=NE({normalizedWarnings:v,options:r,scope:e,scopeFlag:x,updateCheckFailedTotal:f,policyWarningCount:k.warning_count,unmanagedActionRequiredTotal:u.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:p,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:E,warnings:v,policy_warning_count:k.warning_count,policy_violation_count:k.violation_count,policy_blocked_count:k.blocked_count,total_extensions:n.length,managed_total:a,enabled_total:o,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:_,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(b=>b.name).sort((b,N)=>b.localeCompare(N)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:f,top_warnings:v.slice(0,8),remediation:S,...D?{collision_plan:D}:{}}}function gf(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new y(`Invalid --detail value "${e}". Expected summary or deep.`,g.USAGE)}function yf(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Er(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let a=Zc(r);return a?[a]:Qc(r)})();for(let a of i){let o=`${a.layer}:${a.name}:${a.capability}`;t.has(o)||(t.add(o),n.push(a))}}return n}function Sr(){return{version:Wr.version,capabilities:[...Wr.capabilities],legacy_aliases:{...Wr.legacy_aliases}}}function uf(e){let t=I(e.name),n=I(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function wf(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let a=[...new Set(t.filter(d=>d.active).map(d=>I(d.name)))].sort((d,l)=>d.localeCompare(l)),o=[...new Set(n.filter(d=>d.layer==="project").map(d=>I(d.name)))].sort((d,l)=>d.localeCompare(l)),s=new Set(r.map(d=>I(d.name))),c=a.filter(d=>!o.includes(d)&&!s.has(d)).sort((d,l)=>d.localeCompare(l));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:a.length,loaded_project_count:o.length,active_project_names:a,loaded_project_names:o,missing_active_project_names:c}}}import vf from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function xr(e,t,n,r){let i=vf.relative(e,n);if(i!==""&&!fe(e,n)||n===t||fe(t,n))return!1;let a=i.split(vf.sep);return a.includes(".git")?!1:r?!a.some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as LE}from"node:crypto";import se from"node:fs/promises";import ME from"node:os";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]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var bf=3,jE=120,kf=250,FE=12e4,UE=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Ef=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Sf=e=>UE.has(String(Ef(e))),aa=(e,t)=>Ef(e)===t,xf=e=>new Promise(t=>{setTimeout(t,e)}),Af=async e=>{let t=re.join(e,"package.json");await O(t)||await se.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
54
+ `,"utf8")},If=async e=>{let t=Ne(import.meta.url,["../../.."]),n=re.join(e,"node_modules","@unbrained"),r=re.join(n,"pm-cli");await se.mkdir(n,{recursive:!0}),await se.rm(r,{recursive:!0,force:!0}),await se.symlink(t,r,process.platform==="win32"?"junction":"dir")},Ar=async e=>{let t=re.resolve(e),n=re.dirname(t),r=re.parse(n).root,i=await se.realpath(r).catch(()=>r),a=re.relative(r,n),o=a===""?[]:a.split(re.sep);for(let[s,c]of o.entries()){let d=re.join(i,c);try{i=await se.realpath(d)}catch{i=re.join(i,...o.slice(s));break}}return re.join(i,re.basename(t))},Rf=async(e,t,n,r=ME.tmpdir())=>Wt("extension_install_copy",async()=>{let i=re.resolve(e),a=await se.realpath(i).catch(()=>i),o=await Ar(t);if(a===o)return;if(!fe(a,o)){await n(a,t,{recursive:!0,force:!0,filter:u=>xr(a,o,re.resolve(u),!1)});return}let s=await se.realpath(re.resolve(r)).catch(()=>Ar(r)),c=fe(a,s)?re.dirname(a):s;if(fe(a,c))throw new y(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,g.USAGE,{code:"extension_install_source_contains_destination"});let d=await se.mkdtemp(re.join(c,"pm-extension-copy-")),l=re.join(d,"extension");try{await n(a,l,{recursive:!0,force:!0,filter:u=>xr(a,o,re.resolve(u),!0)}),await n(l,t,{recursive:!0,force:!0})}finally{await se.rm(d,{recursive:!0,force:!0})}}),Cf=async(e,t,n=se.cp)=>{for(let r=1;r<=bf;r+=1)try{await Wt("extension_install_copy",async()=>{await se.rm(t,{recursive:!0,force:!0}),await Rf(e,t,n)});return}catch(i){if(!Sf(i)||r===bf)throw i;await xf(kf)}},Es=async e=>{let t;try{t=await se.readFile(re.join(e,"owner.json"),"utf8")}catch(i){if(!At(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},Tf=async(e,t)=>await Es(e)!==t?!1:(await se.rm(e,{recursive:!0,force:!0}),!0),HE=async(e,t)=>{let n;try{n=await se.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await Es(e);return r===null?(await se.rm(e,{recursive:!0,force:!0}),!0):Tf(e,r)},zE=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await Es(e)!==t)return;let a=new Date;await se.utimes(e,a,a)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},GE=async(e,t)=>{await se.mkdir(e);try{await se.writeFile(re.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
55
+ `,"utf8")}catch(n){throw await se.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},WE=async(e,t,n,r,i)=>{for(let a=1;a<=n;a+=1)try{return await GE(e,t),!0}catch(o){if(!aa(o,"EEXIST"))throw o;await HE(e,i)?a-=1:await xf(r)}return!1},Ss=async(e,t,n,r)=>Wt("extension_install",async()=>{let i=re.join(e,"runtime","extension-install-locks"),a=re.join(i,"scope.lock");await se.mkdir(i,{recursive:!0});let{attempts:o=jE,delay_ms:s=kf,stale_ms:c=FE,heartbeat_ms:d}=r??{};if(![o,s,c,d].filter(w=>w!==void 0).every(Number.isFinite))throw new y("Extension install lock timings must be finite numbers.",g.USAGE);let l=Math.max(1,Math.floor(o)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),f=Math.floor(d??m/3);if(m<=0||f<=0||f>=m)throw new y("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",g.USAGE);let p={pid:process.pid,token:LE(),created_at:$(),destination:t};if(!await WE(a,p,l,u,m))throw new y(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let h=zE(a,p.token,f),_=!1;try{let w=await n();return _=!0,w}finally{await h(),await Tf(a,p.token).catch(w=>{if(_)throw w})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var xs=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o])}});return await Promise.all(a),r};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function $f(e,t){let n=I(e),r=t.find(i=>I(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,a)=>i.localeCompare(a)),action_paths:[...r?.action_paths??[]].sort((i,a)=>i.localeCompare(a))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function Of(e,t){let n=new Set((t?.loaded??[]).flatMap(a=>(a.activation?.commands?.length??0)>0?[`${a.layer}:${I(a.name)}`]:[])),r=e.services.overrides.filter(a=>a.service==="output_format").filter(a=>a.passThrough!==!0).filter(a=>!n.has(`${a.layer}:${I(a.name)}`)).map(a=>`extension_output_service_override_global:${a.service}:${a.layer}:${a.name}`),i=e.renderers.overrides.filter(a=>(a.commands?.length??0)===0&&a.resultDiscriminator===void 0).map(a=>`extension_output_renderer_override_global:${a.format}:${a.layer}:${a.name}`);return[...new Set([...r,...i])].sort((a,o)=>a.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var Df=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=ni(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{execFile as qE}from"node:child_process";import{promisify as BE}from"node:util";import JE from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b67e46f9-51ff-501b-98da-74353b4c66d9")}catch{}})();var VE=BE(qE),Nf=1e4;function Pf(e,t,n){if(typeof t=="string")try{let r=JE.resolve(e,t);if(r.type==="version")return r.fetchSpec}catch{}throw new Error(n)}async function KE(e,t){try{return(await VE(gs(),e,{encoding:"utf8",timeout:t,maxBuffer:65536,shell:ys(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function Lf(e,t=KE){let n=$();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let r=Pf(e.package,e.version,"missing_or_invalid_installed_npm_version"),i=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],Nf),a;try{a=JSON.parse(i)}catch{throw new Error("invalid_npm_registry_metadata")}let o=Array.isArray(a)&&a.length===1?a[0]:a,s=Pf(e.package,o,"invalid_npm_registry_version");return{checked_at:n,available:s!==r,remote_version:s}}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}}var YE=(e,t,n)=>{let r=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c=""]=o.split(/\s+/);return{commit:s,ref:c}}),i=r.find(o=>o.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let a=t?.trim();return a?{checked_at:n,remote_commit:i.commit,available:i.commit!==a}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},As=async(e,t=Zi)=>{let n=$();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let r=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,Nf);return YE(i,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(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]="d34e2cc0-5e58-5534-8480-a9ab47ec4a88")}catch{}})();var XE=4;async function Mf(e,t=!1){let n=await xs(e.entries,XE,async r=>{if(!["github","npm"].includes(r.source.kind))return r;if(t)return{...r,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0};let i=r.source.kind==="github"?await As(r.source):await Lf(r.source);return{...r,last_update_check_at:i.checked_at,last_update_remote_commit:"remote_commit"in i?i.remote_commit:void 0,last_update_remote_version:"remote_version"in i?i.remote_version:void 0,update_available:i.available,update_error:i.error}});return{...e,entries:gr(n)}}import ZE from"node:fs/promises";import QE from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function Is(e){return QE.join(e,"extension-migrations.json")}function jf(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Ff(e,t){return`${e.layer}:${e.name}:${t}`}async function eS(e){let t=Is(e);if(!await O(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await ZE.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function Rs(e,t){let n=await eS(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,a)=>{let o=jf(i,a),s=r.get(Ff(i,o));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function tS(e){let t=await Rs(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),r=[],i=!1,a=e.migrations.map((l,u)=>({migration:l,index:u})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:u}of a){let m=jf(l,u),f=Ff(l,m),p=n.get(f),h=String(l.definition.status??"pending").toLowerCase(),_=p?.status??(h==="applied"||h==="failed"?h:"pending");if(_==="applied"){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:_}));let E={key:f,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(f,E),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"applied"}),i=!0}catch(E){let k=E instanceof Error?E.message:String(E),x={key:f,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:k};n.set(f,x),l.definition.status="failed",l.definition.reason=k,r.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"failed",error:k}),i=!0}}if(i){let l=await T(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,f)=>m.key.localeCompare(f.key))};await _i({pmRoot:e.pmRoot,filePath:Is(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
56
+ `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let o=r.filter(l=>l.outcome==="pending").length,s=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:Is(e.pmRoot),total:r.length,pending_count:o,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function Uf(e){let t=await T(e.resolvedRoots.settings_root),n=await Xe({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Ze(n);e.warnings.push(...n.warnings,...r.warnings);let i=await tS({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fcf7df06-e3b8-5476-a76a-cd391839c13d")}catch{}})();function Hf(e,t){let n=e.filter(r=>r.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:r,result:i})=>{let a=i.details;return{alias:r,ok:i.ok,extension:a.extension,source:a.source,source_resolution:a.source_resolution,install_plan:a.install_plan,dry_run:a.dry_run,destination_path:a.destination_path,activated:a.activated,settings_changed:a.settings_changed,command_paths:a.command_paths,action_paths:a.action_paths,command_discovery:a.command_discovery,verification:a.verification,runtime_activation_status:a.runtime_activation_status,activation_diagnostics:a.activation_diagnostics,warnings:i.warnings}})}}import sa from"node:fs/promises";import oa from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var nS=new Set(["node_modules",".git","dist","build","coverage"]);async function zf(e,t,n,r){let i=e.source.kind==="local"?await sa.stat(e.source.absolute_path):void 0,a=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,o=await rS(e.directory,t,r),s={source_mode:a,...a==="archive"?{archive_bytes:i.size}:{},copy:o},c=e.source_root??e.directory;if(a==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await O(oa.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),a==="directory"&&!o.complete){let d=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new y(`Local extension source scan stopped at ${d}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,g.USAGE,{code:"extension_install_incomplete_source_scan",reason:o.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function rS(e,t,n={}){let{maxEntries:r=1e4,maxDepth:i=64,signal:a}=n;if(![r,i].every(u=>Number.isSafeInteger(u)&&u>0))throw new y("maxEntries and maxDepth must be positive safe integers.",g.USAGE);a?.throwIfAborted();let o=await sa.realpath(e),s=await Ar(t),c=await ta(o,s);a?.throwIfAborted();let d=c?"in_place":fe(o,s)?"nested_filtered_snapshot":"directory_snapshot",l={copy_scope:d,source_directory:o,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:r,max_depth:i};return d==="in_place"||await Gf(o,0,l,a),l}async function Gf(e,t,n,r){r?.throwIfAborted();let i=await sa.opendir(e);for await(let a of i){if(r?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=oa.join(e,a.name);if(!xr(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(oa.relative(n.source_directory,o).split(oa.sep).some(s=>nS.has(s))&&(n.development_entries+=1),await iS(o,t,n,r),!n.complete)return}}async function iS(e,t,n,r){let i=await sa.lstat(e);if(r?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await Gf(e,t+1,n,r)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import aS from"node:fs/promises";import oS from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function sS(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function cS(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function Cs(e){let t=oS.join(e,"manifest.json"),n;try{n=await aS.readFile(t,"utf8")}catch(s){if(At(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=r,a=ad(i),o=sS(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:a.findings,warnings:a.findings.map(s=>cS(o,s)),remediation:a.findings.map(s=>s.message)}}function Wf(e){return Cs(Ye(e))}import dS from"node:fs/promises";import lS from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bef4424-f5b8-511b-91f7-0b39cf11f515")}catch{}})();async function uS(e,t){if(e.kind!=="local"||e.input.startsWith(".")||e.input.includes("\\")||e.input.includes("/")&&!/^@[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/u.test(e.input))return e;try{return await dS.lstat(e.absolute_path),e}catch(a){if(!F(a))throw a}let n=e.input.trim(),r=t.filter(a=>a.source.kind==="npm"),i=(r.find(a=>a.name===n)??r.find(a=>a.directory===n)??r.find(a=>a.source.package===n))?.source.package;if(i===void 0)return e;try{let a=lS(i);if(!a.registry||a.name!==i)return e}catch{return e}return vr(`npm:${i}`,{})}async function qf(e,t,n,r=[]){let i=typeof t=="string"?null:await wr(e),a=i===null?null:e.trim().toLowerCase(),o=a===null?null:await Lp(a),s=await uS(vr(i??e,{forceGithub:typeof t=="string",ref:n}),r),c=a===null?null:await Hp(e);return{bundledAliasName:a,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:a===null?s.kind:"builtin",input:a??s.input,...o===null?{}:{package:o}},ambiguous:c!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...a===null?[]:[{kind:"builtin",input:a,...o===null?{}:{package:o},command:`pm install ${a}`}],...c===null?[]:[{kind:"npm",input:`npm:${c.package}`,package:c.package,...c.version===void 0?{}:{version:c.version},directory:c.directory,command:`pm install npm:${c.package}`}]]}}}import nn from"node:fs/promises";import mS from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="776854e4-6df4-507e-b21b-a4d320946642")}catch{}})();var Ts=async e=>nn.readFile(e).catch(t=>{if(aa(t,"ENOENT"))return null;throw t}),Bf=async(e,t,n,r,i)=>Wt("extension_install_backup",async()=>{let a=_r(e),o=zt(t),[s,c]=await Promise.all([Ts(a),Ts(o)]);return r&&await nn.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:a,managedStateContents:s,settingsPath:o,settingsContents:c}}),Jf=async e=>Wt("extension_install_rollback",async()=>{await nn.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await nn.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await nn.rm(t,{force:!0}):(await nn.mkdir(mS.dirname(t),{recursive:!0}),await nn.writeFile(t,n))});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="549164da-d760-52bc-9950-25dacf286775")}catch{}})();var Xf=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],pS=Xf.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),fS={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},hS="__pm_native_output",_S=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Zf=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],gS=["disabled","require_trusted","require_provenance"],Qf={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},yS=e=>{let t=e??Qf,n={};for(let r of _S)n[r]=De(t[r]??[]);return n},wS=(e,t)=>{for(let n of Zf)t[n].length>0&&(e[n]=t[n]);return e},vS=(e,t)=>{for(let n of gS)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},bS=e=>{let t={};for(let n of Zf)t[n]=De(e[n]??[]);return t},kS=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:wS(vS({name:t},e),bS(e))},ES=e=>(e??[]).map(t=>kS(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),SS=e=>{let t=Object.assign({},Qf,e??{}),n=yS(e),r=ES(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},eh=async(e,t)=>{let n=[t],r=await Mp(t);r&&n.push(r);let i=[...new Set(n.map(a=>I(a)).filter(a=>a.length>0))];for(let a of i){let o=e.find(c=>I(c.name)===a);if(o)return o;let s=e.find(c=>I(c.directory)===a);if(s)return s}},th=(e,t)=>{let n=t.trim(),r=new Set(De(e.extensions.enabled));return new Set(De(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},nh=(e,t)=>{let n=t.trim(),r=new Set(De(e.extensions.enabled)),i=new Set(De(e.extensions.disabled)),a=[...r],o=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},xS=(e,t)=>{let n=t.trim(),r=new Set(De(e.extensions.enabled)),i=new Set(De(e.extensions.disabled)),a=[...r],o=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},AS=(e,t)=>{let n=t.trim(),r=new Set(De(e.extensions.enabled)),i=new Set(De(e.extensions.disabled)),a=[...r],o=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},IS=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=Xf.map(([i,a,o])=>({action:a,flag:o,distance:Xc(t,i,n)})).filter(i=>i.distance!==null).sort((i,a)=>i.distance-a.distance)[0];return r?{action:r.action,flag:r.flag}:null},RS=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=IS(e);if(!r)return new y(`One action flag is required. Use one of: ${pS}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let i=`pm ${n} ${r.flag}`;return yi({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(rh),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},CS=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],rh={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},TS=e=>rh[e]??null,$S=(e,t)=>{let n=[...new Set(CS.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=TS(e.trim().toLowerCase());if(r)return r;throw RS(e,t)}if(n.length>1)throw new y("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},OS=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new y('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"},DS=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],ih=e=>{for(let t of DS){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},ah=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,last_update_remote_version:i.last_update_remote_version,update_error:i.update_error,update_check_status:r.status,update_check_reason:r.reason}},PS=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),a=r?th(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ah({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:a},t,r,ih(r))}},NS=async(e,t,n,r,i,a)=>{let o=Pe.join(e,t),s=Pe.join(o,"manifest.json"),c=a.get(I(t));if(!await O(s))return PS(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await jt.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=ds(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(I(u.name))??a.get(I(t));return{summary:ah({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:th(r,u.name)},n,m,ih(m))}},at=async(e,t,n,r)=>{if(!await O(e))return{extensions:[],warnings:[]};let i=(await jt.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,l)=>d.localeCompare(l)),a=new Map(r.entries.map(d=>[I(d.name),d])),o=new Map(r.entries.map(d=>[I(d.directory),d])),s=[],c=[];for(let d of i){let l=await NS(e,d,t,n,a,o);l.warning&&s.push(l.warning),l.summary&&c.push(l.summary)}return{extensions:c.sort((d,l)=>d.name.localeCompare(l.name)),warnings:s.sort((d,l)=>d.localeCompare(l))}},LS=Hd(),MS=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,jS=(e,t,n,r)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),a=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return a&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:MS(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:o,...a?{sdk_dependency_status:"missing"}:{}}},FS=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},oh=e=>e.map(t=>FS(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),sh=(e,t,n)=>{let r=I(e);return t.find(i=>(n===void 0||i.layer===n)&&I(i.name)===r)},US=(e,t,n,r)=>n.find(i=>i.scope===t&&I(i.name)===I(e))?.activation_status??(r?"failed":"unknown"),ch=(e,t,n,r,i)=>LS.enqueue(async()=>{let a=process.env.PM_CLI_PACKAGE_ROOT,o=await jt.mkdtemp(Pe.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Ne(import.meta.url,["../.."]);try{let s=await Xe({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:Va(),cache_bust:!0,module_graph_snapshot_root:o}),c=await Ze({...s}),d=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...oh(c.failed)],l=Object.fromEntries(s.loaded.map(u=>[I(u.name),kd(Sn(c,{extensionName:u.name}))]));return{installed:ra(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await jt.rm(o,{recursive:!0,force:!0}),a===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=a}}),Os=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),a=[...i].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),o=r,s=[];for(let c of a){let d=Pe.join(e,c.directory),l=await $n(d),u=$(),m={kind:"local",input:c.name,location:d};o=yr(o,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:u,updated_at:u,source:m}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return s.length>0&&await On(e,o),{state:o,adopted_entries:s,unmanaged_candidates:a,already_managed_count:n.length-i.length}},HS=(e,t)=>{let n=L(process.cwd(),t.path),r=sn(n,process.cwd()),i=e==="global"?Br(process.cwd()):n,a=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:a,roots:r}},ca=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new y('Options "--gh" and "--github" must match when both are provided.',g.USAGE);return n[0]},zS=e=>fS[e],GS=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,a=zS(e),o=`<${r}>`,s=`pm ${n} ${a} ${o}`;throw new y(`Action "${e}" requires ${i} input.`,g.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},da=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new y('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',g.USAGE);return GS(t,n)},WS=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${I(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${I(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,i,a)=>a.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},qS=(e,t)=>{let n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(r=>r.triggered&&!r.allowed);if(n)throw new y(n.message,g.USAGE)},BS=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},JS=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},VS=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:JS(e),warnings:[...new Set(e.warnings)].sort((i,a)=>i.localeCompare(a)),details:t};return e.action==="doctor"&&Object.defineProperty(r,hS,{value:!0,enumerable:!1,configurable:!1}),r},Ds=async(e,t,n)=>{let r=$S(e,t);qS(r,t);let i=BS(e,r,t),a=OS(t),o=HS(a,n),s={action:r,normalizedTarget:i,scope:a,resolvedRoots:o,warnings:[],options:t,global:n},c={...s,withResult:(d,l=!0)=>VS(s,d,l)};return await I0(c)},KS=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=Jd(r),a={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[a[n],...s,`Install the scaffold: ${Me(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},YS=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([ca(r),r.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new y('Action "init" does not accept --gh/--github/--ref options.',g.USAGE);let a=da(n,t,r),o=await of(a,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:KS(o,r)})},XS=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:a,withResult:o}=e;if(t!==void 0)throw new y('Action "reload" does not accept a target argument.',g.USAGE);let s=await T(n.settings_root),c=Va(),d=await Xe({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:a.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await Ze(d);r.push(...l.warnings);let u={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(u)},ZS=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:a}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new y('Action "catalog" does not accept a package target.',g.USAGE);return a(await jp(n,i,r))},QS=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),e0=e=>({kind:"local",input:e.input,location:e.absolute_path}),t0=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),n0=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),r0=(e,t,n,r)=>e?QS(e,t):n.kind==="local"?e0(n):n.kind==="npm"?t0(n,r):n0(n,r),i0=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:$p(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},a0=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:a,destinationDirectoryName:o}=t,s=await T(r.settings_root),c=await ye(r.selected_root);i.push(...c.warnings);let d=Pe.join(r.selected_root,o),l=await O(d),u=await ta(a.directory,d);await jt.mkdir(r.selected_root,{recursive:!0});let m=await jt.mkdtemp(Pe.join(r.selected_root,".pm-extension-install-backup-")),f=Pe.join(m,"destination");try{let p=await Bf(r.selected_root,r.settings_root,d,l,f),h=r0(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),_=c.state.entries.find(k=>I(k.name)===I(a.manifest.name)),w=i0(_,a.manifest.version,h,$()),v=yr(c.state,{name:a.manifest.name,directory:o,scope:n,manifest_version:a.manifest.version,manifest_entry:a.manifest.entry,capabilities:[...a.manifest.capabilities],contributions:a.manifest.contributions,...w,source:h}),E=nh(s,a.manifest.name);try{u||await Cf(a.directory,d),await Af(d),await If(d),await On(r.selected_root,v),E&&await gi(r.settings_root,s,"settings:write")}catch(k){try{await Jf(p)}catch(x){throw new AggregateError([k,x],`Extension install failed: ${String(k)}; rollback failed: ${String(x)}`,{cause:x})}throw k}return{settings:s,managedState:v,sourceRecord:h,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:E}}finally{await jt.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},o0=async(e,t,n)=>{let r=n.filter(i=>I(i.name)===I(t)).flatMap(i=>i.types.map(a=>({name:a.name,folder:a.folder})));return e.scope==="project"&&r.length>0&&await fr(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},s0=(e,t,n,r,i)=>{let a=sh(t,n.activation_failures,e.scope),o=US(t,e.scope,n.installed,a),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:a,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},c0=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:a,withResult:o}=e,{validated:s,destinationDirectoryName:c}=t,d=await a0(e,t),l=await at(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let u=await ch(r.pm_root,Pe.dirname(r.selected_root),d.settings,l.extensions,a);i.push(...u.warnings);let m=await o0(e,s.manifest.name,u.item_type_registrations),f=$f(s.manifest.name,u.installed),p=s0(e,s.manifest.name,u,f,m),h=u.contribution_inventories[I(s.manifest.name)];return h&&(d.managedState=await Op(r.selected_root,d.managedState,s.manifest.name,h)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:p.activated,settings_changed:d.activationChanged,runtime_activation_status:p.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:h,command_discovery:jS(s.manifest.name,d.sourceRecord,f,p.failure),verification:p.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:p.failure??null}},p.activated)},d0=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new y('Action "install all" does not accept --ref.',g.USAGE);let a=[],o=new Map;for(let s of await Xi()){let c=await wr(s),d=Pe.resolve(c),l=o.get(d);l===void 0&&(l=await Ds(s,{...t,install:!0},n),o.set(d,l)),a.push({alias:s,result:l})}return r.push(...a.flatMap(s=>s.result.warnings)),i(Hf(a,t.dryRun===!0),a.every(s=>s.result.ok))},l0=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:a,installSource:o,sourceResolution:s}=await qf(t,n,e.options.ref,(await ye(r.selected_root)).state.entries);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${d.package}`)}let c=await Jp(o);try{let d=await $n(c.directory,{source_kind:o.kind,source_input:o.input,source_root:c.source_root}),l=Ki(d.manifest.name),u=e.options.dryRun===!0||o.kind==="local"&&i===null?await zf(c,Pe.join(r.selected_root,l),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:d.manifest.name,version:d.manifest.version},source_resolution:s,install_plan:u}):await Ss(r.settings_root,l,()=>c0(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:a,sourceResolution:s,installSource:o,resolvedSource:c,installPlan:u}))}finally{c.cleanup&&await c.cleanup()}},u0=async e=>{let t=ca(e.options),n=t??da(e.normalizedTarget,e.action,e.options);return[t===void 0,Pp(n)].every(Boolean)?d0(e):l0(e,n,t)},m0=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e;if(t!==void 0)throw new y('Action "adopt-all" does not accept a target argument.',g.USAGE);if(ca(a)!==void 0||typeof a.ref=="string"&&a.ref.trim().length>0)throw new y('Action "adopt-all" does not accept --gh/--github/--ref options.',g.USAGE);let s=await T(r.settings_root),c=await ye(r.selected_root);i.push(...c.warnings);let d=await at(r.selected_root,n,s,c.state);i.push(...d.warnings);let l=await Os(r.selected_root,n,d.extensions,c.state),u=await at(r.selected_root,n,s,l.state);i.push(...u.warnings);let m=ia(n,i,u.extensions,a);i.push(...m.warnings);let f=new Map(u.extensions.map(_=>[`${I(_.name)}:${I(_.directory)}`,_])),p=new Map(u.extensions.map(_=>[I(_.directory),_])),h=l.adopted_entries.map(_=>{let w=I(_.directory),v=f.get(`${I(_.name)}:${w}`)??p.get(w);return{..._,...dh(v)}});return o({adopted_all:h.length>0,adopted_count:h.length,already_managed_count:l.already_managed_count,extensions:h,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},dh=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),p0=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=vr(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new y(`Invalid GitHub shorthand "${e}".`,g.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},f0=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o,withResult:s}=e,c=da(n,t,o),d=ca(o),l=await T(i.settings_root),u=await ye(i.selected_root);a.push(...u.warnings);let m=await at(i.selected_root,r,l,u.state);a.push(...m.warnings);let f=await eh(m.extensions,c);if(!f)throw new y(`Installed extension "${c}" was not found in ${r} scope.`,g.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let p=Pe.join(i.selected_root,f.directory),h=await $n(p),_=$(),w=p0(d,c,p,o.ref),v=yr(u.state,{name:h.manifest.name,directory:f.directory,scope:r,manifest_version:h.manifest.version,manifest_entry:h.manifest.entry,capabilities:[...h.manifest.capabilities],contributions:h.manifest.contributions,installed_at:_,updated_at:_,source:w});await On(i.selected_root,v);let E=await at(i.selected_root,r,l,v);a.push(...E.warnings);let k=E.extensions.find(x=>I(x.name)===I(h.manifest.name))??E.extensions.find(x=>I(x.directory)===I(f.directory));return s({adopted:!0,extension:{name:h.manifest.name,directory:f.directory,version:h.manifest.version,entry:h.manifest.entry},source:w,...dh(k)})},lh=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o}=e,s=da(n,t,o),c=await T(i.settings_root),d=await ye(i.selected_root);a.push(...d.warnings);let l=await at(i.selected_root,r,c,d.state);a.push(...l.warnings);let u=await eh(l.extensions,s);if(!u)throw new y(`Installed extension "${s}" was not found in ${r} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},h0=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:a}=await lh(e),o=Pe.join(t.selected_root,a.directory);await jt.rm(o,{recursive:!0,force:!0});let s={...i.state,updated_at:$(),entries:i.state.entries.filter(d=>I(d.name)!==I(a.name)&&I(d.directory)!==I(a.directory))};await On(t.selected_root,s);let c=AS(r,a.name);return c&&await gi(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:a.name,directory:a.directory},destination_path:o,settings_changed:c})},Vf=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:a}=e,{settings:o,candidate:s}=await lh(e),c=t==="activate"?nh(o,s.name):xS(o,s.name);c&&await gi(n.settings_root,o,"settings:write");let d=t==="activate"?await ch(n.pm_root,Pe.dirname(n.selected_root),o,[s],i).then(l=>(r.push(...l.warnings),sh(s.name,l.activation_failures,e.scope))):void 0;return d&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),a({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},d===void 0)},_0=(e,t,n,r,i,a)=>{let o=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],c=i?.adopted_entries.length??0,d=[[a!==null,a??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},$s=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),g0=(e,t,n,r)=>{if(e!=="project"||t||!$s(r))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},y0=(e,t,n)=>{if(String(e??"").trim().length>0)throw new y('Action "doctor" does not accept a target argument.',g.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new y("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",g.USAGE);let i=gf(n.detail),a=n.trace===!0;if([a,i!=="deep"].every(Boolean))throw new y("--trace requires --detail deep with --doctor.",g.USAGE);return{isolated:r,detailMode:i,includeTrace:a}},w0=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await Os(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},v0=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:$s(r),rerun_command:null,pm_global_path_recipe:null};let a=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:$s(r),rerun_command:t?null:a,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},b0=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,global:o,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=y0(t,n,a),u=await T(r.settings_root),m=await ye(r.selected_root);i.push(...m.warnings);let f=await at(r.selected_root,n,u,m.state);i.push(...f.warnings);let{state:p,fix:h}=await w0(e,f.extensions,m.state),_=await at(r.selected_root,n,u,p);i.push(..._.warnings);let w=await Xe({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Ze({...w,loaded:w.loaded}),E=await Wf(r.pm_root);i.push(...E.warnings,...w.warnings),i.push(...ff(w.failed)),i.push(...v.warnings),i.push(...hf(v.failed)),i.push(..._f(w,v)),i.push(...Of(v,w)),i.push(...WS(w,v)),i.push(...Df(v));let k=ra(_.extensions,w,v),x=wf(n,k,w.loaded.map(z=>({layer:z.layer,name:z.name})),w.failed.map(z=>({name:z.name})),w.disabled_by_flag);i.push(...x.warnings);let D=k.filter(z=>z.update_check_status==="failed").map(z=>`extension_update_check_failed:${z.name}`);i.push(...D);let S=ia(n,i,k,a);i.push(...S.warnings);let b=[...S.warnings],N={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},A=Er(b),R=Sr(),Q=S.warning_codes,Ae=g0(n,c,a.vocabulary,w),we=_0(S.remediation,w.failed.length,v.failed.length,a.vocabulary,h,Ae),_e=v0(n,c,a.vocabulary,w),ze={status:S.status,scope:n,warning_count:S.warning_count,warning_codes:Q,total_extensions:k.length,managed_total:k.filter(z=>z.managed).length,enabled_total:k.filter(z=>z.enabled).length,active_total:k.filter(z=>z.active).length,unmanaged_loaded_extension_count:S.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:S.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:S.unmanaged_expected_extension_count,runtime_active_total:k.filter(z=>z.runtime_active===!0).length,activation_status_totals:{ok:k.filter(z=>z.activation_status==="ok").length,failed:k.filter(z=>z.activation_status==="failed").length,not_loaded:k.filter(z=>z.activation_status==="not_loaded").length,unknown:k.filter(z=>z.activation_status==="unknown").length},unknown_capability_count:A.length,capability_contract_version:R.version,update_available_total:S.update_available_total,update_check_status_totals:S.update_check_status_totals,update_health_coverage:S.update_health_coverage,update_health_partial:S.update_health_partial,update_check_failed_total:k.filter(z=>z.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:bs(w.failed),activation_failures:bs(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:x.warnings.length,trace_enabled:l,isolation:_e,policy:N,remediation:we},Ur=h?{requested:!0,applied:h.adopted_entries.length>0,adopted_count:h.adopted_entries.length,already_managed_count:h.already_managed_count,adopted_extensions:h.adopted_entries.map(z=>z.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:_.extensions.filter(z=>z.managed).length,adopted_extensions:[]},Wn={mode:d,summary:ze,triage:S,trace_enabled:l,capability_contract:R,capability_guidance:A,managed_state_fix:Ur,author_manifest:E,isolation:_e,policy:w.policy};if(d==="deep"){let z=l?v.failed:v.failed.map(B=>{let{trace:Hr,...zr}=B;return zr});Wn.deep={warnings:b,warning_codes:Q,capability_contract:R,capability_guidance:A,trace_enabled:l,managed_state:{path:m.path,count:p.entries.length,entries:p.entries},installed_extensions:k,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(B=>({layer:B.layer,directory:B.directory,name:B.name,version:B.version,entry:B.entry,priority:B.priority}))},activation:{failed:z,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:x.summary},l&&(Wn.deep.trace={activation_failures:v.failed.filter(B=>B.trace!==void 0).map(B=>({layer:B.layer,name:B.name,entry_path:B.entry_path,error:B.error,method:B.trace.method,command:B.trace.command,capability:B.trace.capability,missing_capability:B.trace.missing_capability,registration_index:B.trace.registration_index,expected_schema:B.trace.expected_schema,hint:B.trace.hint,received:B.trace.received}))})}return s(Wn)},k0=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,global:o,withResult:s}=e,c=await T(r.settings_root),d=await Xe({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),l=await Ze(d);i.push(...d.warnings),i.push(...l.warnings);let u=cf(t,d,l);if(t!==void 0&&u.extensions.length===0){let m=a.vocabulary==="package"?"package":"extension",f=[...new Set(d.loaded.map(h=>a.vocabulary==="package"&&typeof h.source_package=="string"&&h.source_package.trim().length>0?h.source_package.trim():h.name))].sort((h,_)=>h.localeCompare(_)),p=f.length>0?` Loaded ${m} names: ${f.join(", ")}.`:"";throw new y(`No loaded ${m} named "${t}" was found in ${n} scope.${p} Run pm ${m} explore to list discovered ${m}s.`,g.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},E0=async(e,t,n)=>{let r=n,i=null;return[e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await Os(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"&&(r=await Mf(r,e.options.offline)),{state:r,fix:i}},S0=async(e,t,n)=>{let r=await Xe({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Ze({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:ra(n,r,i),failures:oh(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...r.warnings,...i.warnings])].length,policy:r.policy}}},x0=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},Kf=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e,s=await T(r.settings_root),c=SS(s.extensions.policy),d=await ye(r.selected_root);i.push(...d.warnings);let l=await at(r.selected_root,n,s,d.state);i.push(...l.warnings);let{state:u,fix:m}=await E0(e,l.extensions,d.state),f=await at(r.selected_root,n,s,u);if(i.push(...f.warnings),t==="manage"&&a.offline===!0)for(let v of f.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=f.extensions.filter(E=>E.update_check_status==="failed").map(E=>`extension_update_check_failed:${E.name}`);i.push(...v)}let p=await S0(e,s,f.extensions),h=p.installed,_=ia(n,i,h,a);i.push(..._.warnings);let w={total:h.length,managed_total:h.filter(v=>v.managed).length,enabled_total:h.filter(v=>v.enabled).length,active_total:h.filter(v=>v.active).length,extensions:h,triage:_,policy:c};return p.failures!==void 0&&(w.activation_diagnostics={failed_count:p.failures.length,failed:p.failures}),t==="explore"&&(w.runtime_probe=p.summary),t==="manage"&&(w.runtime_probe=p.summary,w.managed_state_fix=x0(m,h)),o(w)},Yf={init:YS,install:u0,uninstall:h0,explore:Kf,manage:Kf,describe:k0,reload:XS,doctor:b0,catalog:ZS,adopt:f0,"adopt-all":m0,activate:Vf,deactivate:Vf,migrate:Uf},A0=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),I0=e=>A0(e)?Ss(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Yf[e.action](e)):Yf[e.action](e);import{execFile as R0}from"node:child_process";import{realpath as C0}from"node:fs/promises";import uh from"node:path";import{promisify as T0}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9af87d55-dbe2-561b-9f3f-6f12c0416147")}catch{}})();var $0=T0(R0),O0=32*1024*1024,D0=1e4,P0=["search/eval-queries.json"];function Ps(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function N0(e){return`'${e.replaceAll("'","'\\''")}'`}async function L0(e,t=C0){return t(e).catch(()=>uh.resolve(e))}async function la(e){let t=await rt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await L0(e),r=Ps(uh.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=Bo.map(a=>`${r}/${Ps(a)}`);try{let{stdout:a}=await $0("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:O0,windowsHide:!0,timeout:D0}),o=new Set(P0.map(d=>`${r}/${d}`)),s=[...new Set(a.split("\0").filter(d=>d.length>0&&!o.has(Ps(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>s.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:s,tracked_path_count:s.length,remediation_command:s.length===0?null:`git rm --cached -r -- ${c.map(d=>N0(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2e510b32-f27f-5ba5-94b2-8268343359dc")}catch{}})();async function mh(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await An(e,Dt(n));if(i.status==="ok")return{audit:i,count:0,warnings:[]};let a=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:a,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${a}`]:[]}}function ph(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}import{execFile as Ex}from"node:child_process";import{randomUUID as Sx}from"node:crypto";import{readdir as xx,stat as Ax}from"node:fs/promises";import he from"node:path";import{promisify as Ix}from"node:util";import M0 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]="f6def6d2-fbf3-55ce-8654-0c4e76d78a2a")}catch{}})();var j0=Object.freeze({pm_item_scalar_missing:!0});function Dn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function Y(e){return e===void 0?j0:e}function Ft(e){return Ie(C(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function Ns(e,t){let n=je(e);if(n)throw new y(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(o)try{let s=JSON.parse(o);if(typeof s!="object"||s===null||Array.isArray(s))throw new TypeError("history entry must be an object");r.push(s)}catch{throw new y(`History merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}}return r}function Je(e){return C({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function F0(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Je(e[r])===Je(t[r]);)r+=1;return r}function U0(e,t,n,r){let i=[...e,...n],a=new Map(i.map((u,m)=>[u,m])),o=new Map(i.map((u,m)=>[Je(u),m])),s=i.map(()=>new Set);for(let u of[e,t]){let m=u.map(f=>a.get(f)??o.get(Je(f)));for(let f=1;f<m.length;f+=1)m[f-1]!==m[f]&&s[m[f-1]].add(m[f])}let c=i.map(()=>0);for(let u of s)for(let m of u)c[m]+=1;let d=i.map((u,m)=>m).filter(u=>c[u]===0),l=[];for(;d.length>0;){d.sort((m,f)=>{let p=i[m],h=i[f],_=qt(p.ts,h.ts),w=Je(p),v=Je(h);return _||Number(r.has(v))-Number(r.has(w))});let u=d.shift();l.push(i[u]);for(let m of s[u])c[m]-=1,c[m]===0&&d.push(m)}if(l.length!==i.length)throw new y("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",g.GENERIC_FAILURE);return l}function fh(e){return{entries:e,positions:new Map(e.map((t,n)=>[Je(t),n])),index:-1,document:li()}}function Hs(e,t){let n=t??e.index;for(;e.index<n;){let r=oo(e.document,e.entries[e.index+1].patch);if(!r.ok)throw new y("History union cannot preserve a patch that does not apply in its original branch.",g.GENERIC_FAILURE);e.document=r.document,e.index+=1}return e.document}function hh(e,t){if(t!==void 0&&t>e.index+1)throw new y("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",g.GENERIC_FAILURE);return Hs(e,t)}function H0(e,t,n){if(n===0)return;let r=fh(e),i=fh(t),a=Hs(r,n-1);Hs(i,n-1);let o=0,s=new Set([...gh,...yh]);return(c,d)=>{if(o++<n)return c.patch;let l=Je(c),u=hh(r,r.positions.get(l)),m=hh(i,i.positions.get(l)),f=mi(c.patch).filter(v=>{let[E,k]=v.path.slice(1).split("/");return E!=="metadata"||!s.has(k)}),p=oo(d,f);if(!p.ok)throw new y("History union cannot rebase a scalar patch onto the merged replay position; leave the file unresolved for manual recovery.",g.GENERIC_FAILURE);let h=bh(a.metadata,u.metadata,m.metadata,"ours","latest_document_update",String(u.metadata.updated_at),String(m.metadata.updated_at)),_=p.document;for(let v of s)Object.hasOwn(h.merged,v)?_.metadata[v]=h.merged[v]:delete _.metadata[v];let w=ui({metadata:_.metadata,body:_.body});return M0.compare(d,w)}}function FF(e,t,n){let r=Ns(e,"base"),i=Ns(t,"ours"),a=Ns(n,"theirs"),o=[r,i,a].map(f=>f.filter(p=>p.op==="create"));if(o[0].length===0&&o.slice(1).every(f=>f.length>0)||o.some(f=>f.length>1)||new Set(o.flat().map(Je)).size>1)throw new y("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict"});let s=F0(i,a);if(s===i.length&&s===a.length)return{merged:Bt(i),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(s===a.length)return{merged:Bt(i),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:i.length-s,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(s===i.length)return{merged:Bt(a),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:a.length-s,entries_total:a.length,reanchored:!1};let c=i.slice(s),d=new Set(c.map(Je)),l=a.slice(s).filter(f=>!d.has(Je(f))),u=U0(c,a.slice(s),l,d),m=pi([...i.slice(0,s),...u],void 0,{continuousHashSurface:!0,projectPatch:H0(i,a,s)});if(m.skippedOps>0)throw new y(`History union cannot preserve ${m.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,g.GENERIC_FAILURE);return{merged:Bt(m.entries),strategy:"union_reanchor",common_entries:s,entries_from_ours:c.length,entries_from_theirs:l.length,entries_total:m.entries.length,reanchored:!0}}function Ls(e,t){let n=je(e);if(n)throw new y(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(!o)continue;let s;try{s=JSON.parse(o)}catch{throw new y(`Relationship merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}if(typeof s!="object"||s===null||Array.isArray(s)||typeof s.eventId!="string"||typeof s.sequence!="number")throw new y(`Relationship merge input (${t}) line ${i+1} is not a relationship event (eventId + sequence required).`,g.GENERIC_FAILURE);r.push(s)}return r}function ua(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
57
57
  `)}
58
- `}function O0(e){return e.map((t,n)=>({...t,sequence:n+1}))}function NF(e,t,n){Ps(e,"base");let r=Ps(t,"ours"),i=Ps(n,"theirs"),a=Math.min(r.length,i.length),o=0;for(;o<a&&r[o].eventId===i[o].eventId;)o+=1;if(o===r.length&&o===i.length)return{merged:ma(r),strategy:"identical",common_entries:o,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===i.length)return{merged:ma(r),strategy:"fast_forward_ours",common_entries:o,entries_from_ours:r.length-o,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===r.length)return{merged:ma(i),strategy:"fast_forward_theirs",common_entries:o,entries_from_ours:0,entries_from_theirs:i.length-o,entries_total:i.length,reanchored:!1};let s=r.slice(o),c=new Set(s.map(m=>m.eventId)),d=i.slice(o).filter(m=>!c.has(m.eventId)),l=[...s,...d].sort((m,f)=>{if(m.timestamp!==void 0&&f.timestamp!==void 0){let _=qt(m.timestamp,f.timestamp);if(_!==0)return _}else{if(m.timestamp===void 0&&f.timestamp!==void 0)return 1;if(m.timestamp!==void 0)return-1}let p=c.has(m.eventId),h=c.has(f.eventId);return p!==h?Number(h)-Number(p):0}),u=O0([...r.slice(0,o),...l]);return{merged:ma(u),strategy:"union_reanchor",common_entries:o,entries_from_ours:s.length,entries_from_theirs:d.length,entries_total:u.length,reanchored:!0}}var uh=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],mh=["acceptance_criteria"],D0=["updated_at"];function rn(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:C(e)===C(t)}function lh(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(l=>C(l))),a=r(t),o=new Set(a.map(l=>C(l))),s=r(n),c=new Set(s.map(l=>C(l))),d=a.filter(l=>{let u=C(l);return!i.has(u)||c.has(u)});for(let l of s){let u=C(l);!o.has(u)&&!i.has(u)&&d.push(l)}return d}function Rr(e){if(typeof e!="object"||e===null||Array.isArray(e))return C(e);let{provenance:t,...n}=e;return C(n)}function P0(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function N0(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(Rr)),a=r(t),o=new Set(a.map(Rr)),s=r(n),c=new Set(s.map(Rr)),d=a.filter(l=>{let u=Rr(l);return!i.has(u)||c.has(u)});for(let l of s){let u=Rr(l);!o.has(u)&&!i.has(u)&&d.push(P0(l))}return d}function L0(e,t){return qt(String(e),String(t))>=0?e:t}function ph(e,t,n,r){return rn(t,n)?{value:t,from_theirs:!1,conflict:!1}:rn(e,t)?{value:n,from_theirs:!0,conflict:!1}:rn(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function fh(e,t,n,r,i,a,o){let s=ph(e,t,n,r);if(!s.conflict)return{...s,conflict:!1};if(i==="preferred_side")return{...s,resolution_basis:"requested_preference",retained_side:s.from_theirs?"theirs":"ours"};let c=qt(a,o);if(i==="latest_document_update"&&c!==0){let l=c<0;return{value:l?n:t,from_theirs:l,conflict:!0,resolution_basis:"document_updated_at",retained_side:l?"theirs":"ours"}}let d=C(Y(n)).localeCompare(C(Y(t)))<0;return{value:d?n:t,from_theirs:d,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:d?"theirs":"ours"}}function Ns(e){return{...e.metadata}}function Ls(e,t,n){try{let r=il(Ct(e,{...n,requireSupportedFormat:!0}),n),i=Object.entries(r.metadata).find(([,a])=>Pn(a))?.[0];if(i!==void 0)throw new TypeError(`metadata field ${i} uses the reserved missing-scalar evidence marker`);return r}catch(r){throw r instanceof y&&r.context?.code==="item_format_version_unsupported"?r:new y(`Item merge input (${t}) is not a readable item document: ${String(r)}`,g.GENERIC_FAILURE)}}function M0(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?N0(e.baseValue,e.oursValue,e.theirsValue):e.field==="acceptance_criteria"?lh(vi(e.baseValue),vi(e.oursValue),vi(e.theirsValue)).join("; "):lh(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,rn(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function j0(e){let t=fh(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution,e.oursUpdatedAt,e.theirsUpdatedAt);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:Y(e.baseValue),ours:Y(e.oursValue),theirs:Y(e.theirsValue),retained:Y(t.value),discarded:Y(t.from_theirs?e.oursValue:e.theirsValue),retained_side:t.retained_side,resolution_basis:t.resolution_basis})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function hh(e,t,n,r,i,a,o){let s=new Set([...uh,...mh]),c=new Set(D0),d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,m)=>u.localeCompare(m)),l={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let u of d){let m=e[u],f=t[u],p=n[u];if(!M0({field:u,baseValue:m,oursValue:f,theirsValue:p,unionFieldSet:s,accumulator:l})){if(c.has(u)){l.merged[u]=L0(f,p);continue}j0({field:u,baseValue:m,oursValue:f,theirsValue:p,preferred:r,conflictResolution:i,oursUpdatedAt:a,theirsUpdatedAt:o,accumulator:l})}}return l}function LF(e,t,n,r={}){let i=r.preferred??"ours",a=r.conflictResolution??"preferred_side",o=Ls(t,"ours",r),s=Ls(n,"theirs",r);if(e.trim().length===0)throw new y("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict",item_id:o.metadata.id});let c=Ls(e,"base",r);if(c.metadata.id!==o.metadata.id||c.metadata.id!==s.metadata.id)throw new y("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",g.CONFLICT,{code:"item_identity_conflict",item_id:c.metadata.id});let d=Ns(c),l=Ns(o),u=Ns(s),{merged:m,conflictFields:f,fieldsFromTheirs:p,unionFields:h,conflictDecisions:_}=hh(d,l,u,i,a,o.metadata.updated_at,s.metadata.updated_at),w=fh(c.body,o.body,s.body,i,a,o.metadata.updated_at,s.metadata.updated_at);w.conflict?(f.push("body"),_.push({field:"body",base:Y(c.body),ours:Y(o.body),theirs:Y(s.body),retained:Y(w.value),discarded:Y(w.from_theirs?o.body:s.body),retained_side:w.retained_side,resolution_basis:w.resolution_basis})):w.from_theirs&&p.push("body");let v=m;return v.pm_format_version=tl(Math.max(...[c.metadata,o.metadata,s.metadata,v].map(el))),{merged:rl({metadata:v,body:w.value},r),conflict_fields:f,fields_from_theirs:p,union_fields:h,conflict_decisions:_,requested_preference:i,requested_preference_applied:a==="preferred_side",conflict_resolution:a}}function Ms(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function js(e,t){let n=je(e);if(n)throw new y(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,g.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new y(`JSON merge input (${t}) is not valid JSON.`,g.GENERIC_FAILURE)}}function F0(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=d=>{let l=new Map;for(let u of d){let m=C(u);l.set(m,(l.get(m)??0)+1)}return l},i=r(e),a=r(t),o=r(n);for(let[d,l]of i)if((a.get(d)??0)<l||(o.get(d)??0)<l)return null;let s=new Map(a),c=[];for(let d of n){let l=C(d),u=s.get(l)??0;u>0?s.set(l,u-1):c.push(d)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function U0(e,t,n,r,i,a,o){if(!Ms(t)||!Ms(n))return null;let s=Ms(e)?e:{},c={},d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,u)=>l.localeCompare(u));for(let l of d){let u=i.length>0?`${i}.${l}`:l,m=z0(s,t,n,l,r,u,a,o);m!==void 0&&(c[l]=m)}return c}function _h(e,t,n,r,i,a,o){if(rn(t,n))return t;let s=F0(e,t,n);if(s!==null)return s.acceptedTheirs&&o.push(i),s.merged;let c=U0(e,t,n,r,i,a,o);if(c!==null)return c;let d=ph(e,t,n,r);return d.conflict?a.push(i):d.from_theirs&&o.push(i),d.value}function z0(e,t,n,r,i,a,o,s){let c=Object.prototype.hasOwnProperty.call(t,r),d=Object.prototype.hasOwnProperty.call(n,r),l=Object.prototype.hasOwnProperty.call(e,r);if(c&&d)return _h(e[r],t[r],n[r],i,a,o,s);if(c){if(l&&rn(e[r],t[r])){s.push(a);return}return l?(o.push(a),i==="theirs"?void 0:t[r]):t[r]}if(!(l&&rn(e[r],n[r])))return l?(o.push(a),i==="theirs"?n[r]:void 0):(s.push(a),n[r])}function MF(e,t,n,r={}){let i=r.preferred??"ours",a=js(e,"base"),o=js(t,"ours"),s=js(n,"theirs"),c=[],d=[],l=_h(a,o,s,i,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
59
- `,conflict_paths:c,paths_from_theirs:d,preferred:i}}import{constants as gh}from"node:fs";import{lstat as H0,open as G0}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b063a672-991a-5251-a2f3-6a1c7bcafd2f")}catch{}})();var W0={lstat:H0,open:G0};function q0(e){return e.O_NOFOLLOW??0}async function Cr(e,t,n=W0){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let i=await n.open(e,gh.O_RDONLY|q0(gh));try{let a=await i.stat();if(!a.isFile()||a.size>t)return null;let o=Buffer.alloc(a.size),s=0;for(;s<o.length;){let{bytesRead:c}=await i.read(o,s,o.length-s,s);if(c===0)break;s+=c}return(await i.stat()).size===a.size&&s===a.size?o.toString("utf8",0,s):null}finally{await i.close()}}import fa from"node:path";import{execFile as B0}from"node:child_process";import{createHash as yh}from"node:crypto";import{readdir as V0}from"node:fs/promises";import J0 from"node:path";import{promisify as K0}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af5442e7-c8af-5d81-8c89-7f1a98159cec")}catch{}})();var vt=K0(B0),pa=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function JF(e,t,n){let r=t.trim(),i=/^(['"])(.*)\1$/su.exec(r)?.[2]??r;for(let a of["rebase-merge","rebase-apply"])try{let{stdout:o}=await vt("git",["rev-parse","--path-format=absolute","--git-path",`${a}/orig-head`],{cwd:e,timeout:1e4}),s=(await Cr(o.trim(),128))?.trim();if(s===void 0||!pa.test(s))continue;let{stdout:c}=await vt("git",["rev-parse","--verify",`${s}:${i}`],{cwd:e,timeout:1e4}),d=c.trim();return{kind:"rebase",original_head:s,original_blob:d}}catch{}if(n!==void 0&&Object.keys(process.env).some(a=>/^GITHEAD_[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(a)))try{let{stdout:a}=await vt("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[o,s]=a.trim().split(/\r?\n/u);if(o!==s||!pa.test(o))return;let{stdout:c}=await vt("git",["rev-parse","--verify",`${o}:${i}`],{cwd:e,timeout:1e4}),d=c.trim(),l=yh(d.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(n)}\0`).update(n).digest("hex");return d!==l?void 0:{kind:"merge",original_head:o,original_blob:d}}catch{}}function wh(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&(t.kind==="rebase"||t.kind==="merge")&&typeof t.original_head=="string"&&pa.test(t.original_head)&&typeof t.original_blob=="string"&&pa.test(t.original_blob)}async function vh(e,t,n,r){if(r!==void 0&&yh(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(r)}\0`).update(r).digest("hex")!==n.original_blob)return!1;try{let{stdout:i}=await vt("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),a=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await V0(i.trim())).some(d=>a.has(d)))return!1;let{stdout:o}=await vt("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(o.trim()!==n.original_head)return!1;let{stdout:s}=await vt("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(s.trim()!==n.original_blob)return!1;let{stdout:c}=await vt("git",["hash-object","--",J0.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await vt("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35c5d9a8-5ae0-5e97-9ea3-f8a70a5fd7d0")}catch{}})();var Y0=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,X0=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,_a=2048,Z0=64,Q0=1e5,ex=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function bt(e){return Y0.test(e)}var tx=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),ga="bounded_non_sensitive_scalars_v1",nx=new Set(["open","in_progress","blocked","closed","canceled"]),rx=new Set(["risk","confidence","severity"]),ix=new Set(["low","medium","high","critical"]),kh=new Map([["priority",new Set([0,1,2,3,4].map(C))],["status",new Set([...nx].map(C))],...[...rx].map(e=>[e,new Set([...ix].map(C))])]);function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Eh(e,t){return Object.keys(e).every(n=>t.has(n))}function ha(e){return Array.isArray(e)&&e.length<=_a&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Tr(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>Q0||r.depth>Z0)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(at(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function Sh(e){if(!at(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[Eh(e,tx),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),Tr(e.base),Tr(e.ours),Tr(e.theirs),Tr(e.retained),Tr(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function ax(e){if(!at(e))return!1;let t=Object.entries(e);return t.length<=_a&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function ox(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||fa.posix.isAbsolute(e))return!1;let n=fa.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&fa.posix.basename(n,fa.posix.extname(n))===t}function sx(e){return!ha(e.fields_from_theirs)||!ha(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>_a||!e.decisions.every(Sh)?!1:e.merged_field_hashes===void 0||ax(e.merged_field_hashes)}function cx(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],r=[void 0,"clone_local","hash_only","bounded_inline","mixed"],i=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===ga)&&i.includes(e.evidence_source)}function dx(e){return typeof e.created_at=="string"&&fn(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&fn(e.reconciled_at))}function bh(e,t){if(!at(t)||ya(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(i=>i==="pm_value_hash"||i==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let r=t.pm_value;return(r===null||kh.get(e)?.has(C(r))===!0)&&Ft(r)===t.pm_value_hash}function lx(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&bh(r.field,r.retained)&&bh(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,i)=>r+(at(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(at(i.discarded)&&Object.hasOwn(i.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===ga)}function ux(e){return e.operation!==void 0&&!wh(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function mx(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!Eh(e,ex)?"required_fields":typeof e.id!="string"||!bt(e.id)?"receipt_id":typeof e.item_id!="string"||!X0.test(e.item_id)?"item_id":ox(e.item_path,e.item_id)?null:"item_path"}function Us(e,t){if(!at(e))return"required_fields";let n=mx(e);return n!==null?n:ux(e)?sx(e)?cx(e)?dx(e)?t==="durable"&&!lx(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function zs(e){if(!at(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(r=>!at(r)||!Object.hasOwn(r,"retained")||!Object.hasOwn(r,"discarded")?r:{base:Y(void 0),ours:Y(void 0),theirs:Y(void 0),...r})}}function xh(e){if(!at(e))return;if(!ha(e.fields_from_theirs))return"fields_from_theirs";if(!ha(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>_a)return"decisions";let t=e.decisions.findIndex(n=>!Sh(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function Hs(e,t){return Us(e,t)===null}function ya(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function Gs(e,t){let n=Pn(t),r=Ft(n?void 0:t);return!n&&(t===null||kh.get(e)?.has(C(t))===!0)?{pm_value_hash:r,pm_value:t}:{pm_value_hash:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e5e4691-4858-5a54-82b0-65b97d929b57")}catch{}})();var yx=gx(px),Rh=16*1024*1024,wa=100;async function Ws(e){try{let{stdout:t}=await yx("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Ch(e,t){let n=he.dirname(he.resolve(e,t));for(let r=0;r<12;r+=1){if(await O(he.join(n,"settings.json")))return n;let i=he.dirname(n);if(i===n)break;n=i}return null}function qs(e){return he.join(e,"merge-receipts")}function Nn(e){return`${e}.json`}async function Ah(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await Cr(e.receiptPath,Rh)}catch(a){if(At(a))return null;throw a}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=zs(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!Hs(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||he.basename(e.receiptPath)!==Nn(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprints:Bs(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
60
- `}}function $r(e,t=!1){return Ie(C({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:Ie(C(Y(n.retained))),discarded_hash:Ie(C(Y(n.discarded)))})):va(e).decisions}))}function Bs(e){let t=[$r(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push($r(e,!0)),t}function wx(e,t){let{reconciled_at:n,settlement:r,...i}=e;return t.state==="reconciled"?{...i,state:"reconciled",reconciled_at:t.reconciled_at,...t.settlement===void 0?{}:{settlement:t.settlement}}:{...i,state:"pending"}}async function vx(e,t,n){let r=new Map;for(let i of t){let a=e.get(i.id);if(i.state!=="reconciled"||a===void 0)continue;let o=r.get(a.item_id);if(o===void 0){try{o=await dt(he.join(n,"history",`${a.item_id}.jsonl`),a.item_id),Tt(o).ok||(o=[])}catch{o=[]}r.set(a.item_id,o)}let s=a.settlement==="original_git_state_restored",c=C({...va(a),...s?{reason:a.settlement,operation:a.operation}:{}});if(!o.some(d=>{if(d.op!=="merge_reconcile"||d.record_hash_version===void 0)return!1;let l=d.context?.merge;if(typeof l!="object"||l===null||Array.isArray(l))return!1;let u=l[s?"abandoned_receipts":"receipts"];return Array.isArray(u)&&u.some(m=>C(m)===c)})){let{reconciled_at:d,settlement:l,...u}=a;e.set(a.id,{...u,state:"pending"})}}}function va(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:ya(t.retained)??Ft(Pn(t.retained)?void 0:t.retained),discarded_hash:ya(t.discarded)??Ft(Pn(t.discarded)?void 0:t.discarded)}))}}async function _1(e){let t=await Ws(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,i=he.basename(r,he.extname(r)),a={version:1,id:fx(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(s=>({...s,base:Y(s.base),ours:Y(s.ours),theirs:Y(s.theirs),retained:Y(s.retained),discarded:Y(s.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:$(),value_availability:"clone_local"};await Vn(t),await Z(he.join(t,Nn(a.id)),`${JSON.stringify(a,null,2)}
61
- `);let o=await Ch(e.cwd,a.item_path);if(o!==null){let s=qs(o),c=a.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:Gs(u.field,u.retained),discarded:Gs(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),d=c.reduce((u,m)=>u+(Object.hasOwn(m.retained,"pm_value")?1:0)+(Object.hasOwn(m.discarded,"pm_value")?1:0),0),l={...a,decisions:c,value_availability:d===0?"hash_only":d===c.length*2?"bounded_inline":"mixed",value_policy:ga};await Vn(s),await Z(he.join(s,Nn(a.id)),`${JSON.stringify(l,null,2)}
62
- `)}return a}async function Ih(e,t){let n;try{n=await hx(e)}catch(s){let c=await bx(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],i=0,a=[],o=(s,c)=>{if(i+=1,a.length>=wa)return;let d=s.slice(0,-5);a.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...bt(d)?{receipt_id:d}:{candidate_name_hash:Ie(s)}})};for(let s of n.sort((c,d)=>c.localeCompare(d))){if(!s.endsWith(".json"))continue;let c=await kx(e,s,t);c.receipt!==void 0?r.push(c.receipt):o(s,c)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:a,invalid_evidence_truncated:i>a.length}}async function bx(e,t,n=_x){if(!F(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!F(i))return!1;let a=he.dirname(r);if(a===r)return!0;r=a}}async function kx(e,t,n){let r;try{r=await Cr(he.join(e,t),Rh)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=zs(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let a=Us(i,n);if(a!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(a)?"identity_invalid":"schema_invalid",validation_error:a,...a==="collections"?{validation_path:xh(i)}:{}};let o=i;if(t!==Nn(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...d}=o;return{receipt:{...d,requested_preference:o.requested_preference??s??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function kt(e,t={}){let n=await Ws(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await Ih(n,"clone_local"),i=t.pmRoot??he.join(e,".agents","pm"),a=await Ih(qs(i),"durable"),o=new Map(a.receipts.map(d=>[d.id,d])),s=0,c=[];for(let d of r.receipts){let l=o.get(d.id);if(l!==void 0&&!(l.value_policy===void 0?Bs(d):[$r(d)]).includes($r(l))){o.delete(d.id),s+=1,r.invalid_evidence.length+a.invalid_evidence.length+c.length<wa&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:d.id});continue}o.set(d.id,l===void 0?d:wx(d,l))}return await vx(o,a.receipts,i),{receipts:[...o.values()].filter(d=>(t.includeReconciled||d.state==="pending")&&(t.includeLossless!==!1||d.decisions.length>0)).sort((d,l)=>d.created_at.localeCompare(l.created_at)),invalid_evidence_count:r.invalid_evidence_count+a.invalid_evidence_count+s,invalid_evidence:[...r.invalid_evidence,...a.invalid_evidence,...c].slice(0,wa),invalid_evidence_truncated:r.invalid_evidence_truncated||a.invalid_evidence_truncated||r.invalid_evidence_count+a.invalid_evidence_count+s>wa,clone_local_evidence_resolved:n!==null}}function Ln(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function g1(e,t,n={}){let r=await Ws(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!Hs(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=$(),o=he.join(r,Nn(t.id)),s=await Ch(e,t.item_path),c=s===null?null:he.join(qs(s),Nn(t.id)),d=(await Promise.all([Ah({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[Ah({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:a,settlement:n.settlement})]])).filter(l=>l!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(l=>l.modern)?[$r(t)]:Bs(t)).some(l=>d.every(u=>u.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let l of d)await Z(l.path,l.content)}async function y1(e){let t=await kt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:$()}}import{createHash as Ex}from"node:crypto";import ba from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var Sx="2026-08-09T16:15:18.000Z",$h=Symbol("pre-durable-disposition-eligible");function Et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vs(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function Th(e){return Et(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function Oh(e,t){if(typeof e!="string")return!1;let n=ba.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!ba.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(ba.posix.basename(n)===`${t}.toon`||ba.posix.basename(n)===`${t}.md`)}function xx(e,t){return typeof e.receipt_id=="string"&&bt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&Oh(e.item_path,t)}function Dh(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,a=Array.isArray(i)?new Set(i.flatMap(o=>Th(o)?[o.field]:[])):new Set;return Vs(t)&&Vs(n)&&Vs(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(Th)&&a.size===i.length&&t.length===a.size&&t.every(o=>a.has(o))}function Ax(e,t){return xx(e,t)&&Dh(e)}function Ix(e,t){return typeof e.receipt_id=="string"&&bt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&Oh(e.item_path,t)&&Dh(e)}function Rx(e){return e[$h]===!0}function Ph(e,t){if(!Et(e)||!Et(e.context))return[];let n=e.context.merge;return!Et(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!Et(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:Ax(r,t),[$h]:Ix(r,t),...typeof e.ts=="string"&&fn(e.ts)?{eventTimestamp:e.ts}:{}}])}function Nh(e,t,n){if(!Et(e)||e.op!=="merge_reconcile")return[];if(!Et(e.context)||!Et(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!Et(i)||typeof i.receipt_id!="string"||!bt(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!fn(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function Lh(e,t,n=[]){let r=new Map;for(let a of n){let o=`${a.itemId}\0${a.originalHistoryLine}\0${a.receiptId}\0${a.originalEventTimestamp}`;r.set(o,Math.max(r.get(o)??0,a.auditHistoryLine))}let i=a=>Rx(a)&&a.eventTimestamp!==void 0&&qt(a.eventTimestamp,Sx)<0&&(r.get(`${a.itemId}\0${a.line}\0${a.receiptId}\0${a.eventTimestamp}`)??0)>a.line;return{missing:e.filter(a=>!a.legacySummaryAccepted&&!t.has(a.receiptId)&&!i(a)).map(a=>({item_id:a.itemId,history_line:a.line,...bt(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:Ex("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}import{isUtf8 as Cx}from"node:buffer";import{readFile as Tx}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cca38e64-dd53-5086-8825-dc1c8f1cc587")}catch{}})();function $x(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new y("History salvage cannot discard a potentially complete record with trailing corruption.",g.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("History salvage would conceal interior corruption or a malformed record.",g.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(r=>typeof r=="string"))throw new y("History salvage requires complete history records before the invalid tail.",g.CONFLICT,{code:"history_salvage_refused"});return n}function Ox(e){if(je(e))throw new y("Resolve history merge conflicts before salvage.",g.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,r,i=0;for(let[o,s]of e.split(`
63
- `).entries()){if(!s.trim()){n+=s.length+1;continue}let c=$x(s);if(c===null){r===void 0&&(r=n,i=o+1),n+=s.length+1;continue}if(r!==void 0)throw new y("History salvage would discard a record or conceal interior corruption.",g.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.push(c),n+=s.length+1}let a=Tt(t);if(!a.ok||a.item_hash_version===void 0)throw new y("History salvage requires a nonempty verified prefix.",g.CONFLICT,{code:"history_salvage_refused",verification_errors:a.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries:t,itemHashVersion:a.item_hash_version,prefix:r===void 0?e:e.slice(0,r),receipt:r===void 0?null:{first_invalid_line:i,discarded_bytes:Buffer.byteLength(e.slice(r)),discarded_sha256:Ie(e.slice(r)),retained_entries:t.length}}}async function Dx(e,t,n){if(!e.located)return{itemRaw:null,document:n};let r=await Fl(e.located,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n}}async function Mh(e){let t;try{t=await Tx(e)}catch(n){if(F(n))return null;throw n}if(!Cx(t))throw new y("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",g.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function jh(e){let{subject:t,settings:n,options:r,author:i}=e;if([r.normalizeProvenance,r.auditOperation,r.auditContext,r.auditContextById,r.forceAuditEntry,r.mergeReceiptProof,r.mergeReceiptProofById].some(Boolean))throw new y("Tail salvage cannot be combined with other repair modes.",g.USAGE);let a=await Mh(t.historyPath);if(a===null)throw new y(`No history stream exists for ${t.id}.`,g.NOT_FOUND);await Ge({path:t.historyPath,scope:"project"});let o=Ox(a),s=Tl(o.entries,o.entries.length-1),c=pl(s);if(typeof s.metadata.id=="string"&&s.metadata.id!==t.id)throw new y("History belongs to another item; salvage refused.",g.CONFLICT,{code:"history_salvage_refused"});let d=await Dx(t,n,c),l=Lo({itemDocument:d.document,subjectId:t.id,author:i,force:r.force,settings:n}),u=o.itemHashVersion,m=r.dryRun===!0,f=o.receipt!==null;if(f&&!m){let p=await te(e.pmRoot,t.id,n.locks.ttl_seconds,i,!!r.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await Mh(t.historyPath),_=await ve(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),w=_?await V(_.itemPath):null;if(h!==a||w!==d.itemRaw)throw new y("History or item changed while waiting for salvage lock; retry.",g.CONFLICT);let v=li({...ul({hashAlgorithm:Ce(o.entries.at(-1).hash_algorithm),nowIso:$(),author:i,op:"history_salvage",before:c,after:c,message:r.message,context:{history_salvage:o.receipt}}),before_hash:o.entries.at(-1).after_hash,after_hash:o.entries.at(-1).after_hash,item_hash_version:u});await Ui({historyPath:t.historyPath,historyRawUnderLock:a,nextHistoryRaw:`${o.prefix}${JSON.stringify(v)}
64
- `}),l.push(...await X({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return{id:t.id,dry_run:m,changed:f,history:{path:t.historyPath,entries_scanned:o.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:f&&!m,verify_ok:!0,verify_errors:[],item_hash_version_before:u,item_hash_version_after:u,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...o.receipt?{salvage:o.receipt}:{},warnings:l,generated_at:$()}}import{realpath as Gh}from"node:fs/promises";import Js from"node:path";import Wh 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]="42f8db8f-d659-58e9-84af-21ced6d6a403")}catch{}})();function Fh(e,t){return t==="body"?e.body:e.metadata[t]}function Px(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=t;return e==="comments"?typeof n.created_at=="string"&&typeof n.author=="string"&&typeof n.text=="string":typeof n.path=="string"||e==="tests"&&typeof n.command=="string"}function Nx(e){let t={...e};if(t.source_kind==="merge_union"&&(t.source_kind="local_mutation"),t.provenance!==null&&typeof t.provenance=="object"&&!Array.isArray(t.provenance)){let n={...t.provenance};n.source_kind==="merge_union"&&(n.source_kind="local_mutation"),t.provenance=n}return t}function Uh(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(r=>Px(e,r)))return t;let n=t.map(r=>e==="comments"?r:Nx(r));return[...new Map(n.map(r=>[C(r),r])).values()]}function Ks(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(i=>{let a=t.findIndex((o,s)=>!r.has(s)&&Ks(i,o));return a<0?!1:(r.add(a),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,i])=>Object.hasOwn(n,r)&&Ks(i,n[r]))}function zh(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let a=e[i],o=new Set;for(let c of pi(a.patch))o.add(bi(c.path)),c.from&&o.add(bi(c.from));let s=[...n].filter(c=>o.has(c));if(s.length!==0){for(let c of s)n.delete(c);r.push({index:i+1,ts:a.ts,author:a.author,op:a.op,fields:s.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function Lx(e,t,n){let r=Wh.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(bi(p.path));let a=new Set([...i].filter(p=>Ks(Uh(p,Fh(t,p)),Uh(p,Fh(n,p))))),o=new Set([...i].filter(p=>!a.has(p))),s=zh(e,o),c=zh(e,a),d=[...i].sort((p,h)=>p.localeCompare(h)),l=[...o].sort((p,h)=>p.localeCompare(h)),u=[...a].sort((p,h)=>p.localeCompare(h)),m=[...new Set(s.map(p=>p.author))].sort((p,h)=>p.localeCompare(h)),f=[...new Set(c.map(p=>p.author))].sort((p,h)=>p.localeCompare(h));return{reconciled_field_count:i.size,reconciled_fields:d,reverted_field_count:o.size,reverted_fields:l,discarded_events:s,discarded_authors:m,preserved_field_count:a.size,preserved_fields:u,preserved_events:c,preserved_authors:f,recovery_hint:s.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function Mx(e){try{return await Gh(e)}catch{return null}}async function jx(e){if(await Mx(Js.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let t=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),n=e.receipt.merged_field_hashes;if(!n||t.length===0)return null;let r=Object.keys(n).sort();if(t.length!==r.length||t.some((a,o)=>a!==r[o]))return null;let i=e.currentItemReplay.metadata;return t.every(a=>{let o=a==="body"?e.currentItemReplay.body:i[a];return[Ft(o),Ie(C(Y(o)))].includes(n[a])})?{receipt:e.receipt,declaredFields:t}:null}async function Fx(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(o=>o.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Gh(e.itemPath),r=[];for(let o of t){let s=await jx({receipt:o,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});s&&r.push(s)}let i=new Set(r.flatMap(({declaredFields:o})=>o)),a=e.reconciliation?.reconciled_fields;return r.length>0&&(a===void 0||a.length>0&&a.every(o=>i.has(o)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:o})=>o.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function Hh(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:Js.relative(a,t.currentItemPath).split(Js.sep).join("/");if(!n||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||o!==i.item_path||i.operation===void 0||!await vh(a,i.item_path,i.operation,t.currentItemRawBeforeLock))throw new y("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function Ux(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(a=>a.item_id===e.subjectId).map(a=>a.id)??[]),n=(e.options.mergeReceiptProof?await kt(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(a=>a.item_id===e.subjectId&&t.has(a.id))??[],r=e.options.mergeReceiptProof?await Fx({proof:{...e.options.mergeReceiptProof,receipts:n},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(r&&!r.trusted&&e.options.force!==!0)throw new y(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${r.reason}).`,g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let i=r?.trusted?n.filter(a=>r.receipt_ids.includes(a.id)):[];return{mergeReceiptProof:r,effectiveAuditContext:i.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:i.map(va)}}:e.options.auditContext}}function zx(e,t,n){let r=e.located?.itemPath??null,i=t.loadedItem,a=t.entries;if(!i)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let o=mi(i.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:r,matchedChainBefore:_n(o,n,Ce(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:i.raw,loadedItem:i}}function Hx(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function Gx(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=Ce(e.reanchorEntries.at(-1)?.hash_algorithm),i=_n(e.finalReplay,e.itemHashVersion,r),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=i.indexOf(a),s=_n(n,e.itemHashVersion,r),c={hash_algorithm:r,ts:$(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Wh.compare(e.finalReplay,e.currentItemReplay):[],before_hash:i[o],after_hash:s[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(li({...c,event_class:ol(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function Wx(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function Ys(e,t,n){let{pmRoot:r,settings:i,typeRegistry:a}=await go(n.path),o=await ou(r,e,i,a.type_to_folder);return t.salvageTail===!0?jh({pmRoot:r,subject:o,settings:i,typeRegistry:a,options:t,author:W(t.author,i.author_default)}):fm({pmRoot:r,subject:o,settings:i,typeRegistry:a,operation:"history-repair",options:t,transform:s=>Bx({pmRoot:r,subject:o,options:t},s)})}function qx(e,t,n){let r=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&n!==void 0&&t.some(i=>i.record_hash_version!==void 0&&i.op==="merge_reconcile"&&C(i.context)===C(n));return e.forceAuditEntry===!0&&!r}async function Bx(e,t){let{pmRoot:n,subject:r,options:i}=e,a=t.entries,o=t.verification,s=Tt(a),c=i.normalizeProvenance?cm(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=fl(c.entries),l=new Set(c.entries.map(A=>A.item_hash_version).filter(A=>A!==void 0)),u=fi(c.entries,d),m=zx(r,t,d);await Hh(i.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=_n(f,d),h=!1;if(m.currentItemReplay!==null){let A=_n(m.currentItemReplay,d);h=!p.some((R,Q)=>R===A[Q])}let _=h&&m.currentItemReplay?Lx(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await Ux({options:i,pmRoot:n,subjectId:r.id,itemReplayContext:m,reconciliation:_}),E=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,qx(i,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,x=!!i.dryRun,D=Hx({message:i.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=Gx({reanchorEntries:u.entries,changed:E,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:f,author:k,message:D,auditOperation:i.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),N=Wx(E,u.skippedOps,_);return{changed:E,rewrittenEntries:S,beforeWrite:async()=>Hh(i.mergeAbandonmentProof,m,o.ok,u),report:({verification:A,warnings:R})=>({id:r.id,dry_run:x,changed:E,history:{path:r.historyPath,entries_scanned:a.length,chain_drift_before:!o.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:h,audit_entry_added:b,verify_ok:A.ok,verify_errors:A.errors,item_hash_version_before:s.item_hash_version??null,item_hash_version_after:d,version_disposition:l.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},provenance_normalization:{requested:i.normalizeProvenance===!0,...c.receipt},..._?{reconciliation:_}:{},...w?{merge_receipt_proof:w}:{},warnings:[...new Set([...N,...R])].sort((Q,Ae)=>Q.localeCompare(Ae)),generated_at:$()})}}function uU(e,t){if(t&&e!==void 0)throw new y("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",g.USAGE);if(!t&&e===void 0)throw new y("history-repair: provide an item <id> or pass --all to repair every drifted stream.",g.USAGE)}async function mU(e,t){if(e.salvageTail===!0)throw new y("Tail salvage requires one explicit item ID; --all is not supported.",g.USAGE);let{pmRoot:n,settings:r,typeRegistry:i}=await go(t.path),a=[],o=await ut(n,r.item_format,i.type_to_folder,a,r.schema,{forceSourceScan:!0}),s=await Xt(n,o),c=e.normalizeProvenance?await dm(n):[],d=[...new Set([...s.driftedItems,...c])].sort((f,p)=>f.localeCompare(p)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let f of d)try{let p=await Ys(f,{...e,auditContext:e.auditContextById?.[f],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[f]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=p.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...p.warnings.map(_=>`${f}:${_}`)),l.push({id:f,outcome:h,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,l.push({id:f,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await sl(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:o.length,drifted_streams:s.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...a,...u])].sort((f,p)=>f.localeCompare(p)),generated_at:$()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8011ffaf-ce7a-5c0b-930d-ed538bde89f0")}catch{}})();var Vx=new Set(Zl),Bh=25,Mn=8,an=100,Jx=Ee.join("runtime","telemetry","events.jsonl"),Kx=Ee.join("runtime","telemetry","state.json"),Yx=2500,Xx=500,Vh=nu-3,Zx=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function nc(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function rc(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function jn(e){return e.trim().toLowerCase()}function Qs(e,t){let n=jn(e),r=jn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function ic(e){try{return(await St.stat(e)).isDirectory()}catch{return!1}}async function Qx(e){let t=(await St.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>St.readdir(Ee.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>Jn.some(a=>i.name.endsWith(a))).map(i=>Ee.parse(i.name).name)))}async function eA(e,t,n,r){let i=await Ge({path:e,scope:"project"}),a=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!a)return{warnings:i,overThreshold:!1,classification:"live"};let o;try{o=await St.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let s="live";if(a){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{s=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function tA(e,t,n){let r=Ee.join(e,"history");if(!await ic(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await St.readdir(r)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),a=t.enabled?t.max_entries:null,o=[],s=[],c=[],d=[];for(let l of i){let u=Ee.join(r,l),m=l.slice(0,-6),f=await eA(u,m,t,n);o.push(...f.warnings),f.classification==="tombstone"&&c.push(m),f.classification==="orphaned"&&d.push(m),f.overThreshold&&s.push(m)}return{count:i.length,warnings:[...o,...s.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:s,max_entries:a,tombstones:c,orphaned:d}}function ec(e,t){return Ee.relative(e,t).replaceAll("\\","/")}async function Jh(e,t){let n=[...new Set(Object.values(t))].sort((i,a)=>i.localeCompare(a)),r=[];for(let i of n){let a=Ee.join(e,i),o=[];try{o=await St.readdir(a)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&F(s))continue;continue}for(let s of o)Jn.some(c=>s.toLowerCase().endsWith(c))&&r.push(Ee.join(a,s))}return r.sort((i,a)=>ec(e,i).localeCompare(ec(e,a))),r}function nA(e){return!(typeof e=="object"&&e!==null&&"code"in e&&F(e))}async function rA(e,t,n){let r=await Jh(e,t),i=[],a=[],o=[],s=[],c=sn(z());for(let d of r){let l=ec(e,d),u;try{u=await St.readFile(d,"utf8")}catch{i.push(l);continue}let m=je(u);if(m){a.push({path:l,...m});continue}try{let f=Ct(u,{format:ld(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:oi(f.metadata)})}catch{o.push(l)}}return{paths:r,unreadable:i,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function iA(e){let t=Ee.join(e,"history"),n=[],r=[],i=[],a=[],o=[],s=[];try{s=(await St.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){nA(c)&&n.push("history")}for(let c of s){let d=c.slice(0,-6),l;try{l=await St.readFile(Ee.join(t,c),"utf8")}catch{n.push(d);continue}let u=je(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,f)=>{if(m.trim())try{let p=JSON.parse(m);a.push(...Ph(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Nh(p,d,f+1))}catch{i.push({id:d,line:f+1})}})}return{files:s,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:a,mergeReceiptDispositions:o}}function Kh(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function aA(e,t,n,r,i,a){let o=await rA(e,t,n),s=await iA(e),c=si(o.formatVersions,Kn,ai),d=ge(n),l=Ai(a,A=>nl(A,d),er()),u=await ua(e),m=await nt(e),f=await oh(e,m,r,i),p=m===null?null:await Rn(m),h=await kt(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),_=new Set(h.receipts.map(A=>A.id)),w=Lh(s.mergeReceiptReferences,_,s.mergeReceiptDispositions),v=w.missing,E=h.receipts.filter(A=>A.state==="pending"),{pendingDecisions:k,lossless:x}=Ln(E),D=p?.status==="missing"&&p.missing_keys.length===5&&p.drifted_keys.length===0,S=[...o.unreadable.map(A=>`integrity_item_unreadable:${A}`),...o.conflictMarkers.map(A=>`integrity_item_conflict_marker:${A.path}:L${A.line}`),...o.parseFailures.map(A=>`integrity_item_parse_failed:${A}`),...s.unreadable.map(A=>`integrity_history_unreadable:${A}`),...s.conflictMarkers.map(A=>`integrity_history_conflict_marker:${A.id}:L${A.line}`),...s.invalidJson.map(A=>`integrity_history_invalid_json:${A.id}:L${A.line}`),...c.outdated.map(A=>`integrity_item_outdated_format_version:${A}`),...c.ahead.map(A=>`integrity_item_ahead_format_version:${A}`),...Kh(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...p!==null&&p.status!=="ok"?[`merge_driver_configuration_${D?"missing":"drift"}:${p.missing_keys.length+p.drifted_keys.length}`]:[],...f.warnings,...k.length>0?[`merge_decisions_unreviewed:${k.length}`]:[],...x.length>0?[`merge_receipts_pending:${x.length}`]:[],...sh({invalidEvidenceCount:h.invalid_evidence_count,missingHistoryReferenceCount:v.length})],b=[...new Set(S)].sort((A,R)=>A.localeCompare(R)),N=b.filter(A=>!A.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:N.length===0?"ok":"warn",ok:N.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:s.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:s.unreadable.length,history_conflict_markers:s.conflictMarkers.length,history_invalid_json:s.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:p===null||p.status==="ok"?0:p.missing_keys.length+p.drifted_keys.length,merge_fence:f.count,pending_merge_decisions:k.length,lossless_merge_receipts:x.length,invalid_merge_receipt_evidence:h.invalid_evidence_count,missing_merge_receipt_history_references:v.length,accepted_legacy_merge_receipt_references:w.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:w.acceptedDispositionCount},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,hierarchy_integrity:{...l,relations:ot(l.relations,Mn)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:p===null?null:{...p,required:i},merge_fence:f.audit,pending_merge_decision_items:[...new Set(k.map(A=>A.item_id))].sort((A,R)=>A.localeCompare(R)),lossless_merge_receipt_items:[...new Set(x.map(A=>A.item_id))].sort((A,R)=>A.localeCompare(R)),invalid_merge_receipt_evidence_details:h.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:h.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:v.slice(0,an),missing_merge_receipt_history_reference_details_truncated:v.length>an}},warnings:b,gitWorkspaceRoot:m,pendingMergeReceipts:E}}function oA(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function sA(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:oA(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function cA(e,t){return ee(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function dA(e){let t=ee(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function lA(e){return ee(e.reason)??ee(e.error)??ee(e.message)}function Xs(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function uA(e){let t=[],n=[],r=[];e.forEach((a,o)=>{let s=cA(a.definition,o),c=dA(a.definition);if(c==="applied"){t.push({layer:a.layer,name:a.name,id:s,status:c});return}if(c==="failed"){r.push({layer:a.layer,name:a.name,id:s,status:c,reason:lA(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(Xs),n.sort(Xs),r.sort(Xs);let i=[...r.map(a=>`extension_migration_failed:${a.layer}:${a.name}:${a.id}`),...n.map(a=>`extension_migration_pending:${a.layer}:${a.name}:${a.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function Yh(e,t,n,r,i,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>rc(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=[],h=vs(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${Wr.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(_=>_.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(_=>_.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:a,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:s.length,unmanaged_expected_extensions:s,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function mA(e,t,n){let r=await Is(Ke(e)),i=await Ye({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=i.loaded.map(S=>sA(S)),o=await om(i.loaded,Ke(e)),s=await Xe({...i,loaded:i.loaded}),[c,d]=await Promise.all([ye(i.roots.project),ye(i.roots.global)]);await As(e,s.registrations.migrations);let l=uA(s.registrations.migrations),u={failed:s.failed,warnings:s.warnings,hook_counts:s.hook_counts,command_override_count:s.command_override_count,command_handler_count:s.command_handler_count,parser_override_count:s.parser_override_count,preflight_override_count:s.preflight_override_count,service_override_count:s.service_override_count,renderer_override_count:s.renderer_override_count,registration_counts:s.registration_counts,registrations:s.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},m=new Set(c.state.entries.map(S=>jn(S.name))),f=new Set(d.state.entries.map(S=>jn(S.name))),p=[...new Map(i.loaded.filter(S=>!(S.layer==="project"?m:f).has(jn(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,b)=>{let N=`${S.layer}:${S.name}`,A=`${b.layer}:${b.name}`;return N.localeCompare(A)}),h=p.map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),_=p.filter(S=>Qs(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=p.filter(S=>!Qs(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],E=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...o.warnings],k=Sr(E),x=xr(),D=Yh(E,i.failed.length,s.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,_,w);return{check:{name:"extensions",status:E.length===0?"ok":"warn",ok:E.length===0,details:{...i,loaded:a,warnings:E,activation:u,author_manifest:r,triage:D,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:k,host_version_census:o}},warnings:E}}function pA(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function ot(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function fA(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function ka(e,t){let n=ot(e,t);return{...n,sample:n.sample.map(r=>fA(r))}}function q(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function hA(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var _A={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:q(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:q(e.missing_required,t),missing_optional:q(e.missing_optional,t),missing:q(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:q(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:ka(e.discovered,t),effective:ka(e.effective,t),loaded:ka(e.loaded,t),failed:ot(e.failed,t),warnings:q(e.warnings,t),activation:{failed:ot(n.failed,t),warnings:q(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:hA(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:ot(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:q(n.affected_item_ids,t),samples:ot(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:q(e.item_unreadable,t),item_conflict_markers:ot(e.item_conflict_markers,t),item_parse_failures:q(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:q(n.tracked_paths,t)},history_unreadable:q(e.history_unreadable,t),history_conflict_markers:ot(e.history_conflict_markers,t),history_invalid_json:ot(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:q(n.candidate_items,t),confirmed_items:q(n.confirmed_items,t),resolved_false_positive_items:q(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:q(e.drifted_items,t),merge_receipt_attributed_items:q(e.merge_receipt_attributed_items,t),missing_streams:q(e.missing_streams,t),unreadable_streams:q(e.unreadable_streams,t),hash_mismatches:q(e.hash_mismatches,t),chain_mismatches:q(e.chain_mismatches,t),version_skews:q(e.version_skews,t),workspace_state_mismatches:q(e.workspace_state_mismatches,t),workspace_state_missing:q(e.workspace_state_missing,t),workspace_state_unreadable:q(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:q(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:q(e.stale_items_after,t),skipped:e.skipped})};function Xh(e,t){let n=_A[e.name];return n?n(e.details,t):e.details}function gA(e){let t=q(e.warnings,Mn);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:Xh(n,Mn)})),warnings:t.sample,findings:e.findings.filter(n=>t.sample.includes(n.warning)||e.failed_because.includes(n.warning)),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:Mn},generated_at:e.generated_at}}function qh(e){return e.details.skipped===!0}function yA(e){let t=q(e.warnings,Mn),n=e.checks.filter(qh).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!qh(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:e.findings.filter(r=>t.sample.includes(r.warning)||e.failed_because.includes(r.warning)),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:Mn,omitted_checks:n},generated_at:e.generated_at}}function tc(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=pA(e,Bh);return{values:n.values,truncated:n.truncated,total:e.length}}function Ea(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function wA(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return Vx.has(e)?e:null}function Sa(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function Zh(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e.split(`
65
- `)){let s=o.trim();if(s.length!==0){r+=1;try{let c=JSON.parse(s);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,a=Math.max(a,d),d>=Vh&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:a}}function vA(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function bA(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function kA(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||_o().telemetry_disabled?void 0:{attempted:!0,...await Qh(n)}}function EA(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,a=n.last_failed_flush_at,o=a&&(!i||a>i),s=!i,c=t.validEntries>=Xx;return(o||s||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function SA(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function xA(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>tu?[`telemetry_schema_version_behind:${t}`]:[]}function AA(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function IA(){return{..._o(),pm_no_telemetry:Ea("PM_NO_TELEMETRY"),telemetry_otel_disabled:Ea("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:Ea("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:wA()}}function RA(e,t){return e.telemetry.enabled&&t.validEntries>0}function CA(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Qh(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(Yx)});return{probe_url:Sa(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of Zx){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:Sa(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function TA(e,t){let n=Vr(process.cwd()),r=Ee.join(n,Jx),i=Ee.join(n,Kx),a=await V(r),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?Zh(a):vA(),d=await V(i),{runtimeState:l,stateParseFailed:u}=bA(d),m=e.telemetry.endpoint.trim(),f=Sa(m),p=await kA(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...EA(e,c,l),...SA(p),...xA(p),...AA(e,l));let _=RA(e,c),w=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:f,global_pm_root:n,queue_path:r,queue_exists:o,queue_entries:c.validEntries,queue_draining:CA(_,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Vh,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:IA()}},warnings:h}}async function $A(e){let t;try{t=await Pm(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function OA(e){let t="metadata",n=e.items,r=await Xt(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),a=[],o=[];if(i.length>0){n=await ut(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Xt(e.pmRoot,n),a=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,E)=>v.localeCompare(E));let w=new Set(a);o=i.filter(v=>!w.has(v))}let{missingStreams:s,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:f,workspaceStateMissing:p,workspaceStateUnreadable:h}=r,_=[...s.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),...f.map(w=>`history_drift_workspace_state_mismatch:${w}`),...p.map(w=>`history_drift_workspace_state_missing:${w}`),...h.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:_.length===0?"ok":"warn",ok:_.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:a,resolved_false_positive_items:o,authoritative_item_source:i.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:s.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:p.length,workspace_state_unreadable:h.length},missing_streams:s,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:p,workspace_state_unreadable:h}},warnings:_}}function DA(e,t){let n=ki(e),r=Qn(n.settings),i=xi(n.settings,t),a=r.active?Vt(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(r.active&&i.active)}}function PA(){return{refreshed:[],skipped:[],warnings:[]}}async function NA(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?PA():Xl(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function LA(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&yn(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function MA(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function jA(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function e_(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:po(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:po(r,e.vector_store?.adapter??null)}}function FA(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function UA(e,t,n){return e.enabled&&n.length>0&&t}async function zA(e,t,n,r,i){let a=DA(t,e),o=await wn(e),s=a.semanticRuntimeAvailable?yo(n,o.entries):[],c=await NA({pmRoot:e,snapshot:a,refreshPolicy:r,staleBefore:s}),d=await wn(e),l=a.semanticRuntimeAvailable?yo(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=LA({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=MA({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=tc(s,i),h=tc(l,i),_=UA(r,a.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:a.semanticRuntimeAvailable,compatibility_mode_auto_defaults:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:a.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:a.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:FA(r),...e_(t,a),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:a.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Bh,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:jA(r,a.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:f}}function HA(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function t_(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new y("--check-only cannot be combined with --refresh-vectors",g.USAGE);if(n&&e.noRefresh===!0)throw new y("--no-refresh cannot be combined with --refresh-vectors",g.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var GA=new Set(["extensions","locks","search"]);function WA(e){let t=new Set(Qc.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(ed));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of GA)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,a)=>i.localeCompare(a)),optionalDirs:[...n].sort((i,a)=>i.localeCompare(a)),optionalDirSet:n}}async function qA(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:a}=WA(t),o=[],s=[],c=[];for(let d of[...r,...i]){let l=Ee.join(e,d);c.push(...await Ge({path:l,scope:"project"})),!await ic(l)&&(a.has(d)?s.push(d):o.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:o,missingOptionalDirs:s,missingDirs:n?[...o,...s]:[...o],hookWarnings:c}}function n_(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function BA(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?lt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):ut(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Zs(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function VA(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function JA(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function KA(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var ac=e=>e.unknown_event_count??0,oc=e=>e.actionable_unknown_event_count??ac(e);function YA(e,t,n,r,i,a){let o=ac(r),s=oc(r),c=o>0,d=s>0,l=i.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...c?{author_attribution:r}:{},...l?{stale_in_progress:i}:{},...a.outcomes.length>0?{provenance_resolver_outcomes:a.outcomes}:{},...a.invalid_values.length>0?{provenance_invalid_values:a.invalid_values}:{},provenance_sample:a.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function r_(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function XA(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function ZA(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function QA(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function i_(e){let t=new Map;for(let[r,i]of Object.entries(e.remediationSources))for(let a of i)t.has(a)||t.set(a,r);let n=new Map(e.checks.map(r=>[r.name,r]));return e.warnings.map(r=>{let i=t.get(r)??"integrity",a=zo(r)?.code??rc(r),o=n.get(i)?.details,s=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=a==="agent_guidance_outdated"?"pm init --agent-guidance add":a==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":s[a],d=nc(r,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:r,code:a,check:i,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function eI(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function tI(e){for(let t of e.checks){let n=Ho(e.remediationSources[t.name]);eI({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function nI(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),i=new Map;for(let o of e.pendingMergeReceipts){let s=i.get(o.item_id)??[];s.push(o),i.set(o.item_id,s)}let a=[];for(let o of n){if(r.has(o))continue;let s=i.get(o);if(!(!s||s.length===0))try{await Ys(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:s}},e.global),a.push(o)}catch{}}return[...new Set(a)].sort((o,s)=>o.localeCompare(s))}function rI(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}function a_(e,t,n){let r=e.warning_count??e.warnings.length,i={...e,warning_count:r,warning_limit:an,warnings_truncated:r>an,warnings:e.warnings.slice(0,an),findings:(e.findings??[]).filter(o=>e.warnings.slice(0,an).includes(o.warning)||e.failed_because.includes(o.warning))},a=n?yA(i):t.brief===!0?gA(i):i;return{...a,warning_count:r,warning_limit:an,warnings_truncated:r>a.warnings.length,...a.projection?{projection:{...a.projection,warning_count:r,warnings_truncated:r>a.warnings.length}}:{}}}async function o_(e,t={}){let n=L(process.cwd(),e.path);await ne(n);let r=Ht(n),{settings:i,warnings:a}=await gl(n),o=[...new Set(a)],s=G(i,z()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=t_(t),m=await qA(n,s,c),f=HA(i),p=await TA(i,{checkTelemetry:t.checkTelemetry===!0}),h=await mA(n,i,!!e.noExtensions),_=n_(t),w=[],v=await BA({pmRoot:n,settings:i,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),E=v,k=zi(ge(i.schema),v),x=[...(await Em({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(pe=>pe.startsWith("agent_guidance_")),...f,...Hi(k)],D=_.skipDrift?{warnings:[]}:await Il({pmRoot:n,settings:i,itemIds:v.map(pe=>pe.id),commandLabel:"health"}),S=await tA(n,i.history.compact_policy,await Qx(n)),b=await sr(n,20,t.verboseAuthorEvents===!0),N=oc(b),A=N>0?[`history_unknown_author_events:${N}`]:[],R=r_(await Ql(n,v,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),Q=await mm(n),Ae=Q.warnings,we=await $A(n),_e=_.skipIntegrity&&!l?{...Zs("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await aA(n,s.type_to_folder,i.schema,i,l,v),He=_.skipDrift?Zs("history_drift"):await OA({pmRoot:n,items:E,settings:i,typeRegistry:s,itemReadWarnings:w}),zr=[...new Set(w)],Bn=await nI({gitWorkspaceRoot:_e.gitWorkspaceRoot,pendingMergeReceipts:_e.pendingMergeReceipts,historyDriftCheck:He,global:e});rI(He,Bn);let H=_.skipVectors?Zs("vectorization"):await zA(n,i,E,u,t.verboseStaleItems===!0),B=[VA(r,i,o),JA(m,c),KA(x,k),p.check,h.check,YA(v,i,S,b,R.scan,Q),we.check,_e.check,He.check,H.check],Hr=XA({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:zr,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:D.warnings,historySummary:S,authorAttributionWarnings:A,staleInProgressWarnings:R.warnings,provenanceWarnings:Ae,locksCheck:we,integrityCheck:_e,historyDriftCheck:He,vectorizationCheck:H}),Gr=QA({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:zr,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:D.warnings,historySummary:S,authorAttributionWarnings:A,staleInProgressWarnings:R.warnings,provenanceWarnings:Ae,locksCheck:we,integrityCheck:_e,historyDriftCheck:He,vectorizationCheck:H});tI({checks:B,remediationSources:Gr,historyDriftedCount:ZA(He),overThresholdCount:S.over_threshold.length});let Ga=Hr.filter(pe=>!nc(pe,l)),Wa=i_({warnings:Hr,checks:B,remediationSources:Gr,requireMergeDrivers:l}),ny=new Set(Wa.filter(pe=>pe.severity==="gate_failing").map(pe=>pe.check)),ry=new Set(Wa.map(pe=>pe.check));for(let pe of B)pe.ok=!ny.has(pe.name),ry.has(pe.name)&&(pe.status="warn");let iy={ok:Ga.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Ga.length>0?g.GENERIC_FAILURE:0},checks:B,warnings:Hr,findings:Wa,failed_because:Ga,generated_at:$()};return a_(iy,t,_.summaryMode)}var lz={buildHierarchyIntegrityWarnings:Kh,buildExtensionHealthTriageSummary:Yh,buildHealthFindings:i_,buildCapabilityContractMetadata:xr,buildStaleInProgressHealthSummary:r_,buildVectorizationProviderDetails:e_,collectUnknownCapabilityGuidance:Sr,isAdvisoryHealthWarning:nc,isDirectory:ic,isExpectedUnmanagedExtension:Qs,listItemDocumentPaths:Jh,normalizeEndpointForDisplay:Sa,normalizeExtensionNameForMatch:jn,parseTelemetryQueue:Zh,probeTelemetryEndpointHealth:Qh,projectHealthResult:a_,resolveActionableUnknownAuthorEventCount:oc,resolveHealthSkipPolicy:n_,resolveUnknownAuthorEventCount:ac,resolveVectorRefreshPolicy:t_,selectStaleItemDetail:tc,summarizeHealthCheckDetails:Xh,summarizeExtensionList:ka,summarizeRecordList:ot,summarizeStringList:q,telemetryEnvFlagEnabled:Ea,warningCode:rc};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a07d2f98-7c1d-5d0a-be70-5181ed0f7b4f")}catch{}})();function s_(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!su(e,t).ok)return{reason:"unverified_history"};let r=ui(),i={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(r.metadata.status));r=Cl(r,o.patch,a+1,o.op),n.has(String(r.metadata.status))?s||(i=["create","close","cancel","update","update_audit"].includes(o.op)&&Rt(o.ts)?{timestamp:o.ts,source_index:a+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function c_(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function d_(e,t,n,r,i){let a=c_(n),o=t.filter(d=>a.has(d.status)&&!d.closed_at),s=[],c=[];for(let d of r?o:[]){let l;try{let u=await dt(Gt(e,d.id),d.id),{body:m,...f}=d;l=s_(u,{metadata:f,body:m},a)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}s.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:o.length,missing_closed_at_item_ids:o.slice(0,i).map(d=>d.id),missing_closed_at_item_ids_truncated:o.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:s.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:s,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function l_(e,t){let n=L(process.cwd(),t.path),r=await T(n),i=ge(r.schema);await mt({pmRoot:n,settings:r,id:e.item_id,op:"update",author:W(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(a){if(a.metadata.closed_at)return{changedFields:[]};let o=await dt(Gt(n,a.metadata.id),a.metadata.id),s=c_(i),c=s_(o,a,s);if(!("timestamp"in c)||c.timestamp!==e.value)throw new y("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",g.GENERIC_FAILURE);return a.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function iI(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function u_(e){return`${e.item_id} ${e.link_kind}`}function m_(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=iI(i.classification,r.classification),i.owners.set(u_(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[u_(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(a=>{let o=t(a.item_id);return{id:a.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:a.link_kind}}).sort((a,o)=>{let s=a.id.localeCompare(o.id);return s!==0?s:a.field.localeCompare(o.field)})}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00f8052d-480b-5e38-86cf-4574a8ad1e92")}catch{}})();function p_(e,t,n,r,i=40){let a=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,o=new Map(t.map(d=>[d.path,d])),s={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=m_(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=ci(f.status,r)??f.status;r.terminal_statuses.has(p)?(u.push(f),p===r.close_status&&(s.legacy_closed_missing_linked_links_count+=1)):l.push(f)}s.missing_linked_links_count+=d.items.length,s.active_missing_linked_links_count+=l.length,s.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(s.active_missing_linked_paths_count+=1);let m=o.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,a),items_truncated:d.items.length>a}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),s.missing_linked_path_rows_count=c.length,s.missing_linked_path_rows=c.slice(0,a),s.missing_linked_path_rows_truncated=c.length>a,s}import Fn from"node:fs/promises";import Un from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function aI(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let a;try{a=await Fn.readdir(Un.join(e,i))}catch{return}for(let o of a)for(let s of Jn)if(o.toLowerCase().endsWith(s)){r.push({relativePath:`${i}/${o}`,id:o.slice(0,-s.length)});break}})),r.sort((i,a)=>i.relativePath.localeCompare(a.relativePath))}function oI(e,t){let{id:n,relativePath:r,liveItemIds:i,out:a}=e,o=je(t);if(o){a.conflictMarkers.push({id:n,path:r,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=sI(e,t);s!==null&&(s.op==="delete"&&i.has(n)&&a.resurrected.push({id:n,deleted_at:typeof s.ts=="string"?s.ts:"",deleted_by:typeof s.author=="string"?s.author:""}),s.op==="history_repair"&&Array.isArray(s.patch)&&s.patch.length>0&&(a.repairReconciliations+=1))}function sI(e,t){let{id:n,relativePath:r,out:i}=e,a=null,o=!1,s=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of s){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");a=d}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(a.op==="create"){if(o)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return a}function sc(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function cI(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Fn.readdir(Un.join(e,"history"))}catch{return n}for(let i of r.sort((a,o)=>a.localeCompare(o))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let a;try{a=await Fn.readFile(Un.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:sc("history stream",o)});continue}oI({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},a)}return n}function f_(e){let t=je(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function dI(e){let t=[],n=0,r=null;try{r=await V(Ht(e))}catch(a){n+=1,t.push({path:"settings.json",detail:sc("configuration file",a)})}if(r!==null){n+=1;let a=f_(r);a!==null&&t.push({path:"settings.json",detail:a})}let i;try{i=await Fn.readdir(Un.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let a of i.sort((o,s)=>o.localeCompare(s))){if(!a.endsWith(".json"))continue;n+=1;let o;try{o=await Fn.readFile(Un.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:sc("configuration file",c)});continue}let s=f_(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function h_(e,t,n,r={}){let i=await aI(e,n),a=new Set(i.map(u=>u.id)),o=new Map;for(let u of i){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let s=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Un.join(e,u.relativePath);return Ct(await Fn.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await cI(e,a),l=await dI(e);return{item_files_on_disk:i.length,item_ids_on_disk:a.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:s,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import Pc from"node:fs/promises";import{realpathSync as ER}from"node:fs";import{execFile as SR}from"node:child_process";import xe from"node:path";import{promisify as xR}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();var lI=["metadata","resolution"],cc=["metadata","resolution","estimates","timestamps","lifecycle"],uI="completed";function dc(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function __(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function g_(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=__(n.close_reason)??uI;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${dc(r)}`,gate:"resolution"})}return t}function y_(e){let t=[];for(let n of e){let r=__(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${dc(r)}`,gate:"metadata"})}return t}function w_(e,t){return e.map(n=>{let r=_l(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function v_(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function b_(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${dc(n.path)}`})}return t}function k_(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new y(`--fix-scope values must not be empty. Supported values: ${cc.join(", ")}.`,g.USAGE);return new Set(lI)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(cc.includes(i)){n.add(i);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${cc.join(", ")}.`,g.USAGE)}return n}function E_(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function Or(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();var mI=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function pI(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=mI.exec(n);if(!r)return null;let i=r[1],a=i.toUpperCase(),o=i.slice(0,i.lastIndexOf("-")),s=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${a}`)||d.includes(`ISSUE CODE \`${a}\``)||d.includes(`\`${a}\``)||d.includes(`[${a}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||s.has(o.toUpperCase())||l?a:null}function S_(e){return typeof e=="string"&&e.trim().length>0}function fI(e){let t=new Set(e.map(o=>o.id.toLowerCase())),n=new Map,r=new Map;for(let o of e){let s=o.id.toLowerCase(),c=new Set([...o.parent===null?[]:[o.parent.toLowerCase()],...o.derivations].filter(d=>d!==s&&t.has(d)));n.set(s,c);for(let d of c){let l=r.get(d)??[];l.push(s),r.set(d,l)}}let i=[...[...n].filter(([,o])=>o.size===0).map(([o])=>o)],a=new Set;for(let o=0;o<i.length;o+=1)for(let s of r.get(i[o])??[]){let c=n.get(s);c.delete(i[o]),c.size===0&&(a.add(s),i.push(s))}return e.filter(o=>!a.has(o.id.toLowerCase()))}function x_(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||S_(i.duplicate_of))continue;let a=pI(i.title,{...t,evidenceText:i.body});if(a===null)continue;let o=n.get(a);o||(o=[],n.set(a,o)),o.some(s=>s.id===i.id)||o.push({id:i.id,title:i.title,parent:S_(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(s=>["discovered_from","supersedes","incident_from"].includes(s.kind)).map(s=>s.id.trim().toLowerCase()).filter(s=>s!==i.id.toLowerCase())})}let r=[];for(let[i,a]of n){if(a.length<2)continue;let o=fI(a);if(o.length<2)continue;let s=[...o].sort((c,d)=>c.id.localeCompare(d.id));r.push({code:i,count:s.length,ids:s.map(c=>c.id),titles:s.map(c=>c.title)})}return r.sort((i,a)=>i.code.localeCompare(a.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c32504d-254c-5156-a41f-8ffd8e49107f")}catch{}})();function A_(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,a)=>i.localeCompare(a))){let i=t.get(r),a={};for(let o of[...i.keys()].sort((s,c)=>s.localeCompare(c)))a[o]=i.get(o);n[r]=a}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c577e41b-6642-554a-bc4d-0c22170c1e24")}catch{}})();function I_(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function R_(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let a of t){let o=I_(a);if(o.length===0)continue;let s=i.get(o);s?s.push(a):i.set(o,[a])}return e.map(a=>{if(a.includes(",")||a.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:a,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(i.get(I_(a))??[]).filter(s=>s!==a).sort((s,c)=>s.localeCompare(c));return o.length===0?{path:a,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:a,classification:"moved",candidates:o.slice(0,r),candidates_truncated:o.length>r}})}function C_(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var hI=/^[a-z][a-z0-9+.-]+:\/\//i;function Dr(e){return hI.test(e.trim())}import _I from"node:fs/promises";import Se from"node:path";import{glob as gI}from"tinyglobby";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="12655e94-6304-56cf-9f5d-387a26572db0")}catch{}})();var yI=["path","scope","note"],wI=["pattern","glob","path","scope","note"],vI=["path"],bI=["from","to"],kI=new Set(["note","scope"]);function $_(e){let t=e??"project";if(!qa.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${qa.join(", ")} (default: project).`,g.USAGE);return t}function lc(e){if(e.startsWith("```")||e.includes(`
66
- `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||kl(e)}function EI(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function SI(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!lc(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let a=e.slice(t+2,-1).trim();if(a.length>0&&EI(a))return{path:a,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function xI(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let a=SI(r);if(a!==void 0)return[a]}El(r,"--add",`${t} path`,lc(r));let i=lc(r)?Xn(n,"--add"):{path:r};if(Zn(i,"--add",yI),!i.path)throw new y(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return[{path:i.path,scope:$_(i.scope),note:i.note?.trim()||void 0}]}):[]}function AI(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=Xn(n,"--add-glob");Zn(r,"--add-glob",wI);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new y("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:i,scope:$_(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function II(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=Xn(n,"--remove"),i=Object.keys(r).filter(a=>kI.has(a.toLowerCase()));if(i.length>0)throw new y(`--remove identifies a linked artifact by path only and does not accept ${i.map(a=>`"${a}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,g.USAGE);if(Zn(r,"--remove",vI),!r.path)throw new y("--remove key/value form requires path=<value>",g.USAGE);return r.path}return n}):[]}function RI(e){return e?e.map(t=>{let n=Xn(t,"--migrate");Zn(n,"--migrate",bI);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new y("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:r,to:i}}):[]}function Pr(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function CI(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(a=>Pr(a.path,n))),i=[...new Set(t.map(a=>Pr(a,n)).filter(a=>r.has(a)))].sort((a,o)=>a.localeCompare(o));if(i.length!==0)throw new y(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,g.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function xt(e){return e.split(Se.sep).join("/")}function uc(e,t,n=process.cwd()){let r=e.trim();if(Dr(r))return r;if(Se.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return xt(r.replaceAll("\\",Se.sep));let i=Se.relative(t,n);return i.startsWith(`..${Se.sep}`)||i===".."||Se.isAbsolute(i)?xt(Se.normalize(r)):xt(Se.relative(t,Se.resolve(n,r)))}async function TI(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){if(Se.resolve(n,i.pattern)===Se.resolve(n))continue;let a=Se.isAbsolute(i.pattern),o=await gI(i.pattern,{cwd:n,absolute:a,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),s=[...new Set(o.map(c=>uc(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of s)r.push({path:c,scope:i.scope,note:i.note})}return r}function $I(e,t,n){if(t===void 0)return e;if(!n)throw new y("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",g.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function OI(e){return`${e.path}::${e.scope}`}function mc(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function pc(e){return[...new Map(e.map(t=>[OI(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function DI(e,t=process.cwd()){let n=[...new Set(e)].sort((s,c)=>s.localeCompare(c)),r=[],i=[],a=[],o=[];for(let s of n){if(Dr(s)){o.push(s.trim());continue}let c=Se.isAbsolute(s)?s:Se.resolve(t,s);try{(await _I.stat(c)).isFile()?r.push(s):a.push(s)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&At(d)){i.push(s);continue}a.push(s)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:a,remote_references:o}}function PI(e,t,n,r){let i=0;for(let a=0;a<e.length;a+=1){let o=Pr(e[a].path,r);o!==e[a].path&&(e[a]={...e[a],path:o},i+=1)}return{adds:t.map(a=>{let o=Pr(a.path,r);return o!==a.path&&(i+=1),{...a,path:o}}),removes:n.map(a=>Pr(a,r)),count:i}}function NI(e,t,n,r){let i=pc(e);for(let a of t){let o=i.findIndex(s=>s.path===a.path&&s.scope===a.scope);o<0?i.push(a):a.note!==void 0&&(i[o]={...i[o],note:a.note})}if(n.length>0)for(let a=i.length-1;a>=0;a-=1)n.includes(i[a].path)&&i.splice(a,1);return r?i:mc(i)}async function T_(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await DI(t,e.workspaceRoot):void 0}}async function xa(e,t,n,r){let{metadataKey:i}=r,a=Al(),o=L(process.cwd(),n.path),s=Ke(o),c=process.cwd();await ne(o);let d=await T(o),l=G(d,z()),u=await a.resolveList(t.add,"--add"),m=await a.resolveList(t.addGlob,"--add-glob"),f=await a.resolveList(t.remove,"--remove"),p=await a.resolveList(t.migrate,"--migrate"),h=xI(u,r.bareNoun).map(A=>({...A,path:uc(A.path,s,c)})),_=AI(m),w=await TI(_,s,c),v=$I([...h,...w],t.note,h.length>0||_.length>0),E=II(f).map(A=>uc(A,s,c)),k=RI(p);if(CI(v,E,k),!(v.length>0||E.length>0||k.length>0)){let A=await ve(o,e,d.id_prefix,d.item_format,l.type_to_folder);if(!A)throw new y(`Item ${e} not found`,g.NOT_FOUND);let R=(await be(A,{schema:d.schema})).document.metadata[i]??[];return T_({id:A.id,artifacts:R,changed:!1,options:t,workspaceRoot:s})}let x=W(t.author,d.author_default),D=await mt({pmRoot:o,settings:d,id:e,op:r.op,author:x,message:t.message,force:t.force,skipNoop:!0,mutate(A){let R=A.metadata,Q=R[i]??[],Ae=[...Q],we=PI(Ae,v,E,k),_e=NI(Ae,we.adds,we.removes,r.supportsAppendStable&&t.appendStable===!0);_e.length>0?R[i]=_e:delete R[i];let He=!md(Q,_e);return{changedFields:He?[i]:[],warnings:He&&we.count>0?[`path_migrations_applied:${we.count}`]:[]}}}),S=D.item[i]??[],b=D.warnings.find(A=>A.startsWith("path_migrations_applied:")),N=b?Number(b.slice(24)):0;return T_({id:D.item.id,artifacts:S,changed:D.changedFields.includes(i),migrationsApplied:N,options:t,workspaceRoot:s})}function Aa(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="79f1acaf-8ef7-5725-900a-fbeced1c57e6")}catch{}})();async function O_(e,t,n){let r=await xa(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Aa(r,"docs")}import D_ from"node:fs/promises";import ze from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="06b0bd73-d282-5473-a1da-f11c61a0a086")}catch{}})();var LI=32768;function fc(e){return xt(ze.normalize(e))}async function Ia(e){try{return await D_.realpath(e)}catch{return ze.resolve(e)}}function zn(e,t){let n=ze.isAbsolute(e.path)?ze.resolve(e.path):ze.resolve(t,e.path);return`${fc(n)}::${e.scope}`}function Ra(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>Ra(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))Ra(i,t?`${t}.${r}`:r,n)}function MI(e){let t=[];return Ra(e.metadata,"metadata",t),Ra(e.body,"body",t),t}function jI(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function FI(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let a=new Set,o=i.value.slice(0,LI);for(let[s,c]of[[n,i.value],[r,o]]){s.lastIndex=0;for(let d of c.matchAll(s)){let l=jI(d[0]);!l||a.has(l)||(a.add(l),t.push({field:i.field,value:l}))}}}return t}async function UI(e,t,n=t){let r=ze.isAbsolute(e)?ze.resolve(e):ze.resolve(n,e),i;try{i=await D_.stat(r)}catch{return}if(!i.isFile())return;let[a,o]=await Promise.all([Ia(t),Ia(r)]);if(fe(a,o)){let s=ze.relative(a,o);return!s||s.startsWith("..")||ze.isAbsolute(s)?void 0:{path:fc(s),scope:"project"}}return{path:fc(r),scope:"global"}}async function zI(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>zn(c,t))),i=new Map,a=FI(MI(e)),o=new Map;await Promise.all([...new Set(a.map(c=>c.value))].map(async c=>{o.set(c,await UI(c,t,n))}));let s=a.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:d}of s){if(!d)continue;let l=zn(d,t),u=i.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function P_(e,t,n){let r=await xa(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Aa(r,"files")}async function HI(e,t){let n=await Ia(t),r=await Promise.all(e.map(async a=>{let o=a.trim();if(!o)throw new y("Files lookup paths must not be empty.",g.USAGE);if(!ze.isAbsolute(o))return xt(o);let s=await Ia(o);return fe(n,s)?xt(ze.relative(n,s)):xt(s)})),i=[...new Set(r)].sort((a,o)=>a.localeCompare(o));if(i.length===0)throw new y("Files lookup requires at least one path.",g.USAGE);return i}function GI(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new y(`Files lookup ${r} must be a non-negative integer.`,g.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function N_(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function L_(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function WI(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(xt(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(L_)}async function qI(e){if(e.explain)return Xu({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function BI(e){if([e.strictRead,e.noTruncate,e.explain,Gd()].includes(!0))return null;let t=await Ei(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Ml({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function VI(e){let t=[],n=await Si(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=WI({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(s=>/^item_list_(?:item|directory)_read_failed:/u.test(s));if(e.strictRead&&i.length>0)throw new y(`Files lookup could not read every item: ${i.join("; ")}`,g.GENERIC_FAILURE);let a=await qI({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),o=(a?[...r].sort((s,c)=>{let d=a.explanations.get(c.item.id).score-a.explanations.get(s.item.id).score;return d!==0?d:L_(s,c)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:o.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+o.length<r.length,truncated:e.offset+o.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:o.map(s=>({item:N_(s.item),files:s.files,...a?{traceability:a.explanations.get(s.item.id)}:{}})),...a?{traceability_receipt:a.receipt}:{}}}async function SH(e,t){let n=L(process.cwd(),t.path),r=Ke(n);await ne(n);let i=await HI(e.paths,r);if(e.lineRange&&i.length!==1)throw new y("Files lookup line attribution requires exactly one source path.",g.USAGE);let a=await T(n),o=G(a,z()),{offset:s,limit:c}=GI(e),d=await BI({pmRoot:n,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:s,limit:c,has_more:s+d.matches.length<d.total,truncated:s+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:N_(l.item),files:l.files}))}:VI({pmRoot:n,settings:a,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function xH(e,t,n){let r=L(process.cwd(),n.path),i=Ke(r);await ne(r);let a=await T(r),o=G(a,z()),s=await ve(r,e,a.id_prefix,a.item_format,o.type_to_folder);if(!s)throw new y(`Item ${e} not found`,g.NOT_FOUND);let c=await be(s,{schema:a.schema}),d=await zI(c.document,i,process.cwd()),l=d.filter(b=>b.status==="addable"),u=d.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let b=c.document.metadata.files??[];return{id:s.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let p=W(t.author,a.author_default),h=l.map(b=>({path:b.path,scope:b.scope,note:f})),_=[],w=new Set,v=await mt({pmRoot:r,settings:a,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let N=[...b.metadata.files??[]],A=new Set(N.map(Ae=>zn(Ae,i)));_=[],w.clear();for(let[Ae,we]of h.entries()){let _e=zn(we,i);A.has(_e)||(N.push(we),A.add(_e),_.push(we),w.add(Ae))}let R=pc(N),Q=t.appendStable?R:mc(R);return Q.length>0?b.metadata.files=Q:delete b.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==h.length?[`files_discover_skipped_existing:${h.length-_.length}`]:[]}}}),E=v.item.files??[],k=new Set(_.map(b=>zn(b,i))),x=E.filter(b=>k.has(zn(b,i))),D=l.filter((b,N)=>!w.has(N)),S=[...u,...D];return{id:v.item.id,files:E,changed:x.length>0,apply:!0,count:E.length,candidate_count:d.length,addable_count:l.length,added_count:x.length,skipped_existing_count:S.length,candidates:d,added:x,skipped_existing:S}}import{readFileSync as JI}from"node:fs";import Ca from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="597a781e-a00d-5083-8d57-3fae870f9ccd")}catch{}})();var KI=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),hc=new Set(["--pm-path","--path","--author"]),YI={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},XI=new Set(["-p","--package"]),ZI=new Set(["-c","--call"]),QI=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),eR=new Set(["-C","--prefix","--userconfig","--cache"]),CH=new Set(["--cwd"]),TH=new Set(["--cwd"]),tR=new Set(["exec","x"]),$H=new Set(["run","run-script"]),OH=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function nR(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function rR(e,t=process.cwd()){let n=iR(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[r,...i]=n;if(M_(r)||j_(r,t))return i;if(r==="node"&&i[0]&&j_(i[0],t))return i.slice(1);let a=r==="npx"||r==="bunx"?_c(i):r==="pnpm"?sR(i):r==="npm"?cR(i):null;return a&&(M_(a.command)||oR(a.command))?a.args:null}var F_=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let a=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let s of nR(a)){let c=rR(s),d=c?dR(c):null,l=d&&KI.has(d.subcommand)?lR(d.remaining,YI[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&o.add(l)}return[...o].sort((s,c)=>s.localeCompare(c))};function iR(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function DH(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(hc.has(n)){t+=2;continue}t+=1;continue}return n}}function M_(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function aR(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function oR(e){let t=aR(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function j_(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=Ca.resolve(t,e);try{return JSON.parse(JI(Ca.join(Ca.dirname(Ca.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function _c(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let a=i[1];return a?{command:a,args:e.slice(t+1)}:null}if(ZI.has(r)){t+=1;break}t+=XI.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function U_(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function sR(e){let t=U_(e,QI);return t?.subcommand!=="dlx"?null:_c(t.args)}function cR(e){let t=U_(e,eR);return!t||!tR.has(t.subcommand)?null:_c(t.args)}function dR(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(hc.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function lR(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(hc.has(r)||t.has(r))&&(n+=1)}}import{execFile as mR}from"node:child_process";import{readFile as pR}from"node:fs/promises";import G_ from"node:path";import{promisify as fR}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]="4025e3fb-f2f2-57f1-a981-5bbb2381fe67")}catch{}})();function z_(e){if(!(e.pm_context_mode!=="none"||e.workspace_context_mode==="isolated"||e.workspace_context_mode==="snapshot"))throw new y("pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace.",g.USAGE,{code:"linked_test_context_invalid",required:"Set workspace_context_mode to isolated or snapshot when pm_context_mode is none.",examples:[Me(["test","<id>","--add-json",JSON.stringify({command:e.command,pm_context_mode:"none",workspace_context_mode:"isolated"})])]})}var gc=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],uR=new Set(gc);function FH(e){return bl(e,gc)}function UH(e,t){let n={},r=[];for(let[i,a]of Object.entries(e)){let o=i.toLowerCase();if(!uR.has(o)){r.push(i);continue}if(Object.hasOwn(n,o))throw new y(`${t} provides key "${i}" more than once after case normalization`,g.USAGE);n[o]=a}if(r.length>0)throw new y(`${t} does not recognize key${r.length>1?"s":""} ${r.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${gc.join(", ")}.`,g.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new y(`${t} command and cmd must match when both are provided`,g.USAGE);let{cmd:i,...a}=n;return{...a,command:a.command??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]="8f1a3301-8938-5208-9177-72ee29f3d174")}catch{}})();var hR=fR(mR),yc=1,_R="linked-test-trust.json";function wc(e){return G_.join(ud(e),_R)}function H_(){return{version:yc,acknowledged:{}}}async function vc(e){try{let t=JSON.parse(await pR(wc(e),"utf8"));return t.version!==yc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?H_():{version:yc,acknowledged:t.acknowledged}}catch{return H_()}}async function bc(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await hR("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function kc(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function gR(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Bd(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Nr(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function yR(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function XH(e,t,n){if(!e||e.length===0)return e;for(let i of e)z_(i);let r=kc();return yR(e,t,n,await bc(r))}function W_(e){return Ie(C({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function ZH(e,t,n){let r=await vc(e);return q_(t,n,r)}function q_(e,t,n){let r=W_(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let a=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!gR(e.provenance)?a?{fingerprint:r,trusted:!0,reason:"acknowledged",...Nr(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...Nr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...Nr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:a?{fingerprint:r,trusted:!0,reason:"acknowledged",...Nr(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...Nr(i,t)}}async function B_(e,t,n){let r=await vc(e);return t.map(i=>q_(i,n,r))}async function QH(e,t,n){let r=await vc(e),i=t.filter(a=>typeof a.command=="string"&&a.command.length>0).map(W_);for(let a of i)r.acknowledged[a]={acknowledged_at:n};return await Vn(G_.dirname(wc(e))),await Z(wc(e),`${JSON.stringify(r,null,2)}
67
- `),{acknowledged:i.length,fingerprints:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8cca9707-86a7-5ab5-8c7b-92be560254d0")}catch{}})();async function Ta(e){return e.includeBody?ut(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Si(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6322c4ff-92bd-59e5-aa64-ef8d3ef4b57f")}catch{}})();var wR=5;async function vR(e,t){let n=t.hashMismatches.filter(a=>a!==ce);if(n.length===0)return;let r=await T(e),i=G(r,z());for(let a of n){let o=await te(e,a,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let s=await ve(e,a,r.id_prefix,r.item_format,i.type_to_folder);if(s===null)throw new y(`Item ${a} not found`,g.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await be(s,{schema:r.schema});if(c.metadata.id!==a)throw new y(`Item identity changed while validating ${a}`,g.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await Om(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(m=>m!==a),...d[u].filter(m=>m===a)].sort((m,f)=>m.localeCompare(f));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==a),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===a)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await o()}}}async function $a(e,t,n){let r=await Xt(e,t);await vR(e,r);let i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),a=n?Number.POSITIVE_INFINITY:wR,o=r.driftedItems.slice(0,a),s=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:s.length>0?"error":i.length===0?"ok":"warn",ok:s.length===0&&i.length===0,details:{identity_discontinuities:s.slice(0,a),identity_discontinuities_count:s.length,identity_discontinuities_truncated:s.length>a,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:o,drifted_items_truncated:o.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,a)}},warnings:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3caaa82b-d8c7-5bc4-94e5-6699da27fa3c")}catch{}})();function Oa(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],a=new Set([n]),o=s=>{for(let c of(t.get(s)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!a.has(c)){if(a.add(c),i.push(c),o(c))return!0;i.pop(),a.delete(c)}}return!1};return o(n)?[...i]:[...e,n]}function bR(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function kR(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let a=r.resolve(i.kind);if(!a?.hierarchy)continue;let o=n.get(i.id.toLowerCase());o&&(a.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function Ec(e,t=er()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((a,o)=>a.id.localeCompare(o.id))){let a=r.get(i.id),o=bR(i.parent,n);o&&a.push(o),kR(i,r,n,t)}for(let[i,a]of r)r.set(i,[...new Set(a)].sort());return r}function Sc(e,t,n=er()){let r=Ai(e,o=>t?Nd(o,t):o==="closed"||o==="canceled",n),i=Ec(e,n),a=r.cycles.map(o=>o.item_ids);return{cycle_count:a.length,active_cycle_count:r.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(a.flat())].sort(),cycle_sample_paths:a.map(o=>Oa(o,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:r.divergences.map(o=>`${o.child_id}:scalar=${o.scalar_parent_id}:dependencies=${o.dependency_parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2840c80-38f5-5563-b2c0-ef5596cf8f62")}catch{}})();function Ut(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function xc(e){return Ut(e).replace(/\/+$/,"")}function Ve(e){let t=ee(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Ac(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9ef196b2-3eef-5bac-b949-bcb3e947c44d")}catch{}})();var AR=["src","tests","docs"],IR=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],RR=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),CR=["resolution","expected_result","actual_result"],TR=["default","tracked-all","tracked-all-strict"],V_=["core","strict","custom"],Na=["off","warn","error"],Cc=["author","acceptance_criteria","estimated_minutes","close_reason"],Y_=[...Cc,"reviewer","risk","confidence","sprint","release"],Tc=Array.from(new Set(Y_)),$R={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},OR={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},DR={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},PR={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},NR={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},LR=32*1024*1024,MR=1e4,$c=40,Je=5,jR=4096,FR=255,UR=xR(SR);function X_(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?X_(r):r);return t}function zR(e){return{...e,checks:e.checks.map(t=>({...t,details:X_(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function Ma(e,t){return ci(e,t)??e}function Lr(e,t){return t.terminal_statuses.has(Ma(e,t))}function zt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Da(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function HR(e){let t=zt(td),n={blocked_reason:zt(Br.blocked_reason),resolution:zt(Br.resolution),actual_result:zt(Br.actual_result)},r=zt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:zt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:zt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:zt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Da(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Da(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Da(i.resolution,n.resolution)?"default":"settings",actual_result:Da(i.actual_result,n.actual_result)?"default":"settings"}}}function Z_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(V_.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${V_.join(", ")}.`,g.USAGE)}function Q_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Na.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Na.join(", ")}.`,g.USAGE)}function eg(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Na.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Na.join(", ")}.`,g.USAGE)}function GR(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>$R[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function WR(e,t,n){let r=GR(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Cc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Y_],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Cc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var qR=new Set(["acceptance_criteria","estimated_minutes"]);function tg(e,t,n,r){return!r&&qR.has(t)&&Lr(e.status,n)?!1:t==="author"?!ee(e.author):t==="acceptance_criteria"?!ee(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ma(e.status,n)===n.close_status&&!ee(e.close_reason):t==="reviewer"?!ee(e.reviewer):t==="risk"?!ee(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!ee(e.confidence):t==="sprint"?!ee(e.sprint):!ee(e.release)}function ng(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new y(`Unknown --scan-mode value "${e}". Supported values: ${TR.join(", ")}.`,g.USAGE)}function rg(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return xe.resolve(t);let n=xe.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return xe.dirname(xe.dirname(n));let r=xe.resolve(process.cwd()),i=J_(n),a=J_(r),o=xe.relative(i,a);return o.length===0||!o.startsWith("..")&&!xe.isAbsolute(o)?n:r}function J_(e){try{return ER.native(e)}catch{return xe.resolve(e)}}function BR(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Nc(e,t,n){let r=t.length>0?xe.join(e,t):e,i;try{i=await Pc.readdir(r,{withFileTypes:!0})}catch(a){if(F(a))return;throw a}for(let a of i){if(a.name.startsWith("."))continue;let o=t.length>0?xe.join(t,a.name):a.name;if(a.isDirectory()){if(RR.has(a.name))continue;await Nc(e,o,n);continue}a.isFile()&&n.push(Ut(o))}}async function Oc(e){let t=[];for(let n of AR)await Nc(e,n,t);for(let n of IR){let r=xe.join(e,n);try{(await Pc.stat(r)).isFile()&&t.push(Ut(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function ig(e){try{let{stdout:t}=await UR("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:LR,windowsHide:!0,timeout:MR}),n=t.split("\0").map(r=>Ut(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function VR(e,t){let n=new Set,r=xc(Zc);r.length>0&&n.add(r);let i=xc(xe.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((a,o)=>a.localeCompare(o))}function K_(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function JR(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await ig(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Oc(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Oc(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ae(e,t=Je){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function on(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ae(e,$c);return{values:n.values,truncated:n.truncated,total:e.length}}var KR={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},YR={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function XR(e){let t=e.missing_fields.map(n=>`${KR[n]} "${YR[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function ag(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(o=>typeof o=="string"):Lm(t);if(i.length===0)return;let a=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...a?{fix_hints_truncated:!0}:{}}}function og(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var ZR="validate_metadata_duplicate_issue_codes";function sg(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Je,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${ZR}:${e.length}`]}}function QR(e,t,n){let r=Object.fromEntries(Tc.map(i=>[i,[]]));for(let i of e)for(let a of Tc)tg(i,a,t,n)&&r[a].push(i.id);return r}function eC(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let a=t[i];a.length>0&&r.push(`${OR[i]}:${a.length}`)}return r.push(...n),r}function cg(e,t){let n={};for(let r of e.required_fields){let i=t[r],a=i?i.length:0,o=DR[r];n[o]=a}return n}function dg(e,t,n){let r=[];for(let i of e.required_fields){let a=t[i];if(a)for(let o of a){let s=n.get(o)?.type,c=typeof s=="string"&&s.length>0?s:"Unknown";r.push({item_type:c,field:i})}}return r}function tC(e,t,n,r){for(let i of t.required_fields){let a=n[i];if(!a||a.length===0)continue;let o=PR[i],s=NR[i];if(!o||!s)continue;let c=ae(a,r?a.length:Je);e[o]=c.values,e[s]=c.truncated}}function lg(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:ee(n.get(i)?.resolution)})):[]}function ug(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:ee(n.get(i)?.type)})):[]}function nC(e,t,n,r,i){let a=new Map(e.map(w=>[w.id,w])),o=t.profile==="strict",s=QR(e,n,o),c=x_(e,{configuredPrefixes:i}),d=sg(c,r),l=eC(t,s,d.warnings),u=cg(t,s),m=dg(t,s,a),f=A_(m),p={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...Tc],counts:u,missing_by_type:f,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(p.configured_custom_required_fields=[...t.configured_custom_fields]),tC(p,t,s,r);let h=lg(t,s,a),_=ug(t,s,a);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:p},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:_}}function rC(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Ma(m.status,t))),a=[],o=[];for(let m of i){let f=CR.filter(p=>!ee(m[p]));f.length!==0&&(a.push({id:m.id,missing_fields:f}),o.push({id:m.id,missing_fields:f,close_reason:ee(m.close_reason)}))}let s=a.length>0?[`validate_resolution_missing_fields:${a.length}`]:[],c=n?Number.POSITIVE_INFINITY:Je,d=ae(a.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=a.map(m=>XR(m)),u=ae(l,c);return{check:{name:"resolution",status:s.length===0?"ok":"warn",ok:s.length===0,details:{checked_closed_items:i.length,missing_resolution_items:a.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:s,resolutionBackfillRows:o}}function mg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pg(e,t="pm",n=id()){let r=new Set(e.map(a=>a.id)),i=[...e].sort((a,o)=>a.id.localeCompare(o.id));return new Map(i.map(a=>{let o=new Set,s=Ve(a.blocked_by);s&&r.has(s)&&o.add(s),(a.dependencies??[]).filter(d=>{let l=Ve(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ve(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>o.add(d));let c=Ve(a.definition_of_ready);return hg(c??"",t).filter(d=>r.has(d)).forEach(d=>o.add(d)),[a.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function fg(e,t,n){let r=ru(e,n?l=>Lr(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),a=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:Je,s=ae(i,o),c=ae(a,o),d=ae(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+a.length,active_dangling_reference_count:i.length,dangling_reference_rows:s.values,dangling_reference_rows_truncated:s.truncated,legacy_terminal_dangling_reference_count:a.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function hg(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${mg(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,a)=>i.localeCompare(a))}function _g(e){let t=0,n=new Map,r=new Map,i=[],a=new Set,o=[],s=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),a.add(d);for(let u of e.get(d)??[])n.has(u)?a.has(u)&&r.set(d,Math.min(r.get(d),n.get(u))):(s(u),r.set(d,Math.min(r.get(d),r.get(u))));if(r.get(d)!==n.get(d))return;let l=[];for(;i.length>0;){let u=i.pop();if(a.delete(u),l.push(u),u===d)break}l.sort((u,m)=>u.localeCompare(m)),o.push(l)},c=[...e.keys()].sort((d,l)=>d.localeCompare(l));for(let d of c)n.has(d)||s(d);return o.filter(d=>{if(d.length>1)return!0;let l=d[0];return(e.get(l)??[]).includes(l)}).sort((d,l)=>d[0].localeCompare(l[0])||d.length-l.length||d.join(",").localeCompare(l.join(",")))}function gg(e,t="pm"){let n=pg(e,t),r=_g(n),i=[...new Set(r.flat())].sort((o,s)=>o.localeCompare(s)),a=r.map(o=>Oa(o,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:a}}function yg(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function La(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function wg(e,t){let n=La(e).split("/").filter(Boolean),r=La(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function iC(e,t){let n=La(t),r=La(e),i=t.endsWith("/")?t:`${t}/`,a=e.startsWith(i),o=n.length>0&&n===r,s=wg(e,t);return!a&&!o&&s===0?null:a?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:s+500,confidence:"same_directory"}:{score:s,confidence:"shared_directory"}}function aC(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function oC(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(a=>(r==="docs"?a.docs??[]:a.files??[]).map(o=>({item:a,link:o}))).forEach(({item:a,link:o})=>{if(o.scope!=="project")return;let s=Ut(o.path);if(s.length===0||s===e)return;let c=iC(e,s);c!==null&&aC(i,a,c.score)&&(i={item:a,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function vg(e,t){return e.map(n=>{let r=yg(n),i=r==="docs_unowned"?"docs":"files",a=oC(n,r,t),o=a?.id??"<id>";return{path:n,classification:r,owner_candidate:a,remediation_hint:`pm ${i} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function bg(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function sC(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Ve(e[n]);return i?r.some(a=>i.toLowerCase().includes(a)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function cC(e,t,n,r,i){let a=Ve(t.parent),o=a?n.get(r.get(a.toLowerCase())??a):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!Lr(o.status,i)}}function dC(e,t,n,r){let i=Ve(e.blocked_by),a=Ve(e.blocked_reason),o=a?.toLowerCase(),s=Ma(e.status,n),c=[];return t.has(s)?(!i&&!a&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&r.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),a&&c.push("non_blocked_status_has_blocked_reason"),c)}function lC(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),a=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),s={activeItems:e.filter(c=>!Lr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of s.activeItems){let d=sC(c,r);d.length>0&&s.closureLikeRows.push({id:c.id,fields:d});let l=Ve(c.parent),u=l?i.get(a.get(l.toLowerCase())??l):void 0;if(u&&Lr(u.status,n)&&(s.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),s.terminalParentFixRows.push(cC(c,u,i,a,n))),t){let m=dC(c,o,n,r);m.length>0&&s.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,p)=>f.localeCompare(p))})}}return s}function uC(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function Pa(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Ic(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function mC(e,t,n,r,i){let a=[];e.closureLikeRows.length>0&&a.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&a.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&a.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=Pa("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),s=Pa("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=Pa("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=Pa("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=Ic("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=Ic("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=Ic("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...a,...o?[o]:[],...s?[s]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function kg(e){let t=Ut(e);return t.length>jR||t.split(/[\\/]/).some(n=>n.length>FR)}async function pC(e,t){let n=xe.isAbsolute(t)?t:xe.resolve(e,t);if(kg(n))return!1;try{let r=await Pc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return BR(r,["ENOENT","ENOTDIR"])}}async function fC(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(a=>({item:i,artifact:a,link_kind:"files"})),...(i.docs??[]).map(a=>({item:i,artifact:a,link_kind:"docs"}))]);for(let{item:i,artifact:a,link_kind:o}of r){if(a.scope!=="project")continue;if(Dr(a.path)){n.remoteLinkedPaths.add(a.path.trim());continue}let s=Ut(a.path);s.length!==0&&(n.linkedProjectPaths.add(s),await pC(t,a.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:i.id,path:s,link_kind:o})))}return n}function hC(e,t,n,r,i,a){let o=r==="tracked-all-strict",s=o&&!i,c=i||o,d=c?[]:VR(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>K_(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!K_(f,d)),m={};if(l.length>0){let f=on(l,a);m.pm_internals={count:l.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:s,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function Eg(e,t,n,r,i,a,o,s="pm"){let c=lC(e,t,i,a);uC(c);let d=gg(c.activeItems,s),l=Sc(e,i),u=zi(i,e,o?Number.POSITIVE_INFINITY:Je),m=[...mC(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...Hi(u)],f=o?Number.POSITIVE_INFINITY:Je,p=ae(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),f),h=ae(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),f),_=ae(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),f),w=ae(d.cycle_item_ids,f),v=ae(d.cycle_sample_paths,f),E=ae(l.cycle_item_ids,f),k=ae(l.cycle_sample_paths,f),x=ae(l.cardinality_violation_rows,f),D=ae(l.parent_divergence_rows,f),S=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:S?"error":m.length===0?"ok":"warn",ok:!S&&m.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:p.values,active_closure_like_metadata_rows_truncated:p.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:_.values,stale_blocker_rows_truncated:_.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:w.values,dependency_cycle_item_ids_truncated:w.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:E.values,parent_cycle_item_ids_truncated:E.truncated,parent_cycle_sample_paths:k.values,parent_cycle_sample_paths_truncated:k.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:x.values,hierarchy_cardinality_violation_rows_truncated:x.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:D.values,hierarchy_parent_divergence_rows_truncated:D.truncated,stale_blocker_reason_patterns:[...a.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:a.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...a.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:a.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...a.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:a.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...a.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:a.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function Sg(e,t,n,r,i,a,o=ge(nd.schema)){let s=await fC(e,t),c=new Map(e.map(R=>[R.id,R])),d=[...new Set(s.missingLinkedPaths)].sort((R,Q)=>R.localeCompare(Q)),l=await JR(t,r),u=hC(l,n,t,r,i,a),m=u.candidateFiles.filter(R=>!s.linkedProjectPaths.has(R)),f=vg(m,e),p=R_(d,u.candidateFiles),h=new Map(p.map(R=>[R.path,R.classification])),_=p.filter(R=>R.classification==="moved").length,w=s.staleLinkRows.map(R=>({...R,classification:h.get(R.path)??"deleted"})).sort((R,Q)=>R.item_id.localeCompare(Q.item_id)||R.path.localeCompare(Q.path)||R.link_kind.localeCompare(Q.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),m.length>0&&v.push(`validate_files_orphaned_paths:${m.length}`);let E=[...s.remoteLinkedPaths].sort((R,Q)=>R.localeCompare(Q)),k=on(E,a),x=on(d,a),D=on(m,a),S=on(f.map(R=>`${R.path}:${R.classification}:owner_candidate=${R.owner_candidate?.id??"unowned"}`),a),b=a?f:on(bg(f),!1).values,N=on(C_(p),a),A=p_(w,p,R=>c.get(R),o,a?1/0:$c);return A.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${A.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:a?"full":"summary",file_list_summary_limit:$c,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:E.length,remote_linked_paths_total:k.total,remote_linked_paths:k.values,remote_linked_paths_truncated:k.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:x.total,missing_linked_paths:x.values,missing_linked_paths_truncated:x.truncated,missing_linked_paths_moved_count:_,missing_linked_paths_deleted_count:p.filter(R=>R.classification==="deleted").length,missing_linked_paths_malformed_count:p.filter(R=>R.classification==="malformed").length,missing_linked_path_classifications:N.values,missing_linked_path_classifications_truncated:N.truncated,...A,orphaned_paths_count:m.length,orphaned_paths_total:D.total,orphaned_paths:D.values,orphaned_paths_truncated:D.truncated,orphaned_path_classifications:S.values,orphaned_path_classifications_truncated:S.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:b}},warnings:v,staleLinkPruneRows:w}}function _C(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},a)=>{let o=t[a];if(o.trusted)return;let s=Ac(i.command??"");n.push(`${r.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${s}`)}),n}async function xg(e,t,n,r){let i=new Set(e.map(x=>x.id.toLowerCase())),a=0,o=0,s=new Set,c=[],d=e.flatMap(x=>(x.tests??[]).map(D=>({item:x,linkedTest:D}))),l=await bc(kc()),u=await B_(r,d.map(({linkedTest:x})=>x),l),m=_C(d,u);for(let{item:x,linkedTest:D}of d){if(typeof D.command!="string"||D.command.trim().length===0)continue;a+=1;let S=F_(D.command,t);if(S.length!==0){o+=S.length;for(let b of S)s.add(b),i.has(b.toLowerCase())||c.push(`${x.id}:${b}:${Ac(D.command)}`)}}let f=[...new Set(c)].sort((x,D)=>x.localeCompare(D)),p=[...new Set(f.map(x=>x.split(":")[1]??""))].filter(x=>x.length>0).sort((x,D)=>x.localeCompare(D)),h=[];f.length>0&&h.push(`validate_command_references_stale_pm_ids:${f.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let _=n?Number.POSITIVE_INFINITY:Je,w=ae(f,_),v=ae(p,_),E=ae([...s].sort((x,D)=>x.localeCompare(D)),_),k=ae(m,_);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:a,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:E.values,unique_referenced_pm_ids_truncated:E.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:k.values,untrusted_linked_tests_truncated:k.truncated,stale_pm_id_references_count:f.length,stale_pm_ids_count:p.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:h}}function gC(e,t){let n=si(e.map(c=>({ref:c.id,version:oi(c)})),Kn,ai),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:Je,a=ae(n.outdated,i),o=ae(n.ahead,i),s=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:s,ok:s==="ok",details:{checked_items:e.length,current_format_version:Kn,outdated_items_count:n.outdated.length,outdated_items:a.values,outdated_items_truncated:a.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:r}}var Dc="pm validate auto-fix";async function Ag(e,t,n){switch(e.kind){case"set_closed_at":await l_(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Dc};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new y("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Rc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Ig(e,t,n){let r=[],i=[],a=new Map;for(let o of e.filter(s=>Rc(s)===null))try{await Ag(o,t,n),r.push(o)}catch(s){i.push({fix:o,error:s})}for(let o of e.filter(s=>Rc(s)!==null)){let s=Rc(o),c=a.get(s);c?c.push(o):a.set(s,[o])}for(let o of a.values()){let s=o[0];if(!s)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{s.kind==="prune_file_link"?await P_(s.item_id,{remove:c,message:Dc},t):await O_(s.item_id,{remove:c,message:Dc},t),r.push(...o)}catch(d){i.push(...o.map(l=>({fix:l,error:d})))}}return{applied:r,failed:i}}var lW={applyValidateFix:Ag,applyValidateFixes:Ig,attachValidateFixHints:ag,buildCommandReferencesCheck:xg,buildDependencyReferencesCheck:fg,buildCloseReasonBackfillRows:lg,buildFilesCheck:Sg,buildLifecycleCheck:Eg,buildLifecycleDependencyGraph:pg,buildLifecycleParentGraph:Ec,buildEstimateBackfillRows:ug,buildMetadataCounts:cg,buildMissingFieldOccurrences:dg,buildOrphanedPathRows:vg,classifyOrphanedPath:yg,collectDefaultProjectFileCandidates:Oc,collectTrackedGitFileCandidates:ig,detectLifecycleDependencyCycles:gg,detectLifecycleParentCycles:Sc,escapeRegExp:mg,extractItemIds:hg,findLifecycleDependencyCycleComponents:_g,isMetadataFieldMissing:tg,linkedArtifactPathExceedsFilesystemLimits:kg,listFilesRecursive:Nc,resolveDependencyCycleSeverity:Q_,resolveParentCycleSeverity:eg,resolveFileScanMode:ng,resolveLifecycleDependencyCycleSamplePath:Oa,resolveRequestedChecks:og,resolveValidateMetadataProfile:Z_,resolveWorkspaceRoot:rg,sharedDirectoryPrefixLength:wg,summarizeOrphanedPathRows:bg,summarizeDuplicateIssueCodes:sg,toMeaningfulString:Ve};function yC(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function wC(e,t,n,r){let i=await h_(e,new Set(t.map(_=>_.id)),n,{schema:r.schema,extensionFieldNames:sn(z())}),a=[];i.unreadable_item_files.length>0&&a.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&a.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&a.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&a.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&a.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&a.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let o=a.length,s=await ua(e);s.tracked_path_count>0&&a.push(`validate_storage_tracked_runtime_cache_files:${s.tracked_path_count}`);let c=await In(e,Dt(r));c.status==="drift"&&a.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await nt(e),l=d===null?null:await Rn(d);l!==null&&l.status!=="ok"&&a.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await kt(d??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:f,lossless:p}=Ln(m);f.length>0&&a.push(`validate_merge_decisions_unreviewed:${f.length}`),yC(a,u.invalid_evidence_count);let h=o>0?"error":a.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...i,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:f.length,pending_merge_decision_items:[...new Set(f.map(_=>_.item_id))].sort((_,w)=>_.localeCompare(w)),lossless_merge_receipt_count:p.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(p.map(_=>_.item_id))].sort((_,w)=>_.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:s.tracker_relative_root,tracked_paths:s.tracked_paths,tracked_path_count:s.tracked_path_count,remediation_command:s.remediation_command}}},warnings:a}}function st(e,t,n){n&&ag(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function vC(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let i=await Iu(e.pmRoot,e.items,r?1/0:Je,e.sourceIncomplete);st(t,i,n)}if(e.requestedChecks.has("metadata")){let i=nC(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let a=await d_(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,r?1/0:Je);t.closureTimestampFixes=a.fixes,Object.assign(i.check.details,a.details),i.warnings.push(...a.warnings),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",st(t,i,n)}if(e.requestedChecks.has("resolution")){let i=rC(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,st(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=Eg(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,st(t,i,n),st(t,fg(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await Sg(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,st(t,i,n)}return e.requestedChecks.has("command_references")&&st(t,await xg(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&st(t,await $a(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&st(t,gC(e.items,r),n),e.requestedChecks.has("storage_integrity")&&st(t,await wC(e.pmRoot,e.items,G(e.settings,z()).type_to_folder,e.settings),n),t}function bC(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...y_(t.closeReasonBackfillRows)),r.push(...g_(t.resolutionBackfillRows)),r.push(...w_(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...v_(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...b_(t.staleLinkPruneRows)),r}async function kC(e,t,n,r,i,a){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=bC(e,t,n),{applicable:s,gated:c}=E_(o,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await Ig(s,i,a);l.push(...m.applied.map(Or)),u.push(...m.failed.map(({fix:f,error:p})=>({...Or(f),error:p instanceof Error?p.message:String(p)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,f)=>m.localeCompare(f)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(Or),applied_fixes:l,gated_fixes:c.map(m=>({...Or(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function Rg(e,t,n={}){Wd(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new y("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new y("--fix-scope requires --auto-fix.",g.USAGE);let i=k_(e.fixScope),a=L(process.cwd(),t.path);await ne(a);let o=await T(a),s=ge(o.schema),c=G(o,z()),d=og(e),l=[],u=await Ta({includeBody:["history_drift","metadata","completeness"].some(N=>d.has(N)),pmRoot:a,settings:o,typeToFolder:c.type_to_folder,warnings:l}),m=l.length>0;if(d.has("history_drift")){let N=await sr(a);N.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${N.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=Z_(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),h=WR(p,f,o.validation.metadata_required_fields),_=HR(o),w=Q_(e.dependencyCycleSeverity),v=eg(e.parentCycleSeverity),E=ng(e.scanMode),k=rg(a),x=await vC({requestedChecks:d,options:e,global:t,pmRoot:a,workspaceRoot:k,settings:o,items:u,statusRegistry:s,metadataPolicy:h,lifecyclePatternPolicy:_,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:E,initialWarnings:[...new Set(l)],sourceIncomplete:m}),D=r?await kC(e,x,o,i,t,n):void 0,S=[...new Set(x.warnings)].sort((N,A)=>N.localeCompare(A)),b={ok:!x.checks.some(N=>N.status==="error"),has_warnings:S.length>0,checks:x.checks,warnings:S,...D!==void 0?{fixes:D}:{},generated_at:$(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...zR(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as EC}from"node:child_process";import{promisify as SC}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]="d50f9868-5c11-51dc-967e-61ce41225ef1")}catch{}})();var xC=SC(EC),AC=16,IC=3e4;function RC(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(r=>typeof r=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function CC(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let a of Object.entries(i).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(r,a))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${a}`);for(let[a,o]of Object.entries(r)){let s=i[a];if(!s)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${a}`);if(o===null||typeof o!==s.type)throw new TypeError(`assurance provider ${e.id} parameter ${a} must be ${s.type}`)}return{...r}}async function TC(e,t,n,r){let i=CC(e,t),a=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Hd(n)}));a.catch(()=>{});let o;try{let s=await Promise.race([a,new Promise((c,d)=>{o=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??IC),o.unref?.()})]);return RC(e,t.key,s)}finally{clearTimeout(o)}}function Tg(e,t,n,r){let i=e;for(let a of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new Qe(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[a]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(a=>typeof a=="string"))return i;throw new Qe(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function Cg(e,t,n,r){let i=e.checks.find(a=>a.name===t);if(!i)throw new Qe(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:Tg(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function $C(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await xC("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function OC(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(AC,t.length)},async()=>{for(;r<t.length;){let a=r;r+=1;let o=t[a],s=await dt(Gt(e,o.id),o.id);n[a]=s.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function Mr(e,t={}){let n=await T(e),r=G(n),i=ge(n.schema),a=(t.strict_read===!0?(await au(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await ut(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(m=>({...m,id:m.id,status:m.status,type:m.type})),o={path:e},s=z(),c=Object.fromEntries((s?.assurance_providers??[]).map(m=>[m.definition.id,{cost_class:m.runtime_definition.cost_class,network:m.runtime_definition.network}])),d=new Map,l,u;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await $C(e,t.tree_id),items:a,history:t.include_history===!1?[]:await OC(e,a),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...c,...t.provider_capabilities},external:async m=>{if(m.kind==="graph"){let h=C({operation:m.operation,parameters:m.parameters??{}}),_=d.get(h);_===void 0&&(_=cu(m.operation,void 0,void 0,{...m.parameters,full:!0},o),d.set(h,_));let w=await _;return{value:Tg(w,m.field,m.kind),population_size:a.length,cost:a.length}}if(m.kind==="validate"){l??=Rg({counts:!0},o);let h=await l;return Cg(h,m.check,m.field,m.kind)}if(m.kind==="health"){u??=o_(o,{checkOnly:!0,full:!0});let h=await u;return Cg(h,m.check,m.field,m.kind)}let f=t.providers?.[m.provider];if(f)return f(m);let p=yl(s,m.provider);if(!p)throw new TypeError(`assurance provider ${m.provider} is not registered`);return TC(p.runtime_definition,m,e,t.trigger??"sdk")}}}import{createHash as DC}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c72d246d-a7ff-5c9d-8c36-4ebd45b8a69f")}catch{}})();function $g(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:i}=ni({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function PC(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let r=n;if(r.fingerprint!==t||typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return r.offset}function NC(e,t,n,r,i,a){let o=Object.fromEntries(ro.map(f=>[f,0])),s=0,c=0,d=0,l=0,u=[],m=DC("sha256").update(i);for(let f of r){let p=e.membership.get(f),h=n.has(f),_=p.family_ids.length>0;_&&h&&(s+=1),_||(c+=1),h||(d+=1);let w=t.get(f)?.escape_class;w!==void 0&&ro.includes(w)&&(o[w]+=1,l+=1),m.update(C([f,h,t.get(f)??null,p.id,p.family_ids])),(!a||!_||!h)&&u.push(f)}return{classCounts:o,coveredCount:s,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:m.digest("hex")}}function Og(e,t,n={}){Zd(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let i=new Set,a=new Map;for(let k of t){if(i.has(k.id))throw new TypeError(`Duplicate recurrence item ${k.id}`);i.add(k.id);let x=ti(k);x!==void 0&&a.set(k.id,x)}let o=Jd(e.families,a),s=[...o.membership.keys()].sort(),c=C({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:m,classifiedCount:f,selected:p,fingerprint:h}=NC(o,a,i,s,c,n.uncoveredOnly===!0),_=PC(n.cursor,h);if(_>p.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=p.slice(_,_+r).map(k=>{let x=o.membership.get(k),D=i.has(k);return{item_id:k,lineage_id:x.id,lineage_item_count:x.item_ids.length,family_ids:x.family_ids,present:D,...D?x.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=_+w.length,E=s.length===0?null:d.production_defect/s.length;return{ok:u===0&&m===0,fingerprint:h,items:w,total:p.length,has_more:v<p.length,...v<p.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:s.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:m,classified_item_count:f,unclassified_item_count:s.length-f,class_counts:d,escape_rate:f===s.length?E:null,escape_rate_lower_bound:E},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as LC}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]="676125a5-e16e-5fa2-819f-f4028dc0c3c2")}catch{}})();var Lc,Dg=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],Mc=["measurement","assertion","gate"];function MC(e){if(Dg.includes(e))return e;throw wi({command_path:"assurance",token:e,allowed:Dg,display_name:"assurance action"})}function Hn(e,t,n){throw new y(t,g.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function jC(e){if(!e)return Hn("kind",`Assurance declaration kind is required. Expected: ${Mc.join(", ")}`,"pm assurance list measurement");if(Mc.includes(e))return e;throw new y(`Assurance declaration kind is required. Expected: ${Mc.join(", ")}`,g.USAGE)}function Pg(e){if(!e)return Hn("preset",`Assurance preset is required. Expected: ${cr.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(cr.includes(e))return e;throw new y(`Assurance preset is required. Expected: ${cr.join(", ")}`,g.USAGE)}function jc(e){return e.owner?.trim()?e.owner.trim():Hn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function FC(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new y("assurance definition must be valid JSON",g.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new y("assurance put requires a JSON object definition",g.USAGE);return n}async function UC(e){let[t,n,r]=await Promise.all([rr(e,"measurement"),rr(e,"assertion"),rr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Ng(e,t){return t===!0?{id:e.id}:e}async function zC(e,t){let n=t.authorization_decision;if(!n)return[];let r=await Mr(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(o=>o.id===n),a=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!a.has(i.status))throw new y(`Assurance authorization ${n} must name a terminal Decision item`,g.USAGE);return[i.id]}async function HC(e,t){let n=To(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>bn))throw new y(`assurance verdict limit must be an integer from 1 through ${bn}`,g.USAGE);let r=await xu(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function GC(e,t,n){if(e==="presets"){if(t.preset??t.id)return Fi(Pg(t.preset??t.id),jc(t));let i=cr.map(a=>{let o=Fi(a,"pm-owner");return{id:a,title:o.title,description:o.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return vn(()=>Qu(n,Pg(t.preset??t.id),jc(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await em(await Mr(n,{resolve_tree:!1,trigger:"derive"}),jc(t)),a=t.apply?await vn(()=>tm(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...a?{applied:a}:{}}}if(!t.id)return Hn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new y("assurance promote requires --enforcement warn|block",g.USAGE);let r=await Ao(n,"assertion",t.id);return vn(()=>nm(n,r,t.enforcement,{author:t.author,message:t.message}))}async function WC(e,t,n){if(!e.id)return Hn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new y("assurance run requires a trigger",g.USAGE);if(!Jt.includes(e.trigger))throw new y(`Unknown assurance trigger ${e.trigger}. Expected: ${Jt.join(", ")}`,g.USAGE);let i=e.trigger,[a,o]=await Promise.all([UC(t),Mr(t,{...n.workspace,tree_id:e.tree,trigger:i})]),s=await du(()=>bu(r,a,o,{trigger:i,dry_run:e.dry_run===!0}));return s.dry_run||await Su(t,s,{author:e.author,message:e.message}),s}function Lg(e){throw e instanceof y?e:new y(e instanceof Error?e.message:"assurance risk request is invalid",g.USAGE)}function qC(e){if(e.limit!==void 0)throw new y(`assurance ${e.action} does not accept --limit; set limit inside the definition`,g.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new y(`assurance ${e.action} definition must be valid JSON`,g.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?$g(t):ni(t)}catch(n){if(e.action==="risk"&&n instanceof Xd)throw new y(n.message,g.USAGE,{required:"Supply definition.policy with the project's declared recurrence policy and definition.change with the proposed change; no policy is inferred.",recovery:{suggested_retry:`pm assurance ${e.action} --help`,suggested_retry_args:["assurance",e.action,"--help"]}});return Lg(n)}}function BC(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function VC(e,t,n){let r=C(t.policy),i=Lc?.pm_root===e?Lc:void 0,a=new Map(n.map(d=>[d.id,LC("sha256").update(C([Vd(d),ti(d)])).digest("hex")])),o=i?.policy_serialized===r?i:void 0,s=o?BC(o,a):new Set,c=Kd(t.policy,o?n.filter(d=>s.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...s]}:{});return Lc={pm_root:e,policy_serialized:r,item_fingerprints:a,index:c},c}async function JC(e,t){let n=qC(e),r=await Mr(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?Yd(VC(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):Og(n.policy,r.items,n)}catch(i){return Lg(i)}}async function KC(e,t={},n={}){let r=MC(e.action),i=L(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return GC(r,e,i);if(r==="verdicts")return HC(e,i);if(r==="run")return WC(e,i,n);if(["risk","lineages"].includes(r))return JC(e,i);let a=jC(e.kind);if(r==="list")return rr(i,a);if(!e.id)return Hn("id",`assurance ${r} requires an id`,`pm assurance ${r} ${a} <id>`);let o=e.id;if(r==="show")return Ao(i,a,o);if(r==="remove"){let l=await vn(()=>Eu(i,a,o,{author:e.author,message:e.message}));return Ng(l,e.idOnly)}let s=FC(a,e.definition);if(s.id!==o)throw new y(`Assurance definition id ${s.id} does not match requested id ${o}`,g.USAGE);let c={author:e.author,message:e.message,...a==="assertion"?{authorized_decision_ids:await zC(i,s)}:{}},d=await vn(()=>Oi(i,a,s,c));return Ng(d,e.idOnly)}function BW(e,t,n){let r={...e,...t};return KC({action:P(r,"subcommand")??P(r,"assuranceAction")??P(r,"operation")??"",kind:P(r,"kind"),id:P(r,"id"),definition:r.definition,trigger:P(r,"trigger"),tree:P(r,"treeId")??P(r,"tree"),gate:P(r,"gate"),limit:To(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:P(r,"author"),message:P(r,"message"),preset:P(r,"preset"),owner:P(r,"owner"),apply:r.apply===!0,enforcement:P(r,"enforcement")},n)}import Gn from"node:fs/promises";import Fa from"node:path";import ja from"node:fs/promises";import Fc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4fe37a62-2d0f-55f6-bb98-7162e7e8b8fe")}catch{}})();var YC=864e5;function XC(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function ZC(e,t){let n;try{n=await ja.readdir(e,{withFileTypes:!0})}catch(i){if(F(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let a=Fc.join(e,i.name),o;try{o=await ja.readdir(a)}catch(s){F(s)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let s of o)s.endsWith(".json")&&r.push(`${i.name}/${s}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function Mg(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*YC,o=Fc.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await ZC(o,s.warnings);for(let d of c){let l=Fc.join(o,d),u=`checkpoints/${d}`;s.scanned+=1,r?.onRead&&s.warnings.push(...await r.onRead(l));let m;try{m=await ja.readFile(l,"utf8")}catch(w){if(F(w)){s.scanned-=1;continue}s.warnings.push(`checkpoint_unreadable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=XC(m),p=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(p)){s.warnings.push(`checkpoint_unparseable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=i-p,_={file:u,created_at:f,age_seconds:Math.floor(h/1e3),stale:h>a,reason:h>a?"expired":"active"};if(!_.stale){s.retained.push(u),s.entries.push(_);continue}if(!n){try{await ja.unlink(l)}catch(w){if(!F(w)){s.warnings.push(`checkpoint_remove_failed:${d}`),s.retained.push(u),s.entries.push(_);continue}}r?.onWrite&&s.warnings.push(...await r.onWrite(l))}s.removed.push(u),s.entries.push(_)}return s}import Uc from"node:fs/promises";import jg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9c0640f0-505c-5f4a-bb7a-daa3cc775239")}catch{}})();var QC=1440*60*1e3,eT=new Set(["committed","compensated"]);function tT(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function nT(e,t,n,r,i){let a=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(a))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=r-a;return eT.has(t)?o>i?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function rT(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],a=tT(await Uc.readFile(e,"utf8")),o=nT(t,a.status,a.updatedAt,r.nowMs,r.retentionMs);return o.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),o.remove&&!r.dryRun&&(await Uc.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:o,warnings:i}}async function Fg(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*QC,o=jg.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Uc.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(F(d))return s;throw d}for(let d of c){let l=jg.join(o,d),u=`transactions/sdk/${d}`,m=await rT(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:a});s.warnings.push(...m.warnings),s.scanned+=1;let{decision:f}=m;if(!f.remove){s.retained.push(u),s.entries.push(f.entry);continue}s.removed.push(u),s.entries.push(f.entry)}return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38736716-2644-5166-bfec-4ed4bca951b9")}catch{}})();var jr=["index","embeddings","runtime","locks","checkpoints","transactions"],iT=1440*60*1e3,aT=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function oT(e,t,n){let r=t.relativePath,i=Fa.join(e,r),a=await Ge({path:i,scope:"project"});try{let o=await Gn.stat(i);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...a,`not_a_file:${r}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...a,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:a};t.kind==="file"?await Gn.unlink(i):await Gn.rm(i,{recursive:!0,force:!0});let s=await X({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...a,...s]}}catch(o){if(F(o))return{removed:!1,warnings:a};throw o}}async function sT(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],a=[],o=Date.now()-iT;for(let s of n){let c=Fa.join(e,s.relativePath);if(!await O(c))continue;let d=(await Gn.readdir(c)).filter(l=>l.startsWith(s.prefix)).sort();for(let l of d){let u=Fa.posix.join(s.relativePath,l),m=Fa.join(c,l);a.push(...await Ge({path:m,scope:"project"}));let f=await Gn.stat(m).catch(p=>{if(!F(p))throw p});if(f){if(f.mtimeMs>o){i.push(u);continue}r.push(u),!t&&(await Gn.rm(m,{recursive:!0,force:!0}),a.push(...await X({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:a}}function cT(e){if(!e||e.length===0)return[...jr];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new y(`--scope requires at least one value (${jr.join(",")})`,g.USAGE);let n=new Set;for(let r of t){if(!jr.includes(r))throw new y(`Invalid --scope value "${r}". Expected one or more of: ${jr.join(", ")}`,g.USAGE);n.add(r)}return jr.filter(r=>n.has(r))}function dT(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function hq(e,t={}){let n=L(process.cwd(),e.path);await ne(n);let r=await T(n),i=t.dryRun===!0,a=cT(t.scope),o=aT.filter(p=>a.includes(p.scope)),s=[],c=[],d=[];for(let p of o){let h=await oT(n,p,i);h.removed?s.push(p.relativePath):c.push(p.relativePath),d.push(...h.warnings)}if(a.includes("runtime")){let p=await sT(n,i);s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(a.includes("locks")){let p=await Nm(n,{dryRun:i,hooks:{onRead:h=>Ge({path:h,scope:"project"}),onWrite:h=>X({path:h,scope:"project",op:"gc:lock_remove"})}});s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),l={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(a.includes("transactions")){let p=r.checkpoints.retention_days,h=await Fg(n,{dryRun:i,retentionDays:p,hooks:{onRead:_=>Ge({path:_,scope:"project"}),onWrite:_=>X({path:_,scope:"project",op:"gc:transaction_journal_remove"})}});s.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}let m;if(a.includes("checkpoints")){let p=r.checkpoints.retention_days,h=await Mg(n,{dryRun:i,retentionDays:p,hooks:{onRead:_=>Ge({path:_,scope:"project"}),onWrite:_=>X({path:_,scope:"project",op:"gc:checkpoint_remove"})}});s.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),m={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}d.push(...await ei({mode:i?"gc:dry-run":"gc",total_items:o.length}));let f=dT({dryRun:i,scopes:a,removed:s});return{ok:d.length===0,dry_run:i,scope:a,removed:s,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:f,generated_at:$()}}import{execFile as lT}from"node:child_process";import uT from"node:path";import{promisify as mT}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7fe99df0-8454-5667-9205-0b861ba212d1")}catch{}})();var pT=mT(lT),zg="@unbrained/pm-cli",fT="latest",hT={global:["--global"],project:[]};function Ug(e){let t=e.project===!0||e.local===!0||e.scope==="project",n=e.global===!0||e.scope==="global";if(t&&n)throw new y('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"}function za(e){return e.trim().toLowerCase()}function Hg(e,t){let n=za(t);return[e.name,e.directory,e.source.input,e.source.location,e.source.package,e.source.repository,e.source.owner&&e.source.repo?`${e.source.owner}/${e.source.repo}`:void 0].some(r=>typeof r=="string"&&za(r)===n)}function _T(e,t){let n=L(process.cwd(),t.path),r=cn(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function gT(e,t,n){try{let r=await pT(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:r.stdout,stderr:r.stderr}}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr??""):"",a=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new y(`Command failed: ${e} ${t.join(" ")}
68
- ${a}`,g.GENERIC_FAILURE)}}function Ha(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():fT}function Ua(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():zg}async function yT(e,t){let n=e.commandRunner??gT,r=Ua(e),i=Ha(e),a=`${r}@${i}`,o=["npm","install","-g",a];e.repair===!0&&o.push("--force");let s=ad(import.meta.url,["../../.."]),c={requested:!0,status:"planned",package:r,target:a,command:o,before_version:s,...r===zg?{migration_guidance:["Calendar scheduling commands are package-owned. If calendar is absent, run pm package install calendar --project; use pm calendar meet, pm calendar event, or pm calendar remind."]}:{},repair:e.repair===!0};if(t)return c;try{await n(o[0],o.slice(1));let d=await n("pm",["--version"]);return{...c,status:"updated",after_version:d.stdout.trim()||void 0}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function wT(e){return uT.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function vT(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!wT(n)&&e.package&&e.package.trim().length>0?`npm:${e.package.trim()}@${t}`:e.input.startsWith("npm:")?e.input:`npm:${e.input}`}return e.input}async function bT(e,t){let n=vT(e,t);return e.kind!=="local"||await O(n)?n:await O(e.location)?e.location:n}function kT(e,t,n,r){let i=["pm","package","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&r&&r.trim().length>0&&i.push("--ref",r.trim()),i}async function Gg(e,t){let n=_T(e,t);return(await ye(n.selected_root)).state.entries.filter(r=>r.scope===e)}async function ET(e,t,n){let r=await Gg(e,t);return r.find(i=>Hg(i,n.name))??r.find(i=>za(i.directory)===za(n.directory))}async function ST(e,t,n,r,i){let a=Ha(t),o=await bT(e.source,a),s=kT(e.source,o,r,e.source.ref),c={name:e.name,directory:e.directory,scope:r,source:e.source,status:"planned",command:s,previous_version:e.manifest_version};if(i)return c;try{await $s(o,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await ET(r,n,e);return{...c,status:"updated",installed_version:d?.manifest_version}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function xT(e,t,n,r){let i=[n?e.status:void 0,...t.map(a=>a.status)].filter(a=>typeof a=="string");return{requested_cli:n,requested_packages:r,planned:i.filter(a=>a==="planned").length,updated:i.filter(a=>a==="updated").length,skipped:i.filter(a=>a==="skipped").length,failed:i.filter(a=>a==="failed").length}}async function Eq(e,t,n){let r=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&t.packagesOnly===!0){let m=["package","upgrade",...r?[r]:[],"--packages-only","--dry-run",...hT[Ug(t)]];throw new y('Options "--cli-only" and "--packages-only" are mutually exclusive.',g.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:Me(m),suggested_retry_args:m}})}let i=Ug(t),a=t.dryRun===!0;if(t.cliOnly===!0&&r)throw new y('A package target cannot be used with "--cli-only".',g.USAGE);let o=!(t.packagesOnly===!0||r),s=t.cliOnly!==!0,c=o?await yT(t,a):{requested:!1,status:"skipped",package:Ua(t),target:`${Ua(t)}@${Ha(t)}`,command:["npm","install","-g",`${Ua(t)}@${Ha(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await Gg(i,n):[];if(r&&(d=d.filter(m=>Hg(m,r)),d.length===0))throw new y(`Managed package "${r}" was not found in ${i} scope.`,g.NOT_FOUND);let l=[];for(let m of d)l.push(await ST(m,t,n,i,a));let u=xT(c,l,o,s);return{ok:u.failed===0,action:"upgrade",dry_run:a,scope:i,target:r,cli:c,packages:l,summary:u}}import{createHash as AT}from"node:crypto";import{isUtf8 as IT}from"node:buffer";import Fr from"node:fs/promises";import zc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a049f799-3807-59b5-96de-51e900798779")}catch{}})();async function Wg(e){try{return(await Fr.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(F(t))return[];throw t}}function RT(e,t,n,r){let i=t.at(-1),a;for(let c=t.length-1;c>=0;c-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[c].op)){a=t[c];break}let o=t[0]?.context?.history_compaction,s=typeof o=="object"&&o!==null&&"pruned_stream_digest"in o&&typeof o.pruned_stream_digest=="string"?o.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:n,stream_digest:r,latest_after_hash:i?.after_hash??null,latest_record_hash:i?.record_hash??null,latest_hash_algorithm:i?Ce(i.hash_algorithm):null,rewrite_count:t.reduce((c,d)=>c+(d.reanchor_evidence?.length??0),0),checkpoint_digest:s,last_maintenance:a?{op:a.op,ts:a.ts,record_hash:a.record_hash??null}:null}}function CT(e,t,n){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!IT(t))return null;let r=[];for(let i of t.toString("utf8").split(/\r?\n/u)){if(!i.trim())continue;let a=JSON.parse(i);if(typeof a!="object"||a===null||Array.isArray(a))return null;let o=a;if(![o.op,o.author,o.ts,o.before_hash,o.after_hash].every(s=>typeof s=="string")||!Array.isArray(o.patch))return null;r.push(o)}return Yn(r).ok?RT(e,r,t.length,n):null}catch{return null}}async function Hc(e,t){if(!(await Fr.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let n=zc.join(e,"history"),r=await Wg(n),i=new Map,a=[];for(let o of r){let s=o.slice(0,-6),c={id:s,digest:null,stream:null};a.push(c);let d=zc.join(n,o);try{let l=await Fr.lstat(d);if(i.set(o,C([l.ino,l.size,l.mtimeMs,l.ctimeMs])),!l.isFile())continue;let u=await Fr.readFile(d);c.digest=AT(t).update(u).digest("hex"),c.stream=CT(s,u,c.digest)}catch{}}if(C(r)!==C(await Wg(n)))throw new TypeError("attestation history inventory changed during read; retry");for(let[o,s]of i){let c=await Fr.lstat(zc.join(n,o));if(s!==C([c.ino,c.size,c.mtimeMs,c.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54d3c0f4-e663-5e31-aa4e-45ea2f6aaf75")}catch{}})();function Gc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wc(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function Wn(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function TT(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:Wn(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||Wn(e.latest_record_hash,e.latest_hash_algorithm))}function $T(e){return e===null?!0:!Gc(e)||!Wc(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&Rt(e.ts)&&(e.record_hash===null||Wn(e.record_hash,"sha256")||Wn(e.record_hash,"sha512"))}function OT(e,t){return!Gc(e)||!Wc(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)&&Wn(e.stream_digest,t)&&TT(e)&&(e.checkpoint_digest===null||Wn(e.checkpoint_digest,"sha256"))&&$T(e.last_maintenance)}function qg(e){if(!Gc(e)||!Wc(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==ao.format||e.version!==1||typeof e.generated_at!="string"||!Rt(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,n;for(let a of e.streams){if(!OT(a,t))throw new TypeError("Invalid history attestation stream");let o=a.id;if(n!==void 0&&o<=n)throw new TypeError("Invalid history attestation stream order");n=o}let{workspace_digest:r,...i}=e;if(oo(C(i),t)!==r)throw new TypeError("History attestation rollup mismatch");return e}async function Bg(e={}){let t=Ce(e.hashAlgorithm),n=e.generatedAt??$();if(!Rt(n))throw new TypeError("Invalid history attestation timestamp");let r=await Hc(L(e.cwd??process.cwd(),e.pmRoot),t),i=r.filter(o=>o.stream===null);if(i.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${i.map(o=>o.id).join(", ")}`);let a={format:ao.format,version:1,hash_algorithm:t,generated_at:n,streams:r.map(o=>o.stream)};return qg({...a,workspace_digest:oo(C(a),t)})}async function Vg(e,t={}){let n=qg(e),r=await Hc(L(t.cwd??process.cwd(),t.pmRoot),n.hash_algorithm),i=new Map(r.map(l=>[l.id,l])),a=new Map(n.streams.map(l=>[l.id,l])),o=n.streams.filter(l=>!i.has(l.id)).map(l=>l.id),s=r.filter(l=>!a.has(l.id)).map(l=>l.id),c=r.filter(l=>l.stream===null).map(l=>l.id),d=[];for(let l of n.streams){let u=i.get(l.id);u&&(u.digest!==l.stream_digest||C(u.stream)!==C(l))&&d.push({id:l.id,before_digest:l.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:o.length+s.length+c.length+d.length===0,workspace_digest:n.workspace_digest,streams_checked:r.length,changed_streams:d.map(l=>l.id),missing_streams:o,added_streams:s,invalid_streams:c,transitions:d}}import Jg from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bca4afb-f1cc-5627-a377-b30e8005a284")}catch{}})();async function Vq(e,t){for(let r of["verify","output","hashAlgorithm"]){let i=e[r];if(!(r==="verify"&&typeof i=="object"&&i!==null)&&i!==void 0&&(typeof i!="string"||i.trim().length===0))throw new y(`history attest ${r} requires a nonempty string.`,g.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new y("history attest --verify cannot be combined with --output or --hash-algorithm",g.USAGE);let r;try{r=typeof e.verify=="string"?JSON.parse(await Jg.readFile(e.verify,"utf8")):e.verify}catch{throw new y("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",g.USAGE)}return Vg(r,{pmRoot:t.path})}let n=await Bg({pmRoot:t.path,hashAlgorithm:Ce(e.hashAlgorithm)});if(e.output===void 0)return n;try{await Jg.writeFile(e.output,`${JSON.stringify(n,null,2)}
69
- `,{flag:"wx",mode:384})}catch{throw new y("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",g.USAGE)}return{output:e.output,workspace_digest:n.workspace_digest,streams:n.streams.length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42dc4379-016c-5b5d-a15b-37fe3a80dab5")}catch{}})();function Kg(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function Yg(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?Me([...r,"merge","report"],n):e==="history_evidence_invalid"?Me([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?Me([...r,"merge","reconcile"],n):e==="history_repair_required"?Me([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?Me([...r,"merge","install"],n):null}function Xg(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(n=>typeof n=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(n=>typeof n=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function oB(e){let t=L(process.cwd(),e.path);await ne(t);let n=await T(t),r=G(n,z()),i=[],a=await Ta({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),o=await nt(t),[s,c,d,l]=await Promise.all([In(t,Dt(n)),o===null?Promise.resolve(null):Rn(o),kt(o??t,{includeLossless:!0,pmRoot:t}),$a(t,a,!1)]),{pendingDecisions:u,lossless:m}=Ln(d.receipts),f=[...new Set(u.map(w=>w.item_id))].sort((w,v)=>w.localeCompare(v)),p=l.check.details,h=Xg(p),_=Kg({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:m.length,historyEvidenceValid:h.evidence_valid,driftedItemCount:h.drifted_item_count,fence:s,drivers:c});return{ok:_==="ready",state:_,merge_fence:{committed:s,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:f.slice(0,25),pending_item_ids_truncated:f.length>25,lossless_count:m.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:h,next_action:{command:Yg(_,t),reason:_},warnings:[...new Set(i)].sort((w,v)=>w.localeCompare(v)),generated_at:$()}}function sB(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
70
- `)}var cB={commandForWorkspacePositionState:Yg,normalizeWorkspaceHistoryDrift:Xg,selectWorkspacePositionState:Kg};import DT from"node:fs/promises";import Ur from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f02db25d-bedb-5411-b50a-de0fea51a117")}catch{}})();var qc="index/manifest.json",Bc="search/embeddings.jsonl",PT="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function NT(e){return e.progress===!0||process.stderr.isTTY===!0}function de(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
71
- `)}catch{}}function LT(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new y("Reindex mode must be one of keyword|semantic|hybrid",g.USAGE)}async function MT(e,t,n,r){let i=[];return{candidates:await jl(e,t,n,i,r),warnings:i}}async function Jc(e,t,n,r,i){let a=sn(z()),o=[];for(let s of t)if(!(i&&!i.has(s.metadata.id))){if(typeof s.body=="string"){o.push({metadata:s.metadata,body:s.body});continue}try{let c=await DT.readFile(s.item_path,"utf8"),d=Ct(c,{format:s.item_format,schema:n,extensionFieldNames:a,onWarning:l=>r.push(l)});o.push({metadata:s.metadata,body:d.body})}catch{r.push(`item_list_item_read_failed:${Ur.relative(e,s.item_path)}`),o.push({metadata:s.metadata,body:""})}}return o}function jT(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:zl(e,{fields:n})}}var qn=ee;function FT(e){let t=z(),n=qn(e.search?.provider);if(!n)return null;let r=wl(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,a=qn(i.name)??qn(r.definition.name);if(!a)return null;let o=i.embedBatch,s=i.embed_batch,c=i.embed,d=typeof o=="function"?o:typeof s=="function"?s:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:a,embedBatch:d,embed:l}}function UT(e){let t=z(),n=qn(e.vector_store?.adapter);if(!n)return null;let r=vl(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,a=qn(i.name)??qn(r.definition.name);if(!a)return null;let o=i.upsert,s=i.delete;return{adapterName:a,...typeof o=="function"?{upsert:o}:{},...typeof s=="function"?{delete:s}:{}}}function Vc(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new y(`Invalid vector returned by ${t}`,g.GENERIC_FAILURE);return e}async function zT(e,t,n){let r=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let a=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:r}));if(!Array.isArray(a))throw new y(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,g.GENERIC_FAILURE);return a.map((o,s)=>Vc(o,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new y(`Extension search provider "${e.name}" does not implement embed/embedBatch`,g.GENERIC_FAILURE);let i=[];for(let[a,o]of n.entries()){let s=await Promise.resolve(e.embed({input:o,settings:t,model:r}));i.push(Vc(s,`extension search provider "${e.name}" embed output at index ${a}`))}return i}function Zg(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function Qg(e,t,n){let r=n?Vt(n.name,Zg(e)):t?Vt(t.name,t.model):null;if(!r)throw new y("No embedding identity available for semantic reindex mode",g.USAGE);return r}function HT(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function ey(e,t,n,r,i,a,o,s){let c=r?.name??n?.name,d=Hl(c,e.search.embedding_corpus_max_characters).maxCharacters,l=fo(e),u=i.map(p=>Gl(p,{providerName:c,maxCharacters:d,fields:l})),m=[],f=null;if(r)try{m=await zT(r,e,u),f=Vt(r.name,Zg(e))}catch(p){if(!n)throw new y(`Extension search provider "${r.name}" failed to generate embeddings: ${p instanceof Error?p.message:String(p)}`,g.GENERIC_FAILURE);a.push(`Extension search provider "${r.name}" failed; falling back to built-in provider (${p instanceof Error?p.message:String(p)})`)}if(m.length===0){if(!n)throw new y(`No embedding executor available for reindex mode '${t}'`,g.USAGE);let p=await Wl(n,e,u,{onProgress:h=>{h.phase==="complete"&&(o.batches_completed=h.batch_index),de(s,`embedding_batch_${h.phase} batch=${h.batch_index}/${h.batch_total} size=${h.batch_size} completed_inputs=${h.completed_inputs}/${h.total_inputs}`)}});a.push(...p.warnings),o.batching=p.receipt,m=p.vectors,f=Vt(n.name,n.model)}if(de(s,`embedding_complete vectors=${m.length}`),m.length!==i.length)throw new y(`Embedding output size mismatch (expected ${i.length}, received ${m.length})`,g.GENERIC_FAILURE);if(!f)throw new y(`No embedding identity available for reindex mode '${t}'`,g.USAGE);return{vectors:m,embeddingIdentity:f}}async function GT(e,t,n,r,i,a){let o=Object.keys(n);if(t){if(o.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:o.sort((s,c)=>s.localeCompare(c)),settings:r}))}catch(s){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,g.GENERIC_FAILURE)}else o.length>0&&i.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${o.length}`);if(!e)return}e&&await Vl(e,o,{},a)}async function ty(e,t,n,r,i){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:r}))}catch(a){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${a instanceof Error?a.message:String(a)}`,g.GENERIC_FAILURE)}else i.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Bl(e,n)}}function WT(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function qT(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(r=>({id:r.metadata.id,type:r.metadata.type,status:r.metadata.status,priority:r.metadata.priority,updated_at:r.metadata.updated_at}))}}function BT(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Qn(e.settings);if(!t.active&&!e.extensionEmbedding)throw new y(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,g.USAGE);let n=xi(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new y(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,g.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function VT(e){let t=G(e.settings,z()),n=await MT(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(r=>({metadata:r.metadata,body:typeof r.body=="string"?r.body:""}))}}async function JT(e){let t=await wn(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return Qg(e.settings,Qn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&yn(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(PT))}async function KT(e){let t=await wn(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=Qg(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(d=>d.metadata.id)),i=HT(t.entries,r),a=yn(t.embedding,n);e.forceFullSemantic&&!a&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let o=e.forceFullSemantic||a?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),s=new Set(o.map(d=>d.metadata.id)),c=s.size>0?await Jc(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:i,resetRequired:a,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function YT(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await Jc(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,de(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await ey(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:ho(r.vectors,"Reindex embeddings")}}async function XT(e){let t=await ey(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=ho(n,"Reindex embeddings");if(!(!e.resetRequired&&(yn(e.ledgerEmbedding,r)||Kl(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let a=await YT(e);return n=a.vectors,r=a.embeddingIdentity,i=a.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:a.staleDocuments,vectorDimension:i,resetRequired:!0}}async function ZT(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(de(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new y(`Extension vector adapter "${t}" does not support upserting vectors.`,g.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,de(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof y)throw t;if(!e.activeVectorStore)throw new y(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,g.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),de(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){de(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await ql(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,de(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new y(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,g.USAGE)}function QT(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:Vc(t[r],`reindex embeddings output at index ${r}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function e$(e){de(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await XT({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(de(e.progressEnabled,"vector_reset_start"),await GT(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),de(e.progressEnabled,"vector_reset_complete")):await ty(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=QT(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await ZT({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:Jl(t.embeddingIdentity,t.vectorDimension)}}async function t$(e){let t=await KT(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(a=>[a.metadata.id,a.metadata.updated_at]));if(de(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return de(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await ty(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await e$({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let i=new Map(r.staleDocuments.map(a=>[a.metadata.id,a]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(a=>i.get(a.metadata.id)??a),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:r.embeddingMetadata}}async function n$(e){let t=Ur.join(e.pmRoot,qc),n=Ur.join(e.pmRoot,Bc),r=fo(e.settings),i=e.documentsForKeywordArtifacts.map(o=>JSON.stringify(jT(o,e.mode,r))).join(`
58
+ `}function z0(e){return e.map((t,n)=>({...t,sequence:n+1}))}function UF(e,t,n){Ls(e,"base");let r=Ls(t,"ours"),i=Ls(n,"theirs"),a=Math.min(r.length,i.length),o=0;for(;o<a&&r[o].eventId===i[o].eventId;)o+=1;if(o===r.length&&o===i.length)return{merged:ua(r),strategy:"identical",common_entries:o,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===i.length)return{merged:ua(r),strategy:"fast_forward_ours",common_entries:o,entries_from_ours:r.length-o,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===r.length)return{merged:ua(i),strategy:"fast_forward_theirs",common_entries:o,entries_from_ours:0,entries_from_theirs:i.length-o,entries_total:i.length,reanchored:!1};let s=r.slice(o),c=new Set(s.map(m=>m.eventId)),d=i.slice(o).filter(m=>!c.has(m.eventId)),l=[...s,...d].sort((m,f)=>{if(m.timestamp!==void 0&&f.timestamp!==void 0){let _=qt(m.timestamp,f.timestamp);if(_!==0)return _}else{if(m.timestamp===void 0&&f.timestamp!==void 0)return 1;if(m.timestamp!==void 0)return-1}let p=c.has(m.eventId),h=c.has(f.eventId);return p!==h?Number(h)-Number(p):0}),u=z0([...r.slice(0,o),...l]);return{merged:ua(u),strategy:"union_reanchor",common_entries:o,entries_from_ours:s.length,entries_from_theirs:d.length,entries_total:u.length,reanchored:!0}}var gh=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],yh=["acceptance_criteria"],G0=["updated_at"];function rn(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:C(e)===C(t)}function _h(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(l=>C(l))),a=r(t),o=new Set(a.map(l=>C(l))),s=r(n),c=new Set(s.map(l=>C(l))),d=a.filter(l=>{let u=C(l);return!i.has(u)||c.has(u)});for(let l of s){let u=C(l);!o.has(u)&&!i.has(u)&&d.push(l)}return d}function Ir(e){if(typeof e!="object"||e===null||Array.isArray(e))return C(e);let{provenance:t,...n}=e;return C(n)}function W0(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function q0(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(Ir)),a=r(t),o=new Set(a.map(Ir)),s=r(n),c=new Set(s.map(Ir)),d=a.filter(l=>{let u=Ir(l);return!i.has(u)||c.has(u)});for(let l of s){let u=Ir(l);!o.has(u)&&!i.has(u)&&d.push(W0(l))}return d}function B0(e,t){return qt(String(e),String(t))>=0?e:t}function wh(e,t,n,r){return rn(t,n)?{value:t,from_theirs:!1,conflict:!1}:rn(e,t)?{value:n,from_theirs:!0,conflict:!1}:rn(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function vh(e,t,n,r,i,a,o){let s=wh(e,t,n,r);if(!s.conflict)return{...s,conflict:!1};if(i==="preferred_side")return{...s,resolution_basis:"requested_preference",retained_side:s.from_theirs?"theirs":"ours"};let c=qt(a,o);if(i==="latest_document_update"&&c!==0){let l=c<0;return{value:l?n:t,from_theirs:l,conflict:!0,resolution_basis:"document_updated_at",retained_side:l?"theirs":"ours"}}let d=C(Y(n)).localeCompare(C(Y(t)))<0;return{value:d?n:t,from_theirs:d,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:d?"theirs":"ours"}}function Ms(e){return{...e.metadata}}function js(e,t,n){try{let r=ol(Ct(e,{...n,requireSupportedFormat:!0}),n),i=Object.entries(r.metadata).find(([,a])=>Dn(a))?.[0];if(i!==void 0)throw new TypeError(`metadata field ${i} uses the reserved missing-scalar evidence marker`);return r}catch(r){throw r instanceof y&&r.context?.code==="item_format_version_unsupported"?r:new y(`Item merge input (${t}) is not a readable item document: ${String(r)}`,g.GENERIC_FAILURE)}}function J0(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?q0(e.baseValue,e.oursValue,e.theirsValue):e.field==="acceptance_criteria"?_h(wi(e.baseValue),wi(e.oursValue),wi(e.theirsValue)).join("; "):_h(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,rn(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function V0(e){let t=vh(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution,e.oursUpdatedAt,e.theirsUpdatedAt);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:Y(e.baseValue),ours:Y(e.oursValue),theirs:Y(e.theirsValue),retained:Y(t.value),discarded:Y(t.from_theirs?e.oursValue:e.theirsValue),retained_side:t.retained_side,resolution_basis:t.resolution_basis})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function bh(e,t,n,r,i,a,o){let s=new Set([...gh,...yh]),c=new Set(G0),d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,m)=>u.localeCompare(m)),l={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let u of d){let m=e[u],f=t[u],p=n[u];if(!J0({field:u,baseValue:m,oursValue:f,theirsValue:p,unionFieldSet:s,accumulator:l})){if(c.has(u)){l.merged[u]=B0(f,p);continue}V0({field:u,baseValue:m,oursValue:f,theirsValue:p,preferred:r,conflictResolution:i,oursUpdatedAt:a,theirsUpdatedAt:o,accumulator:l})}}return l}function HF(e,t,n,r={}){let i=r.preferred??"ours",a=r.conflictResolution??"preferred_side",o=js(t,"ours",r),s=js(n,"theirs",r);if(e.trim().length===0)throw new y("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict",item_id:o.metadata.id});let c=js(e,"base",r);if(c.metadata.id!==o.metadata.id||c.metadata.id!==s.metadata.id)throw new y("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",g.CONFLICT,{code:"item_identity_conflict",item_id:c.metadata.id});let d=Ms(c),l=Ms(o),u=Ms(s),{merged:m,conflictFields:f,fieldsFromTheirs:p,unionFields:h,conflictDecisions:_}=bh(d,l,u,i,a,o.metadata.updated_at,s.metadata.updated_at),w=vh(c.body,o.body,s.body,i,a,o.metadata.updated_at,s.metadata.updated_at);w.conflict?(f.push("body"),_.push({field:"body",base:Y(c.body),ours:Y(o.body),theirs:Y(s.body),retained:Y(w.value),discarded:Y(w.from_theirs?o.body:s.body),retained_side:w.retained_side,resolution_basis:w.resolution_basis})):w.from_theirs&&p.push("body");let v=m;return v.pm_format_version=rl(Math.max(...[c.metadata,o.metadata,s.metadata,v].map(nl))),{merged:al({metadata:v,body:w.value},r),conflict_fields:f,fields_from_theirs:p,union_fields:h,conflict_decisions:_,requested_preference:i,requested_preference_applied:a==="preferred_side",conflict_resolution:a}}function Fs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Us(e,t){let n=je(e);if(n)throw new y(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,g.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new y(`JSON merge input (${t}) is not valid JSON.`,g.GENERIC_FAILURE)}}function K0(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=d=>{let l=new Map;for(let u of d){let m=C(u);l.set(m,(l.get(m)??0)+1)}return l},i=r(e),a=r(t),o=r(n);for(let[d,l]of i)if((a.get(d)??0)<l||(o.get(d)??0)<l)return null;let s=new Map(a),c=[];for(let d of n){let l=C(d),u=s.get(l)??0;u>0?s.set(l,u-1):c.push(d)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function Y0(e,t,n,r,i,a,o){if(!Fs(t)||!Fs(n))return null;let s=Fs(e)?e:{},c={},d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,u)=>l.localeCompare(u));for(let l of d){let u=i.length>0?`${i}.${l}`:l,m=X0(s,t,n,l,r,u,a,o);m!==void 0&&(c[l]=m)}return c}function kh(e,t,n,r,i,a,o){if(rn(t,n))return t;let s=K0(e,t,n);if(s!==null)return s.acceptedTheirs&&o.push(i),s.merged;let c=Y0(e,t,n,r,i,a,o);if(c!==null)return c;let d=wh(e,t,n,r);return d.conflict?a.push(i):d.from_theirs&&o.push(i),d.value}function X0(e,t,n,r,i,a,o,s){let c=Object.prototype.hasOwnProperty.call(t,r),d=Object.prototype.hasOwnProperty.call(n,r),l=Object.prototype.hasOwnProperty.call(e,r);if(c&&d)return kh(e[r],t[r],n[r],i,a,o,s);if(c){if(l&&rn(e[r],t[r])){s.push(a);return}return l?(o.push(a),i==="theirs"?void 0:t[r]):t[r]}if(!(l&&rn(e[r],n[r])))return l?(o.push(a),i==="theirs"?n[r]:void 0):(s.push(a),n[r])}function zF(e,t,n,r={}){let i=r.preferred??"ours",a=Us(e,"base"),o=Us(t,"ours"),s=Us(n,"theirs"),c=[],d=[],l=kh(a,o,s,i,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
59
+ `,conflict_paths:c,paths_from_theirs:d,preferred:i}}import{constants as Eh}from"node:fs";import{lstat as Z0,open as Q0}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b063a672-991a-5251-a2f3-6a1c7bcafd2f")}catch{}})();var ex={lstat:Z0,open:Q0};function tx(e){return e.O_NOFOLLOW??0}async function Rr(e,t,n=ex){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let i=await n.open(e,Eh.O_RDONLY|tx(Eh));try{let a=await i.stat();if(!a.isFile()||a.size>t)return null;let o=Buffer.alloc(a.size),s=0;for(;s<o.length;){let{bytesRead:c}=await i.read(o,s,o.length-s,s);if(c===0)break;s+=c}return(await i.stat()).size===a.size&&s===a.size?o.toString("utf8",0,s):null}finally{await i.close()}}import pa from"node:path";import{execFile as nx}from"node:child_process";import{createHash as Sh}from"node:crypto";import{readdir as rx}from"node:fs/promises";import ix from"node:path";import{promisify as ax}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]="af5442e7-c8af-5d81-8c89-7f1a98159cec")}catch{}})();var vt=ax(nx),ma=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function QF(e,t,n){let r=t.trim(),i=/^(['"])(.*)\1$/su.exec(r)?.[2]??r;for(let a of["rebase-merge","rebase-apply"])try{let{stdout:o}=await vt("git",["rev-parse","--path-format=absolute","--git-path",`${a}/orig-head`],{cwd:e,timeout:1e4}),s=(await Rr(o.trim(),128))?.trim();if(s===void 0||!ma.test(s))continue;let{stdout:c}=await vt("git",["rev-parse","--verify",`${s}:${i}`],{cwd:e,timeout:1e4}),d=c.trim();return{kind:"rebase",original_head:s,original_blob:d}}catch{}if(n!==void 0&&Object.keys(process.env).some(a=>/^GITHEAD_[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(a)))try{let{stdout:a}=await vt("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[o,s]=a.trim().split(/\r?\n/u);if(o!==s||!ma.test(o))return;let{stdout:c}=await vt("git",["rev-parse","--verify",`${o}:${i}`],{cwd:e,timeout:1e4}),d=c.trim(),l=Sh(d.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(n)}\0`).update(n).digest("hex");return d!==l?void 0:{kind:"merge",original_head:o,original_blob:d}}catch{}}function xh(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&(t.kind==="rebase"||t.kind==="merge")&&typeof t.original_head=="string"&&ma.test(t.original_head)&&typeof t.original_blob=="string"&&ma.test(t.original_blob)}async function Ah(e,t,n,r){if(r!==void 0&&Sh(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(r)}\0`).update(r).digest("hex")!==n.original_blob)return!1;try{let{stdout:i}=await vt("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),a=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await rx(i.trim())).some(d=>a.has(d)))return!1;let{stdout:o}=await vt("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(o.trim()!==n.original_head)return!1;let{stdout:s}=await vt("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(s.trim()!==n.original_blob)return!1;let{stdout:c}=await vt("git",["hash-object","--",ix.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await vt("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35c5d9a8-5ae0-5e97-9ea3-f8a70a5fd7d0")}catch{}})();var ox=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,sx=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,ha=2048,cx=64,dx=1e5,lx=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function bt(e){return ox.test(e)}var ux=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),_a="bounded_non_sensitive_scalars_v1",mx=new Set(["open","in_progress","blocked","closed","canceled"]),px=new Set(["risk","confidence","severity"]),fx=new Set(["low","medium","high","critical"]),Rh=new Map([["priority",new Set([0,1,2,3,4].map(C))],["status",new Set([...mx].map(C))],...[...px].map(e=>[e,new Set([...fx].map(C))])]);function ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ch(e,t){return Object.keys(e).every(n=>t.has(n))}function fa(e){return Array.isArray(e)&&e.length<=ha&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Cr(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>dx||r.depth>cx)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(ot(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function Th(e){if(!ot(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[Ch(e,ux),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),Cr(e.base),Cr(e.ours),Cr(e.theirs),Cr(e.retained),Cr(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function hx(e){if(!ot(e))return!1;let t=Object.entries(e);return t.length<=ha&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function _x(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||pa.posix.isAbsolute(e))return!1;let n=pa.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&pa.posix.basename(n,pa.posix.extname(n))===t}function gx(e){return!fa(e.fields_from_theirs)||!fa(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>ha||!e.decisions.every(Th)?!1:e.merged_field_hashes===void 0||hx(e.merged_field_hashes)}function yx(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],r=[void 0,"clone_local","hash_only","bounded_inline","mixed"],i=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===_a)&&i.includes(e.evidence_source)}function wx(e){return typeof e.created_at=="string"&&pn(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&pn(e.reconciled_at))}function Ih(e,t){if(!ot(t)||ga(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(i=>i==="pm_value_hash"||i==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let r=t.pm_value;return(r===null||Rh.get(e)?.has(C(r))===!0)&&Ft(r)===t.pm_value_hash}function vx(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&Ih(r.field,r.retained)&&Ih(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,i)=>r+(ot(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(ot(i.discarded)&&Object.hasOwn(i.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===_a)}function bx(e){return e.operation!==void 0&&!xh(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function kx(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!Ch(e,lx)?"required_fields":typeof e.id!="string"||!bt(e.id)?"receipt_id":typeof e.item_id!="string"||!sx.test(e.item_id)?"item_id":_x(e.item_path,e.item_id)?null:"item_path"}function zs(e,t){if(!ot(e))return"required_fields";let n=kx(e);return n!==null?n:bx(e)?gx(e)?yx(e)?wx(e)?t==="durable"&&!vx(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function Gs(e){if(!ot(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(r=>!ot(r)||!Object.hasOwn(r,"retained")||!Object.hasOwn(r,"discarded")?r:{base:Y(void 0),ours:Y(void 0),theirs:Y(void 0),...r})}}function $h(e){if(!ot(e))return;if(!fa(e.fields_from_theirs))return"fields_from_theirs";if(!fa(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>ha)return"decisions";let t=e.decisions.findIndex(n=>!Th(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function Ws(e,t){return zs(e,t)===null}function ga(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function qs(e,t){let n=Dn(t),r=Ft(n?void 0:t);return!n&&(t===null||Rh.get(e)?.has(C(t))===!0)?{pm_value_hash:r,pm_value:t}:{pm_value_hash:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e5e4691-4858-5a54-82b0-65b97d929b57")}catch{}})();var Rx=Ix(Ex),Ph=16*1024*1024,ya=100;async function Bs(e){try{let{stdout:t}=await Rx("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Nh(e,t){let n=he.dirname(he.resolve(e,t));for(let r=0;r<12;r+=1){if(await O(he.join(n,"settings.json")))return n;let i=he.dirname(n);if(i===n)break;n=i}return null}function Js(e){return he.join(e,"merge-receipts")}function Pn(e){return`${e}.json`}async function Oh(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await Rr(e.receiptPath,Ph)}catch(a){if(At(a))return null;throw a}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=Gs(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!Ws(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||he.basename(e.receiptPath)!==Pn(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprints:Vs(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
60
+ `}}function Tr(e,t=!1){return Ie(C({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:Ie(C(Y(n.retained))),discarded_hash:Ie(C(Y(n.discarded)))})):wa(e).decisions}))}function Vs(e){let t=[Tr(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(Tr(e,!0)),t}function Cx(e,t){let{reconciled_at:n,settlement:r,...i}=e;return t.state==="reconciled"?{...i,state:"reconciled",reconciled_at:t.reconciled_at,...t.settlement===void 0?{}:{settlement:t.settlement}}:{...i,state:"pending"}}async function Tx(e,t,n){let r=new Map;for(let i of t){let a=e.get(i.id);if(i.state!=="reconciled"||a===void 0)continue;let o=r.get(a.item_id);if(o===void 0){try{o=await dt(he.join(n,"history",`${a.item_id}.jsonl`),a.item_id),Tt(o).ok||(o=[])}catch{o=[]}r.set(a.item_id,o)}let s=a.settlement==="original_git_state_restored",c=C({...wa(a),...s?{reason:a.settlement,operation:a.operation}:{}});if(!o.some(d=>{if(d.op!=="merge_reconcile"||d.record_hash_version===void 0)return!1;let l=d.context?.merge;if(typeof l!="object"||l===null||Array.isArray(l))return!1;let u=l[s?"abandoned_receipts":"receipts"];return Array.isArray(u)&&u.some(m=>C(m)===c)})){let{reconciled_at:d,settlement:l,...u}=a;e.set(a.id,{...u,state:"pending"})}}}function wa(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:ga(t.retained)??Ft(Dn(t.retained)?void 0:t.retained),discarded_hash:ga(t.discarded)??Ft(Dn(t.discarded)?void 0:t.discarded)}))}}async function b1(e){let t=await Bs(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,i=he.basename(r,he.extname(r)),a={version:1,id:Sx(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(s=>({...s,base:Y(s.base),ours:Y(s.ours),theirs:Y(s.theirs),retained:Y(s.retained),discarded:Y(s.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:$(),value_availability:"clone_local"};await qn(t),await Z(he.join(t,Pn(a.id)),`${JSON.stringify(a,null,2)}
61
+ `);let o=await Nh(e.cwd,a.item_path);if(o!==null){let s=Js(o),c=a.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:qs(u.field,u.retained),discarded:qs(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),d=c.reduce((u,m)=>u+(Object.hasOwn(m.retained,"pm_value")?1:0)+(Object.hasOwn(m.discarded,"pm_value")?1:0),0),l={...a,decisions:c,value_availability:d===0?"hash_only":d===c.length*2?"bounded_inline":"mixed",value_policy:_a};await qn(s),await Z(he.join(s,Pn(a.id)),`${JSON.stringify(l,null,2)}
62
+ `)}return a}async function Dh(e,t){let n;try{n=await xx(e)}catch(s){let c=await $x(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],i=0,a=[],o=(s,c)=>{if(i+=1,a.length>=ya)return;let d=s.slice(0,-5);a.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...bt(d)?{receipt_id:d}:{candidate_name_hash:Ie(s)}})};for(let s of n.sort((c,d)=>c.localeCompare(d))){if(!s.endsWith(".json"))continue;let c=await Ox(e,s,t);c.receipt!==void 0?r.push(c.receipt):o(s,c)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:a,invalid_evidence_truncated:i>a.length}}async function $x(e,t,n=Ax){if(!F(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!F(i))return!1;let a=he.dirname(r);if(a===r)return!0;r=a}}async function Ox(e,t,n){let r;try{r=await Rr(he.join(e,t),Ph)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=Gs(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let a=zs(i,n);if(a!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(a)?"identity_invalid":"schema_invalid",validation_error:a,...a==="collections"?{validation_path:$h(i)}:{}};let o=i;if(t!==Pn(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...d}=o;return{receipt:{...d,requested_preference:o.requested_preference??s??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function kt(e,t={}){let n=await Bs(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await Dh(n,"clone_local"),i=t.pmRoot??he.join(e,".agents","pm"),a=await Dh(Js(i),"durable"),o=new Map(a.receipts.map(d=>[d.id,d])),s=0,c=[];for(let d of r.receipts){let l=o.get(d.id);if(l!==void 0&&!(l.value_policy===void 0?Vs(d):[Tr(d)]).includes(Tr(l))){o.delete(d.id),s+=1,r.invalid_evidence.length+a.invalid_evidence.length+c.length<ya&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:d.id});continue}o.set(d.id,l===void 0?d:Cx(d,l))}return await Tx(o,a.receipts,i),{receipts:[...o.values()].filter(d=>(t.includeReconciled||d.state==="pending")&&(t.includeLossless!==!1||d.decisions.length>0)).sort((d,l)=>d.created_at.localeCompare(l.created_at)),invalid_evidence_count:r.invalid_evidence_count+a.invalid_evidence_count+s,invalid_evidence:[...r.invalid_evidence,...a.invalid_evidence,...c].slice(0,ya),invalid_evidence_truncated:r.invalid_evidence_truncated||a.invalid_evidence_truncated||r.invalid_evidence_count+a.invalid_evidence_count+s>ya,clone_local_evidence_resolved:n!==null}}function Nn(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function k1(e,t,n={}){let r=await Bs(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!Ws(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=$(),o=he.join(r,Pn(t.id)),s=await Nh(e,t.item_path),c=s===null?null:he.join(Js(s),Pn(t.id)),d=(await Promise.all([Oh({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[Oh({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:a,settlement:n.settlement})]])).filter(l=>l!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(l=>l.modern)?[Tr(t)]:Vs(t)).some(l=>d.every(u=>u.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let l of d)await Z(l.path,l.content)}async function E1(e){let t=await kt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:$()}}import{createHash as Dx}from"node:crypto";import va from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var Px="2026-08-09T16:15:18.000Z",Mh=Symbol("pre-durable-disposition-eligible");function Et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ks(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function Lh(e){return Et(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function jh(e,t){if(typeof e!="string")return!1;let n=va.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!va.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(va.posix.basename(n)===`${t}.toon`||va.posix.basename(n)===`${t}.md`)}function Nx(e,t){return typeof e.receipt_id=="string"&&bt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&jh(e.item_path,t)}function Fh(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,a=Array.isArray(i)?new Set(i.flatMap(o=>Lh(o)?[o.field]:[])):new Set;return Ks(t)&&Ks(n)&&Ks(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(Lh)&&a.size===i.length&&t.length===a.size&&t.every(o=>a.has(o))}function Lx(e,t){return Nx(e,t)&&Fh(e)}function Mx(e,t){return typeof e.receipt_id=="string"&&bt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&jh(e.item_path,t)&&Fh(e)}function jx(e){return e[Mh]===!0}function Uh(e,t){if(!Et(e)||!Et(e.context))return[];let n=e.context.merge;return!Et(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!Et(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:Lx(r,t),[Mh]:Mx(r,t),...typeof e.ts=="string"&&pn(e.ts)?{eventTimestamp:e.ts}:{}}])}function Hh(e,t,n){if(!Et(e)||e.op!=="merge_reconcile")return[];if(!Et(e.context)||!Et(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!Et(i)||typeof i.receipt_id!="string"||!bt(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!pn(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function zh(e,t,n=[]){let r=new Map;for(let a of n){let o=`${a.itemId}\0${a.originalHistoryLine}\0${a.receiptId}\0${a.originalEventTimestamp}`;r.set(o,Math.max(r.get(o)??0,a.auditHistoryLine))}let i=a=>jx(a)&&a.eventTimestamp!==void 0&&qt(a.eventTimestamp,Px)<0&&(r.get(`${a.itemId}\0${a.line}\0${a.receiptId}\0${a.eventTimestamp}`)??0)>a.line;return{missing:e.filter(a=>!a.legacySummaryAccepted&&!t.has(a.receiptId)&&!i(a)).map(a=>({item_id:a.itemId,history_line:a.line,...bt(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:Dx("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}import{isUtf8 as Fx}from"node:buffer";import{readFile as Ux}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cca38e64-dd53-5086-8825-dc1c8f1cc587")}catch{}})();function Hx(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new y("History salvage cannot discard a potentially complete record with trailing corruption.",g.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("History salvage would conceal interior corruption or a malformed record.",g.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(r=>typeof r=="string"))throw new y("History salvage requires complete history records before the invalid tail.",g.CONFLICT,{code:"history_salvage_refused"});return n}function zx(e){if(je(e))throw new y("Resolve history merge conflicts before salvage.",g.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,r,i=0;for(let[o,s]of e.split(`
63
+ `).entries()){if(!s.trim()){n+=s.length+1;continue}let c=Hx(s);if(c===null){r===void 0&&(r=n,i=o+1),n+=s.length+1;continue}if(r!==void 0)throw new y("History salvage would discard a record or conceal interior corruption.",g.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.push(c),n+=s.length+1}let a=Tt(t);if(!a.ok||a.item_hash_version===void 0)throw new y("History salvage requires a nonempty verified prefix.",g.CONFLICT,{code:"history_salvage_refused",verification_errors:a.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries:t,itemHashVersion:a.item_hash_version,prefix:r===void 0?e:e.slice(0,r),receipt:r===void 0?null:{first_invalid_line:i,discarded_bytes:Buffer.byteLength(e.slice(r)),discarded_sha256:Ie(e.slice(r)),retained_entries:t.length}}}async function Gx(e,t,n){if(!e.located)return{itemRaw:null,document:n};let r=await Hl(e.located,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n}}async function Gh(e){let t;try{t=await Ux(e)}catch(n){if(F(n))return null;throw n}if(!Fx(t))throw new y("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",g.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function Wh(e){let{subject:t,settings:n,options:r,author:i}=e;if([r.normalizeProvenance,r.auditOperation,r.auditContext,r.auditContextById,r.forceAuditEntry,r.mergeReceiptProof,r.mergeReceiptProofById].some(Boolean))throw new y("Tail salvage cannot be combined with other repair modes.",g.USAGE);let a=await Gh(t.historyPath);if(a===null)throw new y(`No history stream exists for ${t.id}.`,g.NOT_FOUND);await Ge({path:t.historyPath,scope:"project"});let o=zx(a),s=Ol(o.entries,o.entries.length-1),c=hl(s);if(typeof s.metadata.id=="string"&&s.metadata.id!==t.id)throw new y("History belongs to another item; salvage refused.",g.CONFLICT,{code:"history_salvage_refused"});let d=await Gx(t,n,c),l=Po({itemDocument:d.document,subjectId:t.id,author:i,force:r.force,settings:n}),u=o.itemHashVersion,m=r.dryRun===!0,f=o.receipt!==null;if(f&&!m){let p=await te(e.pmRoot,t.id,n.locks.ttl_seconds,i,!!r.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await Gh(t.historyPath),_=await ve(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),w=_?await J(_.itemPath):null;if(h!==a||w!==d.itemRaw)throw new y("History or item changed while waiting for salvage lock; retry.",g.CONFLICT);let v=di({...pl({hashAlgorithm:Ce(o.entries.at(-1).hash_algorithm),nowIso:$(),author:i,op:"history_salvage",before:c,after:c,message:r.message,context:{history_salvage:o.receipt}}),before_hash:o.entries.at(-1).after_hash,after_hash:o.entries.at(-1).after_hash,item_hash_version:u});await Fi({historyPath:t.historyPath,historyRawUnderLock:a,nextHistoryRaw:`${o.prefix}${JSON.stringify(v)}
64
+ `}),l.push(...await X({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return{id:t.id,dry_run:m,changed:f,history:{path:t.historyPath,entries_scanned:o.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:f&&!m,verify_ok:!0,verify_errors:[],item_hash_version_before:u,item_hash_version_after:u,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...o.receipt?{salvage:o.receipt}:{},warnings:l,generated_at:$()}}import{realpath as Kh}from"node:fs/promises";import Ys from"node:path";import Yh 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]="42f8db8f-d659-58e9-84af-21ced6d6a403")}catch{}})();function qh(e,t){return t==="body"?e.body:e.metadata[t]}function Wx(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=t;return e==="comments"?typeof n.created_at=="string"&&typeof n.author=="string"&&typeof n.text=="string":typeof n.path=="string"||e==="tests"&&typeof n.command=="string"}function qx(e){let t={...e};if(t.source_kind==="merge_union"&&(t.source_kind="local_mutation"),t.provenance!==null&&typeof t.provenance=="object"&&!Array.isArray(t.provenance)){let n={...t.provenance};n.source_kind==="merge_union"&&(n.source_kind="local_mutation"),t.provenance=n}return t}function Bh(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(r=>Wx(e,r)))return t;let n=t.map(r=>e==="comments"?r:qx(r));return[...new Map(n.map(r=>[C(r),r])).values()]}function Xs(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(i=>{let a=t.findIndex((o,s)=>!r.has(s)&&Xs(i,o));return a<0?!1:(r.add(a),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,i])=>Object.hasOwn(n,r)&&Xs(i,n[r]))}function Jh(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let a=e[i],o=new Set;for(let c of mi(a.patch))o.add(vi(c.path)),c.from&&o.add(vi(c.from));let s=[...n].filter(c=>o.has(c));if(s.length!==0){for(let c of s)n.delete(c);r.push({index:i+1,ts:a.ts,author:a.author,op:a.op,fields:s.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function Bx(e,t,n){let r=Yh.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(vi(p.path));let a=new Set([...i].filter(p=>Xs(Bh(p,qh(t,p)),Bh(p,qh(n,p))))),o=new Set([...i].filter(p=>!a.has(p))),s=Jh(e,o),c=Jh(e,a),d=[...i].sort((p,h)=>p.localeCompare(h)),l=[...o].sort((p,h)=>p.localeCompare(h)),u=[...a].sort((p,h)=>p.localeCompare(h)),m=[...new Set(s.map(p=>p.author))].sort((p,h)=>p.localeCompare(h)),f=[...new Set(c.map(p=>p.author))].sort((p,h)=>p.localeCompare(h));return{reconciled_field_count:i.size,reconciled_fields:d,reverted_field_count:o.size,reverted_fields:l,discarded_events:s,discarded_authors:m,preserved_field_count:a.size,preserved_fields:u,preserved_events:c,preserved_authors:f,recovery_hint:s.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function Jx(e){try{return await Kh(e)}catch{return null}}async function Vx(e){if(await Jx(Ys.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let t=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),n=e.receipt.merged_field_hashes;if(!n||t.length===0)return null;let r=Object.keys(n).sort();if(t.length!==r.length||t.some((a,o)=>a!==r[o]))return null;let i=e.currentItemReplay.metadata;return t.every(a=>{let o=a==="body"?e.currentItemReplay.body:i[a];return[Ft(o),Ie(C(Y(o)))].includes(n[a])})?{receipt:e.receipt,declaredFields:t}:null}async function Kx(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(o=>o.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Kh(e.itemPath),r=[];for(let o of t){let s=await Vx({receipt:o,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});s&&r.push(s)}let i=new Set(r.flatMap(({declaredFields:o})=>o)),a=e.reconciliation?.reconciled_fields;return r.length>0&&(a===void 0||a.length>0&&a.every(o=>i.has(o)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:o})=>o.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function Vh(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:Ys.relative(a,t.currentItemPath).split(Ys.sep).join("/");if(!n||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||o!==i.item_path||i.operation===void 0||!await Ah(a,i.item_path,i.operation,t.currentItemRawBeforeLock))throw new y("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function Yx(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(a=>a.item_id===e.subjectId).map(a=>a.id)??[]),n=(e.options.mergeReceiptProof?await kt(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(a=>a.item_id===e.subjectId&&t.has(a.id))??[],r=e.options.mergeReceiptProof?await Kx({proof:{...e.options.mergeReceiptProof,receipts:n},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(r&&!r.trusted&&e.options.force!==!0)throw new y(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${r.reason}).`,g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let i=r?.trusted?n.filter(a=>r.receipt_ids.includes(a.id)):[];return{mergeReceiptProof:r,effectiveAuditContext:i.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:i.map(wa)}}:e.options.auditContext}}function Xx(e,t,n){let r=e.located?.itemPath??null,i=t.loadedItem,a=t.entries;if(!i)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let o=ui(i.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:r,matchedChainBefore:hn(o,n,Ce(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:i.raw,loadedItem:i}}function Zx(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function Qx(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=Ce(e.reanchorEntries.at(-1)?.hash_algorithm),i=hn(e.finalReplay,e.itemHashVersion,r),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=i.indexOf(a),s=hn(n,e.itemHashVersion,r),c={hash_algorithm:r,ts:$(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Yh.compare(e.finalReplay,e.currentItemReplay):[],before_hash:i[o],after_hash:s[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(di({...c,event_class:cl(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function eA(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function Zs(e,t,n){let{pmRoot:r,settings:i,typeRegistry:a}=await ho(n.path),o=await cu(r,e,i,a.type_to_folder);return t.salvageTail===!0?Wh({pmRoot:r,subject:o,settings:i,typeRegistry:a,options:t,author:W(t.author,i.author_default)}):_m({pmRoot:r,subject:o,settings:i,typeRegistry:a,operation:"history-repair",options:t,transform:s=>nA({pmRoot:r,subject:o,options:t},s)})}function tA(e,t,n){let r=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&n!==void 0&&t.some(i=>i.record_hash_version!==void 0&&i.op==="merge_reconcile"&&C(i.context)===C(n));return e.forceAuditEntry===!0&&!r}async function nA(e,t){let{pmRoot:n,subject:r,options:i}=e,a=t.entries,o=t.verification,s=Tt(a),c=i.normalizeProvenance?lm(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=_l(c.entries),l=new Set(c.entries.map(A=>A.item_hash_version).filter(A=>A!==void 0)),u=pi(c.entries,d),m=Xx(r,t,d);await Vh(i.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=hn(f,d),h=!1;if(m.currentItemReplay!==null){let A=hn(m.currentItemReplay,d);h=!p.some((R,Q)=>R===A[Q])}let _=h&&m.currentItemReplay?Bx(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await Yx({options:i,pmRoot:n,subjectId:r.id,itemReplayContext:m,reconciliation:_}),E=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,tA(i,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,x=!!i.dryRun,D=Zx({message:i.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=Qx({reanchorEntries:u.entries,changed:E,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:f,author:k,message:D,auditOperation:i.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),N=eA(E,u.skippedOps,_);return{changed:E,rewrittenEntries:S,beforeWrite:async()=>Vh(i.mergeAbandonmentProof,m,o.ok,u),report:({verification:A,warnings:R})=>({id:r.id,dry_run:x,changed:E,history:{path:r.historyPath,entries_scanned:a.length,chain_drift_before:!o.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:h,audit_entry_added:b,verify_ok:A.ok,verify_errors:A.errors,item_hash_version_before:s.item_hash_version??null,item_hash_version_after:d,version_disposition:l.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},provenance_normalization:{requested:i.normalizeProvenance===!0,...c.receipt},..._?{reconciliation:_}:{},...w?{merge_receipt_proof:w}:{},warnings:[...new Set([...N,...R])].sort((Q,Ae)=>Q.localeCompare(Ae)),generated_at:$()})}}function _U(e,t){if(t&&e!==void 0)throw new y("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",g.USAGE);if(!t&&e===void 0)throw new y("history-repair: provide an item <id> or pass --all to repair every drifted stream.",g.USAGE)}async function gU(e,t){if(e.salvageTail===!0)throw new y("Tail salvage requires one explicit item ID; --all is not supported.",g.USAGE);let{pmRoot:n,settings:r,typeRegistry:i}=await ho(t.path),a=[],o=await ut(n,r.item_format,i.type_to_folder,a,r.schema,{forceSourceScan:!0}),s=await Xt(n,o),c=e.normalizeProvenance?await um(n):[],d=[...new Set([...s.driftedItems,...c])].sort((f,p)=>f.localeCompare(p)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let f of d)try{let p=await Zs(f,{...e,auditContext:e.auditContextById?.[f],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[f]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=p.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...p.warnings.map(_=>`${f}:${_}`)),l.push({id:f,outcome:h,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,l.push({id:f,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await dl(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:o.length,drifted_streams:s.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...a,...u])].sort((f,p)=>f.localeCompare(p)),generated_at:$()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="28558863-cc40-53d5-822d-d2f3bb3d2247")}catch{}})();var rA=new Set(eu),Xh=25,iA=Ee.join("runtime","telemetry","events.jsonl"),aA=Ee.join("runtime","telemetry","state.json"),oA=2500,sA=500,Zh=iu-3,cA=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function ic(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function ac(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Ln(e){return e.trim().toLowerCase()}function tc(e,t){let n=Ln(e),r=Ln(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function oc(e){try{return(await St.stat(e)).isDirectory()}catch{return!1}}async function dA(e){let t=(await St.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>St.readdir(Ee.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>Bn.some(a=>i.name.endsWith(a))).map(i=>Ee.parse(i.name).name)))}async function lA(e,t,n,r){let i=await Ge({path:e,scope:"project"}),a=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!a)return{warnings:i,overThreshold:!1,classification:"live"};let o;try{o=await St.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let s="live";if(a){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{s=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function uA(e,t,n){let r=Ee.join(e,"history");if(!await oc(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await St.readdir(r)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),a=t.enabled?t.max_entries:null,o=[],s=[],c=[],d=[];for(let l of i){let u=Ee.join(r,l),m=l.slice(0,-6),f=await lA(u,m,t,n);o.push(...f.warnings),f.classification==="tombstone"&&c.push(m),f.classification==="orphaned"&&d.push(m),f.overThreshold&&s.push(m)}return{count:i.length,warnings:[...o,...s.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:s,max_entries:a,tombstones:c,orphaned:d}}function nc(e,t){return Ee.relative(e,t).replaceAll("\\","/")}async function Qh(e,t){let n=[...new Set(Object.values(t))].sort((i,a)=>i.localeCompare(a)),r=[];for(let i of n){let a=Ee.join(e,i),o=[];try{o=await St.readdir(a)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&F(s))continue;continue}for(let s of o)Bn.some(c=>s.toLowerCase().endsWith(c))&&r.push(Ee.join(a,s))}return r.sort((i,a)=>nc(e,i).localeCompare(nc(e,a))),r}function mA(e){return!(typeof e=="object"&&e!==null&&"code"in e&&F(e))}async function pA(e,t,n){let r=await Qh(e,t),i=[],a=[],o=[],s=[],c=on(H());for(let d of r){let l=nc(e,d),u;try{u=await St.readFile(d,"utf8")}catch{i.push(l);continue}let m=je(u);if(m){a.push({path:l,...m});continue}try{let f=Ct(u,{format:md(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:ai(f.metadata)})}catch{o.push(l)}}return{paths:r,unreadable:i,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function fA(e){let t=Ee.join(e,"history"),n=[],r=[],i=[],a=[],o=[],s=[];try{s=(await St.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){mA(c)&&n.push("history")}for(let c of s){let d=c.slice(0,-6),l;try{l=await St.readFile(Ee.join(t,c),"utf8")}catch{n.push(d);continue}let u=je(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,f)=>{if(m.trim())try{let p=JSON.parse(m);a.push(...Uh(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Hh(p,d,f+1))}catch{i.push({id:d,line:f+1})}})}return{files:s,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:a,mergeReceiptDispositions:o}}function e_(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function hA(e,t,n,r,i,a){let o=await pA(e,t,n),s=await fA(e),c=oi(o.formatVersions,Jn,ii),d=ge(n),l=xi(a,A=>il(A,d),Zn()),u=await la(e),m=await rt(e),f=await mh(e,m,r,i),p=m===null?null:await In(m),h=await kt(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),_=new Set(h.receipts.map(A=>A.id)),w=zh(s.mergeReceiptReferences,_,s.mergeReceiptDispositions),v=w.missing,E=h.receipts.filter(A=>A.state==="pending"),{pendingDecisions:k,lossless:x}=Nn(E),D=p?.status==="missing"&&p.missing_keys.length===5&&p.drifted_keys.length===0,S=[...o.unreadable.map(A=>`integrity_item_unreadable:${A}`),...o.conflictMarkers.map(A=>`integrity_item_conflict_marker:${A.path}:L${A.line}`),...o.parseFailures.map(A=>`integrity_item_parse_failed:${A}`),...s.unreadable.map(A=>`integrity_history_unreadable:${A}`),...s.conflictMarkers.map(A=>`integrity_history_conflict_marker:${A.id}:L${A.line}`),...s.invalidJson.map(A=>`integrity_history_invalid_json:${A.id}:L${A.line}`),...c.outdated.map(A=>`integrity_item_outdated_format_version:${A}`),...c.ahead.map(A=>`integrity_item_ahead_format_version:${A}`),...e_(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...p!==null&&p.status!=="ok"?[`merge_driver_configuration_${D?"missing":"drift"}:${p.missing_keys.length+p.drifted_keys.length}`]:[],...f.warnings,...k.length>0?[`merge_decisions_unreviewed:${k.length}`]:[],...x.length>0?[`merge_receipts_pending:${x.length}`]:[],...ph({invalidEvidenceCount:h.invalid_evidence_count,missingHistoryReferenceCount:v.length})],b=[...new Set(S)].sort((A,R)=>A.localeCompare(R)),N=b.filter(A=>!A.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:N.length===0?"ok":"warn",ok:N.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:s.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:s.unreadable.length,history_conflict_markers:s.conflictMarkers.length,history_invalid_json:s.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:p===null||p.status==="ok"?0:p.missing_keys.length+p.drifted_keys.length,merge_fence:f.count,pending_merge_decisions:k.length,lossless_merge_receipts:x.length,invalid_merge_receipt_evidence:h.invalid_evidence_count,missing_merge_receipt_history_references:v.length,accepted_legacy_merge_receipt_references:w.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:w.acceptedDispositionCount},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,hierarchy_integrity:{...l,relations:We(l.relations,ym)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:p===null?null:{...p,required:i},merge_fence:f.audit,pending_merge_decision_items:[...new Set(k.map(A=>A.item_id))].sort((A,R)=>A.localeCompare(R)),lossless_merge_receipt_items:[...new Set(x.map(A=>A.item_id))].sort((A,R)=>A.localeCompare(R)),invalid_merge_receipt_evidence_details:h.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:h.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:v.slice(0,No),missing_merge_receipt_history_reference_details_truncated:v.length>No}},warnings:b,gitWorkspaceRoot:m,pendingMergeReceipts:E}}function _A(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function gA(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:_A(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function yA(e,t){return ee(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function wA(e){let t=ee(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function vA(e){return ee(e.reason)??ee(e.error)??ee(e.message)}function Qs(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function bA(e){let t=[],n=[],r=[];e.forEach((a,o)=>{let s=yA(a.definition,o),c=wA(a.definition);if(c==="applied"){t.push({layer:a.layer,name:a.name,id:s,status:c});return}if(c==="failed"){r.push({layer:a.layer,name:a.name,id:s,status:c,reason:vA(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(Qs),n.sort(Qs),r.sort(Qs);let i=[...r.map(a=>`extension_migration_failed:${a.layer}:${a.name}:${a.id}`),...n.map(a=>`extension_migration_pending:${a.layer}:${a.name}:${a.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function t_(e,t,n,r,i,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>ac(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=[],h=ks(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${Gr.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(_=>_.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(_=>_.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:a,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:s.length,unmanaged_expected_extensions:s,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function kA(e,t,n){let r=await Cs(Ye(e)),i=await Xe({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=i.loaded.map(S=>gA(S)),o=await cm(i.loaded,Ye(e)),s=await Ze({...i,loaded:i.loaded}),[c,d]=await Promise.all([ye(i.roots.project),ye(i.roots.global)]);await Rs(e,s.registrations.migrations);let l=bA(s.registrations.migrations),u={failed:s.failed,warnings:s.warnings,hook_counts:s.hook_counts,command_override_count:s.command_override_count,command_handler_count:s.command_handler_count,parser_override_count:s.parser_override_count,preflight_override_count:s.preflight_override_count,service_override_count:s.service_override_count,renderer_override_count:s.renderer_override_count,registration_counts:s.registration_counts,registrations:s.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},m=new Set(c.state.entries.map(S=>Ln(S.name))),f=new Set(d.state.entries.map(S=>Ln(S.name))),p=[...new Map(i.loaded.filter(S=>!(S.layer==="project"?m:f).has(Ln(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,b)=>{let N=`${S.layer}:${S.name}`,A=`${b.layer}:${b.name}`;return N.localeCompare(A)}),h=p.map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),_=p.filter(S=>tc(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=p.filter(S=>!tc(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],E=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...o.warnings],k=Er(E),x=Sr(),D=t_(E,i.failed.length,s.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,_,w);return{check:{name:"extensions",status:E.length===0?"ok":"warn",ok:E.length===0,details:{...i,loaded:a,warnings:E,activation:u,author_manifest:r,triage:D,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:k,host_version_census:o}},warnings:E}}function rc(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=wm(e,Xh);return{values:n.values,truncated:n.truncated,total:e.length}}function ba(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function EA(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return rA.has(e)?e:null}function ka(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function n_(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e.split(`
65
+ `)){let s=o.trim();if(s.length!==0){r+=1;try{let c=JSON.parse(s);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,a=Math.max(a,d),d>=Zh&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:a}}function SA(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function xA(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function AA(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||fo().telemetry_disabled?void 0:{attempted:!0,...await r_(n)}}function IA(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,a=n.last_failed_flush_at,o=a&&(!i||a>i),s=!i,c=t.validEntries>=sA;return(o||s||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function RA(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function CA(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>ru?[`telemetry_schema_version_behind:${t}`]:[]}function TA(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function $A(){return{...fo(),pm_no_telemetry:ba("PM_NO_TELEMETRY"),telemetry_otel_disabled:ba("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:ba("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:EA()}}function OA(e,t){return e.telemetry.enabled&&t.validEntries>0}function DA(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function r_(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(oA)});return{probe_url:ka(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of cA){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:ka(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function PA(e,t){let n=Br(process.cwd()),r=Ee.join(n,iA),i=Ee.join(n,aA),a=await J(r),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?n_(a):SA(),d=await J(i),{runtimeState:l,stateParseFailed:u}=xA(d),m=e.telemetry.endpoint.trim(),f=ka(m),p=await AA(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...IA(e,c,l),...RA(p),...CA(p),...TA(e,l));let _=OA(e,c),w=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:f,global_pm_root:n,queue_path:r,queue_exists:o,queue_entries:c.validEntries,queue_draining:DA(_,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Zh,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:$A()}},warnings:h}}async function NA(e){let t;try{t=await Um(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function LA(e){let t="metadata",n=e.items,r=await Xt(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),a=[],o=[];if(i.length>0){n=await ut(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Xt(e.pmRoot,n),a=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,E)=>v.localeCompare(E));let w=new Set(a);o=i.filter(v=>!w.has(v))}let{missingStreams:s,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:f,workspaceStateMissing:p,workspaceStateUnreadable:h}=r,_=[...s.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),...f.map(w=>`history_drift_workspace_state_mismatch:${w}`),...p.map(w=>`history_drift_workspace_state_missing:${w}`),...h.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:_.length===0?"ok":"warn",ok:_.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:a,resolved_false_positive_items:o,authoritative_item_source:i.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:s.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:p.length,workspace_state_unreadable:h.length},missing_streams:s,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:p,workspace_state_unreadable:h}},warnings:_}}function MA(e,t){let n=bi(e),r=Xn(n.settings),i=Si(n.settings,t),a=r.active?Jt(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(r.active&&i.active)}}function jA(){return{refreshed:[],skipped:[],warnings:[]}}async function FA(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?jA():Ql(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function UA(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&gn(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function HA(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function zA(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function i_(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:uo(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:uo(r,e.vector_store?.adapter??null)}}function GA(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function WA(e,t,n){return e.enabled&&n.length>0&&t}async function qA(e,t,n,r,i){let a=MA(t,e),o=await yn(e),s=a.semanticRuntimeAvailable?_o(n,o.entries):[],c=await FA({pmRoot:e,snapshot:a,refreshPolicy:r,staleBefore:s}),d=await yn(e),l=a.semanticRuntimeAvailable?_o(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=UA({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=HA({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=rc(s,i),h=rc(l,i),_=WA(r,a.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:a.semanticRuntimeAvailable,compatibility_mode_auto_defaults:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:a.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:a.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:GA(r),...i_(t,a),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:a.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Xh,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:zA(r,a.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:f}}function BA(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function a_(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new y("--check-only cannot be combined with --refresh-vectors",g.USAGE);if(n&&e.noRefresh===!0)throw new y("--no-refresh cannot be combined with --refresh-vectors",g.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var JA=new Set(["extensions","locks","search"]);function VA(e){let t=new Set(td.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(nd));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of JA)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,a)=>i.localeCompare(a)),optionalDirs:[...n].sort((i,a)=>i.localeCompare(a)),optionalDirSet:n}}async function KA(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:a}=VA(t),o=[],s=[],c=[];for(let d of[...r,...i]){let l=Ee.join(e,d);c.push(...await Ge({path:l,scope:"project"})),!await oc(l)&&(a.has(d)?s.push(d):o.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:o,missingOptionalDirs:s,missingDirs:n?[...o,...s]:[...o],hookWarnings:c}}function o_(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function YA(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?lt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):ut(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function ec(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function XA(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function ZA(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function QA(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var sc=e=>e.unknown_event_count??0,cc=e=>e.actionable_unknown_event_count??sc(e);function eI(e,t,n,r,i,a){let o=sc(r),s=cc(r),c=o>0,d=s>0,l=i.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...c?{author_attribution:r}:{},...l?{stale_in_progress:i}:{},...a.outcomes.length>0?{provenance_resolver_outcomes:a.outcomes}:{},...a.invalid_values.length>0?{provenance_invalid_values:a.invalid_values}:{},provenance_sample:a.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function s_(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function tI(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function nI(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function rI(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function c_(e){let t=new Map;for(let[r,i]of Object.entries(e.remediationSources))for(let a of i)t.has(a)||t.set(a,r);let n=new Map(e.checks.map(r=>[r.name,r]));return e.warnings.map(r=>{let i=t.get(r)??"integrity",a=Go(r)?.code??ac(r),o=n.get(i)?.details,s=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=a==="agent_guidance_outdated"?"pm init --agent-guidance add":a==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":s[a],d=ic(r,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:r,code:a,check:i,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function iI(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function aI(e){for(let t of e.checks){let n=Wo(e.remediationSources[t.name]);iI({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function oI(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),i=new Map;for(let o of e.pendingMergeReceipts){let s=i.get(o.item_id)??[];s.push(o),i.set(o.item_id,s)}let a=[];for(let o of n){if(r.has(o))continue;let s=i.get(o);if(!(!s||s.length===0))try{await Zs(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:s}},e.global),a.push(o)}catch{}}return[...new Set(a)].sort((o,s)=>o.localeCompare(s))}function sI(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function d_(e,t={}){let n=L(process.cwd(),e.path);await ne(n);let r=zt(n),{settings:i,warnings:a}=await wl(n),o=[...new Set(a)],s=G(i,H()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=a_(t),m=await KA(n,s,c),f=BA(i),p=await PA(i,{checkTelemetry:t.checkTelemetry===!0}),h=await kA(n,i,!!e.noExtensions),_=o_(t),w=[],v=await YA({pmRoot:n,settings:i,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),E=v,k=Ui(ge(i.schema),v),x=[...(await Cm({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(pe=>pe.startsWith("agent_guidance_")),...f,...Hi(k)],D=_.skipDrift?{warnings:[]}:await Cl({pmRoot:n,settings:i,itemIds:v.map(pe=>pe.id),commandLabel:"health"}),S=await uA(n,i.history.compact_policy,await dA(n)),b=await ar(n,20,t.verboseAuthorEvents===!0),N=cc(b),A=N>0?[`history_unknown_author_events:${N}`]:[],R=s_(await tu(n,v,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),Q=await fm(n),Ae=Q.warnings,we=await NA(n),_e=_.skipIntegrity&&!l?{...ec("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await hA(n,s.type_to_folder,i.schema,i,l,v),ze=_.skipDrift?ec("history_drift"):await LA({pmRoot:n,items:E,settings:i,typeRegistry:s,itemReadWarnings:w}),Ur=[...new Set(w)],Wn=await oI({gitWorkspaceRoot:_e.gitWorkspaceRoot,pendingMergeReceipts:_e.pendingMergeReceipts,historyDriftCheck:ze,global:e});sI(ze,Wn);let z=_.skipVectors?ec("vectorization"):await qA(n,i,E,u,t.verboseStaleItems===!0),B=[XA(r,i,o),ZA(m,c),QA(x,k),p.check,h.check,eI(v,i,S,b,R.scan,Q),we.check,_e.check,ze.check,z.check],Hr=tI({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:Ur,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:D.warnings,historySummary:S,authorAttributionWarnings:A,staleInProgressWarnings:R.warnings,provenanceWarnings:Ae,locksCheck:we,integrityCheck:_e,historyDriftCheck:ze,vectorizationCheck:z}),zr=rI({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:Ur,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:D.warnings,historySummary:S,authorAttributionWarnings:A,staleInProgressWarnings:R.warnings,provenanceWarnings:Ae,locksCheck:we,integrityCheck:_e,historyDriftCheck:ze,vectorizationCheck:z});aI({checks:B,remediationSources:zr,historyDriftedCount:nI(ze),overThresholdCount:S.over_threshold.length});let Ha=Hr.filter(pe=>!ic(pe,l)),za=c_({warnings:Hr,checks:B,remediationSources:zr,requireMergeDrivers:l}),ay=new Set(za.filter(pe=>pe.severity==="gate_failing").map(pe=>pe.check)),oy=new Set(za.map(pe=>pe.check));for(let pe of B)pe.ok=!ay.has(pe.name),oy.has(pe.name)&&(pe.status="warn");let sy={ok:Ha.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Ha.length>0?g.GENERIC_FAILURE:0},checks:B,warnings:Hr,findings:za,failed_because:Ha,generated_at:$()};return jo(sy,t,_.summaryMode)}var _H={buildHierarchyIntegrityWarnings:e_,buildExtensionHealthTriageSummary:t_,buildHealthFindings:c_,buildCapabilityContractMetadata:Sr,buildStaleInProgressHealthSummary:s_,buildVectorizationProviderDetails:i_,collectUnknownCapabilityGuidance:Er,isAdvisoryHealthWarning:ic,isDirectory:oc,isExpectedUnmanagedExtension:tc,listItemDocumentPaths:Qh,normalizeEndpointForDisplay:ka,normalizeExtensionNameForMatch:Ln,parseTelemetryQueue:n_,probeTelemetryEndpointHealth:r_,projectHealthResult:jo,resolveActionableUnknownAuthorEventCount:cc,resolveHealthSkipPolicy:o_,resolveUnknownAuthorEventCount:sc,resolveVectorRefreshPolicy:a_,selectStaleItemDetail:rc,summarizeHealthCheckDetails:Lo,summarizeExtensionList:sr,summarizeRecordList:We,summarizeStringList:q,telemetryEnvFlagEnabled:ba,warningCode:ac};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a07d2f98-7c1d-5d0a-be70-5181ed0f7b4f")}catch{}})();function l_(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!du(e,t).ok)return{reason:"unverified_history"};let r=li(),i={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(r.metadata.status));r=$l(r,o.patch,a+1,o.op),n.has(String(r.metadata.status))?s||(i=["create","close","cancel","update","update_audit"].includes(o.op)&&Rt(o.ts)?{timestamp:o.ts,source_index:a+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function u_(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function m_(e,t,n,r,i){let a=u_(n),o=t.filter(d=>a.has(d.status)&&!d.closed_at),s=[],c=[];for(let d of r?o:[]){let l;try{let u=await dt(Gt(e,d.id),d.id),{body:m,...f}=d;l=l_(u,{metadata:f,body:m},a)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}s.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:o.length,missing_closed_at_item_ids:o.slice(0,i).map(d=>d.id),missing_closed_at_item_ids_truncated:o.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:s.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:s,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function p_(e,t){let n=L(process.cwd(),t.path),r=await T(n),i=ge(r.schema);await mt({pmRoot:n,settings:r,id:e.item_id,op:"update",author:W(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(a){if(a.metadata.closed_at)return{changedFields:[]};let o=await dt(Gt(n,a.metadata.id),a.metadata.id),s=u_(i),c=l_(o,a,s);if(!("timestamp"in c)||c.timestamp!==e.value)throw new y("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",g.GENERIC_FAILURE);return a.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function cI(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function f_(e){return`${e.item_id} ${e.link_kind}`}function h_(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=cI(i.classification,r.classification),i.owners.set(f_(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[f_(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(a=>{let o=t(a.item_id);return{id:a.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:a.link_kind}}).sort((a,o)=>{let s=a.id.localeCompare(o.id);return s!==0?s:a.field.localeCompare(o.field)})}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00f8052d-480b-5e38-86cf-4574a8ad1e92")}catch{}})();function __(e,t,n,r,i=40){let a=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,o=new Map(t.map(d=>[d.path,d])),s={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=h_(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=si(f.status,r)??f.status;r.terminal_statuses.has(p)?(u.push(f),p===r.close_status&&(s.legacy_closed_missing_linked_links_count+=1)):l.push(f)}s.missing_linked_links_count+=d.items.length,s.active_missing_linked_links_count+=l.length,s.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(s.active_missing_linked_paths_count+=1);let m=o.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,a),items_truncated:d.items.length>a}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),s.missing_linked_path_rows_count=c.length,s.missing_linked_path_rows=c.slice(0,a),s.missing_linked_path_rows_truncated=c.length>a,s}import Mn from"node:fs/promises";import jn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function dI(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let a;try{a=await Mn.readdir(jn.join(e,i))}catch{return}for(let o of a)for(let s of Bn)if(o.toLowerCase().endsWith(s)){r.push({relativePath:`${i}/${o}`,id:o.slice(0,-s.length)});break}})),r.sort((i,a)=>i.relativePath.localeCompare(a.relativePath))}function lI(e,t){let{id:n,relativePath:r,liveItemIds:i,out:a}=e,o=je(t);if(o){a.conflictMarkers.push({id:n,path:r,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=uI(e,t);s!==null&&(s.op==="delete"&&i.has(n)&&a.resurrected.push({id:n,deleted_at:typeof s.ts=="string"?s.ts:"",deleted_by:typeof s.author=="string"?s.author:""}),s.op==="history_repair"&&Array.isArray(s.patch)&&s.patch.length>0&&(a.repairReconciliations+=1))}function uI(e,t){let{id:n,relativePath:r,out:i}=e,a=null,o=!1,s=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of s){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");a=d}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(a.op==="create"){if(o)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return a}function dc(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function mI(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Mn.readdir(jn.join(e,"history"))}catch{return n}for(let i of r.sort((a,o)=>a.localeCompare(o))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let a;try{a=await Mn.readFile(jn.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:dc("history stream",o)});continue}lI({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},a)}return n}function g_(e){let t=je(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function pI(e){let t=[],n=0,r=null;try{r=await J(zt(e))}catch(a){n+=1,t.push({path:"settings.json",detail:dc("configuration file",a)})}if(r!==null){n+=1;let a=g_(r);a!==null&&t.push({path:"settings.json",detail:a})}let i;try{i=await Mn.readdir(jn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let a of i.sort((o,s)=>o.localeCompare(s))){if(!a.endsWith(".json"))continue;n+=1;let o;try{o=await Mn.readFile(jn.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:dc("configuration file",c)});continue}let s=g_(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function y_(e,t,n,r={}){let i=await dI(e,n),a=new Set(i.map(u=>u.id)),o=new Map;for(let u of i){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let s=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=jn.join(e,u.relativePath);return Ct(await Mn.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await mI(e,a),l=await pI(e);return{item_files_on_disk:i.length,item_ids_on_disk:a.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:s,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import Lc from"node:fs/promises";import{realpathSync as IR}from"node:fs";import{execFile as RR}from"node:child_process";import xe from"node:path";import{promisify as CR}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();var fI=["metadata","resolution"],lc=["metadata","resolution","estimates","timestamps","lifecycle"],hI="completed";function uc(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function w_(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function v_(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=w_(n.close_reason)??hI;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${uc(r)}`,gate:"resolution"})}return t}function b_(e){let t=[];for(let n of e){let r=w_(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${uc(r)}`,gate:"metadata"})}return t}function k_(e,t){return e.map(n=>{let r=yl(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function E_(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function S_(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${uc(n.path)}`})}return t}function x_(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new y(`--fix-scope values must not be empty. Supported values: ${lc.join(", ")}.`,g.USAGE);return new Set(fI)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(lc.includes(i)){n.add(i);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${lc.join(", ")}.`,g.USAGE)}return n}function A_(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function $r(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();var _I=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function gI(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=_I.exec(n);if(!r)return null;let i=r[1],a=i.toUpperCase(),o=i.slice(0,i.lastIndexOf("-")),s=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${a}`)||d.includes(`ISSUE CODE \`${a}\``)||d.includes(`\`${a}\``)||d.includes(`[${a}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||s.has(o.toUpperCase())||l?a:null}function I_(e){return typeof e=="string"&&e.trim().length>0}function yI(e){let t=new Set(e.map(o=>o.id.toLowerCase())),n=new Map,r=new Map;for(let o of e){let s=o.id.toLowerCase(),c=new Set([...o.parent===null?[]:[o.parent.toLowerCase()],...o.derivations].filter(d=>d!==s&&t.has(d)));n.set(s,c);for(let d of c){let l=r.get(d)??[];l.push(s),r.set(d,l)}}let i=[...[...n].filter(([,o])=>o.size===0).map(([o])=>o)],a=new Set;for(let o=0;o<i.length;o+=1)for(let s of r.get(i[o])??[]){let c=n.get(s);c.delete(i[o]),c.size===0&&(a.add(s),i.push(s))}return e.filter(o=>!a.has(o.id.toLowerCase()))}function R_(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||I_(i.duplicate_of))continue;let a=gI(i.title,{...t,evidenceText:i.body});if(a===null)continue;let o=n.get(a);o||(o=[],n.set(a,o)),o.some(s=>s.id===i.id)||o.push({id:i.id,title:i.title,parent:I_(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(s=>["discovered_from","supersedes","incident_from"].includes(s.kind)).map(s=>s.id.trim().toLowerCase()).filter(s=>s!==i.id.toLowerCase())})}let r=[];for(let[i,a]of n){if(a.length<2)continue;let o=yI(a);if(o.length<2)continue;let s=[...o].sort((c,d)=>c.id.localeCompare(d.id));r.push({code:i,count:s.length,ids:s.map(c=>c.id),titles:s.map(c=>c.title)})}return r.sort((i,a)=>i.code.localeCompare(a.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c32504d-254c-5156-a41f-8ffd8e49107f")}catch{}})();function C_(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,a)=>i.localeCompare(a))){let i=t.get(r),a={};for(let o of[...i.keys()].sort((s,c)=>s.localeCompare(c)))a[o]=i.get(o);n[r]=a}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c577e41b-6642-554a-bc4d-0c22170c1e24")}catch{}})();function T_(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function $_(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let a of t){let o=T_(a);if(o.length===0)continue;let s=i.get(o);s?s.push(a):i.set(o,[a])}return e.map(a=>{if(a.includes(",")||a.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:a,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(i.get(T_(a))??[]).filter(s=>s!==a).sort((s,c)=>s.localeCompare(c));return o.length===0?{path:a,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:a,classification:"moved",candidates:o.slice(0,r),candidates_truncated:o.length>r}})}function O_(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var wI=/^[a-z][a-z0-9+.-]+:\/\//i;function Or(e){return wI.test(e.trim())}import vI from"node:fs/promises";import Se from"node:path";import{glob as bI}from"tinyglobby";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="12655e94-6304-56cf-9f5d-387a26572db0")}catch{}})();var kI=["path","scope","note"],EI=["pattern","glob","path","scope","note"],SI=["path"],xI=["from","to"],AI=new Set(["note","scope"]);function P_(e){let t=e??"project";if(!Ga.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${Ga.join(", ")} (default: project).`,g.USAGE);return t}function mc(e){if(e.startsWith("```")||e.includes(`
66
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||Sl(e)}function II(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function RI(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!mc(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let a=e.slice(t+2,-1).trim();if(a.length>0&&II(a))return{path:a,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function CI(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let a=RI(r);if(a!==void 0)return[a]}xl(r,"--add",`${t} path`,mc(r));let i=mc(r)?Kn(n,"--add"):{path:r};if(Yn(i,"--add",kI),!i.path)throw new y(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return[{path:i.path,scope:P_(i.scope),note:i.note?.trim()||void 0}]}):[]}function TI(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=Kn(n,"--add-glob");Yn(r,"--add-glob",EI);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new y("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:i,scope:P_(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function $I(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=Kn(n,"--remove"),i=Object.keys(r).filter(a=>AI.has(a.toLowerCase()));if(i.length>0)throw new y(`--remove identifies a linked artifact by path only and does not accept ${i.map(a=>`"${a}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,g.USAGE);if(Yn(r,"--remove",SI),!r.path)throw new y("--remove key/value form requires path=<value>",g.USAGE);return r.path}return n}):[]}function OI(e){return e?e.map(t=>{let n=Kn(t,"--migrate");Yn(n,"--migrate",xI);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new y("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:r,to:i}}):[]}function Dr(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function DI(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(a=>Dr(a.path,n))),i=[...new Set(t.map(a=>Dr(a,n)).filter(a=>r.has(a)))].sort((a,o)=>a.localeCompare(o));if(i.length!==0)throw new y(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,g.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function xt(e){return e.split(Se.sep).join("/")}function pc(e,t,n=process.cwd()){let r=e.trim();if(Or(r))return r;if(Se.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return xt(r.replaceAll("\\",Se.sep));let i=Se.relative(t,n);return i.startsWith(`..${Se.sep}`)||i===".."||Se.isAbsolute(i)?xt(Se.normalize(r)):xt(Se.relative(t,Se.resolve(n,r)))}async function PI(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){if(Se.resolve(n,i.pattern)===Se.resolve(n))continue;let a=Se.isAbsolute(i.pattern),o=await bI(i.pattern,{cwd:n,absolute:a,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),s=[...new Set(o.map(c=>pc(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of s)r.push({path:c,scope:i.scope,note:i.note})}return r}function NI(e,t,n){if(t===void 0)return e;if(!n)throw new y("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",g.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function LI(e){return`${e.path}::${e.scope}`}function fc(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function hc(e){return[...new Map(e.map(t=>[LI(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function MI(e,t=process.cwd()){let n=[...new Set(e)].sort((s,c)=>s.localeCompare(c)),r=[],i=[],a=[],o=[];for(let s of n){if(Or(s)){o.push(s.trim());continue}let c=Se.isAbsolute(s)?s:Se.resolve(t,s);try{(await vI.stat(c)).isFile()?r.push(s):a.push(s)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&At(d)){i.push(s);continue}a.push(s)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:a,remote_references:o}}function jI(e,t,n,r){let i=0;for(let a=0;a<e.length;a+=1){let o=Dr(e[a].path,r);o!==e[a].path&&(e[a]={...e[a],path:o},i+=1)}return{adds:t.map(a=>{let o=Dr(a.path,r);return o!==a.path&&(i+=1),{...a,path:o}}),removes:n.map(a=>Dr(a,r)),count:i}}function FI(e,t,n,r){let i=hc(e);for(let a of t){let o=i.findIndex(s=>s.path===a.path&&s.scope===a.scope);o<0?i.push(a):a.note!==void 0&&(i[o]={...i[o],note:a.note})}if(n.length>0)for(let a=i.length-1;a>=0;a-=1)n.includes(i[a].path)&&i.splice(a,1);return r?i:fc(i)}async function D_(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await MI(t,e.workspaceRoot):void 0}}async function Ea(e,t,n,r){let{metadataKey:i}=r,a=Rl(),o=L(process.cwd(),n.path),s=Ye(o),c=process.cwd();await ne(o);let d=await T(o),l=G(d,H()),u=await a.resolveList(t.add,"--add"),m=await a.resolveList(t.addGlob,"--add-glob"),f=await a.resolveList(t.remove,"--remove"),p=await a.resolveList(t.migrate,"--migrate"),h=CI(u,r.bareNoun).map(A=>({...A,path:pc(A.path,s,c)})),_=TI(m),w=await PI(_,s,c),v=NI([...h,...w],t.note,h.length>0||_.length>0),E=$I(f).map(A=>pc(A,s,c)),k=OI(p);if(DI(v,E,k),!(v.length>0||E.length>0||k.length>0)){let A=await ve(o,e,d.id_prefix,d.item_format,l.type_to_folder);if(!A)throw new y(`Item ${e} not found`,g.NOT_FOUND);let R=(await be(A,{schema:d.schema})).document.metadata[i]??[];return D_({id:A.id,artifacts:R,changed:!1,options:t,workspaceRoot:s})}let x=W(t.author,d.author_default),D=await mt({pmRoot:o,settings:d,id:e,op:r.op,author:x,message:t.message,force:t.force,skipNoop:!0,mutate(A){let R=A.metadata,Q=R[i]??[],Ae=[...Q],we=jI(Ae,v,E,k),_e=FI(Ae,we.adds,we.removes,r.supportsAppendStable&&t.appendStable===!0);_e.length>0?R[i]=_e:delete R[i];let ze=!fd(Q,_e);return{changedFields:ze?[i]:[],warnings:ze&&we.count>0?[`path_migrations_applied:${we.count}`]:[]}}}),S=D.item[i]??[],b=D.warnings.find(A=>A.startsWith("path_migrations_applied:")),N=b?Number(b.slice(24)):0;return D_({id:D.item.id,artifacts:S,changed:D.changedFields.includes(i),migrationsApplied:N,options:t,workspaceRoot:s})}function Sa(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="79f1acaf-8ef7-5725-900a-fbeced1c57e6")}catch{}})();async function N_(e,t,n){let r=await Ea(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Sa(r,"docs")}import L_ from"node:fs/promises";import He from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="06b0bd73-d282-5473-a1da-f11c61a0a086")}catch{}})();var UI=32768;function _c(e){return xt(He.normalize(e))}async function xa(e){try{return await L_.realpath(e)}catch{return He.resolve(e)}}function Fn(e,t){let n=He.isAbsolute(e.path)?He.resolve(e.path):He.resolve(t,e.path);return`${_c(n)}::${e.scope}`}function Aa(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>Aa(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))Aa(i,t?`${t}.${r}`:r,n)}function HI(e){let t=[];return Aa(e.metadata,"metadata",t),Aa(e.body,"body",t),t}function zI(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function GI(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let a=new Set,o=i.value.slice(0,UI);for(let[s,c]of[[n,i.value],[r,o]]){s.lastIndex=0;for(let d of c.matchAll(s)){let l=zI(d[0]);!l||a.has(l)||(a.add(l),t.push({field:i.field,value:l}))}}}return t}async function WI(e,t,n=t){let r=He.isAbsolute(e)?He.resolve(e):He.resolve(n,e),i;try{i=await L_.stat(r)}catch{return}if(!i.isFile())return;let[a,o]=await Promise.all([xa(t),xa(r)]);if(fe(a,o)){let s=He.relative(a,o);return!s||s.startsWith("..")||He.isAbsolute(s)?void 0:{path:_c(s),scope:"project"}}return{path:_c(r),scope:"global"}}async function qI(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>Fn(c,t))),i=new Map,a=GI(HI(e)),o=new Map;await Promise.all([...new Set(a.map(c=>c.value))].map(async c=>{o.set(c,await WI(c,t,n))}));let s=a.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:d}of s){if(!d)continue;let l=Fn(d,t),u=i.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function M_(e,t,n){let r=await Ea(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Sa(r,"files")}async function BI(e,t){let n=await xa(t),r=await Promise.all(e.map(async a=>{let o=a.trim();if(!o)throw new y("Files lookup paths must not be empty.",g.USAGE);if(!He.isAbsolute(o))return xt(o);let s=await xa(o);return fe(n,s)?xt(He.relative(n,s)):xt(s)})),i=[...new Set(r)].sort((a,o)=>a.localeCompare(o));if(i.length===0)throw new y("Files lookup requires at least one path.",g.USAGE);return i}function JI(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new y(`Files lookup ${r} must be a non-negative integer.`,g.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function j_(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function F_(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function VI(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(xt(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(F_)}async function KI(e){if(e.explain)return Qu({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function YI(e){if([e.strictRead,e.noTruncate,e.explain,qd()].includes(!0))return null;let t=await ki(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Fl({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function XI(e){let t=[],n=await Ei(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=VI({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(s=>/^item_list_(?:item|directory)_read_failed:/u.test(s));if(e.strictRead&&i.length>0)throw new y(`Files lookup could not read every item: ${i.join("; ")}`,g.GENERIC_FAILURE);let a=await KI({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),o=(a?[...r].sort((s,c)=>{let d=a.explanations.get(c.item.id).score-a.explanations.get(s.item.id).score;return d!==0?d:F_(s,c)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:o.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+o.length<r.length,truncated:e.offset+o.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:o.map(s=>({item:j_(s.item),files:s.files,...a?{traceability:a.explanations.get(s.item.id)}:{}})),...a?{traceability_receipt:a.receipt}:{}}}async function Tz(e,t){let n=L(process.cwd(),t.path),r=Ye(n);await ne(n);let i=await BI(e.paths,r);if(e.lineRange&&i.length!==1)throw new y("Files lookup line attribution requires exactly one source path.",g.USAGE);let a=await T(n),o=G(a,H()),{offset:s,limit:c}=JI(e),d=await YI({pmRoot:n,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:s,limit:c,has_more:s+d.matches.length<d.total,truncated:s+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:j_(l.item),files:l.files}))}:XI({pmRoot:n,settings:a,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function $z(e,t,n){let r=L(process.cwd(),n.path),i=Ye(r);await ne(r);let a=await T(r),o=G(a,H()),s=await ve(r,e,a.id_prefix,a.item_format,o.type_to_folder);if(!s)throw new y(`Item ${e} not found`,g.NOT_FOUND);let c=await be(s,{schema:a.schema}),d=await qI(c.document,i,process.cwd()),l=d.filter(b=>b.status==="addable"),u=d.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let b=c.document.metadata.files??[];return{id:s.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let p=W(t.author,a.author_default),h=l.map(b=>({path:b.path,scope:b.scope,note:f})),_=[],w=new Set,v=await mt({pmRoot:r,settings:a,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let N=[...b.metadata.files??[]],A=new Set(N.map(Ae=>Fn(Ae,i)));_=[],w.clear();for(let[Ae,we]of h.entries()){let _e=Fn(we,i);A.has(_e)||(N.push(we),A.add(_e),_.push(we),w.add(Ae))}let R=hc(N),Q=t.appendStable?R:fc(R);return Q.length>0?b.metadata.files=Q:delete b.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==h.length?[`files_discover_skipped_existing:${h.length-_.length}`]:[]}}}),E=v.item.files??[],k=new Set(_.map(b=>Fn(b,i))),x=E.filter(b=>k.has(Fn(b,i))),D=l.filter((b,N)=>!w.has(N)),S=[...u,...D];return{id:v.item.id,files:E,changed:x.length>0,apply:!0,count:E.length,candidate_count:d.length,addable_count:l.length,added_count:x.length,skipped_existing_count:S.length,candidates:d,added:x,skipped_existing:S}}import{readFileSync as ZI}from"node:fs";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]="597a781e-a00d-5083-8d57-3fae870f9ccd")}catch{}})();var QI=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),gc=new Set(["--pm-path","--path","--author"]),eR={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},tR=new Set(["-p","--package"]),nR=new Set(["-c","--call"]),rR=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),iR=new Set(["-C","--prefix","--userconfig","--cache"]),Nz=new Set(["--cwd"]),Lz=new Set(["--cwd"]),aR=new Set(["exec","x"]),Mz=new Set(["run","run-script"]),jz=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function oR(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function sR(e,t=process.cwd()){let n=cR(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[r,...i]=n;if(U_(r)||H_(r,t))return i;if(r==="node"&&i[0]&&H_(i[0],t))return i.slice(1);let a=r==="npx"||r==="bunx"?yc(i):r==="pnpm"?uR(i):r==="npm"?mR(i):null;return a&&(U_(a.command)||lR(a.command))?a.args:null}var z_=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let a=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let s of oR(a)){let c=sR(s),d=c?pR(c):null,l=d&&QI.has(d.subcommand)?fR(d.remaining,eR[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&o.add(l)}return[...o].sort((s,c)=>s.localeCompare(c))};function cR(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Fz(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(gc.has(n)){t+=2;continue}t+=1;continue}return n}}function U_(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function dR(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function lR(e){let t=dR(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function H_(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=Ia.resolve(t,e);try{return JSON.parse(ZI(Ia.join(Ia.dirname(Ia.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function yc(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let a=i[1];return a?{command:a,args:e.slice(t+1)}:null}if(nR.has(r)){t+=1;break}t+=tR.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function G_(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function uR(e){let t=G_(e,rR);return t?.subcommand!=="dlx"?null:yc(t.args)}function mR(e){let t=G_(e,iR);return!t||!aR.has(t.subcommand)?null:yc(t.args)}function pR(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(gc.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function fR(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(gc.has(r)||t.has(r))&&(n+=1)}}import{execFile as _R}from"node:child_process";import{readFile as gR}from"node:fs/promises";import B_ from"node:path";import{promisify as yR}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]="4025e3fb-f2f2-57f1-a981-5bbb2381fe67")}catch{}})();function W_(e){if(!(e.pm_context_mode!=="none"||e.workspace_context_mode==="isolated"||e.workspace_context_mode==="snapshot"))throw new y("pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace.",g.USAGE,{code:"linked_test_context_invalid",required:"Set workspace_context_mode to isolated or snapshot when pm_context_mode is none.",examples:[Me(["test","<id>","--add-json",JSON.stringify({command:e.command,pm_context_mode:"none",workspace_context_mode:"isolated"})])]})}var wc=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],hR=new Set(wc);function qz(e){return El(e,wc)}function Bz(e,t){let n={},r=[];for(let[i,a]of Object.entries(e)){let o=i.toLowerCase();if(!hR.has(o)){r.push(i);continue}if(Object.hasOwn(n,o))throw new y(`${t} provides key "${i}" more than once after case normalization`,g.USAGE);n[o]=a}if(r.length>0)throw new y(`${t} does not recognize key${r.length>1?"s":""} ${r.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${wc.join(", ")}.`,g.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new y(`${t} command and cmd must match when both are provided`,g.USAGE);let{cmd:i,...a}=n;return{...a,command:a.command??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]="8f1a3301-8938-5208-9177-72ee29f3d174")}catch{}})();var wR=yR(_R),vc=1,vR="linked-test-trust.json";function bc(e){return B_.join(pd(e),vR)}function q_(){return{version:vc,acknowledged:{}}}async function kc(e){try{let t=JSON.parse(await gR(bc(e),"utf8"));return t.version!==vc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?q_():{version:vc,acknowledged:t.acknowledged}}catch{return q_()}}async function Ec(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await wR("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function Sc(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function bR(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Vd(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Pr(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function kR(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function rG(e,t,n){if(!e||e.length===0)return e;for(let i of e)W_(i);let r=Sc();return kR(e,t,n,await Ec(r))}function J_(e){return Ie(C({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function iG(e,t,n){let r=await kc(e);return V_(t,n,r)}function V_(e,t,n){let r=J_(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let a=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!bR(e.provenance)?a?{fingerprint:r,trusted:!0,reason:"acknowledged",...Pr(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...Pr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...Pr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:a?{fingerprint:r,trusted:!0,reason:"acknowledged",...Pr(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...Pr(i,t)}}async function K_(e,t,n){let r=await kc(e);return t.map(i=>V_(i,n,r))}async function aG(e,t,n){let r=await kc(e),i=t.filter(a=>typeof a.command=="string"&&a.command.length>0).map(J_);for(let a of i)r.acknowledged[a]={acknowledged_at:n};return await qn(B_.dirname(bc(e))),await Z(bc(e),`${JSON.stringify(r,null,2)}
67
+ `),{acknowledged:i.length,fingerprints:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8cca9707-86a7-5ab5-8c7b-92be560254d0")}catch{}})();async function Ra(e){return e.includeBody?ut(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Ei(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6322c4ff-92bd-59e5-aa64-ef8d3ef4b57f")}catch{}})();var ER=5;async function SR(e,t){let n=t.hashMismatches.filter(a=>a!==ce);if(n.length===0)return;let r=await T(e),i=G(r,H());for(let a of n){let o=await te(e,a,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let s=await ve(e,a,r.id_prefix,r.item_format,i.type_to_folder);if(s===null)throw new y(`Item ${a} not found`,g.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await be(s,{schema:r.schema});if(c.metadata.id!==a)throw new y(`Item identity changed while validating ${a}`,g.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await jm(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(m=>m!==a),...d[u].filter(m=>m===a)].sort((m,f)=>m.localeCompare(f));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==a),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===a)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await o()}}}async function Ca(e,t,n){let r=await Xt(e,t);await SR(e,r);let i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),a=n?Number.POSITIVE_INFINITY:ER,o=r.driftedItems.slice(0,a),s=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:s.length>0?"error":i.length===0?"ok":"warn",ok:s.length===0&&i.length===0,details:{identity_discontinuities:s.slice(0,a),identity_discontinuities_count:s.length,identity_discontinuities_truncated:s.length>a,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:o,drifted_items_truncated:o.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,a)}},warnings:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3caaa82b-d8c7-5bc4-94e5-6699da27fa3c")}catch{}})();function Ta(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],a=new Set([n]),o=s=>{for(let c of(t.get(s)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!a.has(c)){if(a.add(c),i.push(c),o(c))return!0;i.pop(),a.delete(c)}}return!1};return o(n)?[...i]:[...e,n]}function xR(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function AR(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let a=r.resolve(i.kind);if(!a?.hierarchy)continue;let o=n.get(i.id.toLowerCase());o&&(a.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function xc(e,t=Zn()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((a,o)=>a.id.localeCompare(o.id))){let a=r.get(i.id),o=xR(i.parent,n);o&&a.push(o),AR(i,r,n,t)}for(let[i,a]of r)r.set(i,[...new Set(a)].sort());return r}function Ac(e,t,n=Zn()){let r=xi(e,o=>t?Md(o,t):o==="closed"||o==="canceled",n),i=xc(e,n),a=r.cycles.map(o=>o.item_ids);return{cycle_count:a.length,active_cycle_count:r.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(a.flat())].sort(),cycle_sample_paths:a.map(o=>Ta(o,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:r.divergences.map(o=>`${o.child_id}:scalar=${o.scalar_parent_id}:dependencies=${o.dependency_parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2840c80-38f5-5563-b2c0-ef5596cf8f62")}catch{}})();function Ut(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Ic(e){return Ut(e).replace(/\/+$/,"")}function Ve(e){let t=ee(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Rc(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9ef196b2-3eef-5bac-b949-bcb3e947c44d")}catch{}})();var TR=["src","tests","docs"],$R=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],OR=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),DR=["resolution","expected_result","actual_result"],PR=["default","tracked-all","tracked-all-strict"],Y_=["core","strict","custom"],Da=["off","warn","error"],$c=["author","acceptance_criteria","estimated_minutes","close_reason"],Q_=[...$c,"reviewer","risk","confidence","sprint","release"],Oc=Array.from(new Set(Q_)),NR={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},LR={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},MR={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},jR={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},FR={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},UR=32*1024*1024,HR=1e4,Dc=40,Ke=5,zR=4096,GR=255,WR=CR(RR);function eg(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?eg(r):r);return t}function qR(e){return{...e,checks:e.checks.map(t=>({...t,details:eg(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function Na(e,t){return si(e,t)??e}function Nr(e,t){return t.terminal_statuses.has(Na(e,t))}function Ht(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function $a(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function BR(e){let t=Ht(rd),n={blocked_reason:Ht(qr.blocked_reason),resolution:Ht(qr.resolution),actual_result:Ht(qr.actual_result)},r=Ht(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:Ht(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Ht(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Ht(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:$a(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:$a(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:$a(i.resolution,n.resolution)?"default":"settings",actual_result:$a(i.actual_result,n.actual_result)?"default":"settings"}}}function tg(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Y_.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${Y_.join(", ")}.`,g.USAGE)}function ng(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Da.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Da.join(", ")}.`,g.USAGE)}function rg(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Da.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Da.join(", ")}.`,g.USAGE)}function JR(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>NR[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function VR(e,t,n){let r=JR(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...$c],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Q_],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...$c],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var KR=new Set(["acceptance_criteria","estimated_minutes"]);function ig(e,t,n,r){return!r&&KR.has(t)&&Nr(e.status,n)?!1:t==="author"?!ee(e.author):t==="acceptance_criteria"?!ee(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Na(e.status,n)===n.close_status&&!ee(e.close_reason):t==="reviewer"?!ee(e.reviewer):t==="risk"?!ee(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!ee(e.confidence):t==="sprint"?!ee(e.sprint):!ee(e.release)}function ag(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new y(`Unknown --scan-mode value "${e}". Supported values: ${PR.join(", ")}.`,g.USAGE)}function og(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return xe.resolve(t);let n=xe.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return xe.dirname(xe.dirname(n));let r=xe.resolve(process.cwd()),i=X_(n),a=X_(r),o=xe.relative(i,a);return o.length===0||!o.startsWith("..")&&!xe.isAbsolute(o)?n:r}function X_(e){try{return IR.native(e)}catch{return xe.resolve(e)}}function YR(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Mc(e,t,n){let r=t.length>0?xe.join(e,t):e,i;try{i=await Lc.readdir(r,{withFileTypes:!0})}catch(a){if(F(a))return;throw a}for(let a of i){if(a.name.startsWith("."))continue;let o=t.length>0?xe.join(t,a.name):a.name;if(a.isDirectory()){if(OR.has(a.name))continue;await Mc(e,o,n);continue}a.isFile()&&n.push(Ut(o))}}async function Pc(e){let t=[];for(let n of TR)await Mc(e,n,t);for(let n of $R){let r=xe.join(e,n);try{(await Lc.stat(r)).isFile()&&t.push(Ut(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function sg(e){try{let{stdout:t}=await WR("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:UR,windowsHide:!0,timeout:HR}),n=t.split("\0").map(r=>Ut(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function XR(e,t){let n=new Set,r=Ic(ed);r.length>0&&n.add(r);let i=Ic(xe.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((a,o)=>a.localeCompare(o))}function Z_(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function ZR(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await sg(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Pc(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Pc(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ae(e,t=Ke){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function an(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ae(e,Dc);return{values:n.values,truncated:n.truncated,total:e.length}}var QR={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},eC={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function tC(e){let t=e.missing_fields.map(n=>`${QR[n]} "${eC[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function cg(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(o=>typeof o=="string"):zm(t);if(i.length===0)return;let a=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...a?{fix_hints_truncated:!0}:{}}}function dg(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var nC="validate_metadata_duplicate_issue_codes";function lg(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Ke,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${nC}:${e.length}`]}}function rC(e,t,n){let r=Object.fromEntries(Oc.map(i=>[i,[]]));for(let i of e)for(let a of Oc)ig(i,a,t,n)&&r[a].push(i.id);return r}function iC(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let a=t[i];a.length>0&&r.push(`${LR[i]}:${a.length}`)}return r.push(...n),r}function ug(e,t){let n={};for(let r of e.required_fields){let i=t[r],a=i?i.length:0,o=MR[r];n[o]=a}return n}function mg(e,t,n){let r=[];for(let i of e.required_fields){let a=t[i];if(a)for(let o of a){let s=n.get(o)?.type,c=typeof s=="string"&&s.length>0?s:"Unknown";r.push({item_type:c,field:i})}}return r}function aC(e,t,n,r){for(let i of t.required_fields){let a=n[i];if(!a||a.length===0)continue;let o=jR[i],s=FR[i];if(!o||!s)continue;let c=ae(a,r?a.length:Ke);e[o]=c.values,e[s]=c.truncated}}function pg(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:ee(n.get(i)?.resolution)})):[]}function fg(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:ee(n.get(i)?.type)})):[]}function oC(e,t,n,r,i){let a=new Map(e.map(w=>[w.id,w])),o=t.profile==="strict",s=rC(e,n,o),c=R_(e,{configuredPrefixes:i}),d=lg(c,r),l=iC(t,s,d.warnings),u=ug(t,s),m=mg(t,s,a),f=C_(m),p={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...Oc],counts:u,missing_by_type:f,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(p.configured_custom_required_fields=[...t.configured_custom_fields]),aC(p,t,s,r);let h=pg(t,s,a),_=fg(t,s,a);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:p},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:_}}function sC(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Na(m.status,t))),a=[],o=[];for(let m of i){let f=DR.filter(p=>!ee(m[p]));f.length!==0&&(a.push({id:m.id,missing_fields:f}),o.push({id:m.id,missing_fields:f,close_reason:ee(m.close_reason)}))}let s=a.length>0?[`validate_resolution_missing_fields:${a.length}`]:[],c=n?Number.POSITIVE_INFINITY:Ke,d=ae(a.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=a.map(m=>tC(m)),u=ae(l,c);return{check:{name:"resolution",status:s.length===0?"ok":"warn",ok:s.length===0,details:{checked_closed_items:i.length,missing_resolution_items:a.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:s,resolutionBackfillRows:o}}function hg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _g(e,t="pm",n=od()){let r=new Set(e.map(a=>a.id)),i=[...e].sort((a,o)=>a.id.localeCompare(o.id));return new Map(i.map(a=>{let o=new Set,s=Ve(a.blocked_by);s&&r.has(s)&&o.add(s),(a.dependencies??[]).filter(d=>{let l=Ve(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ve(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>o.add(d));let c=Ve(a.definition_of_ready);return yg(c??"",t).filter(d=>r.has(d)).forEach(d=>o.add(d)),[a.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function gg(e,t,n){let r=au(e,n?l=>Nr(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),a=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:Ke,s=ae(i,o),c=ae(a,o),d=ae(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+a.length,active_dangling_reference_count:i.length,dangling_reference_rows:s.values,dangling_reference_rows_truncated:s.truncated,legacy_terminal_dangling_reference_count:a.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function yg(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${hg(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,a)=>i.localeCompare(a))}function wg(e){let t=0,n=new Map,r=new Map,i=[],a=new Set,o=[],s=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),a.add(d);for(let u of e.get(d)??[])n.has(u)?a.has(u)&&r.set(d,Math.min(r.get(d),n.get(u))):(s(u),r.set(d,Math.min(r.get(d),r.get(u))));if(r.get(d)!==n.get(d))return;let l=[];for(;i.length>0;){let u=i.pop();if(a.delete(u),l.push(u),u===d)break}l.sort((u,m)=>u.localeCompare(m)),o.push(l)},c=[...e.keys()].sort((d,l)=>d.localeCompare(l));for(let d of c)n.has(d)||s(d);return o.filter(d=>{if(d.length>1)return!0;let l=d[0];return(e.get(l)??[]).includes(l)}).sort((d,l)=>d[0].localeCompare(l[0])||d.length-l.length||d.join(",").localeCompare(l.join(",")))}function vg(e,t="pm"){let n=_g(e,t),r=wg(n),i=[...new Set(r.flat())].sort((o,s)=>o.localeCompare(s)),a=r.map(o=>Ta(o,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:a}}function bg(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function Pa(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function kg(e,t){let n=Pa(e).split("/").filter(Boolean),r=Pa(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function cC(e,t){let n=Pa(t),r=Pa(e),i=t.endsWith("/")?t:`${t}/`,a=e.startsWith(i),o=n.length>0&&n===r,s=kg(e,t);return!a&&!o&&s===0?null:a?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:s+500,confidence:"same_directory"}:{score:s,confidence:"shared_directory"}}function dC(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function lC(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(a=>(r==="docs"?a.docs??[]:a.files??[]).map(o=>({item:a,link:o}))).forEach(({item:a,link:o})=>{if(o.scope!=="project")return;let s=Ut(o.path);if(s.length===0||s===e)return;let c=cC(e,s);c!==null&&dC(i,a,c.score)&&(i={item:a,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function Eg(e,t){return e.map(n=>{let r=bg(n),i=r==="docs_unowned"?"docs":"files",a=lC(n,r,t),o=a?.id??"<id>";return{path:n,classification:r,owner_candidate:a,remediation_hint:`pm ${i} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Sg(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function uC(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Ve(e[n]);return i?r.some(a=>i.toLowerCase().includes(a)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function mC(e,t,n,r,i){let a=Ve(t.parent),o=a?n.get(r.get(a.toLowerCase())??a):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!Nr(o.status,i)}}function pC(e,t,n,r){let i=Ve(e.blocked_by),a=Ve(e.blocked_reason),o=a?.toLowerCase(),s=Na(e.status,n),c=[];return t.has(s)?(!i&&!a&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&r.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),a&&c.push("non_blocked_status_has_blocked_reason"),c)}function fC(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),a=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),s={activeItems:e.filter(c=>!Nr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of s.activeItems){let d=uC(c,r);d.length>0&&s.closureLikeRows.push({id:c.id,fields:d});let l=Ve(c.parent),u=l?i.get(a.get(l.toLowerCase())??l):void 0;if(u&&Nr(u.status,n)&&(s.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),s.terminalParentFixRows.push(mC(c,u,i,a,n))),t){let m=pC(c,o,n,r);m.length>0&&s.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,p)=>f.localeCompare(p))})}}return s}function hC(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function Oa(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Cc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function _C(e,t,n,r,i){let a=[];e.closureLikeRows.length>0&&a.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&a.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&a.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=Oa("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),s=Oa("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=Oa("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=Oa("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=Cc("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=Cc("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=Cc("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...a,...o?[o]:[],...s?[s]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function xg(e){let t=Ut(e);return t.length>zR||t.split(/[\\/]/).some(n=>n.length>GR)}async function gC(e,t){let n=xe.isAbsolute(t)?t:xe.resolve(e,t);if(xg(n))return!1;try{let r=await Lc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return YR(r,["ENOENT","ENOTDIR"])}}async function yC(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(a=>({item:i,artifact:a,link_kind:"files"})),...(i.docs??[]).map(a=>({item:i,artifact:a,link_kind:"docs"}))]);for(let{item:i,artifact:a,link_kind:o}of r){if(a.scope!=="project")continue;if(Or(a.path)){n.remoteLinkedPaths.add(a.path.trim());continue}let s=Ut(a.path);s.length!==0&&(n.linkedProjectPaths.add(s),await gC(t,a.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:i.id,path:s,link_kind:o})))}return n}function wC(e,t,n,r,i,a){let o=r==="tracked-all-strict",s=o&&!i,c=i||o,d=c?[]:XR(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>Z_(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Z_(f,d)),m={};if(l.length>0){let f=an(l,a);m.pm_internals={count:l.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:s,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function Ag(e,t,n,r,i,a,o,s="pm"){let c=fC(e,t,i,a);hC(c);let d=vg(c.activeItems,s),l=Ac(e,i),u=Ui(i,e,o?Number.POSITIVE_INFINITY:Ke),m=[..._C(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...Hi(u)],f=o?Number.POSITIVE_INFINITY:Ke,p=ae(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),f),h=ae(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),f),_=ae(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),f),w=ae(d.cycle_item_ids,f),v=ae(d.cycle_sample_paths,f),E=ae(l.cycle_item_ids,f),k=ae(l.cycle_sample_paths,f),x=ae(l.cardinality_violation_rows,f),D=ae(l.parent_divergence_rows,f),S=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:S?"error":m.length===0?"ok":"warn",ok:!S&&m.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:p.values,active_closure_like_metadata_rows_truncated:p.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:_.values,stale_blocker_rows_truncated:_.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:w.values,dependency_cycle_item_ids_truncated:w.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:E.values,parent_cycle_item_ids_truncated:E.truncated,parent_cycle_sample_paths:k.values,parent_cycle_sample_paths_truncated:k.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:x.values,hierarchy_cardinality_violation_rows_truncated:x.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:D.values,hierarchy_parent_divergence_rows_truncated:D.truncated,stale_blocker_reason_patterns:[...a.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:a.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...a.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:a.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...a.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:a.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...a.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:a.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function Ig(e,t,n,r,i,a,o=ge(id.schema)){let s=await yC(e,t),c=new Map(e.map(R=>[R.id,R])),d=[...new Set(s.missingLinkedPaths)].sort((R,Q)=>R.localeCompare(Q)),l=await ZR(t,r),u=wC(l,n,t,r,i,a),m=u.candidateFiles.filter(R=>!s.linkedProjectPaths.has(R)),f=Eg(m,e),p=$_(d,u.candidateFiles),h=new Map(p.map(R=>[R.path,R.classification])),_=p.filter(R=>R.classification==="moved").length,w=s.staleLinkRows.map(R=>({...R,classification:h.get(R.path)??"deleted"})).sort((R,Q)=>R.item_id.localeCompare(Q.item_id)||R.path.localeCompare(Q.path)||R.link_kind.localeCompare(Q.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),m.length>0&&v.push(`validate_files_orphaned_paths:${m.length}`);let E=[...s.remoteLinkedPaths].sort((R,Q)=>R.localeCompare(Q)),k=an(E,a),x=an(d,a),D=an(m,a),S=an(f.map(R=>`${R.path}:${R.classification}:owner_candidate=${R.owner_candidate?.id??"unowned"}`),a),b=a?f:an(Sg(f),!1).values,N=an(O_(p),a),A=__(w,p,R=>c.get(R),o,a?1/0:Dc);return A.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${A.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:a?"full":"summary",file_list_summary_limit:Dc,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:E.length,remote_linked_paths_total:k.total,remote_linked_paths:k.values,remote_linked_paths_truncated:k.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:x.total,missing_linked_paths:x.values,missing_linked_paths_truncated:x.truncated,missing_linked_paths_moved_count:_,missing_linked_paths_deleted_count:p.filter(R=>R.classification==="deleted").length,missing_linked_paths_malformed_count:p.filter(R=>R.classification==="malformed").length,missing_linked_path_classifications:N.values,missing_linked_path_classifications_truncated:N.truncated,...A,orphaned_paths_count:m.length,orphaned_paths_total:D.total,orphaned_paths:D.values,orphaned_paths_truncated:D.truncated,orphaned_path_classifications:S.values,orphaned_path_classifications_truncated:S.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:b}},warnings:v,staleLinkPruneRows:w}}function vC(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},a)=>{let o=t[a];if(o.trusted)return;let s=Rc(i.command??"");n.push(`${r.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${s}`)}),n}async function Rg(e,t,n,r){let i=new Set(e.map(x=>x.id.toLowerCase())),a=0,o=0,s=new Set,c=[],d=e.flatMap(x=>(x.tests??[]).map(D=>({item:x,linkedTest:D}))),l=await Ec(Sc()),u=await K_(r,d.map(({linkedTest:x})=>x),l),m=vC(d,u);for(let{item:x,linkedTest:D}of d){if(typeof D.command!="string"||D.command.trim().length===0)continue;a+=1;let S=z_(D.command,t);if(S.length!==0){o+=S.length;for(let b of S)s.add(b),i.has(b.toLowerCase())||c.push(`${x.id}:${b}:${Rc(D.command)}`)}}let f=[...new Set(c)].sort((x,D)=>x.localeCompare(D)),p=[...new Set(f.map(x=>x.split(":")[1]??""))].filter(x=>x.length>0).sort((x,D)=>x.localeCompare(D)),h=[];f.length>0&&h.push(`validate_command_references_stale_pm_ids:${f.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let _=n?Number.POSITIVE_INFINITY:Ke,w=ae(f,_),v=ae(p,_),E=ae([...s].sort((x,D)=>x.localeCompare(D)),_),k=ae(m,_);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:a,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:E.values,unique_referenced_pm_ids_truncated:E.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:k.values,untrusted_linked_tests_truncated:k.truncated,stale_pm_id_references_count:f.length,stale_pm_ids_count:p.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:h}}function bC(e,t){let n=oi(e.map(c=>({ref:c.id,version:ai(c)})),Jn,ii),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:Ke,a=ae(n.outdated,i),o=ae(n.ahead,i),s=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:s,ok:s==="ok",details:{checked_items:e.length,current_format_version:Jn,outdated_items_count:n.outdated.length,outdated_items:a.values,outdated_items_truncated:a.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:r}}var Nc="pm validate auto-fix";async function Cg(e,t,n){switch(e.kind){case"set_closed_at":await p_(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Nc};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new y("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Tc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Tg(e,t,n){let r=[],i=[],a=new Map;for(let o of e.filter(s=>Tc(s)===null))try{await Cg(o,t,n),r.push(o)}catch(s){i.push({fix:o,error:s})}for(let o of e.filter(s=>Tc(s)!==null)){let s=Tc(o),c=a.get(s);c?c.push(o):a.set(s,[o])}for(let o of a.values()){let s=o[0];if(!s)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{s.kind==="prune_file_link"?await M_(s.item_id,{remove:c,message:Nc},t):await N_(s.item_id,{remove:c,message:Nc},t),r.push(...o)}catch(d){i.push(...o.map(l=>({fix:l,error:d})))}}return{applied:r,failed:i}}var _W={applyValidateFix:Cg,applyValidateFixes:Tg,attachValidateFixHints:cg,buildCommandReferencesCheck:Rg,buildDependencyReferencesCheck:gg,buildCloseReasonBackfillRows:pg,buildFilesCheck:Ig,buildLifecycleCheck:Ag,buildLifecycleDependencyGraph:_g,buildLifecycleParentGraph:xc,buildEstimateBackfillRows:fg,buildMetadataCounts:ug,buildMissingFieldOccurrences:mg,buildOrphanedPathRows:Eg,classifyOrphanedPath:bg,collectDefaultProjectFileCandidates:Pc,collectTrackedGitFileCandidates:sg,detectLifecycleDependencyCycles:vg,detectLifecycleParentCycles:Ac,escapeRegExp:hg,extractItemIds:yg,findLifecycleDependencyCycleComponents:wg,isMetadataFieldMissing:ig,linkedArtifactPathExceedsFilesystemLimits:xg,listFilesRecursive:Mc,resolveDependencyCycleSeverity:ng,resolveParentCycleSeverity:rg,resolveFileScanMode:ag,resolveLifecycleDependencyCycleSamplePath:Ta,resolveRequestedChecks:dg,resolveValidateMetadataProfile:tg,resolveWorkspaceRoot:og,sharedDirectoryPrefixLength:kg,summarizeOrphanedPathRows:Sg,summarizeDuplicateIssueCodes:lg,toMeaningfulString:Ve};function kC(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function EC(e,t,n,r){let i=await y_(e,new Set(t.map(_=>_.id)),n,{schema:r.schema,extensionFieldNames:on(H())}),a=[];i.unreadable_item_files.length>0&&a.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&a.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&a.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&a.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&a.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&a.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let o=a.length,s=await la(e);s.tracked_path_count>0&&a.push(`validate_storage_tracked_runtime_cache_files:${s.tracked_path_count}`);let c=await An(e,Dt(r));c.status==="drift"&&a.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await rt(e),l=d===null?null:await In(d);l!==null&&l.status!=="ok"&&a.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await kt(d??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:f,lossless:p}=Nn(m);f.length>0&&a.push(`validate_merge_decisions_unreviewed:${f.length}`),kC(a,u.invalid_evidence_count);let h=o>0?"error":a.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...i,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:f.length,pending_merge_decision_items:[...new Set(f.map(_=>_.item_id))].sort((_,w)=>_.localeCompare(w)),lossless_merge_receipt_count:p.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(p.map(_=>_.item_id))].sort((_,w)=>_.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:s.tracker_relative_root,tracked_paths:s.tracked_paths,tracked_path_count:s.tracked_path_count,remediation_command:s.remediation_command}}},warnings:a}}function st(e,t,n){n&&cg(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function SC(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let i=await Cu(e.pmRoot,e.items,r?1/0:Ke,e.sourceIncomplete);st(t,i,n)}if(e.requestedChecks.has("metadata")){let i=oC(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let a=await m_(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,r?1/0:Ke);t.closureTimestampFixes=a.fixes,Object.assign(i.check.details,a.details),i.warnings.push(...a.warnings),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",st(t,i,n)}if(e.requestedChecks.has("resolution")){let i=sC(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,st(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=Ag(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,st(t,i,n),st(t,gg(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await Ig(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,st(t,i,n)}return e.requestedChecks.has("command_references")&&st(t,await Rg(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&st(t,await Ca(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&st(t,bC(e.items,r),n),e.requestedChecks.has("storage_integrity")&&st(t,await EC(e.pmRoot,e.items,G(e.settings,H()).type_to_folder,e.settings),n),t}function xC(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...b_(t.closeReasonBackfillRows)),r.push(...v_(t.resolutionBackfillRows)),r.push(...k_(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...E_(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...S_(t.staleLinkPruneRows)),r}async function AC(e,t,n,r,i,a){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=xC(e,t,n),{applicable:s,gated:c}=A_(o,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await Tg(s,i,a);l.push(...m.applied.map($r)),u.push(...m.failed.map(({fix:f,error:p})=>({...$r(f),error:p instanceof Error?p.message:String(p)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,f)=>m.localeCompare(f)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map($r),applied_fixes:l,gated_fixes:c.map(m=>({...$r(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function $g(e,t,n={}){Bd(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new y("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new y("--fix-scope requires --auto-fix.",g.USAGE);let i=x_(e.fixScope),a=L(process.cwd(),t.path);await ne(a);let o=await T(a),s=ge(o.schema),c=G(o,H()),d=dg(e),l=[],u=await Ra({includeBody:["history_drift","metadata","completeness"].some(N=>d.has(N)),pmRoot:a,settings:o,typeToFolder:c.type_to_folder,warnings:l}),m=l.length>0;if(d.has("history_drift")){let N=await ar(a);N.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${N.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=tg(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),h=VR(p,f,o.validation.metadata_required_fields),_=BR(o),w=ng(e.dependencyCycleSeverity),v=rg(e.parentCycleSeverity),E=ag(e.scanMode),k=og(a),x=await SC({requestedChecks:d,options:e,global:t,pmRoot:a,workspaceRoot:k,settings:o,items:u,statusRegistry:s,metadataPolicy:h,lifecyclePatternPolicy:_,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:E,initialWarnings:[...new Set(l)],sourceIncomplete:m}),D=r?await AC(e,x,o,i,t,n):void 0,S=[...new Set(x.warnings)].sort((N,A)=>N.localeCompare(A)),b={ok:!x.checks.some(N=>N.status==="error"),has_warnings:S.length>0,checks:x.checks,warnings:S,...D!==void 0?{fixes:D}:{},generated_at:$(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...qR(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as IC}from"node:child_process";import{promisify as RC}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]="d50f9868-5c11-51dc-967e-61ce41225ef1")}catch{}})();var CC=RC(IC),TC=16,$C=3e4;function OC(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(r=>typeof r=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function DC(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let a of Object.entries(i).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(r,a))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${a}`);for(let[a,o]of Object.entries(r)){let s=i[a];if(!s)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${a}`);if(o===null||typeof o!==s.type)throw new TypeError(`assurance provider ${e.id} parameter ${a} must be ${s.type}`)}return{...r}}async function PC(e,t,n,r){let i=DC(e,t),a=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Wd(n)}));a.catch(()=>{});let o;try{let s=await Promise.race([a,new Promise((c,d)=>{o=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??$C),o.unref?.()})]);return OC(e,t.key,s)}finally{clearTimeout(o)}}function Dg(e,t,n,r){let i=e;for(let a of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new et(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[a]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(a=>typeof a=="string"))return i;throw new et(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function Og(e,t,n,r){let i=e.checks.find(a=>a.name===t);if(!i)throw new et(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:Dg(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function NC(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await CC("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function LC(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(TC,t.length)},async()=>{for(;r<t.length;){let a=r;r+=1;let o=t[a],s=await dt(Gt(e,o.id),o.id);n[a]=s.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function Lr(e,t={}){let n=await T(e),r=G(n),i=ge(n.schema),a=(t.strict_read===!0?(await su(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await ut(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(m=>({...m,id:m.id,status:m.status,type:m.type})),o={path:e},s=H(),c=Object.fromEntries((s?.assurance_providers??[]).map(m=>[m.definition.id,{cost_class:m.runtime_definition.cost_class,network:m.runtime_definition.network}])),d=new Map,l,u;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await NC(e,t.tree_id),items:a,history:t.include_history===!1?[]:await LC(e,a),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...c,...t.provider_capabilities},external:async m=>{if(m.kind==="graph"){let h=C({operation:m.operation,parameters:m.parameters??{}}),_=d.get(h);_===void 0&&(_=lu(m.operation,void 0,void 0,{...m.parameters,full:!0},o),d.set(h,_));let w=await _;return{value:Dg(w,m.field,m.kind),population_size:a.length,cost:a.length}}if(m.kind==="validate"){l??=$g({counts:!0},o);let h=await l;return Og(h,m.check,m.field,m.kind)}if(m.kind==="health"){u??=d_(o,{checkOnly:!0,full:!0});let h=await u;return Og(h,m.check,m.field,m.kind)}let f=t.providers?.[m.provider];if(f)return f(m);let p=vl(s,m.provider);if(!p)throw new TypeError(`assurance provider ${m.provider} is not registered`);return PC(p.runtime_definition,m,e,t.trigger??"sdk")}}}import{createHash as MC}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c72d246d-a7ff-5c9d-8c36-4ebd45b8a69f")}catch{}})();function Pg(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:i}=ti({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function jC(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let r=n;if(r.fingerprint!==t||typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return r.offset}function FC(e,t,n,r,i,a){let o=Object.fromEntries(to.map(f=>[f,0])),s=0,c=0,d=0,l=0,u=[],m=MC("sha256").update(i);for(let f of r){let p=e.membership.get(f),h=n.has(f),_=p.family_ids.length>0;_&&h&&(s+=1),_||(c+=1),h||(d+=1);let w=t.get(f)?.escape_class;w!==void 0&&to.includes(w)&&(o[w]+=1,l+=1),m.update(C([f,h,t.get(f)??null,p.id,p.family_ids])),(!a||!_||!h)&&u.push(f)}return{classCounts:o,coveredCount:s,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:m.digest("hex")}}function Ng(e,t,n={}){el(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let i=new Set,a=new Map;for(let k of t){if(i.has(k.id))throw new TypeError(`Duplicate recurrence item ${k.id}`);i.add(k.id);let x=ei(k);x!==void 0&&a.set(k.id,x)}let o=Yd(e.families,a),s=[...o.membership.keys()].sort(),c=C({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:m,classifiedCount:f,selected:p,fingerprint:h}=FC(o,a,i,s,c,n.uncoveredOnly===!0),_=jC(n.cursor,h);if(_>p.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=p.slice(_,_+r).map(k=>{let x=o.membership.get(k),D=i.has(k);return{item_id:k,lineage_id:x.id,lineage_item_count:x.item_ids.length,family_ids:x.family_ids,present:D,...D?x.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=_+w.length,E=s.length===0?null:d.production_defect/s.length;return{ok:u===0&&m===0,fingerprint:h,items:w,total:p.length,has_more:v<p.length,...v<p.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:s.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:m,classified_item_count:f,unclassified_item_count:s.length-f,class_counts:d,escape_rate:f===s.length?E:null,escape_rate_lower_bound:E},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as UC}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]="676125a5-e16e-5fa2-819f-f4028dc0c3c2")}catch{}})();var jc,Lg=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],Fc=["measurement","assertion","gate"];function HC(e){if(Lg.includes(e))return e;throw yi({command_path:"assurance",token:e,allowed:Lg,display_name:"assurance action"})}function Un(e,t,n){throw new y(t,g.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function zC(e){if(!e)return Un("kind",`Assurance declaration kind is required. Expected: ${Fc.join(", ")}`,"pm assurance list measurement");if(Fc.includes(e))return e;throw new y(`Assurance declaration kind is required. Expected: ${Fc.join(", ")}`,g.USAGE)}function Mg(e){if(!e)return Un("preset",`Assurance preset is required. Expected: ${or.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(or.includes(e))return e;throw new y(`Assurance preset is required. Expected: ${or.join(", ")}`,g.USAGE)}function Uc(e){return e.owner?.trim()?e.owner.trim():Un("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function GC(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new y("assurance definition must be valid JSON",g.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new y("assurance put requires a JSON object definition",g.USAGE);return n}async function WC(e){let[t,n,r]=await Promise.all([tr(e,"measurement"),tr(e,"assertion"),tr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function jg(e,t){return t===!0?{id:e.id}:e}async function qC(e,t){let n=t.authorization_decision;if(!n)return[];let r=await Lr(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(o=>o.id===n),a=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!a.has(i.status))throw new y(`Assurance authorization ${n} must name a terminal Decision item`,g.USAGE);return[i.id]}async function BC(e,t){let n=Ro(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>vn))throw new y(`assurance verdict limit must be an integer from 1 through ${vn}`,g.USAGE);let r=await Iu(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function JC(e,t,n){if(e==="presets"){if(t.preset??t.id)return ji(Mg(t.preset??t.id),Uc(t));let i=or.map(a=>{let o=ji(a,"pm-owner");return{id:a,title:o.title,description:o.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return wn(()=>tm(n,Mg(t.preset??t.id),Uc(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await nm(await Lr(n,{resolve_tree:!1,trigger:"derive"}),Uc(t)),a=t.apply?await wn(()=>rm(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...a?{applied:a}:{}}}if(!t.id)return Un("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new y("assurance promote requires --enforcement warn|block",g.USAGE);let r=await So(n,"assertion",t.id);return wn(()=>im(n,r,t.enforcement,{author:t.author,message:t.message}))}async function VC(e,t,n){if(!e.id)return Un("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new y("assurance run requires a trigger",g.USAGE);if(!Vt.includes(e.trigger))throw new y(`Unknown assurance trigger ${e.trigger}. Expected: ${Vt.join(", ")}`,g.USAGE);let i=e.trigger,[a,o]=await Promise.all([WC(t),Lr(t,{...n.workspace,tree_id:e.tree,trigger:i})]),s=await uu(()=>Eu(r,a,o,{trigger:i,dry_run:e.dry_run===!0}));return s.dry_run||await Au(t,s,{author:e.author,message:e.message}),s}function Fg(e){throw e instanceof y?e:new y(e instanceof Error?e.message:"assurance risk request is invalid",g.USAGE)}function KC(e){if(e.limit!==void 0)throw new y(`assurance ${e.action} does not accept --limit; set limit inside the definition`,g.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new y(`assurance ${e.action} definition must be valid JSON`,g.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?Pg(t):ti(t)}catch(n){if(e.action==="risk"&&n instanceof Qd)throw new y(n.message,g.USAGE,{required:"Supply definition.policy with the project's declared recurrence policy and definition.change with the proposed change; no policy is inferred.",recovery:{suggested_retry:`pm assurance ${e.action} --help`,suggested_retry_args:["assurance",e.action,"--help"]}});return Fg(n)}}function YC(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function XC(e,t,n){let r=C(t.policy),i=jc?.pm_root===e?jc:void 0,a=new Map(n.map(d=>[d.id,UC("sha256").update(C([Kd(d),ei(d)])).digest("hex")])),o=i?.policy_serialized===r?i:void 0,s=o?YC(o,a):new Set,c=Xd(t.policy,o?n.filter(d=>s.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...s]}:{});return jc={pm_root:e,policy_serialized:r,item_fingerprints:a,index:c},c}async function ZC(e,t){let n=KC(e),r=await Lr(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?Zd(XC(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):Ng(n.policy,r.items,n)}catch(i){return Fg(i)}}async function QC(e,t={},n={}){let r=HC(e.action),i=L(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return JC(r,e,i);if(r==="verdicts")return BC(e,i);if(r==="run")return VC(e,i,n);if(["risk","lineages"].includes(r))return ZC(e,i);let a=zC(e.kind);if(r==="list")return tr(i,a);if(!e.id)return Un("id",`assurance ${r} requires an id`,`pm assurance ${r} ${a} <id>`);let o=e.id;if(r==="show")return So(i,a,o);if(r==="remove"){let l=await wn(()=>xu(i,a,o,{author:e.author,message:e.message}));return jg(l,e.idOnly)}let s=GC(a,e.definition);if(s.id!==o)throw new y(`Assurance definition id ${s.id} does not match requested id ${o}`,g.USAGE);let c={author:e.author,message:e.message,...a==="assertion"?{authorized_decision_ids:await qC(i,s)}:{}},d=await wn(()=>$i(i,a,s,c));return jg(d,e.idOnly)}function ZW(e,t,n){let r={...e,...t};return QC({action:P(r,"subcommand")??P(r,"assuranceAction")??P(r,"operation")??"",kind:P(r,"kind"),id:P(r,"id"),definition:r.definition,trigger:P(r,"trigger"),tree:P(r,"treeId")??P(r,"tree"),gate:P(r,"gate"),limit:Ro(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:P(r,"author"),message:P(r,"message"),preset:P(r,"preset"),owner:P(r,"owner"),apply:r.apply===!0,enforcement:P(r,"enforcement")},n)}import Hn from"node:fs/promises";import Ma from"node:path";import La from"node:fs/promises";import Hc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4fe37a62-2d0f-55f6-bb98-7162e7e8b8fe")}catch{}})();var eT=864e5;function tT(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function nT(e,t){let n;try{n=await La.readdir(e,{withFileTypes:!0})}catch(i){if(F(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let a=Hc.join(e,i.name),o;try{o=await La.readdir(a)}catch(s){F(s)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let s of o)s.endsWith(".json")&&r.push(`${i.name}/${s}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function Ug(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*eT,o=Hc.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await nT(o,s.warnings);for(let d of c){let l=Hc.join(o,d),u=`checkpoints/${d}`;s.scanned+=1,r?.onRead&&s.warnings.push(...await r.onRead(l));let m;try{m=await La.readFile(l,"utf8")}catch(w){if(F(w)){s.scanned-=1;continue}s.warnings.push(`checkpoint_unreadable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=tT(m),p=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(p)){s.warnings.push(`checkpoint_unparseable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=i-p,_={file:u,created_at:f,age_seconds:Math.floor(h/1e3),stale:h>a,reason:h>a?"expired":"active"};if(!_.stale){s.retained.push(u),s.entries.push(_);continue}if(!n){try{await La.unlink(l)}catch(w){if(!F(w)){s.warnings.push(`checkpoint_remove_failed:${d}`),s.retained.push(u),s.entries.push(_);continue}}r?.onWrite&&s.warnings.push(...await r.onWrite(l))}s.removed.push(u),s.entries.push(_)}return s}import zc from"node:fs/promises";import Hg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9c0640f0-505c-5f4a-bb7a-daa3cc775239")}catch{}})();var rT=1440*60*1e3,iT=new Set(["committed","compensated"]);function aT(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function oT(e,t,n,r,i){let a=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(a))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=r-a;return iT.has(t)?o>i?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function sT(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],a=aT(await zc.readFile(e,"utf8")),o=oT(t,a.status,a.updatedAt,r.nowMs,r.retentionMs);return o.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),o.remove&&!r.dryRun&&(await zc.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:o,warnings:i}}async function zg(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*rT,o=Hg.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await zc.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(F(d))return s;throw d}for(let d of c){let l=Hg.join(o,d),u=`transactions/sdk/${d}`,m=await sT(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:a});s.warnings.push(...m.warnings),s.scanned+=1;let{decision:f}=m;if(!f.remove){s.retained.push(u),s.entries.push(f.entry);continue}s.removed.push(u),s.entries.push(f.entry)}return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38736716-2644-5166-bfec-4ed4bca951b9")}catch{}})();var Mr=["index","embeddings","runtime","locks","checkpoints","transactions"],cT=1440*60*1e3,dT=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function lT(e,t,n){let r=t.relativePath,i=Ma.join(e,r),a=await Ge({path:i,scope:"project"});try{let o=await Hn.stat(i);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...a,`not_a_file:${r}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...a,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:a};t.kind==="file"?await Hn.unlink(i):await Hn.rm(i,{recursive:!0,force:!0});let s=await X({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...a,...s]}}catch(o){if(F(o))return{removed:!1,warnings:a};throw o}}async function uT(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],a=[],o=Date.now()-cT;for(let s of n){let c=Ma.join(e,s.relativePath);if(!await O(c))continue;let d=(await Hn.readdir(c)).filter(l=>l.startsWith(s.prefix)).sort();for(let l of d){let u=Ma.posix.join(s.relativePath,l),m=Ma.join(c,l);a.push(...await Ge({path:m,scope:"project"}));let f=await Hn.stat(m).catch(p=>{if(!F(p))throw p});if(f){if(f.mtimeMs>o){i.push(u);continue}r.push(u),!t&&(await Hn.rm(m,{recursive:!0,force:!0}),a.push(...await X({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:a}}function mT(e){if(!e||e.length===0)return[...Mr];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new y(`--scope requires at least one value (${Mr.join(",")})`,g.USAGE);let n=new Set;for(let r of t){if(!Mr.includes(r))throw new y(`Invalid --scope value "${r}". Expected one or more of: ${Mr.join(", ")}`,g.USAGE);n.add(r)}return Mr.filter(r=>n.has(r))}function pT(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function bq(e,t={}){let n=L(process.cwd(),e.path);await ne(n);let r=await T(n),i=t.dryRun===!0,a=mT(t.scope),o=dT.filter(p=>a.includes(p.scope)),s=[],c=[],d=[];for(let p of o){let h=await lT(n,p,i);h.removed?s.push(p.relativePath):c.push(p.relativePath),d.push(...h.warnings)}if(a.includes("runtime")){let p=await uT(n,i);s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(a.includes("locks")){let p=await Hm(n,{dryRun:i,hooks:{onRead:h=>Ge({path:h,scope:"project"}),onWrite:h=>X({path:h,scope:"project",op:"gc:lock_remove"})}});s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),l={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(a.includes("transactions")){let p=r.checkpoints.retention_days,h=await zg(n,{dryRun:i,retentionDays:p,hooks:{onRead:_=>Ge({path:_,scope:"project"}),onWrite:_=>X({path:_,scope:"project",op:"gc:transaction_journal_remove"})}});s.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}let m;if(a.includes("checkpoints")){let p=r.checkpoints.retention_days,h=await Ug(n,{dryRun:i,retentionDays:p,hooks:{onRead:_=>Ge({path:_,scope:"project"}),onWrite:_=>X({path:_,scope:"project",op:"gc:checkpoint_remove"})}});s.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),m={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}d.push(...await Qr({mode:i?"gc:dry-run":"gc",total_items:o.length}));let f=pT({dryRun:i,scopes:a,removed:s});return{ok:d.length===0,dry_run:i,scope:a,removed:s,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:f,generated_at:$()}}import{execFile as fT}from"node:child_process";import hT from"node:path";import{promisify as _T}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7fe99df0-8454-5667-9205-0b861ba212d1")}catch{}})();var gT=_T(fT),Wg="@unbrained/pm-cli",yT="latest",wT={global:["--global"],project:[]};function Gg(e){let t=e.project===!0||e.local===!0||e.scope==="project",n=e.global===!0||e.scope==="global";if(t&&n)throw new y('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"}function Fa(e){return e.trim().toLowerCase()}function qg(e,t){let n=Fa(t);return[e.name,e.directory,e.source.input,e.source.location,e.source.package,e.source.repository,e.source.owner&&e.source.repo?`${e.source.owner}/${e.source.repo}`:void 0].some(r=>typeof r=="string"&&Fa(r)===n)}function vT(e,t){let n=L(process.cwd(),t.path),r=sn(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function bT(e,t,n){try{let r=await gT(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:r.stdout,stderr:r.stderr}}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr??""):"",a=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new y(`Command failed: ${e} ${t.join(" ")}
68
+ ${a}`,g.GENERIC_FAILURE)}}function Ua(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():yT}function ja(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():Wg}async function kT(e,t){let n=e.commandRunner??bT,r=ja(e),i=Ua(e),a=`${r}@${i}`,o=["npm","install","-g",a];e.repair===!0&&o.push("--force");let s=sd(import.meta.url,["../../.."]),c={requested:!0,status:"planned",package:r,target:a,command:o,before_version:s,...r===Wg?{migration_guidance:["Calendar scheduling commands are package-owned. If calendar is absent, run pm package install calendar --project; use pm calendar meet, pm calendar event, or pm calendar remind."]}:{},repair:e.repair===!0};if(t)return c;try{await n(o[0],o.slice(1));let d=await n("pm",["--version"]);return{...c,status:"updated",after_version:d.stdout.trim()||void 0}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function ET(e){return hT.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function ST(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!ET(n)&&e.package&&e.package.trim().length>0?`npm:${e.package.trim()}@${t}`:e.input.startsWith("npm:")?e.input:`npm:${e.input}`}return e.input}async function xT(e,t){let n=ST(e,t);return e.kind!=="local"||await O(n)?n:await O(e.location)?e.location:n}function AT(e,t,n,r){let i=["pm","package","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&r&&r.trim().length>0&&i.push("--ref",r.trim()),i}async function Bg(e,t){let n=vT(e,t);return(await ye(n.selected_root)).state.entries.filter(r=>r.scope===e)}async function IT(e,t,n){let r=await Bg(e,t);return r.find(i=>qg(i,n.name))??r.find(i=>Fa(i.directory)===Fa(n.directory))}async function RT(e,t,n,r,i){let a=Ua(t),o=await xT(e.source,a),s=AT(e.source,o,r,e.source.ref),c={name:e.name,directory:e.directory,scope:r,source:e.source,status:"planned",command:s,previous_version:e.manifest_version};if(i)return c;try{await Ds(o,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await IT(r,n,e);return{...c,status:"updated",installed_version:d?.manifest_version}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function CT(e,t,n,r){let i=[n?e.status:void 0,...t.map(a=>a.status)].filter(a=>typeof a=="string");return{requested_cli:n,requested_packages:r,planned:i.filter(a=>a==="planned").length,updated:i.filter(a=>a==="updated").length,skipped:i.filter(a=>a==="skipped").length,failed:i.filter(a=>a==="failed").length}}async function Cq(e,t,n){let r=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&t.packagesOnly===!0){let m=["package","upgrade",...r?[r]:[],"--packages-only","--dry-run",...wT[Gg(t)]];throw new y('Options "--cli-only" and "--packages-only" are mutually exclusive.',g.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:Me(m),suggested_retry_args:m}})}let i=Gg(t),a=t.dryRun===!0;if(t.cliOnly===!0&&r)throw new y('A package target cannot be used with "--cli-only".',g.USAGE);let o=!(t.packagesOnly===!0||r),s=t.cliOnly!==!0,c=o?await kT(t,a):{requested:!1,status:"skipped",package:ja(t),target:`${ja(t)}@${Ua(t)}`,command:["npm","install","-g",`${ja(t)}@${Ua(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await Bg(i,n):[];if(r&&(d=d.filter(m=>qg(m,r)),d.length===0))throw new y(`Managed package "${r}" was not found in ${i} scope.`,g.NOT_FOUND);let l=[];for(let m of d)l.push(await RT(m,t,n,i,a));let u=CT(c,l,o,s);return{ok:u.failed===0,action:"upgrade",dry_run:a,scope:i,target:r,cli:c,packages:l,summary:u}}import{createHash as TT}from"node:crypto";import{isUtf8 as $T}from"node:buffer";import jr from"node:fs/promises";import Gc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a049f799-3807-59b5-96de-51e900798779")}catch{}})();async function Jg(e){try{return(await jr.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(F(t))return[];throw t}}function OT(e,t,n,r){let i=t.at(-1),a;for(let c=t.length-1;c>=0;c-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[c].op)){a=t[c];break}let o=t[0]?.context?.history_compaction,s=typeof o=="object"&&o!==null&&"pruned_stream_digest"in o&&typeof o.pruned_stream_digest=="string"?o.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:n,stream_digest:r,latest_after_hash:i?.after_hash??null,latest_record_hash:i?.record_hash??null,latest_hash_algorithm:i?Ce(i.hash_algorithm):null,rewrite_count:t.reduce((c,d)=>c+(d.reanchor_evidence?.length??0),0),checkpoint_digest:s,last_maintenance:a?{op:a.op,ts:a.ts,record_hash:a.record_hash??null}:null}}function DT(e,t,n){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!$T(t))return null;let r=[];for(let i of t.toString("utf8").split(/\r?\n/u)){if(!i.trim())continue;let a=JSON.parse(i);if(typeof a!="object"||a===null||Array.isArray(a))return null;let o=a;if(![o.op,o.author,o.ts,o.before_hash,o.after_hash].every(s=>typeof s=="string")||!Array.isArray(o.patch))return null;r.push(o)}return Vn(r).ok?OT(e,r,t.length,n):null}catch{return null}}async function Wc(e,t){if(!(await jr.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let n=Gc.join(e,"history"),r=await Jg(n),i=new Map,a=[];for(let o of r){let s=o.slice(0,-6),c={id:s,digest:null,stream:null};a.push(c);let d=Gc.join(n,o);try{let l=await jr.lstat(d);if(i.set(o,C([l.ino,l.size,l.mtimeMs,l.ctimeMs])),!l.isFile())continue;let u=await jr.readFile(d);c.digest=TT(t).update(u).digest("hex"),c.stream=DT(s,u,c.digest)}catch{}}if(C(r)!==C(await Jg(n)))throw new TypeError("attestation history inventory changed during read; retry");for(let[o,s]of i){let c=await jr.lstat(Gc.join(n,o));if(s!==C([c.ino,c.size,c.mtimeMs,c.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54d3c0f4-e663-5e31-aa4e-45ea2f6aaf75")}catch{}})();function qc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bc(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function zn(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function PT(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:zn(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||zn(e.latest_record_hash,e.latest_hash_algorithm))}function NT(e){return e===null?!0:!qc(e)||!Bc(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&Rt(e.ts)&&(e.record_hash===null||zn(e.record_hash,"sha256")||zn(e.record_hash,"sha512"))}function LT(e,t){return!qc(e)||!Bc(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)&&zn(e.stream_digest,t)&&PT(e)&&(e.checkpoint_digest===null||zn(e.checkpoint_digest,"sha256"))&&NT(e.last_maintenance)}function Vg(e){if(!qc(e)||!Bc(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==ro.format||e.version!==1||typeof e.generated_at!="string"||!Rt(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,n;for(let a of e.streams){if(!LT(a,t))throw new TypeError("Invalid history attestation stream");let o=a.id;if(n!==void 0&&o<=n)throw new TypeError("Invalid history attestation stream order");n=o}let{workspace_digest:r,...i}=e;if(io(C(i),t)!==r)throw new TypeError("History attestation rollup mismatch");return e}async function Kg(e={}){let t=Ce(e.hashAlgorithm),n=e.generatedAt??$();if(!Rt(n))throw new TypeError("Invalid history attestation timestamp");let r=await Wc(L(e.cwd??process.cwd(),e.pmRoot),t),i=r.filter(o=>o.stream===null);if(i.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${i.map(o=>o.id).join(", ")}`);let a={format:ro.format,version:1,hash_algorithm:t,generated_at:n,streams:r.map(o=>o.stream)};return Vg({...a,workspace_digest:io(C(a),t)})}async function Yg(e,t={}){let n=Vg(e),r=await Wc(L(t.cwd??process.cwd(),t.pmRoot),n.hash_algorithm),i=new Map(r.map(l=>[l.id,l])),a=new Map(n.streams.map(l=>[l.id,l])),o=n.streams.filter(l=>!i.has(l.id)).map(l=>l.id),s=r.filter(l=>!a.has(l.id)).map(l=>l.id),c=r.filter(l=>l.stream===null).map(l=>l.id),d=[];for(let l of n.streams){let u=i.get(l.id);u&&(u.digest!==l.stream_digest||C(u.stream)!==C(l))&&d.push({id:l.id,before_digest:l.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:o.length+s.length+c.length+d.length===0,workspace_digest:n.workspace_digest,streams_checked:r.length,changed_streams:d.map(l=>l.id),missing_streams:o,added_streams:s,invalid_streams:c,transitions:d}}import Xg from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bca4afb-f1cc-5627-a377-b30e8005a284")}catch{}})();async function Qq(e,t){for(let r of["verify","output","hashAlgorithm"]){let i=e[r];if(!(r==="verify"&&typeof i=="object"&&i!==null)&&i!==void 0&&(typeof i!="string"||i.trim().length===0))throw new y(`history attest ${r} requires a nonempty string.`,g.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new y("history attest --verify cannot be combined with --output or --hash-algorithm",g.USAGE);let r;try{r=typeof e.verify=="string"?JSON.parse(await Xg.readFile(e.verify,"utf8")):e.verify}catch{throw new y("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",g.USAGE)}return Yg(r,{pmRoot:t.path})}let n=await Kg({pmRoot:t.path,hashAlgorithm:Ce(e.hashAlgorithm)});if(e.output===void 0)return n;try{await Xg.writeFile(e.output,`${JSON.stringify(n,null,2)}
69
+ `,{flag:"wx",mode:384})}catch{throw new y("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",g.USAGE)}return{output:e.output,workspace_digest:n.workspace_digest,streams:n.streams.length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42dc4379-016c-5b5d-a15b-37fe3a80dab5")}catch{}})();function Zg(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function Qg(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?Me([...r,"merge","report"],n):e==="history_evidence_invalid"?Me([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?Me([...r,"merge","reconcile"],n):e==="history_repair_required"?Me([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?Me([...r,"merge","install"],n):null}function ey(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(n=>typeof n=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(n=>typeof n=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function mB(e){let t=L(process.cwd(),e.path);await ne(t);let n=await T(t),r=G(n,H()),i=[],a=await Ra({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),o=await rt(t),[s,c,d,l]=await Promise.all([An(t,Dt(n)),o===null?Promise.resolve(null):In(o),kt(o??t,{includeLossless:!0,pmRoot:t}),Ca(t,a,!1)]),{pendingDecisions:u,lossless:m}=Nn(d.receipts),f=[...new Set(u.map(w=>w.item_id))].sort((w,v)=>w.localeCompare(v)),p=l.check.details,h=ey(p),_=Zg({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:m.length,historyEvidenceValid:h.evidence_valid,driftedItemCount:h.drifted_item_count,fence:s,drivers:c});return{ok:_==="ready",state:_,merge_fence:{committed:s,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:f.slice(0,25),pending_item_ids_truncated:f.length>25,lossless_count:m.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:h,next_action:{command:Qg(_,t),reason:_},warnings:[...new Set(i)].sort((w,v)=>w.localeCompare(v)),generated_at:$()}}function pB(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
70
+ `)}var fB={commandForWorkspacePositionState:Qg,normalizeWorkspaceHistoryDrift:ey,selectWorkspacePositionState:Zg};import MT from"node:fs/promises";import Fr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f02db25d-bedb-5411-b50a-de0fea51a117")}catch{}})();var Jc="index/manifest.json",Vc="search/embeddings.jsonl",jT="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function FT(e){return e.progress===!0||process.stderr.isTTY===!0}function de(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
71
+ `)}catch{}}function UT(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new y("Reindex mode must be one of keyword|semantic|hybrid",g.USAGE)}async function HT(e,t,n,r){let i=[];return{candidates:await Ul(e,t,n,i,r),warnings:i}}async function Yc(e,t,n,r,i){let a=on(H()),o=[];for(let s of t)if(!(i&&!i.has(s.metadata.id))){if(typeof s.body=="string"){o.push({metadata:s.metadata,body:s.body});continue}try{let c=await MT.readFile(s.item_path,"utf8"),d=Ct(c,{format:s.item_format,schema:n,extensionFieldNames:a,onWarning:l=>r.push(l)});o.push({metadata:s.metadata,body:d.body})}catch{r.push(`item_list_item_read_failed:${Fr.relative(e,s.item_path)}`),o.push({metadata:s.metadata,body:""})}}return o}function zT(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:Gl(e,{fields:n})}}var Gn=ee;function GT(e){let t=H(),n=Gn(e.search?.provider);if(!n)return null;let r=bl(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,a=Gn(i.name)??Gn(r.definition.name);if(!a)return null;let o=i.embedBatch,s=i.embed_batch,c=i.embed,d=typeof o=="function"?o:typeof s=="function"?s:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:a,embedBatch:d,embed:l}}function WT(e){let t=H(),n=Gn(e.vector_store?.adapter);if(!n)return null;let r=kl(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,a=Gn(i.name)??Gn(r.definition.name);if(!a)return null;let o=i.upsert,s=i.delete;return{adapterName:a,...typeof o=="function"?{upsert:o}:{},...typeof s=="function"?{delete:s}:{}}}function Kc(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new y(`Invalid vector returned by ${t}`,g.GENERIC_FAILURE);return e}async function qT(e,t,n){let r=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let a=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:r}));if(!Array.isArray(a))throw new y(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,g.GENERIC_FAILURE);return a.map((o,s)=>Kc(o,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new y(`Extension search provider "${e.name}" does not implement embed/embedBatch`,g.GENERIC_FAILURE);let i=[];for(let[a,o]of n.entries()){let s=await Promise.resolve(e.embed({input:o,settings:t,model:r}));i.push(Kc(s,`extension search provider "${e.name}" embed output at index ${a}`))}return i}function ty(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function ny(e,t,n){let r=n?Jt(n.name,ty(e)):t?Jt(t.name,t.model):null;if(!r)throw new y("No embedding identity available for semantic reindex mode",g.USAGE);return r}function BT(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function ry(e,t,n,r,i,a,o,s){let c=r?.name??n?.name,d=Wl(c,e.search.embedding_corpus_max_characters).maxCharacters,l=mo(e),u=i.map(p=>ql(p,{providerName:c,maxCharacters:d,fields:l})),m=[],f=null;if(r)try{m=await qT(r,e,u),f=Jt(r.name,ty(e))}catch(p){if(!n)throw new y(`Extension search provider "${r.name}" failed to generate embeddings: ${p instanceof Error?p.message:String(p)}`,g.GENERIC_FAILURE);a.push(`Extension search provider "${r.name}" failed; falling back to built-in provider (${p instanceof Error?p.message:String(p)})`)}if(m.length===0){if(!n)throw new y(`No embedding executor available for reindex mode '${t}'`,g.USAGE);let p=await Bl(n,e,u,{onProgress:h=>{h.phase==="complete"&&(o.batches_completed=h.batch_index),de(s,`embedding_batch_${h.phase} batch=${h.batch_index}/${h.batch_total} size=${h.batch_size} completed_inputs=${h.completed_inputs}/${h.total_inputs}`)}});a.push(...p.warnings),o.batching=p.receipt,m=p.vectors,f=Jt(n.name,n.model)}if(de(s,`embedding_complete vectors=${m.length}`),m.length!==i.length)throw new y(`Embedding output size mismatch (expected ${i.length}, received ${m.length})`,g.GENERIC_FAILURE);if(!f)throw new y(`No embedding identity available for reindex mode '${t}'`,g.USAGE);return{vectors:m,embeddingIdentity:f}}async function JT(e,t,n,r,i,a){let o=Object.keys(n);if(t){if(o.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:o.sort((s,c)=>s.localeCompare(c)),settings:r}))}catch(s){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,g.GENERIC_FAILURE)}else o.length>0&&i.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${o.length}`);if(!e)return}e&&await Kl(e,o,{},a)}async function iy(e,t,n,r,i){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:r}))}catch(a){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${a instanceof Error?a.message:String(a)}`,g.GENERIC_FAILURE)}else i.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Vl(e,n)}}function VT(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function KT(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(r=>({id:r.metadata.id,type:r.metadata.type,status:r.metadata.status,priority:r.metadata.priority,updated_at:r.metadata.updated_at}))}}function YT(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Xn(e.settings);if(!t.active&&!e.extensionEmbedding)throw new y(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,g.USAGE);let n=Si(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new y(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,g.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function XT(e){let t=G(e.settings,H()),n=await HT(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(r=>({metadata:r.metadata,body:typeof r.body=="string"?r.body:""}))}}async function ZT(e){let t=await yn(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return ny(e.settings,Xn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&gn(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(jT))}async function QT(e){let t=await yn(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=ny(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(d=>d.metadata.id)),i=BT(t.entries,r),a=gn(t.embedding,n);e.forceFullSemantic&&!a&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let o=e.forceFullSemantic||a?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),s=new Set(o.map(d=>d.metadata.id)),c=s.size>0?await Yc(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:i,resetRequired:a,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function e$(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await Yc(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,de(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await ry(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:po(r.vectors,"Reindex embeddings")}}async function t$(e){let t=await ry(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=po(n,"Reindex embeddings");if(!(!e.resetRequired&&(gn(e.ledgerEmbedding,r)||Xl(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let a=await e$(e);return n=a.vectors,r=a.embeddingIdentity,i=a.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:a.staleDocuments,vectorDimension:i,resetRequired:!0}}async function n$(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(de(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new y(`Extension vector adapter "${t}" does not support upserting vectors.`,g.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,de(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof y)throw t;if(!e.activeVectorStore)throw new y(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,g.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),de(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){de(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Jl(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,de(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new y(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,g.USAGE)}function r$(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:Kc(t[r],`reindex embeddings output at index ${r}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function i$(e){de(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await t$({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(de(e.progressEnabled,"vector_reset_start"),await JT(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),de(e.progressEnabled,"vector_reset_complete")):await iy(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=r$(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await n$({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:Yl(t.embeddingIdentity,t.vectorDimension)}}async function a$(e){let t=await QT(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(a=>[a.metadata.id,a.metadata.updated_at]));if(de(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return de(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await iy(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await i$({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let i=new Map(r.staleDocuments.map(a=>[a.metadata.id,a]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(a=>i.get(a.metadata.id)??a),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:r.embeddingMetadata}}async function o$(e){let t=Fr.join(e.pmRoot,Jc),n=Fr.join(e.pmRoot,Vc),r=mo(e.settings),i=e.documentsForKeywordArtifacts.map(o=>JSON.stringify(zT(o,e.mode,r))).join(`
72
72
  `);de(e.progressEnabled,"writing keyword artifacts"),await Z(t,`${JSON.stringify(e.manifest,null,2)}
73
73
  `),await Z(n,`${i}
74
- `);let a=[];if(e.mode!=="keyword")try{de(e.progressEnabled,"writing vectorization status ledger"),await Yl(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(o){a.push(`search_vectorization_status_ledger_write_failed:${o instanceof Error?o.message:String(o)}`)}return a}async function fB(e,t){let n=LT(e.mode),r=NT(e),i=e.full===!0;de(r,`start mode=${n}`);let a=L(process.cwd(),t.path);await ne(a);let o=ki(await T(a)).settings,s=null;try{s=await te(a,Rl,o.locks.ttl_seconds,W(void 0,"pm-reindex"),!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms)}catch(c){throw c instanceof y&&c.exitCode===g.CONFLICT?new y("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",g.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=FT(o),d=UT(o),l=BT({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;de(r,"loading item corpus");let m=await VT({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;de(r,`loaded_items=${h.length}`);let _=$(),w=qT(u,_,h),v=Ur.join(a,qc),E=Ur.join(a,Bc),k=u==="keyword"?await Jc(a,p,o.schema,f):h,x=[],D={},S=null,b=WT(u);if(u==="keyword"&&await JT({pmRoot:a,settings:o,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let R=await t$({pmRoot:a,settings:o,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:p,metadataDocuments:h,documentsForKeywordArtifacts:k,forceFullSemantic:i,reindexWarnings:f,semanticWarnings:x,semanticSummary:b,progressEnabled:r});k=R.documentsForKeywordArtifacts,D=R.vectorizationLedgerEntries,S=R.vectorizationEmbeddingMetadata}let N=await n$({pmRoot:a,mode:u,manifest:w,documentsForKeywordArtifacts:k,settings:o,vectorizationLedgerEntries:D,vectorizationEmbeddingMetadata:S,progressEnabled:r}),A=[...await X({path:v,scope:"project",op:"reindex:manifest"}),...await X({path:E,scope:"project",op:"reindex:embeddings"}),...await ei({mode:u,total_items:h.length})];return de(r,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:qc,embeddings:Bc},warnings:[...f,...x,...N,...A],generated_at:_}}finally{await s?.()}}export{M as a,$e as b,Qe as c,vn as d,du as e,uu as f,Jt as g,wo as h,my as i,ko as j,Eo as k,hu as l,kn as m,nr as n,xo as o,$y as p,bu as q,rr as r,Ao as s,Oi as t,Io as u,Eu as v,Su as w,xu as x,sp as y,aP as z,Ev as A,Sv as B,nt as C,PP as D,Hv as E,Py as F,g$ as G,Ru as H,My as I,M$ as J,$b as K,UN as L,GN as M,WN as N,hr as O,qN as P,BN as Q,VN as R,JN as S,KN as T,YN as U,XN as V,ZN as W,QN as X,eL as Y,tL as Z,Es as _,$s as $,PD as aa,Em as ba,zy as ca,Li as da,yO as ea,P as fa,oe as ga,wO as ha,To as ia,vO as ja,bO as ka,Fu as la,kO as ma,EO as na,SO as oa,nw as pa,xO as qa,AO as ra,$o as sa,IO as ta,RO as ua,Co as va,CO as wa,TO as xa,zu as ya,$O as za,iw as Aa,Wu as Ba,zO as Ca,sr as Da,HO as Ea,uw as Fa,mw as Ga,GO as Ha,pw as Ia,O_ as Ja,JO as Ka,Xu as La,P_ as Ma,SH as Na,xH as Oa,cr as Pa,Fi as Qa,Qu as Ra,em as Sa,tm as Ta,nm as Ua,om as Va,cm as Wa,dm as Xa,mm as Ya,Ft as Za,PF as _a,NF as $a,LF as ab,MF as bb,JF as cb,vh as db,va as eb,_1 as fb,kt as gb,g1 as hb,y1 as ib,Sx as jb,Rx as kb,Ph as lb,Dw as mb,fm as nb,Ys as ob,uU as pb,mU as qb,zi as rb,Hi as sb,o_ as tb,lz as ub,s_ as vb,d_ as wb,l_ as xb,p_ as yb,h_ as zb,QI as Ab,eR as Bb,CH as Cb,TH as Db,$H as Eb,OH as Fb,nR as Gb,rR as Hb,iR as Ib,DH as Jb,M_ as Kb,oR as Lb,j_ as Mb,_c as Nb,U_ as Ob,sR as Pb,cR as Qb,dR as Rb,z_ as Sb,gc as Tb,FH as Ub,UH as Vb,bc as Wb,kc as Xb,XH as Yb,ZH as Zb,QH as _b,zR as $b,lW as ac,Rg as bc,Mr as cc,$g as dc,Og as ec,Dg as fc,Mc as gc,KC as hc,BW as ic,hq as jc,Eq as kc,qg as lc,Bg as mc,Vg as nc,Vq as oc,oB as pc,sB as qc,cB as rc,fB as sc};
75
- //# sourceMappingURL=chunk-QOSVJDOO.js.map
74
+ `);let a=[];if(e.mode!=="keyword")try{de(e.progressEnabled,"writing vectorization status ledger"),await Zl(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(o){a.push(`search_vectorization_status_ledger_write_failed:${o instanceof Error?o.message:String(o)}`)}return a}async function vB(e,t){let n=UT(e.mode),r=FT(e),i=e.full===!0;de(r,`start mode=${n}`);let a=L(process.cwd(),t.path);await ne(a);let o=bi(await T(a)).settings,s=null;try{s=await te(a,Tl,o.locks.ttl_seconds,W(void 0,"pm-reindex"),!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms)}catch(c){throw c instanceof y&&c.exitCode===g.CONFLICT?new y("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",g.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=GT(o),d=WT(o),l=YT({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;de(r,"loading item corpus");let m=await XT({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;de(r,`loaded_items=${h.length}`);let _=$(),w=KT(u,_,h),v=Fr.join(a,Jc),E=Fr.join(a,Vc),k=u==="keyword"?await Yc(a,p,o.schema,f):h,x=[],D={},S=null,b=VT(u);if(u==="keyword"&&await ZT({pmRoot:a,settings:o,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let R=await a$({pmRoot:a,settings:o,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:p,metadataDocuments:h,documentsForKeywordArtifacts:k,forceFullSemantic:i,reindexWarnings:f,semanticWarnings:x,semanticSummary:b,progressEnabled:r});k=R.documentsForKeywordArtifacts,D=R.vectorizationLedgerEntries,S=R.vectorizationEmbeddingMetadata}let N=await o$({pmRoot:a,mode:u,manifest:w,documentsForKeywordArtifacts:k,settings:o,vectorizationLedgerEntries:D,vectorizationEmbeddingMetadata:S,progressEnabled:r}),A=[...await X({path:v,scope:"project",op:"reindex:manifest"}),...await X({path:E,scope:"project",op:"reindex:embeddings"}),...await Qr({mode:u,total_items:h.length})];return de(r,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:Jc,embeddings:Vc},warnings:[...f,...x,...N,...A],generated_at:_}}finally{await s?.()}}export{M as a,$e as b,et as c,wn as d,uu as e,pu as f,Vt as g,go as h,hy as i,vo as j,bo as k,gu as l,bn as m,er as n,Eo as o,Py as p,Eu as q,tr as r,So as s,$i as t,xo as u,xu as v,Au as w,Iu as x,pp as y,lP as z,Dv as A,Pv as B,rt as C,FP as D,Zv as E,My as F,b$ as G,Tu as H,Uy as I,H$ as J,Hb as K,qN as L,VN as M,KN as N,fr as O,YN as P,XN as Q,ZN as R,QN as S,eL as T,tL as U,nL as V,rL as W,iL as X,aL as Y,oL as Z,xs as _,Ds as $,FD as aa,Cm as ba,Wy as ca,Ni as da,kO as ea,P as fa,oe as ga,EO as ha,Ro as ia,SO as ja,xO as ka,Hu as la,AO as ma,IO as na,RO as oa,aw as pa,CO as qa,TO as ra,Co as sa,$O as ta,OO as ua,Io as va,DO as wa,PO as xa,Gu as ya,NO as za,sw as Aa,Bu as Ba,qO as Ca,ar as Da,BO as Ea,fw as Fa,hw as Ga,JO as Ha,_w as Ia,N_ as Ja,ZO as Ka,Qu as La,M_ as Ma,Tz as Na,$z as Oa,or as Pa,ji as Qa,tm as Ra,nm as Sa,rm as Ta,im as Ua,cm as Va,lm as Wa,um as Xa,fm as Ya,Ft as Za,FF as _a,UF as $a,HF as ab,zF as bb,QF as cb,Ah as db,wa as eb,b1 as fb,kt as gb,k1 as hb,E1 as ib,Px as jb,jx as kb,Uh as lb,Lw as mb,_m as nb,Zs as ob,_U as pb,gU as qb,Ui as rb,Hi as sb,d_ as tb,_H as ub,l_ as vb,m_ as wb,p_ as xb,__ as yb,y_ as zb,rR as Ab,iR as Bb,Nz as Cb,Lz as Db,Mz as Eb,jz as Fb,oR as Gb,sR as Hb,cR as Ib,Fz as Jb,U_ as Kb,lR as Lb,H_ as Mb,yc as Nb,G_ as Ob,uR as Pb,mR as Qb,pR as Rb,W_ as Sb,wc as Tb,qz as Ub,Bz as Vb,Ec as Wb,Sc as Xb,rG as Yb,iG as Zb,aG as _b,qR as $b,_W as ac,$g as bc,Lr as cc,Pg as dc,Ng as ec,Lg as fc,Fc as gc,QC as hc,ZW as ic,bq as jc,Cq as kc,Vg as lc,Kg as mc,Yg as nc,Qq as oc,mB as pc,pB as qc,fB as rc,vB as sc};
75
+ //# sourceMappingURL=chunk-FW7CSSKL.js.map