@unbrained/pm-cli 2026.10.10 → 2026.10.12

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 (180) hide show
  1. package/.claude-plugin/marketplace.json +1 -36
  2. package/CHANGELOG.md +31 -4
  3. package/dist/cli/commander-usage.d.ts +5 -5
  4. package/dist/cli/commander-usage.js +3 -3
  5. package/dist/cli/error-guidance.d.ts +2 -0
  6. package/dist/cli/error-guidance.js +2 -2
  7. package/dist/cli/help-json-payload.js +1 -1
  8. package/dist/cli/main.d.ts +1 -0
  9. package/dist/cli/main.js +4 -4
  10. package/dist/cli/register-operations.d.ts +9 -4
  11. package/dist/cli/register-operations.js +1 -1
  12. package/dist/cli-bundle/bundle-manifest.json +1 -382
  13. package/dist/cli-bundle/chunks/{chunk-2JYTSTQP.js → chunk-3LQTJN4J.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-YMLF6QT7.js → chunk-6PZPUJW3.js} +28 -28
  15. package/dist/cli-bundle/chunks/{chunk-RUT3CCAG.js → chunk-B465HPS5.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-ESRACL6K.js → chunk-DT3KUUKY.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-SSY4OSJR.js → chunk-GUVKPOY6.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-ILQEZ4Y6.js +2 -0
  19. package/dist/cli-bundle/chunks/{chunk-RBPOO46D.js → chunk-JRRXWH5B.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-MEWBSWE3.js → chunk-LH5QDBMN.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-KNW3RSLS.js → chunk-M5NDSW6E.js} +30 -30
  22. package/dist/cli-bundle/chunks/{chunk-K2UTE75T.js → chunk-MHPU2LDF.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-OBLO45UM.js → chunk-QM3M7GB5.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-S445XEYT.js → chunk-UABZJXIS.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-ZWRLAOA4.js → chunk-X2I2EEAS.js} +2 -2
  26. package/dist/cli-bundle/chunks/{register-list-query-T6BOR67M.js → register-list-query-OR33UEML.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-mutation-6NXR7SAJ.js → register-mutation-R34EJ3NH.js} +2 -2
  28. package/dist/cli-bundle/chunks/register-operations-UHSMEHSF.js +2 -0
  29. package/dist/cli-bundle/chunks/{register-setup-MAYFPKBX.js → register-setup-5E3PT22L.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-SIEGIPNT.js → chunk-7QIZB2F2.js} +7 -7
  31. package/dist/cli-bundle/focused-chunks/{chunk-PLTTMQAW.js → chunk-AJG3DBXR.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/chunk-AXBO53EQ.js +2 -0
  33. package/dist/cli-bundle/focused-chunks/{chunk-W5AE7GKZ.js → chunk-CYEZLKLL.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-PBCYGO7X.js → chunk-FXRWJEQ5.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-GVGFUD52.js → chunk-IKJFAU32.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-DMSADMEU.js → chunk-OGOLIS5R.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/chunk-PPH5N26M.js +2 -0
  38. package/dist/cli-bundle/focused-chunks/{chunk-WAOXID5J.js → chunk-RNAWRTQV.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-B3YW6H2I.js → chunk-RZVNGUT7.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-52UJEHEV.js → chunk-SV6YYZLR.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-EIOQNLBQ.js → chunk-TS46OZD5.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-KNJR2WUO.js → chunk-VBTLX5SN.js} +62 -62
  43. package/dist/cli-bundle/focused-chunks/{chunk-JGFSSR3G.js → chunk-YCOJLIDI.js} +3 -3
  44. package/dist/cli-bundle/focused-chunks/chunk-YDJT33JU.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-AU6VJGTY.js → chunk-Z4T3637Y.js} +2 -2
  46. package/dist/cli-bundle/main.js +22 -22
  47. package/dist/cli-bundle/sdk-authoring.js +1 -1
  48. package/dist/cli-bundle/sdk-contracts.js +1 -1
  49. package/dist/cli-bundle/sdk-core.js +31 -31
  50. package/dist/cli-bundle/sdk-governance.js +1 -1
  51. package/dist/cli-bundle/sdk-graph.js +1 -1
  52. package/dist/cli-bundle/sdk-merge.js +24 -24
  53. package/dist/cli-bundle/sdk-query.js +1 -1
  54. package/dist/cli-bundle/sdk-runtime.js +1 -1
  55. package/dist/cli-bundle/sdk-testing.js +1 -1
  56. package/dist/cli-bundle/sdk.js +9 -9
  57. package/dist/core/history/event-classification.d.ts +1 -1
  58. package/dist/core/history/event-classification.js +1 -1
  59. package/dist/core/item/item-format.d.ts +2 -0
  60. package/dist/core/item/item-format.js +2 -2
  61. package/dist/core/telemetry/runtime.d.ts +1 -1
  62. package/dist/core/telemetry/runtime.js +2 -2
  63. package/dist/core/test/background-runs.d.ts +1 -0
  64. package/dist/core/test/background-runs.js +2 -2
  65. package/dist/sdk/agent/command-suggestions.d.ts +2 -0
  66. package/dist/sdk/agent/command-suggestions.js +1 -1
  67. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  68. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  69. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  70. package/dist/sdk/cli-contracts/registration-helpers.d.ts +1 -4
  71. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  72. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  73. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  74. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  75. package/dist/sdk/core.d.ts +1 -0
  76. package/dist/sdk/core.js +1 -1
  77. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  78. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  79. package/dist/sdk/governance/artifact-ledgers.d.ts +59 -0
  80. package/dist/sdk/governance/artifact-ledgers.js +2 -0
  81. package/dist/sdk/governance.d.ts +1 -0
  82. package/dist/sdk/governance.js +1 -1
  83. package/dist/sdk/index.d.ts +2 -0
  84. package/dist/sdk/index.js +1 -1
  85. package/dist/sdk/public-surface.json +1 -1
  86. package/dist/sdk/test/batch.js +1 -1
  87. package/dist/sdk/test/command-args.d.ts +4 -0
  88. package/dist/sdk/test/command-args.js +2 -0
  89. package/dist/sdk/test/entry.d.ts +3 -0
  90. package/dist/sdk/test/entry.js +1 -1
  91. package/dist/sdk/test/execution.d.ts +15 -4
  92. package/dist/sdk/test/execution.js +2 -2
  93. package/dist/sdk/test/prerequisites.d.ts +6 -0
  94. package/dist/sdk/test/prerequisites.js +2 -0
  95. package/dist/sdk/test/trust.js +1 -1
  96. package/dist/sdk/test/update.d.ts +55 -0
  97. package/dist/sdk/test/update.js +2 -0
  98. package/dist/types.d.ts +4 -0
  99. package/dist/types.js +1 -1
  100. package/docs/LINKED_TEST_EDITS.md +79 -0
  101. package/docs/RELEASE_LEDGER_RECONCILIATION.md +148 -0
  102. package/docs/RELEASE_RELIABILITY.md +4 -0
  103. package/docs/RELEASING.md +53 -13
  104. package/docs/SDK.md +178 -636
  105. package/docs/SDK_EVIDENCE_TRACEABILITY.md +4 -0
  106. package/docs/TESTING.md +13 -0
  107. package/docs/agent-task-token-baseline.json +1 -292
  108. package/docs/agent-task-transcripts.json +1 -478
  109. package/docs/ecosystem-review-2026-09-28.json +1 -2866
  110. package/docs/examples/policy-restricted-extension/manifest.json +1 -22
  111. package/docs/examples/policy-restricted-extension/package.json +1 -8
  112. package/docs/examples/sdk-agent-environment/package.json +1 -8
  113. package/docs/examples/sdk-app-embedding/package.json +1 -9
  114. package/docs/examples/sdk-contract-consumer/package.json +1 -11
  115. package/docs/examples/sdk-custom-tool/package.json +1 -13
  116. package/docs/examples/starter-extension/manifest.json +1 -33
  117. package/docs/examples/starter-extension/package.json +1 -10
  118. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  119. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +8 -3
  120. package/docs/performance/corpus-shape-comparison.json +1 -108
  121. package/docs/performance/latest-scale-report.json +1 -418
  122. package/docs/performance/runner-qualification.md +36 -0
  123. package/docs/performance/scale-100k-report.json +1 -418
  124. package/docs/schemas/extension-manifest.schema.json +1 -165
  125. package/marketplace.json +1 -36
  126. package/package.json +1 -1
  127. package/packages/pm-beads/extensions/beads/manifest.json +1 -28
  128. package/packages/pm-beads/extensions/beads/package.json +1 -3
  129. package/packages/pm-beads/package.json +1 -50
  130. package/packages/pm-calendar/extensions/calendar/manifest.json +1 -22
  131. package/packages/pm-calendar/extensions/calendar/package.json +1 -3
  132. package/packages/pm-calendar/package.json +1 -51
  133. package/packages/pm-command-kit/extensions/command-kit/manifest.json +1 -22
  134. package/packages/pm-command-kit/extensions/command-kit/package.json +1 -3
  135. package/packages/pm-command-kit/package.json +1 -53
  136. package/packages/pm-digital-twin/extensions/digital-twin/manifest.json +1 -19
  137. package/packages/pm-digital-twin/extensions/digital-twin/package.json +1 -3
  138. package/packages/pm-digital-twin/package.json +1 -58
  139. package/packages/pm-governance-audit/extensions/governance-audit/manifest.json +1 -19
  140. package/packages/pm-governance-audit/extensions/governance-audit/package.json +1 -3
  141. package/packages/pm-governance-audit/package.json +1 -55
  142. package/packages/pm-guide-shell/extensions/guide-shell/manifest.json +1 -22
  143. package/packages/pm-guide-shell/extensions/guide-shell/package.json +1 -3
  144. package/packages/pm-guide-shell/package.json +1 -52
  145. package/packages/pm-kanban/extensions/kanban/manifest.json +1 -19
  146. package/packages/pm-kanban/extensions/kanban/package.json +1 -3
  147. package/packages/pm-kanban/package.json +1 -57
  148. package/packages/pm-lifecycle-hooks/extensions/lifecycle-hooks/manifest.json +1 -19
  149. package/packages/pm-lifecycle-hooks/extensions/lifecycle-hooks/package.json +1 -3
  150. package/packages/pm-lifecycle-hooks/package.json +1 -52
  151. package/packages/pm-linked-test-adapters/extensions/linked-test-adapters/manifest.json +1 -29
  152. package/packages/pm-linked-test-adapters/extensions/linked-test-adapters/package.json +1 -3
  153. package/packages/pm-linked-test-adapters/package.json +1 -53
  154. package/packages/pm-search-advanced/extensions/search-advanced/manifest.json +1 -29
  155. package/packages/pm-search-advanced/extensions/search-advanced/package.json +1 -3
  156. package/packages/pm-search-advanced/package.json +1 -54
  157. package/packages/pm-templates/extensions/templates/manifest.json +1 -22
  158. package/packages/pm-templates/extensions/templates/package.json +1 -3
  159. package/packages/pm-templates/package.json +1 -50
  160. package/packages/pm-todos/extensions/todos/manifest.json +1 -29
  161. package/packages/pm-todos/extensions/todos/package.json +1 -3
  162. package/packages/pm-todos/package.json +1 -51
  163. package/packages/pm-vcs/extensions/vcs/manifest.json +1 -19
  164. package/packages/pm-vcs/extensions/vcs/package.json +1 -3
  165. package/packages/pm-vcs/package.json +1 -55
  166. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -25
  167. package/plugins/pm-claude/.mcp.json +1 -8
  168. package/plugins/pm-claude/hooks/hooks.json +1 -17
  169. package/plugins/pm-claude/package.json +1 -9
  170. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -45
  171. package/plugins/pm-codex/.mcp.json +1 -11
  172. package/plugins/pm-codex/mcp.json +1 -11
  173. package/plugins/pm-codex/package.json +1 -9
  174. package/plugins/pm-codex/plugin.json +1 -45
  175. package/runtime-dependencies.json +1 -512
  176. package/dist/cli-bundle/chunks/chunk-BXSXT5Z6.js +0 -2
  177. package/dist/cli-bundle/chunks/register-operations-PDOBQZUJ.js +0 -2
  178. package/dist/cli-bundle/focused-chunks/chunk-2CJWTLQG.js +0 -2
  179. package/dist/cli-bundle/focused-chunks/chunk-MJQ253F3.js +0 -2
  180. package/dist/cli-bundle/focused-chunks/chunk-WOEZJUA2.js +0 -2
@@ -1,76 +1,76 @@
1
- import{a as za,c as Gr,d as qr,e as yd,g as wd,h as Ga,i as vd,j as sn,k as cn,l as bd,m as kd,n as qa,o as xd,p as dn,q as ln,r as Ad,s as Id,t as Ba}from"./chunk-W5AE7GKZ.js";import{e as ei,f as Xa,h as Za}from"./chunk-WAOXID5J.js";import{B as Hd,C as Xr,D as zd,E as Ya,G as Wd,H as Gd,J as qd,K as Zr,M as Qr,a as ud,g as Ha,i as md}from"./chunk-2CJWTLQG.js";import{K as tu}from"./chunk-52UJEHEV.js";import{D as ro,E as pi,Ha as Bl,Ia as Vl,Ma as Jl,Na as Kl,T as fi,U as kl,V as io,W as Kn,Y as ao,aa as Pl,ba as Nl,ca as Ll,da as Ml,ea as gi,f as pl,g as fl,ga as jl,h as hl,ha as Fl,ia as Ul,ja as qt,k as mi,ka as Hl,kb as Zl,la as hn,ma as zl,mb as co,na as oo,nb as Ql,o as Vn,oa as _n,ob as eu,p as _l,pa as Wl,q as gl,qa as Gl,r as Jn,ra as ql,s as yl,sa as so,u as no,v as wl,wb as lo,z as vl}from"./chunk-JGFSSR3G.js";import{a as fd,b as on,c as Wa,d as hd,e as _d,f as ot,g as Br,h as gd,i as xt}from"./chunk-PLTTMQAW.js";import{$ as Xd,$a as bl,Aa as sl,Ab as ne,Ba as cl,Bb as ve,Cb as be,D as G,Da as Rt,Db as Ol,E as Bd,Ea as Bn,Eb as _i,Fa as dl,Fb as ct,Ga as oi,Gb as dt,H as Ce,Ha as Gt,I as Qa,Ia as ce,Ja as si,Jb as Dl,Ka as ll,Kb as lt,La as to,Ma as ci,Na as fn,O as Vd,Oa as di,P as ti,Pa as ul,S as ni,T as ri,Ta as Te,V as Jd,W as Me,Wa as ml,Xa as T,Y as It,Ya as li,Yb as Yn,Z as Kd,Za as ui,_ as Yd,_b as yi,aa as st,ba as Zd,fc as Yl,ga as Qd,gb as Sl,ha as eo,hb as El,ia as ii,ic as Xl,ja as mn,jb as xl,kb as Al,la as ai,lb as Ct,ma as el,mb as Il,na as tl,nb as Rl,pa as nl,qb as Cl,ra as rl,rb as Tl,ta as il,va as al,wb as hi,xa as pn,ya as ol,yb as $l}from"./chunk-SIEGIPNT.js";import{b as rn,e as le,g as Le,i as Re,j as Ke,n as ge,o as Sd,p as Vr,r as Ed}from"./chunk-PBCYGO7X.js";import{$ as g,$a as L,$c as Ye,$d as At,Ac as Kr,Ba as fe,Bb as Ve,Bc as Pd,Ca as Ne,Cc as Nd,Da as Qc,Db as Je,Ec as Ld,Fa as ee,Ia as ed,Mc as H,Na as td,Nb as pd,Pc as X,Rc as He,S as Bc,Sb as Jr,Sc as Md,T as Vc,Ta as nd,Tb as Rd,Tc as Yr,Ua as rd,Ub as Va,V as Jc,Va as W,Vb as Ja,Wb as Ka,X as Kc,Y as zr,Yb as Cd,Yd as $,Z as Yc,Zb as Td,Zd as Ud,_a as qn,_c as jd,_d as un,a as Ur,aa as y,ab as Be,ac as $d,ae as Wt,bb as Wr,bd as Fd,cb as Ut,d as Hr,eb as id,fb as Ht,fe as te,ha as Xc,hb as ad,hc as Od,i as Wc,ib as od,jb as sd,ka as Zc,l as Gc,m as qc,ma as Fa,ra as Gn,rb as cd,sa as O,sb as zt,ta as Et,tb as C,ua as F,ub as dd,va as V,vb as Ie,w as ja,xb as Ua,ya as Z,yb as ld,yc as Dd,zb as an}from"./chunk-B3YW6H2I.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}},Xe=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function gn(e){try{return await e()}catch(t){throw t instanceof M?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function nu(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 Kg}from"node:crypto";import Yg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var yn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="416aaf09-e4f6-5d10-aee0-eba374f1cd83")}catch{}})();var iu=1,Bt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],uo=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Xg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Zg=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,wi=30,vi=5e3,au=4,Qg=50;function ut(e,t){if(!Zg.test(e))throw new M(`${t} must be a stable lowercase id`)}function ey(e,t){if(!Number.isFinite(e)||e<0)throw new M(`${t} must be a finite non-negative number`)}function Xn(e){let t=Xg.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 po(e,t){return C(e)===C(t)}function ou(e,t){if(t.polarity==="equals")return po(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 su(e){let t=Xn(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>ou(r.observed,t)===(r.expected==="pass"))}function ty(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!po(e.value,t.value)}function ny(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 ty(Xn(e),Xn(t))||n[t.enforcement]<n[e.enforcement]||r}function ry(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 iy(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 ay(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 fo(e){ut(e.id,"measurement.id"),e.max_cost!==void 0&&ey(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 ${uo.join(", ")}`);let n=Reflect.get(t,"kind");if(!uo.includes(n))throw new M(`measurement.source.kind must be one of ${uo.join(", ")}`);let r=t;if(r.kind==="items"&&ry(r),r.kind==="dependency_kind"&&iy(r),r.kind==="prose_edge_gap"&&ay(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"&&(ut(r.provider,"provider source provider"),ut(r.key,"provider source key")),e}function ho(e){if(ut(e.id,"assertion.id"),ut(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=Xn(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"&&ut(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(!su(e))throw new M(`assertion ${e.id} negative control does not prove its bound`);return e}function oy(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)ut(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(!Bt.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 cu(e){if(ut(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)ut(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new M(`gate.triggers is required and must be an array of ${Bt.join(", ")}`);if(e.triggers.length===0)throw new M("gate requires at least one trigger");for(let t of e.triggers)if(!Bt.includes(t))throw new M(`gate trigger must be one of ${Bt.join(", ")}`);return e.provider_policy&&oy(e.provider_policy),e}function wn(e){if(e.version!==iu)throw new M(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(fo(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(ho(r),t.has(`assertion:${r.id}`))throw new M(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){cu(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 du(e))if(!n.has(r))throw new M(`${i.join(", ")} references missing measurement ${r}`);return e}function _o(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)_o(n,t)}function du(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=[];_o(r.source.expression,i);for(let a of i)n(a,`derived measurement ${r.id}`)}return t}function sy(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"&&_o(o.source.expression,n)}return i}function Zn(){return{version:iu,measurements:[],assertions:[],gates:[]}}function cy(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 po(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function dy(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 ly(e,t){let n=[],r=Fa(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let a of i.dependencies??[]){let o=Fa(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===r&&dy(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 uy(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 my(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 mo(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function py(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(mo(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(mo(o.id,s));for(let s of uy(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 fy(e,t){let n=py(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=mo(o.holder_id,d);if(n.linked_pairs.has(l)||my(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 hy(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 _y(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 gy(e,t){let n=e.source;return n.kind==="items"?cy(n,t):n.kind==="dependency_kind"?ly(n,t):n.kind==="prose_edge_gap"?fy(n,t):n.kind==="history"?hy(n,t):n.kind==="links"?_y(n,t):null}function lu(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 yy(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 uu(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 mu(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 pu(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 uu(e.operands,au,o=>mu(o,t,n,r,i));return{value:yy(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 wy(e,t,n,r,i){fo(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await mu(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=gy(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=lu([...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:${Kg("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 pu(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=wy(e,t,n,r,i).catch(s=>{if(s instanceof Xe&&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 Xe(s.message,c);throw d.cause=s,d}throw s});return i.cache.set(e.id,o),o}async function go(e,t,n=[e]){return pu(e,t,n,[],{cache:new Map,charged:new Set})}function vy(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 by(e,t,n={}){ho(e);let r=Xn(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:vy(t.value,r),verdict:i?"retired":ou(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:su(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function ky(e,t,n,r){let i=sy(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 ru(e,t,n,r,i){try{return await go(n,r,i)}catch(a){if(a instanceof Xe){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 fu(e,t,n,r){wn(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}`);ky(i,t,n,r.trigger);let a=await uu(i.assertion_ids,au,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 ru(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 by(d,await ru(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:lu(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function bi(e){return Yg.join(e,"assurance.json")}async function hu(e){let t=await V(bi(e));return t===null?Zn():ki(t)}function ki(e){try{return wn(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function Si(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Sy(e,t){e==="measurement"?fo(t):e==="assertion"?ho(t):cu(t)}async function Qn(e,t){let n=structuredClone(Si(await hu(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function yo(e,t,n){let r=Si(await hu(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Ei(e,t,n,r={}){Sy(t,n);let i=await T(e),a=G(r.author,i.author_default),o=await fn({pmRoot:e,filePath:bi(e),op:`assurance:${t}:put`,author:a,message:r.message,lockTtlSeconds:wi,lockWaitMs:vi,mutate:s=>{let c=s===null?Zn():ki(s),d=Si(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&ny(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),wn(c),{raw:`${JSON.stringify(c,null,2)}
2
- `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function wo(e,t,n={}){let r=Zn();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),wn(r);let i=await T(e),a=G(n.author,i.author_default),o=await fn({pmRoot:e,filePath:bi(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:wi,lockWaitMs:vi,mutate:s=>{let c=s===null?Zn():ki(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"),wn(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 _u(e,t,n,r={}){let i=await T(e),a=G(r.author,i.author_default),o=await fn({pmRoot:e,filePath:bi(e),op:`assurance:${t}:remove`,author:a,message:r.message,lockTtlSeconds:wi,lockWaitMs:vi,mutate:s=>{let c=s===null?Zn():ki(s);if(t==="measurement"){let u=du(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=Si(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),wn(c),{raw:`${JSON.stringify(c,null,2)}
4
- `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function gu(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await T(e);await ci({pmRoot:e,op:"assurance:gate:verdict",author:G(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:wi,lockWaitMs:vi})}async function yu(e,t={}){let n=t.limit??Qg;if(!Number.isInteger(n)||n<1||n>yn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${yn}`);return(await st(si(e),ce)).reverse().filter(r=>r.op==="assurance:gate:verdict").map(r=>r.context?.assurance_verdict).filter(r=>typeof r=="object"&&r!==null&&"gate_id"in r).filter(r=>t.gate_id===void 0||r.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var er={type:"string",minLength:1,maxLength:128,pattern:"\\S"},xi={type:"array",minItems:1,maxItems:Va,items:er},wu={...xi,items:{...er,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},Ey={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,xi])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:er,id:er}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:wu}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:xi}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:wu,authors:xi}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Va,items:{type:"array",minItems:2,maxItems:2,items:er}}}}]}}},o$={$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:Rd,items:Ey}}};(function(){try{var e=typeof window<"u"?window:typeof 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 vu(e,t,n,r){let i=await Ct(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"]}:bu(i,t,n,r)}function xy(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function bu(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 S=a.get(_.type)??{items:0,violations:0,missing_fields:0};S.items+=1;for(let k of v)u+=1,S.violations+=1,S.missing_fields+=k.missing_fields.length,k.effect==="refuse"&&(f+=1),i.length<n&&i.push({id:_.id,type:_.type,status:_.status,decision:k});a.set(_.type,S)}let h=r||f>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:h,ok:h==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:l,governed_items:d,ungoverned_items:t.length-d,contract_status:xy(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 Ay 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 Iy(){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 Eu(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 Ry(e,t){let n=L(process.cwd(),e.path);await ne(n);let r=await T(n);return{pmRoot:n,settings:r,author:G(t,r.author_default)}}function ku(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
- `)>xl)throw new y("Policy registry exceeds its byte ceiling.",g.USAGE);return o}async function Su(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:ku(e,t,await Ct(r.pmRoot),n)};let i=await fn({pmRoot:r.pmRoot,filePath:Ay.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=ku(e,t,Al(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 Cy(e,t,n){let r,i=await Dl({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(a){let o=(await Ct(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 Il(n.pmRoot,a.metadata.id),r={policy_id:o.id,policy_fingerprint:Cd(o),content_fingerprint:Td(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 Ty(e,t){let n=Eu(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 A$(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:Iy()};let i=await Ry(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Ct(i.pmRoot)};if(e==="policy-put"){let l=Ty(t,n.definition);return Su(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 Su(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 Cy(t,n,i)}let a=W(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,...Eu(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 Rl(i.pmRoot,await Ct(i.pmRoot),{operation:"update",author:i.author,before:c,after:d,completeness_only:n.definition===void 0})}}import{createHash as Lu}from"node:crypto";import tr from"node:fs/promises";import nr from"node:path";import{Option as B$}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2ab212f-4af5-5084-b436-9a35d17af809")}catch{}})();function $y(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 Ai(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 mt(e,t){return e[t]===!1?!0:void 0}function xu(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Au(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function Iu(e){let t=i=>Ha(e,Ai(ei,i)),n=i=>md(e,Ai(Xa,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:$y(e,Ai(Xa,"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:xu(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 Au(r,e),r}function ie(e,t){let n=Ai(ud,t),r=Ha(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 Oy(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:mt(e,"notes"),noLearnings:mt(e,"learnings"),noFiles:mt(e,"files")??t,filterFilesMissing:t,noDocs:mt(e,"docs")??n,filterDocsMissing:n,noTests:mt(e,"tests"),noComments:mt(e,"comments"),noDeps:mt(e,"deps"),emptyBody:U(e,"emptyBody"),noLinkedCommand:mt(e,"linkedCommand")}}function Ru(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:mt(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:xu(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:U(e,"filterResolutionMissing"),filterMetadataMissing:U(e,"filterMetadataMissing"),...Oy(e)};return Au(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]="bd5ef423-5675-585c-ac2f-0b7548636596")}catch{}})();var Dy=Symbol("pm.mcp-mutation-transport"),Py=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function Ri(e){return Dy in e}function Ci(e,t){return Ri(e)?yl(t):no(e,t)}function iO(e,t,n=[]){let r=no(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 aO(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function vn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ko(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 oO(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 sO(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 Ny=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Tu=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"]),Ly=new Set([...Tu].filter(e=>e!=="file")),My=new Set(["files","files-discover","docs","test","test-all"]),$u=new Set(["comments","notes","learnings"]);function jy(e,t){if(!(!$u.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 Fy=new Set(["claim","release","start-task","pause-task","close-task"]),Uy={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun","offline"],package:["dryRun","offline"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Hy=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Ou(e,t=""){let n={},r=My.has(t),i=t==="files"||t==="files-discover"||t==="docs",a=$u.has(t)?Ly:Tu;for(let[o,s]of Object.entries(e)){if(Array.isArray(s)&&Ny.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 zy(e,t,n){let r=P(e,"author");return r!==void 0?r:n!==void 0&&Fy.has(n)?P(e,"assignee")??P(t,"assignee"):void 0}function Wy(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function cO(e,t){let n=vn(e.options)?e.options:void 0,r=td(e.options),i={},a=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of Uy[t??""]??[])a(c);for(let c of Hy)a(c);t!==void 0&&Ri(e)&&jy(t,r);let o=Ou({...i,...r},t);if(t==="history-attest"&&Ri(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=Ri(e)?e:n??e;return Ci(s,Wy(o,zy(e,o,t)))}function dO(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 lO(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 Gy(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 uO(e){return!Py.has(Gy(e))}function mO(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function So(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function pO(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 fO(e,t){let n=Ci(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function bo(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:ro(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 vo(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return So(e)}function Ii(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function hO(e){let t=vo(e.kind),n=vo(e.exemptIsolate),r=vo(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Ii(e.maxDepth),limit:Ii(e.limit),after:P(e,"after"),direction:P(e,"direction"),maxPaths:Ii(e.maxPaths),sample:Ii(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function Du(e){let t=Ru(e);return e.ids!==void 0&&(t.ids=ro(e.ids)),t}function _O(e){return{status:P(e,"filterStatus"),list:vn(e.list)?Du(e.list):bo(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 qy=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 Cu(e){let t={};for(let[n,r]of Object.entries(e))qy.has(n)||(t[n]=r);return Pu(t)}function Pu(e){let t=Ou(e,"update-many");for(let n of ei)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return Iu(t)}function gO(e){if(vn(e.list)||vn(e.update)){let t=vn(e.update)?e.update:Cu(e),n=Ci(e,Pu(t));return{status:oe(e,"filterStatus"),list:vn(e.list)?Du(e.list):bo(e),update:wl(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:bo(e),update:Ci(e,Cu(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:P(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69bf315a-01aa-56d9-bd56-196d6792dea2")}catch{}})();function je(e,t){throw new y(e,g.USAGE,t)}var By="2026-07-15T06:22:12.276Z",Vy=Date.parse(By),Jy=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Nu=e=>typeof e=="string"?e:"",Mu=e=>{let t=e??{},n=Nu(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Nu(t.ts))>=Vy);return Jy[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=Mu(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 IO=(e,t,n=20,r=new Set)=>ju(e,t,n,r);function Fu(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 rr=async(e,t=20,n=!1)=>{let r=nr.join(e,"history"),i;try{i=(await tr.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=Fu(await tr.readFile(nr.join(r,p),"utf8"))}catch{h=new Set}for(let w of i){let v;try{v=await tr.readFile(nr.join(r,w),"utf8")}catch{continue}let S=w.slice(0,-6),k=ju(S,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(S),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 Ky(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 Yy(e){try{return Fu(await tr.readFile(nr.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function Xy(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 Zy(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{je(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Mu(i)!=="actionable_unknown"&&je(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:Lu("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Uu(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&je("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&je("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&je("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let a=Ky(t.all_actionable===!0?(await rr(e,0,!0)).actionable_events:r),o=await Yy(e),s=new Map;for(let m of a)if(Xy(m)||je(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!s.has(m.item_id))try{s.set(m.item_id,(await tr.readFile(nr.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{je(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=a.map(m=>Zy(m,o,s.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Lu("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 RO(e,t,n=50){return(await Uu(e,t,n)).plan}function Qy(e,t){let n=e.length>0;return n&&t&&je("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&je("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:ew(e),all_actionable:t}}function ew(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),a=r===ce||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!a||!Number.isSafeInteger(i)||i<1)&&je(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function CO(e,t){let n=Qy(So(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return tw(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 tw(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",a=await Uu(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:g.SUCCESS,plan:a.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&je("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||je("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==a.plan.plan_fingerprint)throw new y("Author acknowledgment selection changed after preview; no history was mutated.",g.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let o=a.completeCoordinates.filter(({disposition: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 ci({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:o,attributed_author:r}},message:i,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms}),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 nw}from"node:child_process";import Hu 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 zu(e,t){return new Promise((n,r)=>{nw("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,a)=>{i?r(i):n(a)})})}function Wu(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 PO(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Wu(n),!n)throw new RangeError("Source line range must use start:end.");return n}function rw(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 iw(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 aw(e){let t=Hu.relative(e.workspaceRoot,Hu.resolve(e.workspaceRoot,e.sourcePath)),n=await zu(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await zu(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:rw(n),commitItems:iw(r),available:!0}}function ow(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 sw(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=ow({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 cw(e,t,n){let r=Xl(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=sw({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 dw(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await aw({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function lw(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 uw(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Gu(e){Wu(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 dw(e),r=uw(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=cw(a.item.id,e.corpus,t),d=lw({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 ir=["software-delivery","research","agent-evaluation","operations"];function qu(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 Ti(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=>qu(`${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 $i(e,t){return e==="software-delivery"?Ti(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Ti(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Ti(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Ti(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function Bu(e,t,n,r={}){return wo(e,$i(t,n).declarations,r)}async function Vu(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 go(a,r)).value,s=qu(`${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 Ju(e,t,n={}){return wo(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 Ku(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 Ei(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Zu from"node:fs/promises";import{createRequire as mw}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 Yu(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 pw(e){return e.includes(`${Oe.sep}.pnpm${Oe.sep}`)?"pnpm":e.includes(`${Oe.sep}node_modules${Oe.sep}`)?"npm":"other"}async function Xu(e){try{let t=JSON.parse(await Zu.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 Eo(e){try{return await Zu.realpath(e)}catch{return Oe.resolve(e)}}async function Qu(e,t,n=Ne(import.meta.url,["../../.."])){let r=await Eo(t),i=await Eo(Oe.join(n,"package.json")),a=await Xu(i),o=new Map;a!==void 0&&o.set(i,{version:a,path:Yu(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=mw(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await Eo(l),m=await Xu(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:Yu(u,r),layout:pw(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 xo from"node:fs/promises";import Ao 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 em=8388608,fw=new Set(["resolved","failed"]),hw=[{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 Ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Io(e){return hw.find(t=>t.matches(e))?.kind}function tm(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let a=Ze(i.agent_provenance)?i.agent_provenance:void 0;if(a===void 0||!el(i).ok)return i;let o={},s=!1;for(let[d,l]of Object.entries(a)){let u=Ze(l)?Io(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,tl(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 nm(e){let t=[];for(let n of await rm(e)??[])try{let r=await xo.readFile(Ao.join(e,"history",n),"utf8");for(let i of r.split(`
8
- `)){if(i.trim().length===0)continue;let a=im(i);if(!(a===null||!Ze(a.agent_provenance))&&Object.values(a.agent_provenance).some(o=>Ze(o)&&Io(o.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function rm(e){try{return(await xo.readdir(Ao.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function _w(e,t,n){let r;try{r=await xo.open(Ao.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 im(e){try{let t=JSON.parse(e);return Ze(t)?t:null}catch{return null}}function gw(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=Ze(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([o,s])=>{if(!Ze(s))return;let c=Io(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)}),!Ze(e.context))return;let a=e.context.agent_provenance_outcomes;Ze(a)&&Object.entries(a).forEach(([o,s])=>{if(!Ze(s)||typeof s.resolver!="string"||!fw.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 yw(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=im(s);if(c===null){a.malformed_events+=1;continue}if(typeof c.ts=="string"&&At(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)}gw(c,t,n)}return{eventsRead:o,truncated:!1}}function ww(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 am(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:em,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 rm(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await _w(e,u,Math.max(0,em-o));if(m===null){n.unreadable_sources+=1;continue}o+=m.bytesRead;let f=yw(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:ww(d,l,n.complete),events_read:a,truncated:s}}import vw 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 Ro(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 bw(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 Oi(e){let t=e.writeHistoryRaw??Z;try{await t(e.historyPath,e.nextHistoryRaw),await eo(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await vw.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await eo(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function om(e){let t=[...Ro({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 bw({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 sm(e){let{subject:t,settings:n,operation:r,options:i}=e,a=await Xd(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=G(i.author,n.author_default),c=await e.transform({raw:a.raw,entries:a.entries,verification:Bn(a.entries),loadedItem:o,author:s}),d=Bn(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 om({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 Oi({historyPath:t.historyPath,nextHistoryRaw:Gt(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 Di(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=Sd(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 Pi(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}import To from"node:fs/promises";import ue from"node:path";import kw from"node:readline/promises";import{stdin as Sw,stdout as Ni}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 vD=["ask","add","skip","status"],Ew=["AGENTS.md","CLAUDE.md"],xw=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Aw=8,$o=1,Iw="<!-- pm-cli:agent-guidance:start:",Rw=`<!-- pm-cli:agent-guidance:start:v${$o} -->`,Co="<!-- pm-cli:agent-guidance:end -->",or="Add workflow guidance later: pm init --agent-guidance add";var Cw=()=>kw.createInterface({input:Sw,output:Ni});function bn(e,t){let n=ue.relative(e,t);return n.length===0?ue.basename(t):n.split(ue.sep).join("/")}function cm(e){return e.endsWith(`
1
+ import{a as qa,c as Vr,d as Jr,e as kd,g as Ed,h as Va,i as Sd,j as ln,k as un,l as xd,m as Ad,n as Ja,o as Cd,p as mn,q as pn,r as Td,s as $d,t as Ka}from"./chunk-CYEZLKLL.js";import{e as ri,f as eo,h as to}from"./chunk-RNAWRTQV.js";import{B as qd,C as ei,D as Bd,E as Qa,G as Vd,H as Jd,J as Kd,K as ti,M as ni,a as hd,g as Wa,i as _d}from"./chunk-AXBO53EQ.js";import{K as ou}from"./chunk-SV6YYZLR.js";import{D as oo,E as _i,Ha as Xl,Ia as Zl,Ma as Ql,Na as eu,T as gi,U as Il,V as so,W as Zn,Y as co,aa as Fl,ba as Ul,ca as zl,da as Hl,ea as vi,f as gl,g as yl,ga as Gl,h as wl,ha as Wl,i as vl,ia as ql,ja as Vt,k as hi,ka as Bl,kb as ru,la as yn,ma as Vl,mb as mo,na as lo,nb as iu,o as Yn,oa as wn,ob as au,p as bl,pa as Jl,q as kl,qa as Kl,r as Xn,ra as Yl,s as El,sa as uo,u as ao,v as Sl,wb as po,z as xl}from"./chunk-YCOJLIDI.js";import{a as yd,b as dn,c as Ba,d as wd,e as vd,f as st,g as Kr,h as bd,i as It}from"./chunk-AJG3DBXR.js";import{$ as el,$b as bi,Ba as ul,Bb as ne,Ca as ml,Cb as ve,D as W,Db as be,E as Yd,Ea as Tt,Eb as Ml,Fa as Kn,Fb as wi,Ga as pl,Gb as dt,H as Ce,Ha as di,Hb as lt,I as no,Ia as Bt,Ja as ce,Ka as li,Kb as jl,La as fl,Lb as ut,Ma as io,Na as ui,O as Xd,Oa as gn,P as ii,Pa as mi,Qa as hl,S as ai,T as oi,Ua as Te,V as Zd,W as je,Xa as _l,Ya as T,Z as Ct,Za as pi,Zb as Qn,_ as Qd,_a as fi,aa as tl,ab as Al,ba as ct,ca as nl,gc as tu,ha as rl,hb as Rl,ia as ro,ib as Cl,ja as si,jc as nu,ka as hn,kb as Tl,lb as $l,ma as ci,mb as $t,na as il,nb as Ol,oa as al,ob as Dl,qa as ol,rb as Pl,sa as sl,sb as Nl,ua as cl,wa as dl,xb as yi,ya as _n,za as ll,zb as Ll}from"./chunk-7QIZB2F2.js";import{b as sn,e as le,g as Le,i as Re,j as Xe,n as ge,o as Id,p as Yr,r as Rd}from"./chunk-FXRWJEQ5.js";import{$ as g,$a as L,$c as Me,$d as Rt,Ac as Zr,Ba as fe,Bb as Ke,Bc as jd,Ca as Ne,Cc as Fd,Da as rd,Db as Ye,Ec as Ud,Fa as ee,Ia as id,Mc as z,Na as ad,Nb as gd,Pc as X,Rc as Ge,S as Yc,Sb as Xr,Sc as zd,T as Xc,Ta as od,Tb as Od,Tc as Qr,Ua as sd,Ub as Ya,V as Zc,Va as G,Vb as Xa,Wb as Za,X as Qc,Y as qr,Yb as Dd,Yd as $,Z as ed,Zb as Pd,Zd as Wd,_a as Jn,_c as Hd,_d as fn,a as Gr,aa as y,ab as Je,ac as Nd,ae as qt,bb as Br,bd as Gd,cb as Ht,d as Wr,eb as cd,fb as Gt,fe as te,ha as td,hb as dd,hc as Ld,i as Vc,ib as ld,jb as ud,ka as nd,l as Jc,m as Kc,ma as Ha,ra as Vn,rb as md,sa as O,sb as Wt,ta as At,tb as C,ua as F,ub as pd,va as V,vb as Ie,w as za,xb as Ga,ya as Z,yb as fd,yc as Md,zb as cn}from"./chunk-RZVNGUT7.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}},Ze=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function 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 su(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 ty}from"node:crypto";import ny from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="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 du=1,Jt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],fo=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],ry=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],iy=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,ki=30,Ei=5e3,lu=4,ay=50;function mt(e,t){if(!iy.test(e))throw new M(`${t} must be a stable lowercase id`)}function oy(e,t){if(!Number.isFinite(e)||e<0)throw new M(`${t} must be a finite non-negative number`)}function er(e){let t=ry.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 _o(e,t){return C(e)===C(t)}function uu(e,t){if(t.polarity==="equals")return _o(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 mu(e){let t=er(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>uu(r.observed,t)===(r.expected==="pass"))}function sy(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!_o(e.value,t.value)}function cy(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 sy(er(e),er(t))||n[t.enforcement]<n[e.enforcement]||r}function dy(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 ly(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 uy(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 go(e){mt(e.id,"measurement.id"),e.max_cost!==void 0&&oy(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 ${fo.join(", ")}`);let n=Reflect.get(t,"kind");if(!fo.includes(n))throw new M(`measurement.source.kind must be one of ${fo.join(", ")}`);let r=t;if(r.kind==="items"&&dy(r),r.kind==="dependency_kind"&&ly(r),r.kind==="prose_edge_gap"&&uy(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"&&(mt(r.provider,"provider source provider"),mt(r.key,"provider source key")),e}function yo(e){if(mt(e.id,"assertion.id"),mt(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=er(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"&&mt(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(!mu(e))throw new M(`assertion ${e.id} negative control does not prove its bound`);return e}function my(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)mt(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 pu(e){if(mt(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)mt(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&&my(e.provider_policy),e}function kn(e){if(e.version!==du)throw new M(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(go(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(yo(r),t.has(`assertion:${r.id}`))throw new M(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){pu(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 fu(e))if(!n.has(r))throw new M(`${i.join(", ")} references missing measurement ${r}`);return e}function wo(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)wo(n,t)}function fu(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=[];wo(r.source.expression,i);for(let a of i)n(a,`derived measurement ${r.id}`)}return t}function py(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"&&wo(o.source.expression,n)}return i}function tr(){return{version:du,measurements:[],assertions:[],gates:[]}}function fy(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 _o(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function hy(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 _y(e,t){let n=[],r=Ha(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let a of i.dependencies??[]){let o=Ha(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===r&&hy(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 gy(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 yy(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 ho(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function wy(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(ho(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(ho(o.id,s));for(let s of gy(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 vy(e,t){let n=wy(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=ho(o.holder_id,d);if(n.linked_pairs.has(l)||yy(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 by(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 ky(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 Ey(e,t){let n=e.source;return n.kind==="items"?fy(n,t):n.kind==="dependency_kind"?_y(n,t):n.kind==="prose_edge_gap"?vy(n,t):n.kind==="history"?by(n,t):n.kind==="links"?ky(n,t):null}function hu(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 Sy(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 _u(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 gu(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 yu(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 _u(e.operands,lu,o=>gu(o,t,n,r,i));return{value:Sy(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 xy(e,t,n,r,i){go(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await gu(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=Ey(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=hu([...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:${ty("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 yu(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=xy(e,t,n,r,i).catch(s=>{if(s instanceof Ze&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new Ze(s.message,c);throw d.cause=s,d}throw s});return i.cache.set(e.id,o),o}async function vo(e,t,n=[e]){return yu(e,t,n,[],{cache:new Map,charged:new Set})}function Ay(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 Iy(e,t,n={}){yo(e);let r=er(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:Ay(t.value,r),verdict:i?"retired":uu(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:mu(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Ry(e,t,n,r){let i=py(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 cu(e,t,n,r,i){try{return await vo(n,r,i)}catch(a){if(a instanceof Ze){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 wu(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}`);Ry(i,t,n,r.trigger);let a=await _u(i.assertion_ids,lu,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 cu(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 Iy(d,await cu(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:hu(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function Si(e){return ny.join(e,"assurance.json")}async function vu(e){let t=await V(Si(e));return t===null?tr():xi(t)}function xi(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 Ai(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Cy(e,t){e==="measurement"?go(t):e==="assertion"?yo(t):pu(t)}async function nr(e,t){let n=structuredClone(Ai(await vu(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function bo(e,t,n){let r=Ai(await vu(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Ii(e,t,n,r={}){Cy(t,n);let i=await T(e),a=W(r.author,i.author_default),o=await gn({pmRoot:e,filePath:Si(e),op:`assurance:${t}:put`,author:a,message:r.message,lockTtlSeconds:ki,lockWaitMs:Ei,mutate:s=>{let c=s===null?tr():xi(s),d=Ai(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&cy(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 ko(e,t,n={}){let r=tr();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:Si(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:ki,lockWaitMs:Ei,mutate:s=>{let c=s===null?tr():xi(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 bu(e,t,n,r={}){let i=await T(e),a=W(r.author,i.author_default),o=await gn({pmRoot:e,filePath:Si(e),op:`assurance:${t}:remove`,author:a,message:r.message,lockTtlSeconds:ki,lockWaitMs:Ei,mutate:s=>{let c=s===null?tr():xi(s);if(t==="measurement"){let u=fu(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=Ai(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 ku(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await T(e);await ui({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:ki,lockWaitMs:Ei})}async function Eu(e,t={}){let n=t.limit??ay;if(!Number.isInteger(n)||n<1||n>bn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${bn}`);return(await ct(li(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 rr={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Ri={type:"array",minItems:1,maxItems:Ya,items:rr},Su={...Ri,items:{...rr,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},Ty={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,Ri])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:rr,id:rr}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Su}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Ri}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Su,authors:Ri}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Ya,items:{type:"array",minItems:2,maxItems:2,items:rr}}}}]}}},h$={$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:Od,items:Ty}}};(function(){try{var e=typeof window<"u"?window:typeof 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 xu(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"]}:Au(i,t,n,r)}function $y(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Au(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=Nd(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:$y(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 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]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function Dy(){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 Cu(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 Py(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 Iu(e,t,n,r){if(e==="policy-mode")return Za({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let a=Xa(r.definition),o=Za({...n,policies:[...i,a].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
5
+ `)>Tl)throw new y("Policy registry exceeds its byte ceiling.",g.USAGE);return o}async function Ru(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:Iu(e,t,await $t(r.pmRoot),n)};let i=await gn({pmRoot:r.pmRoot,filePath:Oy.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=Iu(e,t,$l(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 Ny(e,t,n){let r,i=await jl({...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 Ol(n.pmRoot,a.metadata.id),r={policy_id:o.id,policy_fingerprint:Dd(o),content_fingerprint:Pd(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 Ly(e,t){let n=Cu(t),r=Xa({...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 N$(e,t,n={},r={}){if(!Xr.includes(e))throw new y("Unknown workflow policy action.",g.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:Dy()};let i=await Py(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=Ly(t,n.definition);return Ru(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 Ru(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 Ny(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,...Cu(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 Dl(i.pmRoot,await $t(i.pmRoot),{operation:"update",author:i.author,before:c,after:d,completeness_only:n.definition===void 0})}}import{createHash as zu}from"node:crypto";import ir from"node:fs/promises";import ar from"node:path";import{Option as rO}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 pt(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 My(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),pt(n,"--match",t.match),pt(n,"--only-index",typeof t.onlyIndex=="number"?String(t.onlyIndex):t.onlyIndex),Fe(n,"--only-last",t.onlyLast),Kt(n,"--measure",t.measure),pt(n,"--metric-below",t.metricBelow),pt(n,"--metric-diff",t.metricDiff),jy(n,t),pt(n,"--author",t.author),pt(n,"--message",t.message),Fe(n,"--force",t.force),n}function jy(e,t){pt(e,"--timeout",t.timeout),Kt(e,"--env-set",t.envSet),Kt(e,"--env-clear",t.envClear),Fe(e,"--shared-host-safe",t.sharedHostSafe),pt(e,"--pm-context",t.pmContext),Fe(e,"--override-linked-pm-context",t.overrideLinkedPmContext),pt(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]="28bbc7e0-cdd8-5966-b2be-43910681cd94")}catch{}})();function Fy(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 Ci(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 ft(e,t){return e[t]===!1?!0:void 0}function Tu(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function $u(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function Ou(e){let t=i=>Wa(e,Ci(ri,i)),n=i=>_d(e,Ci(eo,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:Fy(e,Ci(eo,"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:Tu(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 $u(r,e),r}function ie(e,t){let n=Ci(hd,t),r=Wa(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 Uy(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:ft(e,"notes"),noLearnings:ft(e,"learnings"),noFiles:ft(e,"files")??t,filterFilesMissing:t,noDocs:ft(e,"docs")??n,filterDocsMissing:n,noTests:ft(e,"tests"),noComments:ft(e,"comments"),noDeps:ft(e,"deps"),emptyBody:U(e,"emptyBody"),noLinkedCommand:ft(e,"linkedCommand")}}function Du(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:ft(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:Tu(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:U(e,"filterResolutionMissing"),filterMetadataMissing:U(e,"filterMetadataMissing"),...Uy(e)};return $u(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]="bd5ef423-5675-585c-ac2f-0b7548636596")}catch{}})();var zy=Symbol("pm.mcp-mutation-transport"),Hy=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function $i(e){return zy in e}function Oi(e,t){return $i(e)?El(t):ao(e,t)}function _O(e,t,n=[]){let r=ao(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 gO(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 xo(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 yO(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 wO(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 Gy=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Nu=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"]),Wy=new Set([...Nu].filter(e=>e!=="file")),qy=new Set(["files","files-discover","docs","test","test-all"]),Lu=new Set(["comments","notes","learnings"]);function By(e,t){if(!(!Lu.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 Vy=new Set(["claim","release","start-task","pause-task","close-task"]),Jy={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun","offline"],package:["dryRun","offline"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Ky=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Mu(e,t=""){let n={},r=qy.has(t),i=t==="files"||t==="files-discover"||t==="docs",a=Lu.has(t)?Wy:Nu;for(let[o,s]of Object.entries(e)){if(Array.isArray(s)&&Gy.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 Yy(e,t,n){let r=P(e,"author");return r!==void 0?r:n!==void 0&&Vy.has(n)?P(e,"assignee")??P(t,"assignee"):void 0}function Xy(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function vO(e,t){let n=En(e.options)?e.options:void 0,r=ad(e.options),i={},a=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of Jy[t??""]??[])a(c);for(let c of Ky)a(c);t!==void 0&&$i(e)&&By(t,r);let o=Mu({...i,...r},t);if(t==="history-attest"&&$i(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=$i(e)?e:n??e;return Oi(s,Xy(o,Yy(e,o,t)))}function bO(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 kO(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 Zy(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 EO(e){return!Hy.has(Zy(e))}function SO(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function Ao(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function xO(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 AO(e,t){let n=Oi(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function So(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:oo(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 Eo(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return Ao(e)}function Ti(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function IO(e){let t=Eo(e.kind),n=Eo(e.exemptIsolate),r=Eo(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Ti(e.maxDepth),limit:Ti(e.limit),after:P(e,"after"),direction:P(e,"direction"),maxPaths:Ti(e.maxPaths),sample:Ti(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 ju(e){let t=Du(e);return e.ids!==void 0&&(t.ids=oo(e.ids)),t}function RO(e){return{status:P(e,"filterStatus"),list:En(e.list)?ju(e.list):So(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 Qy=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 Pu(e){let t={};for(let[n,r]of Object.entries(e))Qy.has(n)||(t[n]=r);return Fu(t)}function Fu(e){let t=Mu(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 Ou(t)}function CO(e){if(En(e.list)||En(e.update)){let t=En(e.update)?e.update:Pu(e),n=Oi(e,Fu(t));return{status:oe(e,"filterStatus"),list:En(e.list)?ju(e.list):So(e),update:Sl(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:So(e),update:Oi(e,Pu(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 ew="2026-07-15T06:22:12.276Z",tw=Date.parse(ew),nw=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Uu=e=>typeof e=="string"?e:"",Hu=e=>{let t=e??{},n=Uu(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Uu(t.ts))>=tw);return nw[r][i]};function Gu(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=Hu(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 FO=(e,t,n=20,r=new Set)=>Gu(e,t,n,r);function Wu(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 or=async(e,t=20,n=!1)=>{let r=ar.join(e,"history"),i;try{i=(await ir.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=Wu(await ir.readFile(ar.join(r,p),"utf8"))}catch{h=new Set}for(let w of i){let v;try{v=await ir.readFile(ar.join(r,w),"utf8")}catch{continue}let E=w.slice(0,-6),k=Gu(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 rw(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 iw(e){try{return Wu(await ir.readFile(ar.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function aw(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 ow(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 Hu(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:zu("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function qu(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=rw(t.all_actionable===!0?(await or(e,0,!0)).actionable_events:r),o=await iw(e),s=new Map;for(let m of a)if(aw(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 ir.readFile(ar.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=>ow(m,o,s.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=zu("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 UO(e,t,n=50){return(await qu(e,t,n)).plan}function sw(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:cw(e),all_actionable:t}}function cw(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 zO(e,t){let n=sw(Ao(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return dw(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 dw(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",a=await qu(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 ui({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 lw}from"node:child_process";import Bu 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 Vu(e,t){return new Promise((n,r)=>{lw("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,a)=>{i?r(i):n(a)})})}function Ju(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function BO(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Ju(n),!n)throw new RangeError("Source line range must use start:end.");return n}function uw(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 mw(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 pw(e){let t=Bu.relative(e.workspaceRoot,Bu.resolve(e.workspaceRoot,e.sourcePath)),n=await Vu(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Vu(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:uw(n),commitItems:mw(r),available:!0}}function fw(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 hw(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=fw({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 _w(e,t,n){let r=nu(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=hw({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 gw(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await pw({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function yw(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 ww(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Ku(e){Ju(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await gw(e),r=ww(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=_w(a.item.id,e.corpus,t),d=yw({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 sr=["software-delivery","research","agent-evaluation","operations"];function Yu(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 Di(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=>Yu(`${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 Pi(e,t){return e==="software-delivery"?Di(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Di(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Di(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Di(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function Xu(e,t,n,r={}){return ko(e,Pi(t,n).declarations,r)}async function Zu(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(i=>!n.has(i.status))};return await Promise.all(["files","tests","docs"].map(async i=>{let a={id:`derived-active-missing-${i}`,description:`Observed active items missing ${i} evidence.`,source:{kind:"links",link:i,state:"missing"}},o=(await vo(a,r)).value,s=Yu(`${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 Qu(e,t,n={}){return ko(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 em(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 Ii(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import rm from"node:fs/promises";import{createRequire as vw}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 tm(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 bw(e){return e.includes(`${Oe.sep}.pnpm${Oe.sep}`)?"pnpm":e.includes(`${Oe.sep}node_modules${Oe.sep}`)?"npm":"other"}async function nm(e){try{let t=JSON.parse(await rm.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 Io(e){try{return await rm.realpath(e)}catch{return Oe.resolve(e)}}async function im(e,t,n=Ne(import.meta.url,["../../.."])){let r=await Io(t),i=await Io(Oe.join(n,"package.json")),a=await nm(i),o=new Map;a!==void 0&&o.set(i,{version:a,path:tm(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=vw(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await Io(l),m=await nm(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:tm(u,r),layout:bw(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 Ro from"node:fs/promises";import Co 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 am=8388608,kw=new Set(["resolved","failed"]),Ew=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function Qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function To(e){return Ew.find(t=>t.matches(e))?.kind}function om(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let a=Qe(i.agent_provenance)?i.agent_provenance:void 0;if(a===void 0||!il(i).ok)return i;let o={},s=!1;for(let[d,l]of Object.entries(a)){let u=Qe(l)?To(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,al(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 sm(e){let t=[];for(let n of await cm(e)??[])try{let r=await Ro.readFile(Co.join(e,"history",n),"utf8");for(let i of r.split(`
8
+ `)){if(i.trim().length===0)continue;let a=dm(i);if(!(a===null||!Qe(a.agent_provenance))&&Object.values(a.agent_provenance).some(o=>Qe(o)&&To(o.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function cm(e){try{return(await Ro.readdir(Co.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function Sw(e,t,n){let r;try{r=await Ro.open(Co.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 dm(e){try{let t=JSON.parse(e);return Qe(t)?t:null}catch{return null}}function xw(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=Qe(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([o,s])=>{if(!Qe(s))return;let c=To(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)}),!Qe(e.context))return;let a=e.context.agent_provenance_outcomes;Qe(a)&&Object.entries(a).forEach(([o,s])=>{if(!Qe(s)||typeof s.resolver!="string"||!kw.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 Aw(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=dm(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)}xw(c,t,n)}return{eventsRead:o,truncated:!1}}function Iw(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 lm(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:am,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 cm(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await Sw(e,u,Math.max(0,am-o));if(m===null){n.unreadable_sources+=1;continue}o+=m.bytesRead;let f=Aw(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:Iw(d,l,n.complete),events_read:a,truncated:s}}import Rw 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 $o(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 Cw(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 Ni(e){let t=e.writeHistoryRaw??Z;try{await t(e.historyPath,e.nextHistoryRaw),await ro(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await Rw.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await ro(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function um(e){let t=[...$o({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 Cw({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 mm(e){let{subject:t,settings:n,operation:r,options:i}=e,a=await tl(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:Kn(a.entries),loadedItem:o,author:s}),d=Kn(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 um({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 Ni({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 Li(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=Id(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 Mi(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}import Do from"node:fs/promises";import ue from"node:path";import Tw from"node:readline/promises";import{stdin as $w,stdout as ji}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 OD=["ask","add","skip","status"],Ow=["AGENTS.md","CLAUDE.md"],Dw=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Pw=8,Po=1,Nw="<!-- pm-cli:agent-guidance:start:",Lw=`<!-- pm-cli:agent-guidance:start:v${Po} -->`,Oo="<!-- pm-cli:agent-guidance:end -->",dr="Add workflow guidance later: pm init --agent-guidance add";var Mw=()=>Tw.createInterface({input:$w,output:ji});function Sn(e,t){let n=ue.relative(e,t);return n.length===0?ue.basename(t):n.split(ue.sep).join("/")}function pm(e){return e.endsWith(`
11
11
  `)?e:`${e}
12
- `}function Tw(e){return e.includes(`\r
12
+ `}function jw(e){return e.includes(`\r
13
13
  `)?`\r
14
14
  `:`
15
- `}function dm(e){let t=e.indexOf(Iw);if(t===-1)return null;let n=e.indexOf(Co,t);return n===-1?null:{start_index:t,end_index:n+Co.length}}function $w(e){return dm(e)!==null}function Ow(e,t="<your project test command>"){return[Rw,"## 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.","",Co,""].join(e)}function lm(e,t="<your project test command>"){let n=Tw(e),r=Ow(n,t),i=dm(e);if(i){let s=e.slice(i.end_index),c=s.startsWith(`\r
15
+ `}function fm(e){let t=e.indexOf(Nw);if(t===-1)return null;let n=e.indexOf(Oo,t);return n===-1?null:{start_index:t,end_index:n+Oo.length}}function Fw(e){return fm(e)!==null}function Uw(e,t="<your project test command>"){return[Lw,"## 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.","",Oo,""].join(e)}function hm(e,t="<your project test command>"){let n=jw(e),r=Uw(n,t),i=fm(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=cm(`${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=pm(`${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=cm(`${e}${a}${r}`);return{next_content:o,changed:o!==e}}async function um(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 To.readFile(ue.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=Dw(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 Dw(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 Pw(e,t){let n=ue.dirname(e);return ue.basename(e)==="pm"&&ue.basename(n)===".agents"?ue.dirname(n):ue.resolve(t,e)}function Nw(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 Lw(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 Mw(e){let t=Cw();try{Ni.write(`
21
+ `,o=pm(`${e}${a}${r}`);return{next_content:o,changed:o!==e}}async function _m(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 Do.readFile(ue.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=zw(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 zw(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 Hw(e,t){let n=ue.dirname(e);return ue.basename(e)==="pm"&&ue.basename(n)===".agents"?ue.dirname(n):ue.resolve(t,e)}function Gw(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 Ww(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 qw(e){let t=Mw();try{ji.write(`
22
22
  Agent guidance check
23
- `),Ni.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 Ni.write(`
25
- `),Lw(n,!0)}finally{t.close()}}function mm(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:$o,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 pm(e){let t=[],n=await um(e);for(let r of Ew){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 To.readFile(i,"utf8"),s=o.toLowerCase(),c=xw.filter(l=>s.includes(l)),d=$w(o);t.push({file_path:i,exists:a,has_guidance:d||c.length>=Aw,has_marker:d,outdated:d&&lm(o,n).changed})}return t}function Vt(e,t){e.includes(t)||e.push(t)}function jw(e,t){let n=mm(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function fm(e,t=ue.dirname(e)){let n=await O(e)?await To.readFile(e,"utf8"):"",r=lm(n,await um(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 Fw(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>bn(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>bn(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>bn(e.projectRoot,t.file_path))}}async function Uw(e,t,n){return e?await pm(n):t}function ar(e,t,n){e.state={...e.state,...n,template_version:$o,last_checked_files:t}}async function hm(e,t){if(t.presentBefore)return;let n=await fm(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Hw(e,t){t||(e.warnings.push("agent_guidance:missing"),Vt(e.nextSteps,or))}function zw(e,t){e.skipped=!0,ar(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Vt(e.nextSteps,or)}async function Ww(e,t){await hm(e,t),ar(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Gw(e,t){e.state.declined&&ar(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function qw(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Vt(e.nextSteps,or)}async function Bw(e,t){if(e.prompted=!0,await Mw(t.targetRelativePath)){await hm(e,t),ar(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,ar(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Vt(e.nextSteps,or)}function Vw(e){e.warnings.push("agent_guidance:missing_non_interactive"),Vt(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Vt(e.nextSteps,or)}async function Jw(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Hw(n,t.presentBefore),n):t.mode==="skip"?(zw(n,t.checkedFiles),n):t.mode==="add"?(await Ww(n,t),n):t.presentBefore?(Gw(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(qw(n),n):t.interactive?(await Bw(n,t),n):(Vw(n),n)}async function _m(e){let t=Pw(e.pm_root,e.cwd),n=await pm(t),r=Nw(n,t),i=bn(t,r),a=n.map(l=>bn(t,l.file_path)),o=n.some(l=>l.has_guidance),s=await Jw(mm(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 fm(l.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=jw(e.settings,s.state);n=await Uw(s.applied,n,t);let d=n.filter(l=>l.outdated).map(l=>bn(t,l.file_path));return d.length>0&&(s.warnings.push(`agent_guidance_outdated:${d.join(",")}`),Vt(s.nextSteps,"pm init --agent-guidance add")),{summary:Fw({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 kt from"node:fs/promises";import Se from"node:path";import sr from"node:fs/promises";import{createHash as Kw}from"node:crypto";import ym 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 Oo=new Set([void 0,...Bd]),wm=11,Yw="history-drift-cache.json";function vm(e){return ym.join(e,"runtime",Yw)}async function Xw(e){try{let t=await sr.readFile(vm(e),"utf8"),n=JSON.parse(t);return n.version!==wm||n.history_item_hash_version!==ii||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!Oo.has(r.hash_algorithm)||!mn.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&mn.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}function bm(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function km(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 Zw(e,t,n,r,i){let a=si(e),o;try{o=await sr.stat(a)}catch(d){return F(d)||i.unreadableStreams.push(ce),!1}let s=i.missingStreams.length,c=await Sm({itemId:ce,historyPath:a,stat:o,cached:t[ce],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(ce),c.verification.chainOk||i.chainMismatches.push(ce),n[ce]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion,hash_algorithm:c.verification.hashAlgorithm},c.cacheDirty):(i.missingStreams.splice(s),c.cacheDirty)}function Qw(e){return!Oo.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!mn.includes(e.item_hash_version)}async function ev(e){let t=await sr.readFile(e,"utf8"),n=Kw("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=Rt(r),o=r.some(Qw),s=r[r.length-1],c=Oo.has(s.hash_algorithm),d=s.item_hash_version,l=d!==void 0&&mn.includes(d),u=l?d:a.item_hash_version;return{latestAfterHash:i,hashAlgorithm:c?Ce(s.hash_algorithm):void 0,identityDiscontinuities:il(r),chainOk:a.ok,versionSkew:o,latestHashComparable:c&&u!==void 0&&(!o||l||d===void 0),contentHash:n,itemHashVersion:u??ii}}function tv(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function gm(e,t,n){try{return await ev(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function nv(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 Sm(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(tv(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await gm(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await gm(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!nv(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&&mn.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function Em(e,t,n,r){let i,a;try{i=Ht(e,t.id),a=await sr.stat(i)}catch(d){return(F(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let o=await Sm({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&&(nl({metadata:c,body:s},o.verification.itemHashVersion,o.verification.hashAlgorithm).includes(o.verification.latestAfterHash)||r.hashMismatches.push(t.id)),o.cacheDirty}async function rv(e,t){if(!(t.unreadableStreams.includes(ce)||t.chainMismatches.includes(ce)||t.versionSkews.includes(ce)))try{let n=await ll(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 xm(e,t){let n=bm();return await Em(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),km(n)}async function Jt(e,t,n={}){let r=bm(),i=(await Xw(e))?.entries??{},a={},o=!1,s=n.cacheHitVerification!=="metadata",c={previousEntries:i,nextEntries:a,verifyCacheHitByContent:s};for(let l of t)await Em(e,l,c,r)&&(o=!0);let d=await Zw(e,i,a,s,r);if(o||=d,await rv(e,r),o||Object.keys(i).length!==Object.keys(a).length){let l=vm(e);try{await sr.mkdir(ym.dirname(l),{recursive:!0}),await Z(l,JSON.stringify({version:wm,history_item_hash_version:ii,entries:a}))}catch{}}return km(r)}import cr from"node:fs/promises";import Li from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5974276-3b45-5ad6-a7aa-e05a33807ee7")}catch{}})();function iv(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 Am(e,t,n){let r=iv(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 Im(e,t){let n=t??Date.now(),r=Li.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 cr.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 cr.readFile(Li.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}=Am(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 Rm(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Li.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await cr.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=Li.join(a,c),l=`locks/${c}`;if(r?.onRead){let f=await r.onRead(d);o.warnings.push(...f)}let u;try{u=await cr.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=Am(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 cr.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]="3d7db45e-123f-596b-afc7-b698f2b2f45c")}catch{}})();var av=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Do(e){if(typeof e!="string")return;let t=e.trim();for(let n of av)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Po(e){let t={};for(let n of e){let r=Do(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Cm(e){return Object.values(Po(e))}import Lt 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 ov=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function kn(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Kr(t.extensionName));for(let _ of t.extensionNames??[])n.add(Kr(_));let r=_=>n.size===0||n.has(Kr(_)),i=(_,w)=>Tm(_.filter(v=>r(v.name)).map(w)),a=(_,w)=>Tm(_.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:Pd(e,t),commands:i(o.commands,_=>_.command),command_overrides:i(s.overrides,_=>_.command),command_handlers:i(s.handlers,_=>_.command),hooks:ov.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 Tm(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import Eb from"node:path";import{mkdir as xb}from"node:fs/promises";import{access as kv,readFile as qo,realpath as Tt}from"node:fs/promises";import{constants as Sv}from"node:fs";import{execFile as Ev}from"node:child_process";import J from"node:path";import{promisify as xv}from"node:util";import{readFile as sv,writeFile as cv}from"node:fs/promises";import dr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1de99e25-e132-5071-833e-37361b4cc7e6")}catch{}})();var Om="# pm-cli:runtime-cache:start",No="# pm-cli:runtime-cache:end",Dm=".agents/pm",Lo=["runtime/","search/","locks/","transactions/","checkpoints/"],dv=["search/eval-queries.json"];async function $m(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 Pm(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function Mo(e){let t=e.replaceAll("\\","/");return dr.isAbsolute(e)||t===".."||t.startsWith("../")}function lv(e=Dm){let t=Pm(e);return[Om,...Lo.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...dv.map(n=>`!${t}/${n}`),No].join(`
26
- `)}async function qD(e,t={}){let n=dr.join(e,".gitignore"),r=Dm;if(t.pmRoot!==void 0){let d=Pm(dr.relative(dr.resolve(e),dr.resolve(t.pmRoot)));if(Mo(d))return{path:n,changed:!1};d.length>0&&(r=d)}let i="";try{i=await $m(()=>sv(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&F(d)))throw d}let a=i.indexOf(Om),o=i.indexOf(No),s=(a>=0&&o>=a?`${i.slice(0,a)}${i.slice(o+No.length)}`:i).trimEnd(),c=`${s.length>0?`${s}
23
+ `),ji.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 ji.write(`
25
+ `),Ww(n,!0)}finally{t.close()}}function gm(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:Po,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 ym(e){let t=[],n=await _m(e);for(let r of Ow){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 Do.readFile(i,"utf8"),s=o.toLowerCase(),c=Dw.filter(l=>s.includes(l)),d=Fw(o);t.push({file_path:i,exists:a,has_guidance:d||c.length>=Pw,has_marker:d,outdated:d&&hm(o,n).changed})}return t}function Yt(e,t){e.includes(t)||e.push(t)}function Bw(e,t){let n=gm(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function wm(e,t=ue.dirname(e)){let n=await O(e)?await Do.readFile(e,"utf8"):"",r=hm(n,await _m(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 Vw(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 Jw(e,t,n){return e?await ym(n):t}function cr(e,t,n){e.state={...e.state,...n,template_version:Po,last_checked_files:t}}async function vm(e,t){if(t.presentBefore)return;let n=await wm(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Kw(e,t){t||(e.warnings.push("agent_guidance:missing"),Yt(e.nextSteps,dr))}function Yw(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 Xw(e,t){await vm(e,t),cr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Zw(e,t){e.state.declined&&cr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Qw(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Yt(e.nextSteps,dr)}async function ev(e,t){if(e.prompted=!0,await qw(t.targetRelativePath)){await vm(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 tv(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 nv(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Kw(n,t.presentBefore),n):t.mode==="skip"?(Yw(n,t.checkedFiles),n):t.mode==="add"?(await Xw(n,t),n):t.presentBefore?(Zw(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Qw(n),n):t.interactive?(await ev(n,t),n):(tv(n),n)}async function bm(e){let t=Hw(e.pm_root,e.cwd),n=await ym(t),r=Gw(n,t),i=Sn(t,r),a=n.map(l=>Sn(t,l.file_path)),o=n.some(l=>l.has_guidance),s=await nv(gm(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 wm(l.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=Bw(e.settings,s.state);n=await Jw(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:Vw({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 rv}from"node:crypto";import Em 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 No=new Set([void 0,...Yd]),Sm=11,iv="history-drift-cache.json";function xm(e){return Em.join(e,"runtime",iv)}async function av(e){try{let t=await lr.readFile(xm(e),"utf8"),n=JSON.parse(t);return n.version!==Sm||n.history_item_hash_version!==si||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!No.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 Am(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function Im(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 ov(e,t,n,r,i){let a=li(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 Rm({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 sv(e){return!No.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!hn.includes(e.item_hash_version)}async function cv(e){let t=await lr.readFile(e,"utf8"),n=rv("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(sv),s=r[r.length-1],c=No.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:cl(r),chainOk:a.ok,versionSkew:o,latestHashComparable:c&&u!==void 0&&(!o||l||d===void 0),contentHash:n,itemHashVersion:u??si}}function dv(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function km(e,t,n){try{return await cv(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function lv(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 Rm(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(dv(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await km(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await km(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!lv(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 Cm(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 Rm({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&&(ol({metadata:c,body:s},o.verification.itemHashVersion,o.verification.hashAlgorithm).includes(o.verification.latestAfterHash)||r.hashMismatches.push(t.id)),o.cacheDirty}async function uv(e,t){if(!(t.unreadableStreams.includes(ce)||t.chainMismatches.includes(ce)||t.versionSkews.includes(ce)))try{let n=await fl(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 Tm(e,t){let n=Am();return await Cm(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),Im(n)}async function Xt(e,t,n={}){let r=Am(),i=(await av(e))?.entries??{},a={},o=!1,s=n.cacheHitVerification!=="metadata",c={previousEntries:i,nextEntries:a,verifyCacheHitByContent:s};for(let l of t)await Cm(e,l,c,r)&&(o=!0);let d=await ov(e,i,a,s,r);if(o||=d,await uv(e,r),o||Object.keys(i).length!==Object.keys(a).length){let l=xm(e);try{await lr.mkdir(Em.dirname(l),{recursive:!0}),await Z(l,JSON.stringify({version:Sm,history_item_hash_version:si,entries:a}))}catch{}}return Im(r)}import ur from"node:fs/promises";import Fi 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 mv(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 $m(e,t,n){let r=mv(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 Om(e,t){let n=t??Date.now(),r=Fi.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(Fi.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}=$m(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 Dm(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Fi.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=Fi.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=$m(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]="3d7db45e-123f-596b-afc7-b698f2b2f45c")}catch{}})();var pv=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Lo(e){if(typeof e!="string")return;let t=e.trim();for(let n of pv)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Mo(e){let t={};for(let n of e){let r=Lo(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Pm(e){return Object.values(Mo(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 fv=[["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(Zr(t.extensionName));for(let _ of t.extensionNames??[])n.add(Zr(_));let r=_=>n.size===0||n.has(Zr(_)),i=(_,w)=>Nm(_.filter(v=>r(v.name)).map(w)),a=(_,w)=>Nm(_.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:jd(e,t),commands:i(o.commands,_=>_.command),command_overrides:i(s.overrides,_=>_.command),command_handlers:i(s.handlers,_=>_.command),hooks:fv.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 Nm(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 Tv,readFile as Jo,realpath as Ot}from"node:fs/promises";import{constants as $v}from"node:fs";import{execFile as Ov}from"node:child_process";import J from"node:path";import{promisify as Dv}from"node:util";import{readFile as hv,writeFile as _v}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 Mm="# pm-cli:runtime-cache:start",jo="# pm-cli:runtime-cache:end",jm=".agents/pm",Fo=["runtime/","search/","locks/","transactions/","checkpoints/"],gv=["search/eval-queries.json"];async function Lm(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 Fm(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function Uo(e){let t=e.replaceAll("\\","/");return mr.isAbsolute(e)||t===".."||t.startsWith("../")}function yv(e=jm){let t=Fm(e);return[Mm,...Fo.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...gv.map(n=>`!${t}/${n}`),jo].join(`
26
+ `)}async function rP(e,t={}){let n=mr.join(e,".gitignore"),r=jm;if(t.pmRoot!==void 0){let d=Fm(mr.relative(mr.resolve(e),mr.resolve(t.pmRoot)));if(Uo(d))return{path:n,changed:!1};d.length>0&&(r=d)}let i="";try{i=await Lm(()=>hv(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&F(d)))throw d}let a=i.indexOf(Mm),o=i.indexOf(jo),s=(a>=0&&o>=a?`${i.slice(0,a)}${i.slice(o+jo.length)}`:i).trimEnd(),c=`${s.length>0?`${s}
27
27
 
28
- `:""}${lv(r)}
29
- `;return c===i?{path:n,changed:!1}:(await $m(()=>cv(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 uv="PM_SOURCE_CONTEXT_ACCESS",mv="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Nm(e){let t=e[uv],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[mv]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}import{execFile as pv}from"node:child_process";import fv from"node:path";import{promisify as hv}from"node:util";import{setTimeout as _v}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 Fo=hv(pv);async function Sn(e,t){let n=performance.now()+5e3,r=25;for(;;)try{await Fo("git",["config",...t],{cwd:e,env:{...Qe(),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 _v(Math.min(r,a)),r=Math.min(r*2,200)}}function Qe(){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 jo(e,t){try{return(await Fo("git",["config","--local",...t==="core.bare"||t==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",t],{cwd:e,env:Qe(),timeout:1e4})).stdout.trim()}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code===1)return;throw n}}async function Lm(e){if(await jo(e,"extensions.worktreeConfig")==="true")return"--worktree";let{stdout:t}=await Fo("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"],{cwd:e,env:Qe(),timeout:1e4}),[n,r]=t.trim().split(/\r?\n/);if(n===r)return"--local";let i=fv.join(r,"config.worktree");for(let a of["core.bare","core.worktree"]){let o=await jo(e,a);o===void 0||a==="core.bare"&&o!=="true"||(await Sn(e,["--file",i,a,o]),await Sn(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 jo(e,s);c!==void 0&&await Sn(e,["--file",i,s,c])}return await Sn(e,["--local","extensions.worktreeConfig","true"]),"--worktree"}import Mm from"node:fs";import Mi from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2d40ac36-0627-5636-9679-5669dbacf06b")}catch{}})();var jm="@unbrained/pm-cli";var zo=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,Wo="2026.8.31";function ji(e){let t=e.match(zo);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function Go(e,t){let n=ji(e),r=ji(t);if(!n||!r)return null;for(let i=0;i<n.length;i+=1){let a=n[i]-r[i];if(a!==0)return Math.sign(a)}return 0}function Uo(e){return Go(e,Wo)!==-1?3:2}function Ho(e){try{let t=JSON.parse(Mm.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function gv(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(r=>({inclusive:r[1]==="<=",version:r[2]})),n=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...t,{inclusive:!0,version:n[1]}]:t}function yv(e){let t=e.split("||").map(n=>gv(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(r=>{let i=Go(Wo,r.version);return i!==null&&(r.inclusive?i!==1:i===-1)}))}}function wv(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let r=n[jm],i=typeof r=="string"?r.trim():"",a=/^[<!]/u.test(i)?void 0:i.match(zo)?.[0];if(!a)return[];let o=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(i),s=yv(i);return[{version:a,constraint:o?"exact":s.bounded?"range":"minimum",...o?{}:{declaration:i},history_epoch_compatible:o?Go(a,Wo)!==-1:s.compatible}]})}function vv(e){let t=Ho(Mi.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let n=t["node_modules/@unbrained/pm-cli"];if(typeof n!="object"||n===null)return;let r=n.version;return typeof r=="string"?r:void 0}function bv(e,t){try{let n=Mm.readFileSync(Mi.join(e,t),"utf8").split(/\r?\n/u),r=n.findIndex(o=>o.includes(jm));if(r<0)return;let i=n[r].match(/^\s*/u)[0].length,a=[n[r]];for(let o=r+1;o<n.length;o+=1){let s=n[o],c=s.trim(),d=s.match(/^\s*/u)[0].length;if(c.length>0&&d<=i)break;a.push(s)}return a.join(`
30
- `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??a[0].match(zo)?.[0]}catch{return}}function Fm(e){let t=[],n=Ho(Mi.join(e,"package.json"));n&&t.push(...wv(n).map(a=>({...a,source:"package.json"})));let r=Ho(Mi.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof r=="string"&&ji(r)&&t.push({version:r,source:"installed-package",constraint:"exact",history_epoch_compatible:Uo(r)===3});let i=vv(e);i&&ji(i)&&t.push({version:i,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Uo(i)===3});for(let a of["pnpm-lock.yaml","yarn.lock"]){let o=bv(e,a);o&&t.push({version:o,source:a,constraint:"exact",history_epoch_compatible:Uo(o)===3})}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36ccb98d-6645-52fe-aac2-be11f3a63c25")}catch{}})();var Kt=xv(Ev),Fi="# pm-cli:merge-drivers:start",Av="# pm-cli:merge-drivers:end",lr="# pm-cli:merge-drivers:v2:start",zm="# pm-cli:merge-drivers:v2:end",Iv="merge-fence",Rv="merge-attributes";function Um(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function Cv(e,t){let n=await Tt(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(n))return;let{stdout:r}=await Kt(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return r.trim()===t?n:void 0}async function Tv(){let e=Ne(import.meta.url,["../../.."]),t=process.execPath,n=!1,r=await Tt(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 kv(s,Sv.X_OK),i!==void 0){let c=await Cv(s,i);if(c!==void 0){t=c,n=!0;break}continue}if(s!==r&&await Tt(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`${Um(t)} ${Um(J.join(e,"dist","cli.js"))}`}var Wm=[{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 $v(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=Nm(e.environment),a=!!(n&&r),o=t===void 0&&a&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let s=L(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}return o?{pm_root:J.resolve(r),workspace_start:J.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:a?L(e.cwd,".agents/pm"):L(e.cwd),workspace_start:e.cwd,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}async function et(e){try{let{stdout:t}=await Kt("git",["rev-parse","--show-toplevel"],{cwd:e,env:Qe(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await Tt(t.trim())}catch{return null}}async function Gm(e){let t=await et(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function Bo(e,t){return J.relative(e,t).replaceAll("\\","/")}function ze(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Hm(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 Ov(e,t,n){if(Fm(t).filter(i=>i.constraint==="exact").some(i=>i.version!==n))return!1;let r=await et(e);if(r!==null&&r!==await Tt(t)){let i=await Promise.all([r,t].map(async a=>{let o=await Kt("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:a,env:Qe(),timeout:1e4});return Tt(o.stdout.trim())}));if(i[0]===i[1])return!1}return!0}async function Dv(e,t,n){let r=Hm(e,0);if(r===null||e[r.nextOffset]!==" ")return!1;let i=Hm(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 qo(J.join(a,"package.json"),"utf8")),s=typeof o.bin=="string"?o.bin:o.bin?.pm;return await Ov(a,n,o.version)?o.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function Vo(e,t){let n=e.length>0?`${e}/`:"",r=[`${ze(`${n}**/*.toon`)} merge=pm-item-toon`,`${ze(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${ze(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${ze(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${ze(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${ze(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${ze(`${n}settings.json`)} merge=pm-json`),r.push(`${ze(`${n}**/*.json`)} merge=pm-json`),r.push(`${ze(`${n}extensions/**`)} -merge`),r.push(`${ze(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function qm(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(Fi,n),i=e.indexOf(lr,n),a=r===-1?i:i===-1?r:Math.min(r,i);if(a===-1)break;let o=a===i,s=o?lr:Fi,c=o?zm:Av,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(`
31
- `).map(u=>u.trim()).filter(Boolean)}),n=l}return t}function Bm(e,t,n){let r=new Set(t),i=ze(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 Vm(e,t,n,r){let i=J.join(e,".gitattributes"),a=r?null:(await Kt("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:Qe(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),o=a===null?null:await te(a,Rv,120,"merge-fence",!1,!0,5e3);try{let s=await V(i)??"",c=[lr,...n,zm].join(`
32
- `),d=qm(s),l=d.filter(m=>Bm(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
+ `:""}${yv(r)}
29
+ `;return c===i?{path:n,changed:!1}:(await Lm(()=>_v(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 wv="PM_SOURCE_CONTEXT_ACCESS",vv="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Um(e){let t=e[wv],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[vv]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}import{execFile as bv}from"node:child_process";import kv from"node:path";import{promisify as Ev}from"node:util";import{setTimeout as Sv}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 Ho=Ev(bv);async function An(e,t){let n=performance.now()+5e3,r=25;for(;;)try{await Ho("git",["config",...t],{cwd:e,env:{...et(),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 Sv(Math.min(r,a)),r=Math.min(r*2,200)}}function et(){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 zo(e,t){try{return(await Ho("git",["config","--local",...t==="core.bare"||t==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",t],{cwd:e,env:et(),timeout:1e4})).stdout.trim()}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code===1)return;throw n}}async function zm(e){if(await zo(e,"extensions.worktreeConfig")==="true")return"--worktree";let{stdout:t}=await Ho("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"],{cwd:e,env:et(),timeout:1e4}),[n,r]=t.trim().split(/\r?\n/);if(n===r)return"--local";let i=kv.join(r,"config.worktree");for(let a of["core.bare","core.worktree"]){let o=await zo(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 zo(e,s);c!==void 0&&await An(e,["--file",i,s,c])}return await An(e,["--local","extensions.worktreeConfig","true"]),"--worktree"}import Hm from"node:fs";import Ui from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2d40ac36-0627-5636-9679-5669dbacf06b")}catch{}})();var Gm="@unbrained/pm-cli";var qo=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,Bo="2026.8.31";function zi(e){let t=e.match(qo);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function Vo(e,t){let n=zi(e),r=zi(t);if(!n||!r)return null;for(let i=0;i<n.length;i+=1){let a=n[i]-r[i];if(a!==0)return Math.sign(a)}return 0}function Go(e){return Vo(e,Bo)!==-1?3:2}function Wo(e){try{let t=JSON.parse(Hm.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function xv(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(r=>({inclusive:r[1]==="<=",version:r[2]})),n=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...t,{inclusive:!0,version:n[1]}]:t}function Av(e){let t=e.split("||").map(n=>xv(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(r=>{let i=Vo(Bo,r.version);return i!==null&&(r.inclusive?i!==1:i===-1)}))}}function Iv(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let r=n[Gm],i=typeof r=="string"?r.trim():"",a=/^[<!]/u.test(i)?void 0:i.match(qo)?.[0];if(!a)return[];let o=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(i),s=Av(i);return[{version:a,constraint:o?"exact":s.bounded?"range":"minimum",...o?{}:{declaration:i},history_epoch_compatible:o?Vo(a,Bo)!==-1:s.compatible}]})}function Rv(e){let t=Wo(Ui.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let n=t["node_modules/@unbrained/pm-cli"];if(typeof n!="object"||n===null)return;let r=n.version;return typeof r=="string"?r:void 0}function Cv(e,t){try{let n=Hm.readFileSync(Ui.join(e,t),"utf8").split(/\r?\n/u),r=n.findIndex(o=>o.includes(Gm));if(r<0)return;let i=n[r].match(/^\s*/u)[0].length,a=[n[r]];for(let o=r+1;o<n.length;o+=1){let s=n[o],c=s.trim(),d=s.match(/^\s*/u)[0].length;if(c.length>0&&d<=i)break;a.push(s)}return a.join(`
30
+ `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??a[0].match(qo)?.[0]}catch{return}}function Wm(e){let t=[],n=Wo(Ui.join(e,"package.json"));n&&t.push(...Iv(n).map(a=>({...a,source:"package.json"})));let r=Wo(Ui.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof r=="string"&&zi(r)&&t.push({version:r,source:"installed-package",constraint:"exact",history_epoch_compatible:Go(r)===3});let i=Rv(e);i&&zi(i)&&t.push({version:i,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Go(i)===3});for(let a of["pnpm-lock.yaml","yarn.lock"]){let o=Cv(e,a);o&&t.push({version:o,source:a,constraint:"exact",history_epoch_compatible:Go(o)===3})}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36ccb98d-6645-52fe-aac2-be11f3a63c25")}catch{}})();var Zt=Dv(Ov),Hi="# pm-cli:merge-drivers:start",Pv="# pm-cli:merge-drivers:end",pr="# pm-cli:merge-drivers:v2:start",Vm="# pm-cli:merge-drivers:v2:end",Nv="merge-fence",Lv="merge-attributes";function qm(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function Mv(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(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 Tv(s,$v.X_OK),i!==void 0){let c=await Mv(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`${qm(t)} ${qm(J.join(e,"dist","cli.js"))}`}var Jm=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function Fv(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=Um(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 tt(e){try{let{stdout:t}=await Zt("git",["rev-parse","--show-toplevel"],{cwd:e,env:et(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await Ot(t.trim())}catch{return null}}async function Km(e){let t=await tt(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 Bm(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 Uv(e,t,n){if(Wm(t).filter(i=>i.constraint==="exact").some(i=>i.version!==n))return!1;let r=await tt(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:et(),timeout:1e4});return Ot(o.stdout.trim())}));if(i[0]===i[1])return!1}return!0}async function zv(e,t,n){let r=Bm(e,0);if(r===null||e[r.nextOffset]!==" ")return!1;let i=Bm(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 Uv(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`),r.push(`${We(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function Ym(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(Hi,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:Hi,c=o?Vm:Pv,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(`
31
+ `).map(u=>u.trim()).filter(Boolean)}),n=l}return t}function Xm(e,t,n){let r=new Set(t),i=We(n.length>0?`${n}/`:"").slice(0,-1);return e.some(a=>r.has(a)||a.startsWith(i)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(a.slice(i.length)))}async function Zm(e,t,n,r){let i=J.join(e,".gitattributes"),a=r?null:(await Zt("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:et(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),o=a===null?null:await te(a,Lv,120,"merge-fence",!1,!0,5e3);try{let s=await V(i)??"",c=[pr,...n,Vm].join(`
32
+ `),d=Ym(s),l=d.filter(m=>Xm(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}
33
33
 
34
34
  `:""}${c}
35
- `}return u===s?{path:i,changed:!1}:(r||await Z(i,u),{path:i,changed:!0})}finally{await o?.()}}function $t(e){let t=W(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function En(e,t){let n=J.resolve(e),r=null,i="",a=n;for(let _=0;_<8;_+=1){let w=J.join(a,".gitattributes");try{let S=await qo(w,"utf8");if(S.includes(lr)||S.includes(Fi)){r=a,i=S;break}}catch{}let v=J.dirname(a);if(v===a)break;a=v}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=J.join(r,".gitattributes"),s=Bo(r,n),c=qm(i),d=Vo(s,t),l=c.filter(_=>Bm(_.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 xn(e){let t=[],n=[];for(let r of Wm){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 Kt("git",["config","--get",i],{cwd:e,env:Qe(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=o.trim();await Dv(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 Jm(e){let t;try{t=await Gm(J.resolve(e))}catch{return{status:"no_git"}}let n=Bo(t,J.resolve(e)),r=await T(e),i=G(void 0,r.author_default),a=await te(e,Iv,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 qo(o,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&F(u))return{status:"not_installed",path:o};throw u}if(!s.includes(lr)&&!s.includes(Fi))return{status:"not_installed",path:o};let c=await T(e),d=$t(c),l=await Vm(t,n,Vo(n,d),!1);return{status:l.changed?"refreshed":"unchanged",path:l.path}}finally{await a()}}async function xP(e,t){let n=$v({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await ne(r);let i=await Gm(n.workspace_start);return Nv({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function Pv(e,t){let n=(await Kt("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:e,env:Qe(),timeout:1e4})).stdout.trim(),r=await te(n,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{let i=await Lm(e),a;try{a=(await Kt("git",["config",i,"--null","--get-regexp","."],{cwd:e,env:Qe(),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(`
36
- `);return[s.slice(0,c),s.slice(c+1)]}));for(let s of t)o.get(s.key)!==s.value&&await Sn(e,[i,s.key,s.value])}finally{await r()}}async function Nv(e){let t=J.resolve(e.pmRoot),n=J.resolve(e.workspaceRoot),r=e.dryRun===!0,i,a;try{[i,a]=await Promise.all([Tt(t),Tt(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=Bo(a,i);if(Mo(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=$t(s),d=Vo(o,c),l=[],u=await Tv();for(let f of Wm)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 Pv(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 Vm(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 Lv=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Mv(e){let t=Lv.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function jv(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Km(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=Mv(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=jv(o);a.push({name:c,prefix:o,count:s.count,examples:s.examples,shadows_builtin:fd(c)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}import{createHash as sp}from"node:crypto";import Xt from"node:fs/promises";import In from"node:path";import{mkdir as Fv,readFile as Uv}from"node:fs/promises";import ep from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0bd9a904-c076-5c2a-a9d8-42a543625e33")}catch{}})();var Jo=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Hv="sdk-workspace-transaction",zv=/^[a-zA-Z0-9._-]+$/,Wv=30,Gv=3e3;function tp(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!zv.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Ym(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 qv(e){return{pmRoot:Ym(e.pmRoot,"Transaction pmRoot"),transactionId:tp(e.transactionId,"Transaction id"),author:Ym(e.author,"Transaction author")}}function Xm(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 np(e,t){return ep.join(e,"transactions","sdk",`${t}.json`)}async function Ot(e,t){t.updatedAt=$();let n=np(e,t.transactionId);await Fv(ep.dirname(n),{recursive:!0}),await Z(n,`${JSON.stringify(t,null,2)}
37
- `)}function Bv(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Yt(e){return Object.assign(Object.create(null),e)}function Vv(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 Ko(e,t){return e===void 0?void 0:Vv(e,t)}function Yo(e,t,n,r){let i=Ko(n,r);i===void 0?delete e[t]:e[t]=i}function Zm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qm(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Jv(e,t){if(!Qm(e.startedStepIds,t)||!Qm(e.completedStepIds,t)||!Zm(e.results)||!Zm(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 Kv(e,t,n){let r;try{r=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let i=r,a=i.schemaVersion===1&&i.transactionId===t,o=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((l,u)=>l===n[u]),s=Jv(i,n),c=Bv(i),d=["applying","compensating","compensated","committed"].includes(String(i.status));if(!a||!o||!s||!c||!d)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...i,results:Yt(i.results),compensationData:Yt(i.compensationData)}}async function Yv(e,t,n,r,i){let a=i,o=a!==void 0;if(a?.status==="compensating"&&await rp(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:Yt(),compensationData:Yt()},await Ot(e.pmRoot,a),await pt(e,a,"prepared")}return{journal:a,recovered:o}}async function Xv(e,t,n){try{await Qv(t,e.steps),await Ot(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=Ko(o.result,`Step ${a.id} result`);if(o.state!=="applied"){let c=await a.prepareCompensation?.();Yo(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 Ot(e.pmRoot,t);let d=await a.apply();s=Ko(d,`Step ${a.id} result`)}await pt(e,t,"step_applied",a.id),r.add(a.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),Yo(t.results,a.id,s,`Step ${a.id} result`),await Ot(e.pmRoot,t),await pt(e,t,"step_recorded",a.id)}return await pt(e,t,"committing"),t.status="committed",await Ot(e.pmRoot,t),await pt(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Yt(t.results)}}catch(r){if(r instanceof Jo||t.status==="committed")throw r;try{await rp(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function Zv(e,t,n){try{return Kv(await Uv(np(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&F(r))return;throw r}}async function pt(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function Qv(e,t){let n=new Set,r=Yt();for(let i of t){let a=await i.inspect();a.state==="applied"&&(n.add(i.id),Yo(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 rp(e,t){t.status="compensating",await Ot(e.pmRoot,t),await pt(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 pt(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 Ot(e.pmRoot,t),await pt(e,t,"step_compensated",i.id)}t.status="compensated",await Ot(e.pmRoot,t),await pt(e,t,"compensated")}async function ip(e){let{pmRoot:t,transactionId:n,author:r}=qv(e),i=Xm(e.lockTtlSeconds,Wv,"Transaction lock TTL"),a=Xm(e.lockWaitMs,Gv,"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=tp(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,Hv,i,r,!1,!1,a);try{let l=await Zv(t,n,s),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Yt(l.results)};let m=await Yv(c,n,r,s,l);return await Xv(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 ft(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function cp(e){let t=ft(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function dp(e,t){let n=Zo(e),r=ft(t,"migrationScope");return`auto-${sp("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function Zo(e){let t=e.kind==="rename-type"?{kind:e.kind,from:ft(e.from,"source"),to:ft(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:le(ft(e.from,"source")),to:le(ft(e.to,"target")),...e.type===void 0?{}:{type:ft(e.type,"type")}}:{kind:e.kind,from:le(ft(e.from,"source")),to:le(ft(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function eb(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function tb(e,t,n){let r=Re(t.schema),i=eb(n);return Ke(e,r.files[i],Le[i])}function lp(e,t){return In.join(e,"transactions","schema",`${t}-plan.json`)}function Ui(e){return e.length===0?null:JSON.parse(e)}async function An(e){let t=await V(e);return{exists:t!==null,raw:t??""}}async function up(e,t){t.exists?await Z(e,t.raw):await Xt.rm(e,{force:!0})}function nb(e,t,n){let r=ot(e),i=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),a=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(a>=0)return xt(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 xt(r)}function rb(e,t,n){let r=sn(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 cn(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 cn(r)}function ib(e,t,n){let r=dn(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 ln(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 ln(r)}function ab(e,t,n){return t.kind==="rename-type"?nb(e,t,n):t.kind==="rename-field"?rb(e,t,n):ib(e,t,n)}function Dt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Qo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Rn(e){return Array.isArray(e)?e.map(t=>Qo(t)).filter(t=>t!==void 0):[]}function ob(e,t){for(let n of Rn(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>Dt(r,t)));for(let n of Rn(e.type_workflows))n.type=Dt(n.type,t)}function sb(e,t){for(let r of Rn(e.definitions))r.default_status=Dt(r.default_status,t);let n=Qo(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=Dt(i,t);for(let r of Rn(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(a=>Dt(a,t)):i))}function cb(e,t){for(let n of Rn(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>Dt(i,t)));for(let r of["options","command_option_policies"])for(let i of Rn(n[r])){let a=r==="options"?"key":"option";i[a]=Dt(i[a],t)}}}function db(e,t){let n=Qo(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]=Dt(n[r],t)}function Xo(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"?ob(r,t):t.kind==="rename-field"?cb(r,t):sb(r,t),db(r,t),`${JSON.stringify(r,null,2)}
38
- `}function mp(e,t){if(t.kind==="rename-type"){let r=ot(e).definitions;return{source:r.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=sn(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=dn(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function lb(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 ub(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 pp(e,t){let n=Zo(t.request),r=t.migrationId===void 0?dp(n,t.migrationScope??"plan"):cp(t.migrationId),i=e.map(c=>ub(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),a=sp("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 mb(e){let t=W(e.settings,H()),n=[...new Set(Object.values(t.type_to_folder))],r=await hi(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},a=r?await Cl({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 ct(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function pb(e,t){let n=await V(lp(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: ${ed(r)}`,g.GENERIC_FAILURE)}}async function fb(e,t){let n=lp(e,t.migration_id);await Xt.mkdir(In.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await Z(n,`${JSON.stringify(r,null,2)}
39
- `)}function hb(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function _b(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 ap(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 op(e){return{id:e.id,inspect:async()=>{let t=await An(e.filePath),n=mp(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 An(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await An(e.filePath);return await Z(e.filePath,ab(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 up(e.filePath,{exists:t.exists,raw:t.raw})}}}function gb(e){return{id:e.stepId,inspect:async()=>{let t=await An(e.filePath);return{state:Xo(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await An(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await An(e.filePath);return await Z(e.filePath,Xo(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 up(e.filePath,{exists:t.exists,raw:t.raw})}}}function yb(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await T(e.pmRoot),n=W(t,H()).type_to_folder,r=await _b({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=lb(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=W(t,H()).type_to_folder,r=await lt({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:ap(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await T(e.pmRoot),n=W(t,H()).type_to_folder;await lt({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:ap(r,e.request,"reverse")}}})}}}async function wb(e){let t=await pb(e.pmRoot,e.migrationId);if(t){if(!hb(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 mb({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...pp(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function vb(e){let t=mp(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 fb(e.pmRoot,e.plan)}async function bb(e){let t=Re(e.settings.schema),n=[...new Set([["types",Le.types],["fields",Le.fields],["workflows",Le.workflows]].map(([i,a])=>Ke(e.pmRoot,t.files[i],a)).filter(i=>i!==e.schemaPath))];try{let i=In.join(e.pmRoot,"templates"),a=await Xt.readdir(i,{withFileTypes:!0});n.push(...a.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>In.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&&Xo(a,e.request)!==a&&r.push({filePath:i,beforeRaw:a})}return{paths:n,snapshots:r}}async function kb(e){for(let t of e.snapshots){let n=await Xt.readFile(t.filePath,"utf8"),r=In.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await to({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Ui(t.beforeRaw),after:Ui(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 Sb(e,t,n){let r=Zo(e),i=L(process.cwd(),n.path);await ne(i);let a=t.migrationId===void 0?dp(r,await Xt.realpath(i)):cp(t.migrationId),o=await T(i),s=G(t.author,o.author_default),c=await wb({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=tb(i,o,r),u=await Xt.readFile(l,"utf8");c.stored||await vb({pmRoot:i,schemaPath:l,request:r,plan:d});let m=await bb({pmRoot:i,schemaPath:l,settings:o,request:r}),f=[op({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...m.paths.map((w,v)=>gb({filePath:w,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>yb({pmRoot:i,id:w.id,request:r,author:s,force:t.force===!0})),op({id:"retire-source",filePath:l,request:r,phase:"retire"})],p=await ip({pmRoot:i,transactionId:`schema-${a}`,author:s,steps:f,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),h=await Xt.readFile(l,"utf8"),{historyPath:_}=await to({pmRoot:i,author:s,documentPath:In.relative(i,l).replaceAll("\\","/"),before:Ui(u),after:Ui(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 kb({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 CN=[...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"],Hi="schema-types",fp="schema-statuses",hp="schema-fields";function Pt(e){return di({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 ON(e,t,n){let r=L(process.cwd(),n.path);await ht(r);let i;try{i=Wa({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=Ke(r,o.files.types,Le.types),c=[],d=G(t.author,a.author_default),l=Te(a),u=await te(r,Hi,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=ot(f)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.GENERIC_FAILURE)}try{hd(i,p);let h=new Map,_=W(a,H());for(let[w,v]of Object.entries(_.type_to_folder)){let S=v.trim().toLowerCase();S.length>0&&!h.has(S)&&h.set(S,w)}_d(i,p,h)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}m=Br(p,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await Pt({pmRoot:r,filePath:s,raw:xt(m.file),op:"schema:add-type",author:d,settings:a}),await ur(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 _p(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Nt(c),generated_at:$()}}async function ht(e){await ne(e)}async function _p(e,t){try{let n=await Jm(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 Nt(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Ab(e,t,n,r){let i=W(t,H()),a=r.trim().toLowerCase();return(await ct(e,t.item_format,i.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===a).length}async function Ib(e,t,n,r){let i=W(t,H()),a=ge(n),o=le(r);return(await ct(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 Rb(e,t,n,r,i){if(i.length===0||qa.has(i))return;let a=await Ib(t,n,r,i);a>0&&e.push(`items_using_status:${a}`);let o=Cb(r.workflow,i);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function Cb(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 DN(e,t,n){let r=L(process.cwd(),n.path);await ht(r);let i=await T(r),a=Re(i.schema),o=Ke(r,a.files.types,Le.types),s=[],c=G(t.author,i.author_default),d=Te(i),l=await te(r,Hi,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=ot(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=gd(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 Ab(r,i,a,p);h>0&&s.push(`items_using_type:${h}`)}await Pt({pmRoot:r,filePath:o,raw:xt(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 _p(r,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:o,definitions:u.file.definitions.length},warnings:Nt(s),generated_at:$()}}function es(e,t){return Ke(e,t.files.statuses,Le.statuses)}function zi(e,t){return Ke(e,t.files.fields,Le.fields)}function gp(e,t){return Ke(e,t.files.types,Le.types)}async function ur(e,t,n,r){for(let i of t){let a=rd(i.folder??nd(i.name)),o=Eb.join(e,a);await O(o)||(await xb(o,{recursive:!0}),n.push(...await X({path:o,scope:"project",op:r})))}}function ts(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 Tb(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 $b(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 PN(e,t,n){let r=L(process.cwd(),n.path);await ht(r);let i;try{i=xd({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=es(r,o),c=ge(o);try{Ba(i,c.alias_to_id)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}let d=Tb(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 "${on(i.id)}" --role active`,`pm schema add-status "${on(i.id)}" --role blocked`]});let l=[],u=G(t.author,a.author_default),m=Te(a),f=await te(r,fp,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{_=dn(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=$b(_.statuses);try{Ba(i,w)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.USAGE)}p=Ad(_,i,d),await Pt({pmRoot:r,filePath:s,raw:ln(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:Nt(l),generated_at:$()}}async function NN(e,t,n){let r=L(process.cwd(),n.path);await ht(r);let i=await T(r),a=Re(i.schema),o=es(r,a),s=[],c=G(t.author,i.author_default),d=Te(i),l=await te(r,fp,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=dn(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=Id(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 Rb(s,r,i,a,p),await Pt({pmRoot:r,filePath:o,raw:ln(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:Nt(s),generated_at:$()}}function yp(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 Ob(e,t,n){return{...yp(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 wp(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 vp(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function Db(){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 Pb(e){let t=ge(e),n=[],r=[];for(let i of t.definitions){let a=wp(i);a.source==="builtin"?n.push(a):r.push(a)}return{builtin:n,custom:r}}async function mr(e){let t=L(process.cwd(),e.path);await ht(t);let n=await T(t),r=Re(n.schema),i=Ke(t,r.files.types,Le.types),a=es(t,r),o=W(n,H()),s=Db(),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 LN(e){let t=await mr(e),n=[],r=[],i=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=vp(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=yp(s);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let a=Pb(t.schema),o=Vr(t.schema).definitions.map(ts);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 MN(e,t){let n=(e??"").trim();if(n.length===0)throw new y("Type name must not be empty.",g.USAGE);let r=await mr(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 "${on(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Ob(i,vp(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:$()}}async function jN(e,t){let n=le(e);if(n.length===0)throw new y("Status id must not be empty.",g.USAGE);let r=await mr(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 "${on(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:wp(o),file:{path:r.statusesPath},generated_at:$()}}async function FN(e,t,n){let r=L(process.cwd(),n.path);await ht(r);let i;try{i=vd({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=zi(r,o),c=[],d=Qr(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=G(t.author,a.author_default),u=Te(a),m=await te(r,hp,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=sn(p)}catch(_){throw new y(_ instanceof Error?_.message:String(_),g.GENERIC_FAILURE)}f=bd(h,i),await Pt({pmRoot:r,filePath:s,raw:cn(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:Nt(c),generated_at:$()}}async function Nb(e,t,n,r){let i=W(t,H());return(await ct(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 UN(e,t,n){let r=L(process.cwd(),n.path);await ht(r);let i=await T(r),a=Re(i.schema),o=zi(r,a),s=[],c=G(t.author,i.author_default),d=Te(i),l=await te(r,hp,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=sn(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=kd(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 Nb(r,i,a,h);_>0&&s.push(`items_using_field:${_}`)}await Pt({pmRoot:r,filePath:o,raw:cn(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:Nt(s),generated_at:$()}}async function HN(e){let t=await mr(e),n=Vr(t.schema).definitions.map(ts);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:zi(t.pmRoot,t.schema)},generated_at:$()}}async function zN(e,t){let n=le(e);if(n.length===0)throw new y("Field key must not be empty.",g.USAGE);let r=await mr(t),i=Vr(r.schema).by_key.get(n);if(!i)throw new y(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${on(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:ts(i),file:{path:zi(r.pmRoot,r.schema)},generated_at:$()}}async function WN(e,t,n){let r=L(process.cwd(),n.path);await ht(r);let i;try{let h=wd(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${yd.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=gp(r,o),c=[],d=G(t.author,a.author_default),l=Te(a),u=[],m=[],f,p=await te(r,Hi,a.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms);try{let h=await V(s),_;try{_=ot(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=_;for(let v of Ga(i)){let S=Br(w,v);w=S.file,(S.replaced?m:u).push(S.definition.name)}f=w.definitions.length,await Pt({pmRoot:r,filePath:s,raw:xt(w),op:"schema:apply-preset",author:d,settings:a}),await ur(r,Ga(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:Nt(c),generated_at:$()}}function Lb(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 GN(e,t){let n=L(process.cwd(),t.path);await ht(n);let r=await T(n),i=Re(r.schema),a=gp(n,i),o=Lb(e.minCount),s=W(r,H()),c=(await ct(n,r.item_format,s.type_to_folder,[],i)).map(v=>typeof v.title=="string"?v.title:""),d=Km(c,{minCount:o}),l=[],u=[],m=[],f=[],p;if(!e.apply){let v;try{v=ot(await V(a))}catch(S){throw new y(S instanceof Error?S.message:String(S),g.GENERIC_FAILURE)}return p=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:d,registered:u,replaced:m,skipped:f,file:{path:a,definitions:p},warnings:l,generated_at:$()}}let h=G(e.author,r.author_default),_=Te(r),w=await te(n,Hi,r.locks.ttl_seconds,h,!!e.force,_.force_required_for_stale_lock,r.locks.wait_ms);try{let v=await V(a),S;try{S=ot(v)}catch(x){throw new y(x instanceof Error?x.message:String(x),g.GENERIC_FAILURE)}let k=S;for(let x of d){if(x.shadows_builtin){f.push({name:x.name,reason:"shadows_builtin"});continue}let D;try{D=Wa({name:x.name})}catch{f.push({name:x.name,reason:"invalid_type_token"});continue}let E=Br(k,D);k=E.file,(E.replaced?m:u).push(E.definition.name)}p=k.definitions.length,await Pt({pmRoot:n,filePath:a,raw:xt(k),op:"schema:infer-types",author:h,settings:r}),await ur(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:Nt(l),generated_at:$()}}import bp 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]="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 Wi(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 rs(e){return cd(e)}async function Mb(e){try{let t=JSON.parse(await bp.readFile(ns.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 jb(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 Mb(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 Cn(e,t={}){let n=ns.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 bp.readFile(n,"utf8"))}catch(o){throw new y(`Failed to parse extension manifest at "${n}": ${Fb(o)}`,g.USAGE)}let i=rs(r);if(!i)throw new y(`Extension manifest at "${n}" is invalid.`,g.USAGE);let a=ns.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 jb(i,a,t);if(!await ld(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 Fb(e){return e instanceof Error?e.message:String(e)}import is from"node:fs/promises";import Ub 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 Hb=".managed-extensions.json",Gi=1;function pr(e){return Ub.join(e,Hb)}function zb(){return{version:Gi,updated_at:$(),entries:[]}}function fr(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 kp(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 Wb(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 Gb(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(!Wb(t))return null;let n=Gb(t.source);if(!n)return null;let r=od(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 Bb(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Gi||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=qb(r);i&&n.push(i)}return{version:Gi,updated_at:ke(t.updated_at)??$(),entries:fr(n)}}async function ye(e){let t=pr(e),n=zb();try{let r=await is.readFile(t,"utf8"),i=JSON.parse(r),a=Bb(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 Tn(e,t){let n=pr(e),r={version:Gi,updated_at:$(),entries:fr(t.entries)};await is.mkdir(e,{recursive:!0}),await is.writeFile(n,`${JSON.stringify(r,null,2)}
40
- `,"utf8")}function hr(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:fr(n)}}async function Sp(e,t,n,r){let i=t.entries.find(o=>I(o.name)===I(n));if(!i)return t;let a=hr(t,{...i,contributions:r});return await Tn(e,a),a}import{execFile as rk}from"node:child_process";import K from"node:fs/promises";import ls from"node:os";import j from"node:path";import{fileURLToPath as ik}from"node:url";import{promisify as ak}from"node:util";import ok from"npm-package-arg";import{extract as sk,list as ck}from"tar";import Vb from"node:fs/promises";import We from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var Jb="PM_CLI_PACKAGE_ROOT",Ep={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Kb=new Set(["*","all"]);function as(){let e=[],t=process.env[Jb];return typeof t=="string"&&t.trim().length>0&&e.push(We.resolve(t.trim())),e.push(Ne(import.meta.url,["../../.."])),[...new Set(e)]}async function _r(e){let t=e.trim().toLowerCase(),n=await Ap(t);if(n)return n;let r=Ep[t];if(!r)return null;for(let i of as()){let a=We.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await O(We.join(a,"manifest.json")))return a}return null}function xp(e){return Kb.has(e.trim().toLowerCase())}function Yb(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Xb(e,t){let n=await Vb.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=We.join(e,r.name);if(!await O(We.join(i,"package.json")))continue;let a=await Gr(i),o=a.aliases&&a.aliases.length>0?a.aliases:[Yb(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 os(){let e=new Map;for(let t of as()){let n=We.join(t,"packages");await O(n)&&await Xb(n,e)}for(let[t,n]of Object.entries(Ep))if(!e.has(t))for(let r of as()){let i=We.join(r,"packages",n.package_directory);if(await O(We.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 qi(){return(await os()).map(e=>e.alias)}async function Ap(e){let t=e.trim().toLowerCase();return(await os()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function Ip(e){let t=await Ap(e);return t?(await Gr(t)).package_name??null:null}async function Rp(e){let t=await _r(e);if(!t)return null;try{let n=await qr(t);return n.length!==1?null:(await Cn(n[0])).manifest.name}catch{return null}}function Zb(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function Qb(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(We.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:Zb(e),media:e.catalog?.media}}}async function Cp(e,t,n={}){let r=an(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=>We.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 os()){let f=We.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 Gr(f.package_root);c.push(Qb(h,f,p,e,s,o))}let l=tk(n.fields),u=l?c.map(m=>nk(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 ek=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 tk(e){if(e===void 0)return;let t=Vl(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=>!ek.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 nk(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 $p=ak(rk),Vi="@unbrained/pm-cli",dk={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},ss;async function Op(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 cs(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 lk(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 gr(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 lk(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 cs(s,n,r)}catch{return null}})();if(i)return i;let a=n.startsWith("github.com/")?n.slice(11):null;if(a){let o=cs(a,n,r);if(!o)throw new y(`Invalid GitHub source "${n}".`,g.USAGE);return o}if(t.forceGithub){let o=cs(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 Bi(e,t=$p,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(" ")}
41
- ${a}`,g.GENERIC_FAILURE)}}function us(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function ms(e=process.platform){return e==="win32"}async function Dp(e,t,n=$p,r=process.platform,i=process.env){let a=us(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:ms(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(" ")}
42
- ${d}`,g.GENERIC_FAILURE)}}function Pp(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 Np(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 uk(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 mk(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return uk(e)||t.includes("not found")}function pk(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function fk(e){let t=Pp(e),n=pk(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 hk(e,t){if(!mk(t))return null;let n=fk(e);return new y(n.message,g.NOT_FOUND,n.context)}async function Lp(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=ik(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 _k(e){let t=await Lp(e);if(t)return t;let n=gk(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function gk(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!Np(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 Tp(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 yk(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 wk(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=yk(n,t);return r?[r]:[]})}function vk(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 bk(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:Tp(t,o)}}let i=wk(r),a=vk(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:Tp(t,a.filename),package:a.name??a.key,version:a.version}}async function kk(e){return Sk(e,Dp)}async function Sk(e,t){let n=await Lp(e.spec);if(n){if((await K.stat(n)).isFile()&&Mp(n))return ds(n);let a=j.join(n,"package.json"),o=await O(a)?JSON.parse(await K.readFile(a,"utf8")):{};return{directory:await Ji(n,e.input),package:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,cleanup:async()=>{}}}let r=await K.mkdtemp(j.join(ls.tmpdir(),"pm-npm-package-source-")),i=j.join(r,"pack");await K.mkdir(i,{recursive:!0});try{let a=await _k(e.spec),o=await t(["pack",a,"--json","--pack-destination",i]),s=bk(o,i,Np(e.spec)?void 0:Pp(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 ds(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}),hk(e.spec,a)||a}}function Mp(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function _t(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 Ek(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&_t(`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===".."))&&_t(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&_t(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&_t(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&_t(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&_t(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&_t(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function ds(e,t=dk){(await K.stat(e)).size>t.maxArchiveBytes&&_t(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await K.mkdtemp(j.join(ls.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 ck({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(a===void 0)try{Ek(d,t,i)}catch(l){a=l}}}),a!==void 0)throw a;i.packageJsonEntries!==1&&_t(`Local package archive must contain exactly one package/package.json entry; found ${i.packageJsonEntries}.`),await sk({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 xk(o),{directory:await Ji(o,e),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{await K.rm(n,{recursive:!0,force:!0})}}}catch(o){throw await K.rm(n,{recursive:!0,force:!0}),o}}async function xk(e,t=Dp){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=$k(i),o=Ak(i);if(a.length===0&&!o)return;let s={...r};delete s.devDependencies;let c={...s};Ik(c),await K.writeFile(n,`${JSON.stringify(c,null,2)}
43
- `,"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 Rk(e)}finally{await K.writeFile(n,`${JSON.stringify(s,null,2)}
44
- `,"utf8")}}function Ak(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Vi in t)return!0;return!1}function Ik(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Vi],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function Rk(e){let t=Ne(import.meta.url,["../../.."]),[n,r]=Vi.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,Ck(process.platform))}function Ck(e){return e==="win32"?"junction":"dir"}function Tk(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{ok.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 $k(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===Vi||typeof i!="string"||i.trim().length===0||t.has(r))continue;let a=i.trim();t.set(r,Tk(r,a))}return[...t.values()]}async function Ji(e,t){let n=await qr(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>j.relative(e,i).replaceAll(j.sep,"/")).sort((i,a)=>i.localeCompare(a));throw new y(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,g.USAGE)}throw new y(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,g.USAGE)}async function Ok(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(j.posix.join(".agents/pm/extensions",t.subpath)),n.push(j.posix.join(".custom/pm-extensions",t.subpath)),n.push(j.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let a=j.resolve(e,i);if(fe(e,a)&&await O(j.join(a,"manifest.json")))return{directory:a,resolved_subpath:i}}if(await O(j.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await Ji(e,t.input);return{directory:r,resolved_subpath:j.relative(e,r).replaceAll(j.sep,"/")}}function Dk(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 Pk(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Dk(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()):"";ss?.key!==o&&(ss={key:o,aliases:await qi()}),r=ss.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 Pk(e)}if(r.isFile()&&Mp(e.absolute_path)){let a=await ds(e.absolute_path);return{source:e,directory:a.directory,source_root:j.dirname(a.directory),resolved_subpath:j.relative(j.dirname(a.directory),a.directory).replaceAll(j.sep,"/"),npm_package:a.package,npm_version:a.version,cleanup:a.cleanup}}if(!r.isDirectory())throw new y(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,g.USAGE);let i=await Ji(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await kk(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(ls.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Bi(n);let r=await Bi(["-C",t,"rev-parse","HEAD"]),i=await Ok(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await K.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await K.rm(t,{recursive:!0,force:!0}),r}}async function Ki(e,t){if(!await O(e)||!await O(t))return!1;let[n,r]=await Promise.all([K.realpath(e),K.realpath(t)]);return n===r}import yr from"node:fs/promises";import wr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var ps=1,Zt="2026.6.24",Nk=">=22.18.0",Lk={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Fp=new Set([...Od.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(pd).map(e=>e.toLowerCase()),"scaffold"]),Mk="^6.0.0",jk="^22.0.0",zp=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],tt=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Up(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Wp(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 Gp(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 Fk={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Hp=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],qp={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"]},Uk={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"]'},Hk={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."},zk={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."},Bp="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Wk={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."]},Gk={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`."]},Bk={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 Vp(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 Jp(e,t){return e==="schema"?qk[t]:e==="profile"?Bk[t]:Gk[t]}function Vk(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&&Fp.has(i));return`${(Fp.has(n)||a?["starter",...t]:t).join(" ")} ping`}function Kp(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 Jk(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({",...Kp(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 Kk(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=Uk[n],f=e,p=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,_=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});",""]:[],S=i?fs(e,t,"search",m):[],k=a?fs(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 {",...Up(Wp({extensionName:e,itemTypeName:f,itemTypeFolder:p,fieldName:h,migrationId:_,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});",""]:[],D=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Up(Gp(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});",""]:[],E=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});",""]:[],b=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;",...tt,"});",""]:[],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;",...tt,"});",""]:[],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;",...tt,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...zp,`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;",...tt,"});","",...v,...S,...k,...x,...D,...E,...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(`
45
- `)}function Yk(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 Xk={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"},Zk={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function Qk(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function eS(e,t,n){let r=[],i=[...Qk(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({",...Kp(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 tS(e,t,n){let r=eS(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(`
46
- `)}function fs(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;",...tt];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(a)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(Wp({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Gp(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 nS(e,t,n){let r=n==="parser",i=JSON.stringify([...qp[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" };',"",...zp,`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(Zt)},`," },",` target: { pmVersion: ${JSON.stringify(Zt)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});","",...fs(e,t,n,i)].join(`
47
- `)}function rS(e,t,n){let r=Vp(n,"package"),i=Jp(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 (${Xk[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`.",Bp,"- `.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 ${Zk[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 \`${ps}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Zt}\`. 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(`
48
- `)}function iS(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 aS(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 oS(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 sS(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 cS(e,t,n,r="commands",i=!1){let a=`pm-${e}`,o=qp[r],s=Yk(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:ps,pm_min_version:Zt,trusted:!0,sandbox_profile:"strict",permissions:{...Lk},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
49
- `,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Jk(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(`
50
- `),l=`${JSON.stringify(Fk,null,2)}
51
- `,u=Hk[r],m=Vp(r,"package"),f=`${JSON.stringify({name:a,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Nk},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Zt}`},devDependencies:{"@types/node":jk,typescript:Mk},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)}
52
- `,p=Kk(e,t,r),h=zk[r],_=["node_modules/","*.log","*.tsbuildinfo",""].join(`
53
- `),w=iS(e),v=["```ts",`import { ${aS(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...oS(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...sS(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],S=[`# ${a}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,h,Bp,"- `.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`.",...Wk[r],...Jp(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Zt}\`. 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 \`${ps}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Zt}\`. 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(`
54
- `);return{"package.json":f,"manifest.json":c,"index.ts":i?tS(e,t,r):d,"index.test.ts":i?nS(e,t,r):p,"tsconfig.json":l,".gitignore":_,"README.md":i?rS(a,t,r):S}}async function Yp(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!Hp.includes(i))throw new y(`Unknown scaffold capability "${n}". Supported capabilities: ${Hp.join(", ")}.`,g.USAGE);let a=i;if(r&&t!=="package")throw new y("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",g.USAGE);let o=r?"declarative":"imperative",s=e.trim(),c=wr.resolve(process.cwd(),s),d=Wi(wr.basename(c)).replace(/^(?:pm-)+/u,""),l=Vk(d),u=cS(d,l,t,a,r),m=!1;if(await O(c)){if(!(await yr.stat(c)).isDirectory())throw new y(`Scaffold target "${c}" exists and is not a directory.`,g.CONFLICT)}else await yr.mkdir(c,{recursive:!0}),m=!0;for(let[p,h]of Object.entries(u)){let _=wr.join(c,p);if(await O(_)&&await yr.readFile(_,"utf8")!==h)throw new y(`Scaffold file "${p}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,g.CONFLICT)}let f=[];for(let[p,h]of Object.entries(u)){let _=wr.join(c,p);if(await O(_)){f.push({path:p,status:"unchanged"});continue}await yr.mkdir(wr.dirname(_),{recursive:!0}),await yr.writeFile(_,h,"utf8"),f.push({path:p,status:"created"})}return{extension_name: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 Xp(e,t){return`${e}:${I(t)}`}function dS(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 Zp(e,t,n){let r=new Set(n.failed.map(d=>Xp(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(Xp(d.layer,d.name))?"failed":"ok",surfaces:kn(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:kn(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:kn(n,c),command_ownership:dS(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 hs(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function Yi(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 lS(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)Yi(t,r.name,r.command),Yi(n,r.name,r.action);for(let r of e.commands.handlers)Yi(t,r.name,r.command);for(let r of e.commands.overrides)Yi(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Qp(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function uS(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:a}=e;return t?i.has(n)||a.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function Xi(e,t,n){let r=new Set(t.loaded.map(c=>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}=lS(n);return e.map(c=>{let d=I(c.name),l=Qp(o.get(d)),u=Qp(s.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},f=uS({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:i,activationFailedNames:a});return{...c,...f,...m}})}function mS(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 nf=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 pS(e){return nf.has(df(e))}function ef(e){return e==="project"||e==="global"}function rf(e){let t=e.split(":"),n=t[0];if(!n||!nf.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!ef(r)||!ef(a)||!i||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:a,name:o}}}function fS(e){let t=new Set;for(let n of e){let r=rf(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function _s(e,t){let n=e.filter(pS);if(n.length===0)return null;let r=fS(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 hS(e,t,n,r){let i=t.map(u=>rf(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 af(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 of(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 sf(e,t){let n=[];for(let r of Nd(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 _S=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${me(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${Ur.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${me(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${me(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${me(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function gS(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=_s(t,{deactivate:`${me(n,"deactivate")} <name> ${i}`,doctor:`${me(n,"doctor")} ${i} --detail deep --trace`});f&&u.push(f);for(let p of _S)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 Zi(e,t,n,r={}){let i=[...new Set(t)].sort((b,N)=>b.localeCompare(N)),a=n.filter(b=>b.managed).length,o=n.filter(b=>b.enabled).length,s=n.filter(b=>b.active).length,c=n.filter(b=>b.update_check_status==="checked"&&b.update_available===!0).length,d=n.filter(b=>b.managed===!1),l=d.filter(b=>tf(b)).map(b=>b.name).sort((b,N)=>b.localeCompare(N)),u=d.filter(b=>!tf(b)).map(b=>b.name).sort((b,N)=>b.localeCompare(N)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let b of n)m[b.update_check_status]+=1;let f=m.failed,p=n.filter(b=>b.update_check_status==="skipped_non_github"&&b.source?.kind!=="builtin").length,h=Object.entries({skipped_unmanaged:u.length,skipped_non_github:p,failed:f,not_checked:m.not_checked}).filter(([,b])=>b>0).map(([b,N])=>`extension_update_health_partial_coverage:${b}:${N}`),_=h.length>0,w=_?"partial":"full",v=[...new Set([...i,...h])].sort((b,N)=>b.localeCompare(N)),S=[...new Set(v.map(b=>df(b)))].sort((b,N)=>b.localeCompare(N)),k=mS(v),x=e==="global"?"--global":"--project",D=hS(e,i,n,r),E=gS({normalizedWarnings:v,options:r,scope:e,scopeFlag:x,updateCheckFailedTotal:f,policyWarningCount:k.warning_count,unmanagedActionRequiredTotal:u.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:p,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:S,warnings:v,policy_warning_count:k.warning_count,policy_violation_count:k.violation_count,policy_blocked_count:k.blocked_count,total_extensions:n.length,managed_total:a,enabled_total:o,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:_,unmanaged_loaded_extension_count: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:E,...D?{collision_plan:D}:{}}}function cf(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 df(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function vr(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let a=Gc(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 br(){return{version:Hr.version,capabilities:[...Hr.capabilities],legacy_aliases:{...Hr.legacy_aliases}}}function tf(e){let t=I(e.name),n=I(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function lf(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 uf from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function kr(e,t,n,r){let i=uf.relative(e,n);if(i!==""&&!fe(e,n)||n===t||fe(t,n))return!1;let a=i.split(uf.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 yS}from"node:crypto";import se from"node:fs/promises";import wS 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 mf=3,vS=120,pf=250,bS=12e4,kS=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),ff=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,hf=e=>kS.has(String(ff(e))),Qi=(e,t)=>ff(e)===t,_f=e=>new Promise(t=>{setTimeout(t,e)}),gf=async e=>{let t=re.join(e,"package.json");await O(t)||await se.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
55
- `,"utf8")},yf=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")},Sr=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))},wf=async(e,t,n,r=wS.tmpdir())=>zt("extension_install_copy",async()=>{let i=re.resolve(e),a=await se.realpath(i).catch(()=>i),o=await Sr(t);if(a===o)return;if(!fe(a,o)){await n(a,t,{recursive:!0,force:!0,filter:u=>kr(a,o,re.resolve(u),!1)});return}let s=await se.realpath(re.resolve(r)).catch(()=>Sr(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=>kr(a,o,re.resolve(u),!0)}),await n(l,t,{recursive:!0,force:!0})}finally{await se.rm(d,{recursive:!0,force:!0})}}),vf=async(e,t,n=se.cp)=>{for(let r=1;r<=mf;r+=1)try{await zt("extension_install_copy",async()=>{await se.rm(t,{recursive:!0,force:!0}),await wf(e,t,n)});return}catch(i){if(!hf(i)||r===mf)throw i;await _f(pf)}},gs=async e=>{let t;try{t=await se.readFile(re.join(e,"owner.json"),"utf8")}catch(i){if(!Et(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},bf=async(e,t)=>await gs(e)!==t?!1:(await se.rm(e,{recursive:!0,force:!0}),!0),SS=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 gs(e);return r===null?(await se.rm(e,{recursive:!0,force:!0}),!0):bf(e,r)},ES=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await gs(e)!==t)return;let a=new Date;await se.utimes(e,a,a)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},xS=async(e,t)=>{await se.mkdir(e);try{await se.writeFile(re.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
56
- `,"utf8")}catch(n){throw await se.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},AS=async(e,t,n,r,i)=>{for(let a=1;a<=n;a+=1)try{return await xS(e,t),!0}catch(o){if(!Qi(o,"EEXIST"))throw o;await SS(e,i)?a-=1:await _f(r)}return!1},ys=async(e,t,n,r)=>zt("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=vS,delay_ms:s=pf,stale_ms:c=bS,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:yS(),created_at:$(),destination:t};if(!await AS(a,p,l,u,m))throw new y(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let h=ES(a,p.token,f),_=!1;try{let w=await n();return _=!0,w}finally{await h(),await bf(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 ws=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 kf(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 Sf(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 Ef=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Qr(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{execFile as IS}from"node:child_process";import{promisify as RS}from"node:util";import CS 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 TS=RS(IS),Af=1e4;function xf(e,t,n){if(typeof t=="string")try{let r=CS.resolve(e,t);if(r.type==="version")return r.fetchSpec}catch{}throw new Error(n)}async function $S(e,t){try{return(await TS(us(),e,{encoding:"utf8",timeout:t,maxBuffer:65536,shell:ms(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function If(e,t=$S){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=xf(e.package,e.version,"missing_or_invalid_installed_npm_version"),i=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],Af),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=xf(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 OS=(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"}},vs=async(e,t=Bi)=>{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,Af);return OS(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 DS=4;async function Rf(e,t=!1){let n=await ws(e.entries,DS,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 vs(r.source):await If(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:fr(n)}}import PS 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]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function bs(e){return NS.join(e,"extension-migrations.json")}function Cf(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 Tf(e,t){return`${e.layer}:${e.name}:${t}`}async function LS(e){let t=bs(e);if(!await O(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await PS.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 ks(e,t){let n=await LS(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,a)=>{let o=Cf(i,a),s=r.get(Tf(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 MS(e){let t=await ks(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=Cf(l,u),f=Tf(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 S={key:f,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(f,S),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(S){let k=S instanceof Error?S.message:String(S),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 di({pmRoot:e.pmRoot,filePath:bs(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
57
- `,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:bs(e.pmRoot),total:r.length,pending_count:o,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function $f(e){let t=await T(e.resolvedRoots.settings_root),n=await Ve({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Je(n);e.warnings.push(...n.warnings,...r.warnings);let i=await MS({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 Of(e,t){let n=e.filter(r=>r.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:r,result:i})=>{let a=i.details;return{alias:r,ok:i.ok,extension:a.extension,source:a.source,source_resolution:a.source_resolution,install_plan:a.install_plan,dry_run:a.dry_run,destination_path:a.destination_path,activated:a.activated,settings_changed:a.settings_changed,command_paths:a.command_paths,action_paths:a.action_paths,command_discovery:a.command_discovery,verification:a.verification,runtime_activation_status:a.runtime_activation_status,activation_diagnostics:a.activation_diagnostics,warnings:i.warnings}})}}import ta from"node:fs/promises";import ea from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var jS=new Set(["node_modules",".git","dist","build","coverage"]);async function Df(e,t,n,r){let i=e.source.kind==="local"?await ta.stat(e.source.absolute_path):void 0,a=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,o=await FS(e.directory,t,r),s={source_mode:a,...a==="archive"?{archive_bytes:i.size}:{},copy:o},c=e.source_root??e.directory;if(a==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await O(ea.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),a==="directory"&&!o.complete){let 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 FS(e,t,n={}){let{maxEntries:r=1e4,maxDepth:i=64,signal:a}=n;if(![r,i].every(u=>Number.isSafeInteger(u)&&u>0))throw new y("maxEntries and maxDepth must be positive safe integers.",g.USAGE);a?.throwIfAborted();let o=await ta.realpath(e),s=await Sr(t),c=await Ki(o,s);a?.throwIfAborted();let 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 Pf(o,0,l,a),l}async function Pf(e,t,n,r){r?.throwIfAborted();let i=await ta.opendir(e);for await(let a of i){if(r?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=ea.join(e,a.name);if(!kr(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(ea.relative(n.source_directory,o).split(ea.sep).some(s=>jS.has(s))&&(n.development_entries+=1),await US(o,t,n,r),!n.complete)return}}async function US(e,t,n,r){let i=await ta.lstat(e);if(r?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await Pf(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 HS from"node:fs/promises";import zS 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 WS(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function GS(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 Ss(e){let t=zS.join(e,"manifest.json"),n;try{n=await HS.readFile(t,"utf8")}catch(s){if(Et(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=Xc(i),o=WS(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:a.findings,warnings:a.findings.map(s=>GS(o,s)),remediation:a.findings.map(s=>s.message)}}function Nf(e){return Ss(Be(e))}import qS from"node:fs/promises";import BS 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 VS(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 qS.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=BS(i);if(!a.registry||a.name!==i)return e}catch{return e}return gr(`npm:${i}`,{})}async function Lf(e,t,n,r=[]){let i=typeof t=="string"?null:await _r(e),a=i===null?null:e.trim().toLowerCase(),o=a===null?null:await Ip(a),s=await VS(gr(i??e,{forceGithub:typeof t=="string",ref:n}),r),c=a===null?null:await Op(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 Qt from"node:fs/promises";import JS 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 Es=async e=>Qt.readFile(e).catch(t=>{if(Qi(t,"ENOENT"))return null;throw t}),Mf=async(e,t,n,r,i)=>zt("extension_install_backup",async()=>{let a=pr(e),o=Ut(t),[s,c]=await Promise.all([Es(a),Es(o)]);return r&&await Qt.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:a,managedStateContents:s,settingsPath:o,settingsContents:c}}),jf=async e=>zt("extension_install_rollback",async()=>{await Qt.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Qt.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 Qt.rm(t,{force:!0}):(await Qt.mkdir(JS.dirname(t),{recursive:!0}),await Qt.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 zf=[["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"]],KS=zf.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),YS={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"},XS="__pm_native_output",ZS=["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"],Wf=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],QS=["disabled","require_trusted","require_provenance"],Gf={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:[]},eE=e=>{let t=e??Gf,n={};for(let r of ZS)n[r]=De(t[r]??[]);return n},tE=(e,t)=>{for(let n of Wf)t[n].length>0&&(e[n]=t[n]);return e},nE=(e,t)=>{for(let n of QS)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},rE=e=>{let t={};for(let n of Wf)t[n]=De(e[n]??[]);return t},iE=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:tE(nE({name:t},e),rE(e))},aE=e=>(e??[]).map(t=>iE(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),oE=e=>{let t=Object.assign({},Gf,e??{}),n=eE(e),r=aE(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}},qf=async(e,t)=>{let n=[t],r=await Rp(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}},Bf=(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)},Vf=(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")},sE=(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")},cE=(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")},dE=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=zf.map(([i,a,o])=>({action:a,flag:o,distance:Wc(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},lE=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=dE(e);if(!r)return new y(`One action flag is required. Use one of: ${KS}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let i=`pm ${n} ${r.flag}`;return ui({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(Jf),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},uE=[["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"]],Jf={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},mE=e=>Jf[e]??null,pE=(e,t)=>{let n=[...new Set(uE.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=mE(e.trim().toLowerCase());if(r)return r;throw lE(e,t)}if(n.length>1)throw new y("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},fE=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"},hE=[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"}}],Kf=e=>{for(let t of hE){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Yf=(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}},_E=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),a=r?Bf(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Yf({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:a},t,r,Kf(r))}},gE=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 _E(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await Lt.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=rs(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(I(u.name))??a.get(I(t));return{summary:Yf({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:Bf(r,u.name)},n,m,Kf(m))}},nt=async(e,t,n,r)=>{if(!await O(e))return{extensions:[],warnings:[]};let i=(await Lt.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 gE(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))}},yE=Dd(),wE=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,vE=(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:wE(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"}:{}}},bE=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},Xf=e=>e.map(t=>bE(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),Zf=(e,t,n)=>{let r=I(e);return t.find(i=>(n===void 0||i.layer===n)&&I(i.name)===r)},kE=(e,t,n,r)=>n.find(i=>i.scope===t&&I(i.name)===I(e))?.activation_status??(r?"failed":"unknown"),Qf=(e,t,n,r,i)=>yE.enqueue(async()=>{let a=process.env.PM_CLI_PACKAGE_ROOT,o=await Lt.mkdtemp(Pe.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Ne(import.meta.url,["../.."]);try{let s=await Ve({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:Ua(),cache_bust:!0,module_graph_snapshot_root:o}),c=await Je({...s}),d=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...Xf(c.failed)],l=Object.fromEntries(s.loaded.map(u=>[I(u.name),sd(kn(c,{extensionName:u.name}))]));return{installed:Xi(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 Lt.rm(o,{recursive:!0,force:!0}),a===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=a}}),As=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 Cn(d),u=$(),m={kind:"local",input:c.name,location:d};o=hr(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 Tn(e,o),{state:o,adopted_entries:s,unmanaged_candidates:a,already_managed_count:n.length-i.length}},SE=(e,t)=>{let n=L(process.cwd(),t.path),r=an(n,process.cwd()),i=e==="global"?Wr(process.cwd()):n,a=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:a,roots:r}},na=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new y('Options "--gh" and "--github" must match when both are provided.',g.USAGE);return n[0]},EE=e=>YS[e],xE=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,a=EE(e),o=`<${r}>`,s=`pm ${n} ${a} ${o}`;throw new y(`Action "${e}" requires ${i} input.`,g.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},ra=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new y('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',g.USAGE);return xE(t,n)},AE=(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))},IE=(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)},RE=(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},CE=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},TE=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:CE(e),warnings:[...new Set(e.warnings)].sort((i,a)=>i.localeCompare(a)),details:t};return e.action==="doctor"&&Object.defineProperty(r,XS,{value:!0,enumerable:!1,configurable:!1}),r},Is=async(e,t,n)=>{let r=pE(e,t);IE(r,t);let i=RE(e,r,t),a=fE(t),o=SE(a,n),s={action:r,normalizedTarget:i,scope:a,resolvedRoots:o,warnings:[],options:t,global:n},c={...s,withResult:(d,l=!0)=>TE(s,d,l)};return await d0(c)},$E=(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: ${Ye(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`]},OE=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([na(r),r.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new y('Action "init" does not accept --gh/--github/--ref options.',g.USAGE);let a=ra(n,t,r),o=await Yp(a,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:$E(o,r)})},DE=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=Ua(),d=await Ve({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 Je(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)},PE=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 Cp(n,i,r))},NE=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),LE=e=>({kind:"local",input:e.input,location:e.absolute_path}),ME=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),jE=(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}),FE=(e,t,n,r)=>e?NE(e,t):n.kind==="local"?LE(n):n.kind==="npm"?ME(n,r):jE(n,r),UE=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:kp(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},HE=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 Ki(a.directory,d);await Lt.mkdir(r.selected_root,{recursive:!0});let m=await Lt.mkdtemp(Pe.join(r.selected_root,".pm-extension-install-backup-")),f=Pe.join(m,"destination");try{let p=await Mf(r.selected_root,r.settings_root,d,l,f),h=FE(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),_=c.state.entries.find(k=>I(k.name)===I(a.manifest.name)),w=UE(_,a.manifest.version,h,$()),v=hr(c.state,{name:a.manifest.name,directory:o,scope:n,manifest_version:a.manifest.version,manifest_entry:a.manifest.entry,capabilities:[...a.manifest.capabilities],contributions:a.manifest.contributions,...w,source:h}),S=Vf(s,a.manifest.name);try{u||await vf(a.directory,d),await gf(d),await yf(d),await Tn(r.selected_root,v),S&&await li(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:S}}finally{await Lt.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},zE=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 ur(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},WE=(e,t,n,r,i)=>{let a=Zf(t,n.activation_failures,e.scope),o=kE(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)]}}},GE=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:a,withResult:o}=e,{validated:s,destinationDirectoryName:c}=t,d=await HE(e,t),l=await nt(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let u=await Qf(r.pm_root,Pe.dirname(r.selected_root),d.settings,l.extensions,a);i.push(...u.warnings);let m=await zE(e,s.manifest.name,u.item_type_registrations),f=kf(s.manifest.name,u.installed),p=WE(e,s.manifest.name,u,f,m),h=u.contribution_inventories[I(s.manifest.name)];return h&&(d.managedState=await Sp(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:vE(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)},qE=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 qi()){let c=await _r(s),d=Pe.resolve(c),l=o.get(d);l===void 0&&(l=await Is(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(Of(a,t.dryRun===!0),a.every(s=>s.result.ok))},BE=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:a,installSource:o,sourceResolution:s}=await Lf(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 Cn(c.directory,{source_kind:o.kind,source_input:o.input,source_root:c.source_root}),l=Wi(d.manifest.name),u=e.options.dryRun===!0||o.kind==="local"&&i===null?await Df(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 ys(r.settings_root,l,()=>GE(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:a,sourceResolution:s,installSource:o,resolvedSource:c,installPlan:u}))}finally{c.cleanup&&await c.cleanup()}},VE=async e=>{let t=na(e.options),n=t??ra(e.normalizedTarget,e.action,e.options);return[t===void 0,xp(n)].every(Boolean)?qE(e):BE(e,n,t)},JE=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e;if(t!==void 0)throw new y('Action "adopt-all" does not accept a target argument.',g.USAGE);if(na(a)!==void 0||typeof a.ref=="string"&&a.ref.trim().length>0)throw new y('Action "adopt-all" does not accept --gh/--github/--ref options.',g.USAGE);let s=await T(r.settings_root),c=await ye(r.selected_root);i.push(...c.warnings);let d=await nt(r.selected_root,n,s,c.state);i.push(...d.warnings);let l=await As(r.selected_root,n,d.extensions,c.state),u=await nt(r.selected_root,n,s,l.state);i.push(...u.warnings);let m=Zi(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{..._,...eh(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})},eh=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),KE=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=gr(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}},YE=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o,withResult:s}=e,c=ra(n,t,o),d=na(o),l=await T(i.settings_root),u=await ye(i.selected_root);a.push(...u.warnings);let m=await nt(i.selected_root,r,l,u.state);a.push(...m.warnings);let f=await qf(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 Cn(p),_=$(),w=KE(d,c,p,o.ref),v=hr(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 Tn(i.selected_root,v);let S=await nt(i.selected_root,r,l,v);a.push(...S.warnings);let k=S.extensions.find(x=>I(x.name)===I(h.manifest.name))??S.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,...eh(k)})},th=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o}=e,s=ra(n,t,o),c=await T(i.settings_root),d=await ye(i.selected_root);a.push(...d.warnings);let l=await nt(i.selected_root,r,c,d.state);a.push(...l.warnings);let u=await qf(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}},XE=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:a}=await th(e),o=Pe.join(t.selected_root,a.directory);await Lt.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 Tn(t.selected_root,s);let c=cE(r,a.name);return c&&await li(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:a.name,directory:a.directory},destination_path:o,settings_changed:c})},Ff=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:a}=e,{settings:o,candidate:s}=await th(e),c=t==="activate"?Vf(o,s.name):sE(o,s.name);c&&await li(n.settings_root,o,"settings:write");let d=t==="activate"?await Qf(n.pm_root,Pe.dirname(n.selected_root),o,[s],i).then(l=>(r.push(...l.warnings),Zf(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)},ZE=(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))]},xs=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),QE=(e,t,n,r)=>{if(e!=="project"||t||!xs(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.`},e0=(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=cf(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}},t0=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await As(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},n0=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:xs(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:xs(r),rerun_command:t?null:a,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},r0=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,global:o,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=e0(t,n,a),u=await T(r.settings_root),m=await ye(r.selected_root);i.push(...m.warnings);let f=await nt(r.selected_root,n,u,m.state);i.push(...f.warnings);let{state:p,fix:h}=await t0(e,f.extensions,m.state),_=await nt(r.selected_root,n,u,p);i.push(..._.warnings);let w=await Ve({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Je({...w,loaded:w.loaded}),S=await Nf(r.pm_root);i.push(...S.warnings,...w.warnings),i.push(...af(w.failed)),i.push(...v.warnings),i.push(...of(v.failed)),i.push(...sf(w,v)),i.push(...Sf(v,w)),i.push(...AE(w,v)),i.push(...Ef(v));let k=Xi(_.extensions,w,v),x=lf(n,k,w.loaded.map(z=>({layer:z.layer,name:z.name})),w.failed.map(z=>({name:z.name})),w.disabled_by_flag);i.push(...x.warnings);let D=k.filter(z=>z.update_check_status==="failed").map(z=>`extension_update_check_failed:${z.name}`);i.push(...D);let E=Zi(n,i,k,a);i.push(...E.warnings);let b=[...E.warnings],N={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},A=vr(b),R=br(),Q=E.warning_codes,Ae=QE(n,c,a.vocabulary,w),we=ZE(E.remediation,w.failed.length,v.failed.length,a.vocabulary,h,Ae),_e=n0(n,c,a.vocabulary,w),Ue={status:E.status,scope:n,warning_count:E.warning_count,warning_codes:Q,total_extensions:k.length,managed_total:k.filter(z=>z.managed).length,enabled_total:k.filter(z=>z.enabled).length,active_total:k.filter(z=>z.active).length,unmanaged_loaded_extension_count:E.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:E.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:E.unmanaged_expected_extension_count,runtime_active_total:k.filter(z=>z.runtime_active===!0).length,activation_status_totals:{ok:k.filter(z=>z.activation_status==="ok").length,failed:k.filter(z=>z.activation_status==="failed").length,not_loaded:k.filter(z=>z.activation_status==="not_loaded").length,unknown:k.filter(z=>z.activation_status==="unknown").length},unknown_capability_count:A.length,capability_contract_version:R.version,update_available_total:E.update_available_total,update_check_status_totals:E.update_check_status_totals,update_health_coverage:E.update_health_coverage,update_health_partial:E.update_health_partial,update_check_failed_total:k.filter(z=>z.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:hs(w.failed),activation_failures:hs(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},Mr=h?{requested:!0,applied:h.adopted_entries.length>0,adopted_count:h.adopted_entries.length,already_managed_count:h.already_managed_count,adopted_extensions:h.adopted_entries.map(z=>z.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:_.extensions.filter(z=>z.managed).length,adopted_extensions:[]},Wn={mode:d,summary:Ue,triage:E,trace_enabled:l,capability_contract:R,capability_guidance:A,managed_state_fix:Mr,author_manifest:S,isolation:_e,policy:w.policy};if(d==="deep"){let z=l?v.failed:v.failed.map(B=>{let{trace:jr,...Fr}=B;return Fr});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)},i0=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 Ve({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),l=await Je(d);i.push(...d.warnings),i.push(...l.warnings);let u=Zp(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})},a0=async(e,t,n)=>{let r=n,i=null;return[e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await As(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"&&(r=await Rf(r,e.options.offline)),{state:r,fix:i}},o0=async(e,t,n)=>{let r=await Ve({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Je({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:Xi(n,r,i),failures:Xf(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}}},s0=(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},Uf=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e,s=await T(r.settings_root),c=oE(s.extensions.policy),d=await ye(r.selected_root);i.push(...d.warnings);let l=await nt(r.selected_root,n,s,d.state);i.push(...l.warnings);let{state:u,fix:m}=await a0(e,l.extensions,d.state),f=await nt(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(S=>S.update_check_status==="failed").map(S=>`extension_update_check_failed:${S.name}`);i.push(...v)}let p=await o0(e,s,f.extensions),h=p.installed,_=Zi(n,i,h,a);i.push(..._.warnings);let w={total:h.length,managed_total:h.filter(v=>v.managed).length,enabled_total:h.filter(v=>v.enabled).length,active_total:h.filter(v=>v.active).length,extensions:h,triage:_,policy:c};return p.failures!==void 0&&(w.activation_diagnostics={failed_count:p.failures.length,failed:p.failures}),t==="explore"&&(w.runtime_probe=p.summary),t==="manage"&&(w.runtime_probe=p.summary,w.managed_state_fix=s0(m,h)),o(w)},Hf={init:OE,install:VE,uninstall:XE,explore:Uf,manage:Uf,describe:i0,reload:DE,doctor:r0,catalog:PE,adopt:YE,"adopt-all":JE,activate:Ff,deactivate:Ff,migrate:$f},c0=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),d0=e=>c0(e)?ys(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Hf[e.action](e)):Hf[e.action](e);import{execFile as l0}from"node:child_process";import{realpath as u0}from"node:fs/promises";import nh from"node:path";import{promisify as m0}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 p0=m0(l0),f0=32*1024*1024,h0=1e4,_0=["search/eval-queries.json"];function Rs(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function g0(e){return`'${e.replaceAll("'","'\\''")}'`}async function y0(e,t=u0){return t(e).catch(()=>nh.resolve(e))}async function ia(e){let t=await et(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await y0(e),r=Rs(nh.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=Lo.map(a=>`${r}/${Rs(a)}`);try{let{stdout:a}=await p0("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:f0,windowsHide:!0,timeout:h0}),o=new Set(_0.map(d=>`${r}/${d}`)),s=[...new Set(a.split("\0").filter(d=>d.length>0&&!o.has(Rs(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=>g0(`:(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 rh(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await En(e,$t(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 ih(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 ax}from"node:child_process";import{randomUUID as ox}from"node:crypto";import{readdir as sx,stat as cx}from"node:fs/promises";import he from"node:path";import{promisify as dx}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5134bd12-d808-588f-af5d-fc71e5153e95")}catch{}})();var w0=Object.freeze({pm_item_scalar_missing:!0});function $n(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?w0:e}function Mt(e){return Ie(C(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function Cs(e,t){let n=Me(e);if(n)throw new y(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(o)try{let s=JSON.parse(o);if(typeof s!="object"||s===null||Array.isArray(s))throw new TypeError("history entry must be an object");r.push(s)}catch{throw new y(`History merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}}return r}function gt(e){return C({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function v0(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&gt(e[r])===gt(t[r]);)r+=1;return r}function b1(e,t,n){let r=Cs(e,"base"),i=Cs(t,"ours"),a=Cs(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(gt)).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=v0(i,a);if(s===i.length&&s===a.length)return{merged:Gt(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:Gt(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:Gt(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(gt)),l=a.slice(s).filter(f=>!d.has(gt(f))),u=[...c,...l].sort((f,p)=>{let h=Wt(f.ts,p.ts);if(h!==0)return h;let _=d.has(gt(f)),w=d.has(gt(p));return _!==w?Number(w)-Number(_):gt(f).localeCompare(gt(p))}),m=oi([...i.slice(0,s),...u],void 0,{continuousHashSurface:!0});if(m.skippedOps>0)throw new y(`History union cannot preserve ${m.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,g.GENERIC_FAILURE);return{merged:Gt(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 Ts(e,t){let n=Me(e);if(n)throw new y(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(!o)continue;let s;try{s=JSON.parse(o)}catch{throw new y(`Relationship merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}if(typeof s!="object"||s===null||Array.isArray(s)||typeof s.eventId!="string"||typeof s.sequence!="number")throw new y(`Relationship merge input (${t}) line ${i+1} is not a relationship event (eventId + sequence required).`,g.GENERIC_FAILURE);r.push(s)}return r}function aa(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
35
+ `}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(pr)||E.includes(Hi)){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=Ym(i),d=Yo(s,t),l=c.filter(_=>Xm(_.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 Jm){let i=`merge.${r.key}.driver`,a=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`;try{let{stdout:o}=await Zt("git",["config","--get",i],{cwd:e,env:et(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=o.trim();await zv(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 Qm(e){let t;try{t=await Km(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,Nv,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(pr)&&!s.includes(Hi))return{status:"not_installed",path:o};let c=await T(e),d=Dt(c),l=await Zm(t,n,Yo(n,d),!1);return{status:l.changed?"refreshed":"unchanged",path:l.path}}finally{await a()}}async function MP(e,t){let n=Fv({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await ne(r);let i=await Km(n.workspace_start);return Gv({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function Hv(e,t){let n=(await Zt("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:e,env:et(),timeout:1e4})).stdout.trim(),r=await te(n,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{let i=await zm(e),a;try{a=(await Zt("git",["config",i,"--null","--get-regexp","."],{cwd:e,env:et(),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(`
36
+ `);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 Gv(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(Uo(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 jv();for(let f of Jm)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 Hv(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 Zm(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 Wv=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function qv(e){let t=Wv.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Bv(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function ep(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=qv(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=Bv(o);a.push({name:c,prefix:o,count:s.count,examples:s.examples,shadows_builtin:yd(c)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}import{createHash as mp}from"node:crypto";import en from"node:fs/promises";import Tn from"node:path";import{mkdir as Vv,readFile as Jv}from"node:fs/promises";import ap from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0bd9a904-c076-5c2a-a9d8-42a543625e33")}catch{}})();var Xo=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Kv="sdk-workspace-transaction",Yv=/^[a-zA-Z0-9._-]+$/,Xv=30,Zv=3e3;function op(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Yv.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function tp(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 Qv(e){return{pmRoot:tp(e.pmRoot,"Transaction pmRoot"),transactionId:op(e.transactionId,"Transaction id"),author:tp(e.author,"Transaction author")}}function np(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 sp(e,t){return ap.join(e,"transactions","sdk",`${t}.json`)}async function Pt(e,t){t.updatedAt=$();let n=sp(e,t.transactionId);await Vv(ap.dirname(n),{recursive:!0}),await Z(n,`${JSON.stringify(t,null,2)}
37
+ `)}function eb(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 tb(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:tb(e,t)}function Qo(e,t,n,r){let i=Zo(n,r);i===void 0?delete e[t]:e[t]=i}function rp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ip(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function nb(e,t){if(!ip(e.startedStepIds,t)||!ip(e.completedStepIds,t)||!rp(e.results)||!rp(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 rb(e,t,n){let r;try{r=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let i=r,a=i.schemaVersion===1&&i.transactionId===t,o=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((l,u)=>l===n[u]),s=nb(i,n),c=eb(i),d=["applying","compensating","compensated","committed"].includes(String(i.status));if(!a||!o||!s||!c||!d)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);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 cp(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 ht(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 ht(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 ht(e,t,"step_recorded",a.id)}return await ht(e,t,"committing"),t.status="committed",await Pt(e.pmRoot,t),await ht(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 cp(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 Jv(sp(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&F(r))return;throw r}}async function ht(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 cp(e,t){t.status="compensating",await Pt(e.pmRoot,t),await ht(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 ht(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 ht(e,t,"step_compensated",i.id)}t.status="compensated",await Pt(e.pmRoot,t),await ht(e,t,"compensated")}async function dp(e){let{pmRoot:t,transactionId:n,author:r}=Qv(e),i=np(e.lockTtlSeconds,Xv,"Transaction lock TTL"),a=np(e.lockWaitMs,Zv,"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=op(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,Kv,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 _t(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function pp(e){let t=_t(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function fp(e,t){let n=ts(e),r=_t(t,"migrationScope");return`auto-${mp("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function ts(e){let t=e.kind==="rename-type"?{kind:e.kind,from:_t(e.from,"source"),to:_t(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:le(_t(e.from,"source")),to:le(_t(e.to,"target")),...e.type===void 0?{}:{type:_t(e.type,"type")}}:{kind:e.kind,from:le(_t(e.from,"source")),to:le(_t(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 Xe(e,r.files[i],Le[i])}function hp(e,t){return Tn.join(e,"transactions","schema",`${t}-plan.json`)}function Gi(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 _p(e,t){t.exists?await Z(e,t.raw):await en.rm(e,{force:!0})}function lb(e,t,n){let r=st(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 ns(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function $n(e){return Array.isArray(e)?e.map(t=>ns(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=ns(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=ns(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 es(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)}
38
+ `}function gp(e,t){if(t.kind==="rename-type"){let r=st(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 yp(e,t){let n=ts(t.request),r=t.migrationId===void 0?fp(n,t.migrationScope??"plan"):pp(t.migrationId),i=e.map(c=>wb(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),a=mp("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 yi(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 Pl({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 dt(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(hp(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: ${id(r)}`,g.GENERIC_FAILURE)}}async function kb(e,t){let n=hp(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)}
39
+ `)}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 lp(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 up(e){return{id:e.id,inspect:async()=>{let t=await Cn(e.filePath),n=gp(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 _p(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:es(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,es(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 _p(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 ut({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:lp(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 ut({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:lp(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:{...yp(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Rb(e){let t=gp(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])=>Xe(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&&es(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 io({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Gi(t.beforeRaw),after:Gi(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=ts(e),i=L(process.cwd(),n.path);await ne(i);let a=t.migrationId===void 0?fp(r,await en.realpath(i)):pp(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=[up({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})),up({id:"retire-source",filePath:l,request:r,phase:"retire"})],p=await dp({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 io({pmRoot:i,author:s,documentPath:Tn.relative(i,l).replaceAll("\\","/"),before:Gi(u),after:Gi(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 zN=[...Xr,"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"],Wi="schema-types",wp="schema-statuses",vp="schema-fields";function Lt(e){return mi({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 WN(e,t,n){let r=L(process.cwd(),n.path);await gt(r);let i;try{i=Ba({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=Xe(r,o.files.types,Le.types),c=[],d=W(t.author,a.author_default),l=Te(a),u=await te(r,Wi,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=st(f)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.GENERIC_FAILURE)}try{wd(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)}vd(i,p,h)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}m=Kr(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 bp(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 gt(e){await ne(e)}async function bp(e,t){try{let n=await Qm(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 dt(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 dt(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||Ja.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 qN(e,t,n){let r=L(process.cwd(),n.path);await gt(r);let i=await T(r),a=Re(i.schema),o=Xe(r,a.files.types,Le.types),s=[],c=W(t.author,i.author_default),d=Te(i),l=await te(r,Wi,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=st(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=bd(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 bp(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 rs(e,t){return Xe(e,t.files.statuses,Le.statuses)}function qi(e,t){return Xe(e,t.files.fields,Le.fields)}function kp(e,t){return Xe(e,t.files.types,Le.types)}async function fr(e,t,n,r){for(let i of t){let a=sd(i.folder??od(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 is(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 BN(e,t,n){let r=L(process.cwd(),n.path);await gt(r);let i;try{i=Cd({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=rs(r,o),c=ge(o);try{Ka(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,wp,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{Ka(i,w)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.USAGE)}p=Td(_,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 VN(e,t,n){let r=L(process.cwd(),n.path);await gt(r);let i=await T(r),a=Re(i.schema),o=rs(r,a),s=[],c=W(t.author,i.author_default),d=Te(i),l=await te(r,wp,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=$d(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 Ep(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{...Ep(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 Sp(e){return{id:e.id,source:Ja.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 xp(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=Sp(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 gt(t);let n=await T(t),r=Re(n.schema),i=Xe(t,r.files.types,Le.types),a=rs(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 JN(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=xp(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=Ep(s);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let a=Hb(t.schema),o=Yr(t.schema).definitions.map(is);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 KN(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 "${dn(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Ub(i,xp(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:$()}}async function YN(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 "${dn(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Sp(o),file:{path:r.statusesPath},generated_at:$()}}async function XN(e,t,n){let r=L(process.cwd(),n.path);await gt(r);let i;try{i=Sd({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=qi(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,vp,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=xd(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 dt(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 ZN(e,t,n){let r=L(process.cwd(),n.path);await gt(r);let i=await T(r),a=Re(i.schema),o=qi(r,a),s=[],c=W(t.author,i.author_default),d=Te(i),l=await te(r,vp,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=Ad(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 QN(e){let t=await hr(e),n=Yr(t.schema).definitions.map(is);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:qi(t.pmRoot,t.schema)},generated_at:$()}}async function eL(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=Yr(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:is(i),file:{path:qi(r.pmRoot,r.schema)},generated_at:$()}}async function tL(e,t,n){let r=L(process.cwd(),n.path);await gt(r);let i;try{let h=Ed(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${kd.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=kp(r,o),c=[],d=W(t.author,a.author_default),l=Te(a),u=[],m=[],f,p=await te(r,Wi,a.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms);try{let h=await V(s),_;try{_=st(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=_;for(let v of Va(i)){let E=Kr(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,Va(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 nL(e,t){let n=L(process.cwd(),t.path);await gt(n);let r=await T(n),i=Re(r.schema),a=kp(n,i),o=Wb(e.minCount),s=G(r,z()),c=(await dt(n,r.item_format,s.type_to_folder,[],i)).map(v=>typeof v.title=="string"?v.title:""),d=ep(c,{minCount:o}),l=[],u=[],m=[],f=[],p;if(!e.apply){let v;try{v=st(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,Wi,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=st(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=Ba({name:x.name})}catch{f.push({name:x.name,reason:"invalid_type_token"});continue}let S=Kr(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 Ap from"node:fs/promises";import as 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 Bi(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 os(e){return md(e)}async function qb(e){try{let t=JSON.parse(await Ap.readFile(as.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=as.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 Ap.readFile(n,"utf8"))}catch(o){throw new y(`Failed to parse extension manifest at "${n}": ${Vb(o)}`,g.USAGE)}let i=os(r);if(!i)throw new y(`Extension manifest at "${n}" is invalid.`,g.USAGE);let a=as.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 fd(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 ss 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",Vi=1;function _r(e){return Jb.join(e,Kb)}function Yb(){return{version:Vi,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 Ip(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=ld(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!==Vi||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=Qb(r);i&&n.push(i)}return{version:Vi,updated_at:ke(t.updated_at)??$(),entries:gr(n)}}async function ye(e){let t=_r(e),n=Yb();try{let r=await ss.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=_r(e),r={version:Vi,updated_at:$(),entries:gr(t.entries)};await ss.mkdir(e,{recursive:!0}),await ss.writeFile(n,`${JSON.stringify(r,null,2)}
40
+ `,"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 Rp(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 Dn(e,a),a}import{execFile as uk}from"node:child_process";import K from"node:fs/promises";import ps 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",Cp={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},rk=new Set(["*","all"]);function cs(){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 wr(e){let t=e.trim().toLowerCase(),n=await $p(t);if(n)return n;let r=Cp[t];if(!r)return null;for(let i of cs()){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 Tp(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 Vr(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 ds(){let e=new Map;for(let t of cs()){let n=qe.join(t,"packages");await O(n)&&await ak(n,e)}for(let[t,n]of Object.entries(Cp))if(!e.has(t))for(let r of cs()){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 Ji(){return(await ds()).map(e=>e.alias)}async function $p(e){let t=e.trim().toLowerCase();return(await ds()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function Op(e){let t=await $p(e);return t?(await Vr(t)).package_name??null:null}async function Dp(e){let t=await wr(e);if(!t)return null;try{let n=await Jr(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(qa.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 Pp(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 ds()){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 Vr(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:qa.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=Zl(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 Lp=pk(uk),Yi="@unbrained/pm-cli",gk={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},ls;async function Mp(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 us(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 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 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 us(s,n,r)}catch{return null}})();if(i)return i;let a=n.startsWith("github.com/")?n.slice(11):null;if(a){let o=us(a,n,r);if(!o)throw new y(`Invalid GitHub source "${n}".`,g.USAGE);return o}if(t.forceGithub){let o=us(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 Ki(e,t=Lp,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(" ")}
41
+ ${a}`,g.GENERIC_FAILURE)}}function fs(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function hs(e=process.platform){return e==="win32"}async function jp(e,t,n=Lp,r=process.platform,i=process.env){let a=fs(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:hs(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(" ")}
42
+ ${d}`,g.GENERIC_FAILURE)}}function Fp(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 Up(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=Fp(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 zp(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 zp(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(!Up(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 Np(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:Np(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:Np(t,a.filename),package:a.name??a.key,version:a.version}}async function Tk(e){return $k(e,jp)}async function $k(e,t){let n=await zp(e.spec);if(n){if((await K.stat(n)).isFile()&&Hp(n))return ms(n);let a=j.join(n,"package.json"),o=await O(a)?JSON.parse(await K.readFile(a,"utf8")):{};return{directory:await Xi(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(ps.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,Up(e.spec)?void 0:Fp(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 ms(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 Hp(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function yt(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&&yt(`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===".."))&&yt(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&yt(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&yt(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&yt(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&yt(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&yt(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function ms(e,t=gk){(await K.stat(e)).size>t.maxArchiveBytes&&yt(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await K.mkdtemp(j.join(ps.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&&yt(`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 Xi(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=jp){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)}
43
+ `,"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)}
44
+ `,"utf8")}}function Pk(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Yi 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[Yi],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function Lk(e){let t=Ne(import.meta.url,["../../.."]),[n,r]=Yi.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===Yi||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 Xi(e,t){let n=await Jr(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 Xi(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()):"";ls?.key!==o&&(ls={key:o,aliases:await Ji()}),r=ls.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 Gp(e){if(e.kind==="local"){let r;try{r=await K.stat(e.absolute_path)}catch{throw await Hk(e)}if(r.isFile()&&Hp(e.absolute_path)){let a=await ms(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 Xi(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(ps.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Ki(n);let r=await Ki(["-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 Zi(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 _s=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},Wp=new Set([...Ld.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(gd).map(e=>e.toLowerCase()),"scaffold"]),qk="^6.0.0",Bk="^22.0.0",Vp=["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."," }"," }","}",""],nt=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function qp(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Jp(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function Kp(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"]},Bp=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Yp={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."},Xp="- `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 Zp(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function Qp(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&&Wp.has(i));return`${(Wp.has(n)||a?["starter",...t]:t).join(" ")} ping`}function ef(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({",...ef(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;",...nt,"});",""]:[],E=i?gs(e,t,"search",m):[],k=a?gs(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 {",...qp(Jp({extensionName:e,itemTypeName:f,itemTypeFolder:p,fieldName:h,migrationId:_,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...nt,"});",""]:[],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 {",...qp(Kp(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...nt,"});",""]:[],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;",...nt,"});",""]:[],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;",...nt,"});",""]:[],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;",...nt,"});",""]:[],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;",...nt,"});",""]:[];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";',"",...Vp,`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;",...nt,"});","",...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(`
45
+ `)}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({",...ef(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(`
46
+ `)}function gs(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;",...nt];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(a)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(Jp({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Kp(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([...Yp[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" };',"",...Vp,`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;",...nt,"});","",...gs(e,t,n,i)].join(`
47
+ `)}function uE(e,t,n){let r=Zp(n,"package"),i=Qp(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`.",Xp,"- `.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 \`${_s}\` 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(`
48
+ `)}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=Yp[r],s=iE(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:_s,pm_min_version:tn,trusted:!0,sandbox_profile:"strict",permissions:{...Wk},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
49
+ `,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(`
50
+ `),l=`${JSON.stringify(Vk,null,2)}
51
+ `,u=Kk[r],m=Zp(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)}
52
+ `,p=rE(e,t,r),h=Yk[r],_=["node_modules/","*.log","*.tsbuildinfo",""].join(`
53
+ `),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,Xp,"- `.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],...Qp(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 \`${_s}\` 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(`
54
+ `);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 tf(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!Bp.includes(i))throw new y(`Unknown scaffold capability "${n}". Supported capabilities: ${Bp.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=Bi(kr.basename(c)).replace(/^(?:pm-)+/u,""),l=tE(d),u=_E(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 nf(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 rf(e,t,n){let r=new Set(n.failed.map(d=>nf(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(nf(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 ys(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function Qi(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)Qi(t,r.name,r.command),Qi(n,r.name,r.action);for(let r of e.commands.handlers)Qi(t,r.name,r.command);for(let r of e.commands.overrides)Qi(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function af(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 ea(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=af(o.get(d)),u=af(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 cf=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 cf.has(ff(e))}function of(e){return e==="project"||e==="global"}function df(e){let t=e.split(":"),n=t[0];if(!n||!cf.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!of(r)||!of(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=df(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function ws(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=>df(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 lf(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 uf(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 mf(e,t){let n=[];for(let r of Fd(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: ${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 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=ws(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 ta(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=>sf(b)).map(b=>b.name).sort((b,N)=>b.localeCompare(N)),u=d.filter(b=>!sf(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=>ff(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 pf(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 ff(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=Jc(r);return a?[a]:Kc(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 sf(e){let t=I(e.name),n=I(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function hf(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 _f 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=_f.relative(e,n);if(i!==""&&!fe(e,n)||n===t||fe(t,n))return!1;let a=i.split(_f.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 gf=3,RE=120,yf=250,CE=12e4,TE=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),wf=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,vf=e=>TE.has(String(wf(e))),na=(e,t)=>wf(e)===t,bf=e=>new Promise(t=>{setTimeout(t,e)}),kf=async e=>{let t=re.join(e,"package.json");await O(t)||await se.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
55
+ `,"utf8")},Ef=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))},Sf=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 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})}}),xf=async(e,t,n=se.cp)=>{for(let r=1;r<=gf;r+=1)try{await Wt("extension_install_copy",async()=>{await se.rm(t,{recursive:!0,force:!0}),await Sf(e,t,n)});return}catch(i){if(!vf(i)||r===gf)throw i;await bf(yf)}},vs=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},Af=async(e,t)=>await vs(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 vs(e);return r===null?(await se.rm(e,{recursive:!0,force:!0}),!0):Af(e,r)},OE=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await vs(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)}
56
+ `,"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(!na(o,"EEXIST"))throw o;await $E(e,i)?a-=1:await bf(r)}return!1},bs=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=yf,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 Af(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 ks=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 If(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 Rf(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 Cf=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 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),$f=1e4;function Tf(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(fs(),e,{encoding:"utf8",timeout:t,maxBuffer:65536,shell:hs(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function Of(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=Tf(e.package,e.version,"missing_or_invalid_installed_npm_version"),i=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],$f),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=Tf(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"}},Es=async(e,t=Ki)=>{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,$f);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 Df(e,t=!1){let n=await ks(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 Es(r.source):await Of(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 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 Ss(e){return GE.join(e,"extension-migrations.json")}function Pf(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 Nf(e,t){return`${e.layer}:${e.name}:${t}`}async function WE(e){let t=Ss(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 xs(e,t){let n=await WE(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,a)=>{let o=Pf(i,a),s=r.get(Nf(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 xs(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=Pf(l,u),f=Nf(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 mi({pmRoot:e.pmRoot,filePath:Ss(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
57
+ `,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:Ss(e.pmRoot),total:r.length,pending_count:o,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function Lf(e){let t=await T(e.resolvedRoots.settings_root),n=await Ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Ye(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 Mf(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 ia from"node:fs/promises";import ra 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 jf(e,t,n,r){let i=e.source.kind==="local"?await ia.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(ra.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 ia.realpath(e),s=await Ar(t),c=await Zi(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 Ff(o,0,l,a),l}async function Ff(e,t,n,r){r?.throwIfAborted();let i=await ia.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=ra.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(ra.relative(n.source_directory,o).split(ra.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 ia.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 Ff(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 As(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=td(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 Uf(e){return As(Je(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 vr(`npm:${i}`,{})}async function zf(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 Op(a),s=await tS(vr(i??e,{forceGithub:typeof t=="string",ref:n}),r),c=a===null?null:await Mp(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 Is=async e=>nn.readFile(e).catch(t=>{if(na(t,"ENOENT"))return null;throw t}),Hf=async(e,t,n,r,i)=>Wt("extension_install_backup",async()=>{let a=_r(e),o=Ht(t),[s,c]=await Promise.all([Is(a),Is(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}}),Gf=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 Vf=[["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=Vf.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"],Jf=["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"],Kf={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??Kf,n={};for(let r of oS)n[r]=De(t[r]??[]);return n},dS=(e,t)=>{for(let n of Jf)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 Jf)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({},Kf,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}},Yf=async(e,t)=>{let n=[t],r=await Dp(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}},Xf=(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)},Zf=(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=Vf.map(([i,a,o])=>({action:a,flag:o,distance:Vc(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 fi({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(Qf),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"]],Qf={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},vS=e=>Qf[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"}}],eh=e=>{for(let t of ES){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},th=(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?Xf(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:th({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:a},t,r,eh(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=os(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(I(u.name))??a.get(I(t));return{summary:th({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:Xf(r,u.name)},n,m,eh(m))}},rt=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=Md(),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},nh=e=>e.map(t=>CS(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),rh=(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"),ih=(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 Ke({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:Ga(),cache_bust:!0,module_graph_snapshot_root:o}),c=await Ye({...s}),d=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...nh(c.failed)],l=Object.fromEntries(s.loaded.map(u=>[I(u.name),ud(xn(c,{extensionName:u.name}))]));return{installed:ea(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}}),Cs=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=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 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"?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}},aa=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`}]}})},oa=(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},Ts=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=Hd(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([aa(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=oa(n,t,r),o=await tf(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=Ga(),d=await Ke({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 Ye(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 Pp(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}:Ip(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 Zi(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 Hf(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=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=Zf(s,a.manifest.name);try{u||await xf(a.directory,d),await kf(d),await Ef(d),await Dn(r.selected_root,v),E&&await pi(r.settings_root,s,"settings:write")}catch(k){try{await Gf(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 fr(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},XS=(e,t,n,r,i)=>{let a=rh(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 rt(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let u=await ih(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=If(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 Rp(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 Ji()){let c=await wr(s),d=Pe.resolve(c),l=o.get(d);l===void 0&&(l=await Ts(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(Mf(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 zf(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 Gp(o);try{let d=await On(c.directory,{source_kind:o.kind,source_input:o.input,source_root:c.source_root}),l=Bi(d.manifest.name),u=e.options.dryRun===!0||o.kind==="local"&&i===null?await jf(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 bs(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=aa(e.options),n=t??oa(e.normalizedTarget,e.action,e.options);return[t===void 0,Tp(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(aa(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 rt(r.selected_root,n,s,c.state);i.push(...d.warnings);let l=await Cs(r.selected_root,n,d.extensions,c.state),u=await rt(r.selected_root,n,s,l.state);i.push(...u.warnings);let m=ta(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{..._,...ah(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})},ah=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=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}},i0=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o,withResult:s}=e,c=oa(n,t,o),d=aa(o),l=await T(i.settings_root),u=await ye(i.selected_root);a.push(...u.warnings);let m=await rt(i.selected_root,r,l,u.state);a.push(...m.warnings);let f=await Yf(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=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 Dn(i.selected_root,v);let E=await rt(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,...ah(k)})},oh=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o}=e,s=oa(n,t,o),c=await T(i.settings_root),d=await ye(i.selected_root);a.push(...d.warnings);let l=await rt(i.selected_root,r,c,d.state);a.push(...l.warnings);let u=await Yf(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 oh(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 pi(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:a.name,directory:a.directory},destination_path:o,settings_changed:c})},Wf=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:a}=e,{settings:o,candidate:s}=await oh(e),c=t==="activate"?Zf(o,s.name):hS(o,s.name);c&&await pi(n.settings_root,o,"settings:write");let d=t==="activate"?await ih(n.pm_root,Pe.dirname(n.selected_root),o,[s],i).then(l=>(r.push(...l.warnings),rh(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))]},Rs=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||!Rs(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=pf(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 Cs(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:Rs(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:Rs(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 rt(r.selected_root,n,u,m.state);i.push(...f.warnings);let{state:p,fix:h}=await d0(e,f.extensions,m.state),_=await rt(r.selected_root,n,u,p);i.push(..._.warnings);let w=await Ke({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Ye({...w,loaded:w.loaded}),E=await Uf(r.pm_root);i.push(...E.warnings,...w.warnings),i.push(...lf(w.failed)),i.push(...v.warnings),i.push(...uf(v.failed)),i.push(...mf(w,v)),i.push(...Rf(v,w)),i.push(...PS(w,v)),i.push(...Cf(v));let k=ea(_.extensions,w,v),x=hf(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=ta(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=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:ys(w.failed),activation_failures:ys(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(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:Ur,author_manifest:E,isolation:_e,policy:w.policy};if(d==="deep"){let H=l?v.failed:v.failed.map(B=>{let{trace:zr,...Hr}=B;return Hr});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 Ke({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),l=await Ye(d);i.push(...d.warnings),i.push(...l.warnings);let u=rf(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 Cs(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"&&(r=await Df(r,e.options.offline)),{state:r,fix:i}},f0=async(e,t,n)=>{let r=await Ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Ye({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:ea(n,r,i),failures:nh(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},qf=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 rt(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 rt(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,_=ta(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)},Bf={init:US,install:t0,uninstall:a0,explore:qf,manage:qf,describe:m0,reload:zS,doctor:u0,catalog:HS,adopt:i0,"adopt-all":n0,activate:Wf,deactivate:Wf,migrate:Lf},_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)?bs(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Bf[e.action](e)):Bf[e.action](e);import{execFile as y0}from"node:child_process";import{realpath as w0}from"node:fs/promises";import sh 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 $s(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function x0(e){return`'${e.replaceAll("'","'\\''")}'`}async function A0(e,t=w0){return t(e).catch(()=>sh.resolve(e))}async function sa(e){let t=await tt(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=$s(sh.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=Fo.map(a=>`${r}/${$s(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($s(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 ch(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 dh(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";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5134bd12-d808-588f-af5d-fc71e5153e95")}catch{}})();var I0=Object.freeze({pm_item_scalar_missing:!0});function 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?I0:e}function Ft(e){return Ie(C(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function Os(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 wt(e){return C({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function R0(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&wt(e[r])===wt(t[r]);)r+=1;return r}function D1(e,t,n){let r=Os(e,"base"),i=Os(t,"ours"),a=Os(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(wt)).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=R0(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(wt)),l=a.slice(s).filter(f=>!d.has(wt(f))),u=[...c,...l].sort((f,p)=>{let h=qt(f.ts,p.ts);if(h!==0)return h;let _=d.has(wt(f)),w=d.has(wt(p));return _!==w?Number(w)-Number(_):wt(f).localeCompare(wt(p))}),m=di([...i.slice(0,s),...u],void 0,{continuousHashSurface:!0});if(m.skippedOps>0)throw new y(`History union cannot preserve ${m.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,g.GENERIC_FAILURE);return{merged: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 Ds(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 ca(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
58
58
  `)}
59
- `}function b0(e){return e.map((t,n)=>({...t,sequence:n+1}))}function k1(e,t,n){Ts(e,"base");let r=Ts(t,"ours"),i=Ts(n,"theirs"),a=Math.min(r.length,i.length),o=0;for(;o<a&&r[o].eventId===i[o].eventId;)o+=1;if(o===r.length&&o===i.length)return{merged:aa(r),strategy:"identical",common_entries:o,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===i.length)return{merged:aa(r),strategy:"fast_forward_ours",common_entries:o,entries_from_ours:r.length-o,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===r.length)return{merged:aa(i),strategy:"fast_forward_theirs",common_entries:o,entries_from_ours:0,entries_from_theirs:i.length-o,entries_total:i.length,reanchored:!1};let s=r.slice(o),c=new Set(s.map(m=>m.eventId)),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 _=Wt(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=b0([...r.slice(0,o),...l]);return{merged:aa(u),strategy:"union_reanchor",common_entries:o,entries_from_ours:s.length,entries_from_theirs:d.length,entries_total:u.length,reanchored:!0}}var k0=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],S0=["acceptance_criteria"],E0=["updated_at"];function en(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:C(e)===C(t)}function ah(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 Er(e){if(typeof e!="object"||e===null||Array.isArray(e))return C(e);let{provenance:t,...n}=e;return C(n)}function x0(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 A0(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(Er)),a=r(t),o=new Set(a.map(Er)),s=r(n),c=new Set(s.map(Er)),d=a.filter(l=>{let u=Er(l);return!i.has(u)||c.has(u)});for(let l of s){let u=Er(l);!o.has(u)&&!i.has(u)&&d.push(x0(l))}return d}function I0(e,t){return Wt(String(e),String(t))>=0?e:t}function oh(e,t,n,r){return en(t,n)?{value:t,from_theirs:!1,conflict:!1}:en(e,t)?{value:n,from_theirs:!0,conflict:!1}:en(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function sh(e,t,n,r,i,a,o){let s=oh(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=Wt(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 $s(e){return{...e.metadata}}function Os(e,t,n){try{let r=Yd(It(e,n),n),i=Object.entries(r.metadata).find(([,a])=>$n(a))?.[0];if(i!==void 0)throw new TypeError(`metadata field ${i} uses the reserved missing-scalar evidence marker`);return r}catch(r){throw new y(`Item merge input (${t}) is not a readable item document: ${String(r)}`,g.GENERIC_FAILURE)}}function R0(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?A0(e.baseValue,e.oursValue,e.theirsValue):e.field==="acceptance_criteria"?ah(mi(e.baseValue),mi(e.oursValue),mi(e.theirsValue)).join("; "):ah(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,en(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function C0(e){let t=sh(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 T0(e,t,n,r,i,a,o){let s=new Set([...k0,...S0]),c=new Set(E0),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(!R0({field:u,baseValue:m,oursValue:f,theirsValue:p,unionFieldSet:s,accumulator:l})){if(c.has(u)){l.merged[u]=I0(f,p);continue}C0({field:u,baseValue:m,oursValue:f,theirsValue:p,preferred:r,conflictResolution:i,oursUpdatedAt:a,theirsUpdatedAt:o,accumulator:l})}}return l}function S1(e,t,n,r={}){let i=r.preferred??"ours",a=r.conflictResolution??"preferred_side",o=Os(t,"ours",r),s=Os(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=Os(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=$s(c),l=$s(o),u=$s(s),{merged:m,conflictFields:f,fieldsFromTheirs:p,unionFields:h,conflictDecisions:_}=T0(d,l,u,i,a,o.metadata.updated_at,s.metadata.updated_at),w=sh(c.body,o.body,s.body,i,a,o.metadata.updated_at,s.metadata.updated_at);return w.conflict?(f.push("body"),_.push({field:"body",base:Y(c.body),ours:Y(o.body),theirs:Y(s.body),retained:Y(w.value),discarded:Y(w.from_theirs?o.body:s.body),retained_side:w.retained_side,resolution_basis:w.resolution_basis})):w.from_theirs&&p.push("body"),{merged:Kd({metadata:m,body:w.value},r),conflict_fields:f,fields_from_theirs:p,union_fields:h,conflict_decisions:_,requested_preference:i,requested_preference_applied:a==="preferred_side",conflict_resolution:a}}function Ds(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ps(e,t){let n=Me(e);if(n)throw new y(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,g.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new y(`JSON merge input (${t}) is not valid JSON.`,g.GENERIC_FAILURE)}}function $0(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=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 O0(e,t,n,r,i,a,o){if(!Ds(t)||!Ds(n))return null;let s=Ds(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=D0(s,t,n,l,r,u,a,o);m!==void 0&&(c[l]=m)}return c}function ch(e,t,n,r,i,a,o){if(en(t,n))return t;let s=$0(e,t,n);if(s!==null)return s.acceptedTheirs&&o.push(i),s.merged;let c=O0(e,t,n,r,i,a,o);if(c!==null)return c;let d=oh(e,t,n,r);return d.conflict?a.push(i):d.from_theirs&&o.push(i),d.value}function D0(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 ch(e[r],t[r],n[r],i,a,o,s);if(c){if(l&&en(e[r],t[r])){s.push(a);return}return l?(o.push(a),i==="theirs"?void 0:t[r]):t[r]}if(!(l&&en(e[r],n[r])))return l?(o.push(a),i==="theirs"?n[r]:void 0):(s.push(a),n[r])}function E1(e,t,n,r={}){let i=r.preferred??"ours",a=Ps(e,"base"),o=Ps(t,"ours"),s=Ps(n,"theirs"),c=[],d=[],l=ch(a,o,s,i,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
60
- `,conflict_paths:c,paths_from_theirs:d,preferred:i}}import{constants as dh}from"node:fs";import{lstat as P0,open as N0}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 L0={lstat:P0,open:N0};function M0(e){return e.O_NOFOLLOW??0}async function xr(e,t,n=L0){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let i=await n.open(e,dh.O_RDONLY|M0(dh));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 sa from"node:path";import{execFile as j0}from"node:child_process";import{createHash as lh}from"node:crypto";import{readdir as F0}from"node:fs/promises";import U0 from"node:path";import{promisify as H0}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 yt=H0(j0),oa=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function N1(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 yt("git",["rev-parse","--path-format=absolute","--git-path",`${a}/orig-head`],{cwd:e,timeout:1e4}),s=(await xr(o.trim(),128))?.trim();if(s===void 0||!oa.test(s))continue;let{stdout:c}=await yt("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 yt("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[o,s]=a.trim().split(/\r?\n/u);if(o!==s||!oa.test(o))return;let{stdout:c}=await yt("git",["rev-parse","--verify",`${o}:${i}`],{cwd:e,timeout:1e4}),d=c.trim(),l=lh(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 uh(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"&&oa.test(t.original_head)&&typeof t.original_blob=="string"&&oa.test(t.original_blob)}async function mh(e,t,n,r){if(r!==void 0&&lh(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 yt("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 F0(i.trim())).some(d=>a.has(d)))return!1;let{stdout:o}=await yt("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(o.trim()!==n.original_head)return!1;let{stdout:s}=await yt("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(s.trim()!==n.original_blob)return!1;let{stdout:c}=await yt("git",["hash-object","--",U0.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await yt("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 z0=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,W0=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,da=2048,G0=64,q0=1e5,B0=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 wt(e){return z0.test(e)}var V0=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),la="bounded_non_sensitive_scalars_v1",J0=new Set(["open","in_progress","blocked","closed","canceled"]),K0=new Set(["risk","confidence","severity"]),Y0=new Set(["low","medium","high","critical"]),fh=new Map([["priority",new Set([0,1,2,3,4].map(C))],["status",new Set([...J0].map(C))],...[...K0].map(e=>[e,new Set([...Y0].map(C))])]);function rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hh(e,t){return Object.keys(e).every(n=>t.has(n))}function ca(e){return Array.isArray(e)&&e.length<=da&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Ar(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>q0||r.depth>G0)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(rt(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function _h(e){if(!rt(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[hh(e,V0),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"),Ar(e.base),Ar(e.ours),Ar(e.theirs),Ar(e.retained),Ar(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function X0(e){if(!rt(e))return!1;let t=Object.entries(e);return t.length<=da&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function Z0(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||sa.posix.isAbsolute(e))return!1;let n=sa.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&sa.posix.basename(n,sa.posix.extname(n))===t}function Q0(e){return!ca(e.fields_from_theirs)||!ca(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>da||!e.decisions.every(_h)?!1:e.merged_field_hashes===void 0||X0(e.merged_field_hashes)}function ex(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],r=[void 0,"clone_local","hash_only","bounded_inline","mixed"],i=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===la)&&i.includes(e.evidence_source)}function tx(e){return typeof e.created_at=="string"&&un(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&un(e.reconciled_at))}function ph(e,t){if(!rt(t)||ua(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||fh.get(e)?.has(C(r))===!0)&&Mt(r)===t.pm_value_hash}function nx(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&ph(r.field,r.retained)&&ph(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,i)=>r+(rt(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(rt(i.discarded)&&Object.hasOwn(i.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===la)}function rx(e){return e.operation!==void 0&&!uh(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function ix(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||!hh(e,B0)?"required_fields":typeof e.id!="string"||!wt(e.id)?"receipt_id":typeof e.item_id!="string"||!W0.test(e.item_id)?"item_id":Z0(e.item_path,e.item_id)?null:"item_path"}function Ns(e,t){if(!rt(e))return"required_fields";let n=ix(e);return n!==null?n:rx(e)?Q0(e)?ex(e)?tx(e)?t==="durable"&&!nx(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function Ls(e){if(!rt(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(r=>!rt(r)||!Object.hasOwn(r,"retained")||!Object.hasOwn(r,"discarded")?r:{base:Y(void 0),ours:Y(void 0),theirs:Y(void 0),...r})}}function gh(e){if(!rt(e))return;if(!ca(e.fields_from_theirs))return"fields_from_theirs";if(!ca(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>da)return"decisions";let t=e.decisions.findIndex(n=>!_h(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function Ms(e,t){return Ns(e,t)===null}function ua(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 js(e,t){let n=$n(t),r=Mt(n?void 0:t);return!n&&(t===null||fh.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 lx=dx(ax),vh=16*1024*1024,ma=100;async function Fs(e){try{let{stdout:t}=await lx("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 bh(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 Us(e){return he.join(e,"merge-receipts")}function On(e){return`${e}.json`}async function yh(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await xr(e.receiptPath,vh)}catch(a){if(Et(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=Ls(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!Ms(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||he.basename(e.receiptPath)!==On(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:Hs(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
61
- `}}function Ir(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)))})):pa(e).decisions}))}function Hs(e){let t=[Ir(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(Ir(e,!0)),t}function ux(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 mx(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 st(he.join(n,"history",`${a.item_id}.jsonl`),a.item_id),Rt(o).ok||(o=[])}catch{o=[]}r.set(a.item_id,o)}let s=a.settlement==="original_git_state_restored",c=C({...pa(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 pa(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:ua(t.retained)??Mt($n(t.retained)?void 0:t.retained),discarded_hash:ua(t.discarded)??Mt($n(t.discarded)?void 0:t.discarded)}))}}async function rF(e){let t=await Fs(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:ox(),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 Gn(t),await Z(he.join(t,On(a.id)),`${JSON.stringify(a,null,2)}
62
- `);let o=await bh(e.cwd,a.item_path);if(o!==null){let s=Us(o),c=a.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:js(u.field,u.retained),discarded:js(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:la};await Gn(s),await Z(he.join(s,On(a.id)),`${JSON.stringify(l,null,2)}
63
- `)}return a}async function wh(e,t){let n;try{n=await sx(e)}catch(s){let c=await px(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>=ma)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},...wt(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 fx(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 px(e,t,n=cx){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 fx(e,t,n){let r;try{r=await xr(he.join(e,t),vh)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=Ls(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let a=Ns(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:gh(i)}:{}};let o=i;if(t!==On(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 vt(e,t={}){let n=await Fs(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await wh(n,"clone_local"),i=t.pmRoot??he.join(e,".agents","pm"),a=await wh(Us(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?Hs(d):[Ir(d)]).includes(Ir(l))){o.delete(d.id),s+=1,r.invalid_evidence.length+a.invalid_evidence.length+c.length<ma&&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:ux(d,l))}return await mx(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,ma),invalid_evidence_truncated:r.invalid_evidence_truncated||a.invalid_evidence_truncated||r.invalid_evidence_count+a.invalid_evidence_count+s>ma,clone_local_evidence_resolved:n!==null}}function Dn(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 iF(e,t,n={}){let r=await Fs(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(!Ms(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=$(),o=he.join(r,On(t.id)),s=await bh(e,t.item_path),c=s===null?null:he.join(Us(s),On(t.id)),d=(await Promise.all([yh({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[yh({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)?[Ir(t)]:Hs(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 aF(e){let t=await vt(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 hx}from"node:crypto";import fa 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 _x="2026-08-09T16:15:18.000Z",Sh=Symbol("pre-durable-disposition-eligible");function bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zs(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 kh(e){return bt(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 Eh(e,t){if(typeof e!="string")return!1;let n=fa.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!fa.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(fa.posix.basename(n)===`${t}.toon`||fa.posix.basename(n)===`${t}.md`)}function gx(e,t){return typeof e.receipt_id=="string"&&wt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&Eh(e.item_path,t)}function xh(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=>kh(o)?[o.field]:[])):new Set;return zs(t)&&zs(n)&&zs(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(kh)&&a.size===i.length&&t.length===a.size&&t.every(o=>a.has(o))}function yx(e,t){return gx(e,t)&&xh(e)}function wx(e,t){return typeof e.receipt_id=="string"&&wt(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&&Eh(e.item_path,t)&&xh(e)}function vx(e){return e[Sh]===!0}function Ah(e,t){if(!bt(e)||!bt(e.context))return[];let n=e.context.merge;return!bt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!bt(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:yx(r,t),[Sh]:wx(r,t),...typeof e.ts=="string"&&un(e.ts)?{eventTimestamp:e.ts}:{}}])}function Ih(e,t,n){if(!bt(e)||e.op!=="merge_reconcile")return[];if(!bt(e.context)||!bt(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!bt(i)||typeof i.receipt_id!="string"||!wt(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"||!un(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 Rh(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=>vx(a)&&a.eventTimestamp!==void 0&&Wt(a.eventTimestamp,_x)<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,...wt(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:hx("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}import{isUtf8 as bx}from"node:buffer";import{readFile as kx}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 Sx(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 Ex(e){if(Me(e))throw new y("Resolve history merge conflicts before salvage.",g.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,r,i=0;for(let[o,s]of e.split(`
64
- `).entries()){if(!s.trim()){n+=s.length+1;continue}let c=Sx(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=Rt(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 xx(e,t,n){if(!e.located)return{itemRaw:null,document:n};let r=await Ol(e.located,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n}}async function Ch(e){let t;try{t=await kx(e)}catch(n){if(F(n))return null;throw n}if(!bx(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 Th(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 Ch(t.historyPath);if(a===null)throw new y(`No history stream exists for ${t.id}.`,g.NOT_FOUND);await He({path:t.historyPath,scope:"project"});let o=Ex(a),s=El(o.entries,o.entries.length-1),c=ol(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 xx(t,n,c),l=Ro({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 Ch(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=ai({...rl({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 Oi({historyPath:t.historyPath,historyRawUnderLock:a,nextHistoryRaw:`${o.prefix}${JSON.stringify(v)}
65
- `}),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 Ph}from"node:fs/promises";import Ws from"node:path";import Nh 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]="289c841a-1355-54a5-a3e3-f59de2abd58c")}catch{}})();function $h(e,t){return t==="body"?e.body:e.metadata[t]}function Gs(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)&&Gs(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)&&Gs(i,n[r]))}function Oh(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 cl(a.patch))o.add(pi(c.path)),c.from&&o.add(pi(c.from));let s=[...n].filter(c=>o.has(c));if(s.length!==0){for(let c of s)n.delete(c);r.push({index:i+1,ts:a.ts,author:a.author,op:a.op,fields:s.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function Ax(e,t,n){let r=Nh.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(pi(p.path));let a=new Set([...i].filter(p=>Gs($h(t,p),$h(n,p)))),o=new Set([...i].filter(p=>!a.has(p))),s=Oh(e,o),c=Oh(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 Ix(e){try{return await Ph(e)}catch{return null}}async function Rx(e){if(await Ix(Ws.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[Mt(o),Ie(C(Y(o)))].includes(n[a])})?{receipt:e.receipt,declaredFields:t}:null}async function Cx(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 Ph(e.itemPath),r=[];for(let o of t){let s=await Rx({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 Dh(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:Ws.relative(a,t.currentItemPath).split(Ws.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 mh(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 Tx(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 vt(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 Cx({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(pa)}}:e.options.auditContext}}function $x(e,t,n){let r=e.located?.itemPath??null,i=t.loadedItem,a=t.entries;if(!i)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let o=sl(i.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:r,matchedChainBefore:pn(o,n,Ce(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:i.raw,loadedItem:i}}function Ox(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 Dx(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=pn(e.finalReplay,e.itemHashVersion,r),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=i.indexOf(a),s=pn(n,e.itemHashVersion,r),c={hash_algorithm:r,ts:$(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Nh.compare(e.finalReplay,e.currentItemReplay):[],before_hash:i[o],after_hash:s[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(ai({...c,event_class:Zd(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function Px(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 qs(e,t,n){let{pmRoot:r,settings:i,typeRegistry:a}=await co(n.path),o=await Ql(r,e,i,a.type_to_folder);return t.salvageTail===!0?Th({pmRoot:r,subject:o,settings:i,typeRegistry:a,options:t,author:G(t.author,i.author_default)}):sm({pmRoot:r,subject:o,settings:i,typeRegistry:a,operation:"history-repair",options:t,transform:s=>Lx({pmRoot:r,subject:o,options:t},s)})}function Nx(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 Lx(e,t){let{pmRoot:n,subject:r,options:i}=e,a=t.entries,o=t.verification,s=Rt(a),c=i.normalizeProvenance?tm(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=dl(c.entries),l=new Set(c.entries.map(A=>A.item_hash_version).filter(A=>A!==void 0)),u=oi(c.entries,d),m=$x(r,t,d);await Dh(i.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=pn(f,d),h=!1;if(m.currentItemReplay!==null){let A=pn(m.currentItemReplay,d);h=!p.some((R,Q)=>R===A[Q])}let _=h&&m.currentItemReplay?Ax(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await Tx({options:i,pmRoot:n,subjectId:r.id,itemReplayContext:m,reconciliation:_}),S=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,Nx(i,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,x=!!i.dryRun,D=Ox({message:i.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:E,auditEntryAdded:b}=Dx({reanchorEntries:u.entries,changed:S,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:f,author:k,message:D,auditOperation:i.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),N=Px(S,u.skippedOps,_);return{changed:S,rewrittenEntries:E,beforeWrite:async()=>Dh(i.mergeAbandonmentProof,m,o.ok,u),report:({verification:A,warnings:R})=>({id:r.id,dry_run:x,changed:S,history:{path:r.historyPath,entries_scanned:a.length,chain_drift_before:!o.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:h,audit_entry_added:b,verify_ok: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 ZF(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 QF(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 co(t.path),a=[],o=await dt(n,r.item_format,i.type_to_folder,a,r.schema,{forceSourceScan:!0}),s=await Jt(n,o),c=e.normalizeProvenance?await nm(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 qs(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 Qd(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]="1c246528-8709-5f7c-a813-6e2894763d3c")}catch{}})();var Mx=new Set(ql),Mh=25,Pn=8,tn=100,jx=Se.join("runtime","telemetry","events.jsonl"),Fx=Se.join("runtime","telemetry","state.json"),Ux=2500,Hx=500,jh=Kl-3,zx=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Xs(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 Zs(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Nn(e){return e.trim().toLowerCase()}function Js(e,t){let n=Nn(e),r=Nn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function Qs(e){try{return(await kt.stat(e)).isDirectory()}catch{return!1}}async function Wx(e){let t=(await kt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>kt.readdir(Se.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>qn.some(a=>i.name.endsWith(a))).map(i=>Se.parse(i.name).name)))}async function Gx(e,t,n,r){let i=await He({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 kt.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 qx(e,t,n){let r=Se.join(e,"history");if(!await Qs(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await kt.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=Se.join(r,l),m=l.slice(0,-6),f=await Gx(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 Ks(e,t){return Se.relative(e,t).replaceAll("\\","/")}async function Fh(e,t){let n=[...new Set(Object.values(t))].sort((i,a)=>i.localeCompare(a)),r=[];for(let i of n){let a=Se.join(e,i),o=[];try{o=await kt.readdir(a)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&F(s))continue;continue}for(let s of o)qn.some(c=>s.toLowerCase().endsWith(c))&&r.push(Se.join(a,s))}return r.sort((i,a)=>Ks(e,i).localeCompare(Ks(e,a))),r}function Bx(e){return!(typeof e=="object"&&e!==null&&"code"in e&&F(e))}async function Vx(e,t,n){let r=await Fh(e,t),i=[],a=[],o=[],s=[],c=rn(H());for(let d of r){let l=Ks(e,d),u;try{u=await kt.readFile(d,"utf8")}catch{i.push(l);continue}let m=Me(u);if(m){a.push({path:l,...m});continue}try{let f=It(u,{format:id(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:ti(f.metadata)})}catch{o.push(l)}}return{paths:r,unreadable:i,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function Jx(e){let t=Se.join(e,"history"),n=[],r=[],i=[],a=[],o=[],s=[];try{s=(await kt.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){Bx(c)&&n.push("history")}for(let c of s){let d=c.slice(0,-6),l;try{l=await kt.readFile(Se.join(t,c),"utf8")}catch{n.push(d);continue}let u=Me(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(...Ah(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Ih(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 Uh(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 Kx(e,t,n,r,i,a){let o=await Vx(e,t,n),s=await Jx(e),c=ni(o.formatVersions),d=ge(n),l=yi(a,A=>Jd(A,d),Yn()),u=await ia(e),m=await et(e),f=await rh(e,m,r,i),p=m===null?null:await xn(m),h=await vt(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),_=new Set(h.receipts.map(A=>A.id)),w=Rh(s.mergeReceiptReferences,_,s.mergeReceiptDispositions),v=w.missing,S=h.receipts.filter(A=>A.state==="pending"),{pendingDecisions:k,lossless:x}=Dn(S),D=p?.status==="missing"&&p.missing_keys.length===5&&p.drifted_keys.length===0,E=[...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}`),...Uh(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}`]:[],...ih({invalidEvidenceCount:h.invalid_evidence_count,missingHistoryReferenceCount:v.length})],b=[...new Set(E)].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:it(l.relations,Pn)},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,tn),missing_merge_receipt_history_reference_details_truncated:v.length>tn}},warnings:b,gitWorkspaceRoot:m,pendingMergeReceipts:S}}function Yx(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function Xx(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:Yx(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Zx(e,t){return ee(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function Qx(e){let t=ee(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function eA(e){return ee(e.reason)??ee(e.error)??ee(e.message)}function Bs(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 tA(e){let t=[],n=[],r=[];e.forEach((a,o)=>{let s=Zx(a.definition,o),c=Qx(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:eA(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(Bs),n.sort(Bs),r.sort(Bs);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 Hh(e,t,n,r,i,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>Zs(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=[],h=_s(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: ${Ur.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 nA(e,t,n){let r=await Ss(Be(e)),i=await Ve({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=i.loaded.map(E=>Xx(E)),o=await Qu(i.loaded,Be(e)),s=await Je({...i,loaded:i.loaded}),[c,d]=await Promise.all([ye(i.roots.project),ye(i.roots.global)]);await ks(e,s.registrations.migrations);let l=tA(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(E=>Nn(E.name))),f=new Set(d.state.entries.map(E=>Nn(E.name))),p=[...new Map(i.loaded.filter(E=>!(E.layer==="project"?m:f).has(Nn(E.name))).map(E=>[`${E.layer}:${E.name}`,{layer:E.layer,name:E.name,directory:E.directory}])).values()].sort((E,b)=>{let N=`${E.layer}:${E.name}`,A=`${b.layer}:${b.name}`;return N.localeCompare(A)}),h=p.map(E=>`${E.layer}:${E.name}`).sort((E,b)=>E.localeCompare(b)),_=p.filter(E=>Js(E.name,E.directory)).map(E=>`${E.layer}:${E.name}`).sort((E,b)=>E.localeCompare(b)),w=p.filter(E=>!Js(E.name,E.directory)).map(E=>`${E.layer}:${E.name}`).sort((E,b)=>E.localeCompare(b)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],S=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...o.warnings],k=vr(S),x=br(),D=Hh(S,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:S.length===0?"ok":"warn",ok:S.length===0,details:{...i,loaded:a,warnings:S,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:S}}function rA(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function it(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function iA(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 ha(e,t){let n=it(e,t);return{...n,sample:n.sample.map(r=>iA(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 aA(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 oA={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:ha(e.discovered,t),effective:ha(e.effective,t),loaded:ha(e.loaded,t),failed:it(e.failed,t),warnings:q(e.warnings,t),activation:{failed:it(n.failed,t),warnings:q(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:aA(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:it(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:q(n.affected_item_ids,t),samples:it(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:q(e.item_unreadable,t),item_conflict_markers:it(e.item_conflict_markers,t),item_parse_failures:q(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:q(n.tracked_paths,t)},history_unreadable:q(e.history_unreadable,t),history_conflict_markers:it(e.history_conflict_markers,t),history_invalid_json:it(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:q(n.candidate_items,t),confirmed_items:q(n.confirmed_items,t),resolved_false_positive_items:q(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:q(e.drifted_items,t),merge_receipt_attributed_items:q(e.merge_receipt_attributed_items,t),missing_streams:q(e.missing_streams,t),unreadable_streams:q(e.unreadable_streams,t),hash_mismatches:q(e.hash_mismatches,t),chain_mismatches:q(e.chain_mismatches,t),version_skews:q(e.version_skews,t),workspace_state_mismatches:q(e.workspace_state_mismatches,t),workspace_state_missing:q(e.workspace_state_missing,t),workspace_state_unreadable:q(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:q(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:q(e.stale_items_after,t),skipped:e.skipped})};function zh(e,t){let n=oA[e.name];return n?n(e.details,t):e.details}function sA(e){let t=q(e.warnings,Pn);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:zh(n,Pn)})),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:Pn},generated_at:e.generated_at}}function Lh(e){return e.details.skipped===!0}function cA(e){let t=q(e.warnings,Pn),n=e.checks.filter(Lh).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!Lh(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:Pn,omitted_checks:n},generated_at:e.generated_at}}function Ys(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=rA(e,Mh);return{values:n.values,truncated:n.truncated,total:e.length}}function _a(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function dA(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return Mx.has(e)?e:null}function ga(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 Wh(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e.split(`
66
- `)){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>=jh&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:a}}function lA(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function uA(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 mA(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||so().telemetry_disabled?void 0:{attempted:!0,...await Gh(n)}}function pA(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>=Hx;return(o||s||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function fA(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function hA(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Jl?[`telemetry_schema_version_behind:${t}`]:[]}function _A(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 gA(){return{...so(),pm_no_telemetry:_a("PM_NO_TELEMETRY"),telemetry_otel_disabled:_a("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:_a("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:dA()}}function yA(e,t){return e.telemetry.enabled&&t.validEntries>0}function wA(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Gh(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(Ux)});return{probe_url:ga(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:ga(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function vA(e,t){let n=Wr(process.cwd()),r=Se.join(n,jx),i=Se.join(n,Fx),a=await V(r),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?Wh(a):lA(),d=await V(i),{runtimeState:l,stateParseFailed:u}=uA(d),m=e.telemetry.endpoint.trim(),f=ga(m),p=await mA(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...pA(e,c,l),...fA(p),...hA(p),..._A(e,l));let _=yA(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:wA(_,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:jh,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:gA()}},warnings:h}}async function bA(e){let t;try{t=await Im(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 kA(e){let t="metadata",n=e.items,r=await Jt(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 dt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Jt(e.pmRoot,n),a=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,S)=>v.localeCompare(S));let w=new Set(a);o=i.filter(v=>!w.has(v))}let{missingStreams:s,unreadableStreams:c,hashMismatches: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 SA(e,t){let n=fi(e),r=Kn(n.settings),i=gi(n.settings,t),a=r.active?qt(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(r.active&&i.active)}}function EA(){return{refreshed:[],skipped:[],warnings:[]}}async function xA(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?EA():Gl(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function AA(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&hn(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function IA(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 RA(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function qh(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:io(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:io(r,e.vector_store?.adapter??null)}}function CA(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function TA(e,t,n){return e.enabled&&n.length>0&&t}async function $A(e,t,n,r,i){let a=SA(t,e),o=await _n(e),s=a.semanticRuntimeAvailable?lo(n,o.entries):[],c=await xA({pmRoot:e,snapshot:a,refreshPolicy:r,staleBefore:s}),d=await _n(e),l=a.semanticRuntimeAvailable?lo(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=AA({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=IA({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=Ys(s,i),h=Ys(l,i),_=TA(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:CA(r),...qh(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:Mh,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:RA(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 OA(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 Bh(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 DA=new Set(["extensions","locks","search"]);function PA(e){let t=new Set(Vc.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(Jc));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of DA)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 NA(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:a}=PA(t),o=[],s=[],c=[];for(let d of[...r,...i]){let l=Se.join(e,d);c.push(...await He({path:l,scope:"project"})),!await Qs(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 Vh(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 LA(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?ct(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):dt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Vs(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function MA(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 FA(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 ec=e=>e.unknown_event_count??0,tc=e=>e.actionable_unknown_event_count??ec(e);function UA(e,t,n,r,i,a){let o=ec(r),s=tc(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 Jh(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function HA(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 WA(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 Kh(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=Do(r)?.code??Zs(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=Xs(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 GA(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 qA(e){for(let t of e.checks){let n=Po(e.remediationSources[t.name]);GA({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function BA(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 qs(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 VA(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 Yh(e,t,n){let r=e.warning_count??e.warnings.length,i={...e,warning_count:r,warning_limit:tn,warnings_truncated:r>tn,warnings:e.warnings.slice(0,tn),findings:(e.findings??[]).filter(o=>e.warnings.slice(0,tn).includes(o.warning)||e.failed_because.includes(o.warning))},a=n?cA(i):t.brief===!0?sA(i):i;return{...a,warning_count:r,warning_limit:tn,warnings_truncated:r>a.warnings.length,...a.projection?{projection:{...a.projection,warning_count:r,warnings_truncated:r>a.warnings.length}}:{}}}async function Xh(e,t={}){let n=L(process.cwd(),e.path);await ne(n);let r=Ut(n),{settings:i,warnings:a}=await ml(n),o=[...new Set(a)],s=W(i,H()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=Bh(t),m=await NA(n,s,c),f=OA(i),p=await vA(i,{checkTelemetry:t.checkTelemetry===!0}),h=await nA(n,i,!!e.noExtensions),_=Vh(t),w=[],v=await LA({pmRoot:n,settings:i,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),S=v,k=Di(ge(i.schema),v),x=[...(await _m({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,...Pi(k)],D=_.skipDrift?{warnings:[]}:await bl({pmRoot:n,settings:i,itemIds:v.map(pe=>pe.id),commandLabel:"health"}),E=await qx(n,i.history.compact_policy,await Wx(n)),b=await rr(n,20,t.verboseAuthorEvents===!0),N=tc(b),A=N>0?[`history_unknown_author_events:${N}`]:[],R=Jh(await Bl(n,v,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),Q=await am(n),Ae=Q.warnings,we=await bA(n),_e=_.skipIntegrity&&!l?{...Vs("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await Kx(n,s.type_to_folder,i.schema,i,l,v),Ue=_.skipDrift?Vs("history_drift"):await kA({pmRoot:n,items:S,settings:i,typeRegistry:s,itemReadWarnings:w}),Mr=[...new Set(w)],Wn=await BA({gitWorkspaceRoot:_e.gitWorkspaceRoot,pendingMergeReceipts:_e.pendingMergeReceipts,historyDriftCheck:Ue,global:e});VA(Ue,Wn);let z=_.skipVectors?Vs("vectorization"):await $A(n,i,S,u,t.verboseStaleItems===!0),B=[MA(r,i,o),jA(m,c),FA(x,k),p.check,h.check,UA(v,i,E,b,R.scan,Q),we.check,_e.check,Ue.check,z.check],jr=HA({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:Mr,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:D.warnings,historySummary:E,authorAttributionWarnings:A,staleInProgressWarnings:R.warnings,provenanceWarnings:Ae,locksCheck:we,integrityCheck:_e,historyDriftCheck:Ue,vectorizationCheck:z}),Fr=WA({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:Mr,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:D.warnings,historySummary:E,authorAttributionWarnings:A,staleInProgressWarnings:R.warnings,provenanceWarnings:Ae,locksCheck:we,integrityCheck:_e,historyDriftCheck:Ue,vectorizationCheck:z});qA({checks:B,remediationSources:Fr,historyDriftedCount:zA(Ue),overThresholdCount:E.over_threshold.length});let La=jr.filter(pe=>!Xs(pe,l)),Ma=Kh({warnings:jr,checks:B,remediationSources:Fr,requireMergeDrivers:l}),Bg=new Set(Ma.filter(pe=>pe.severity==="gate_failing").map(pe=>pe.check)),Vg=new Set(Ma.map(pe=>pe.check));for(let pe of B)pe.ok=!Bg.has(pe.name),Vg.has(pe.name)&&(pe.status="warn");let Jg={ok:La.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&La.length>0?g.GENERIC_FAILURE:0},checks:B,warnings:jr,findings:Ma,failed_because:La,generated_at:$()};return Yh(Jg,t,_.summaryMode)}var XU={buildHierarchyIntegrityWarnings:Uh,buildExtensionHealthTriageSummary:Hh,buildHealthFindings:Kh,buildCapabilityContractMetadata:br,buildStaleInProgressHealthSummary:Jh,buildVectorizationProviderDetails:qh,collectUnknownCapabilityGuidance:vr,isAdvisoryHealthWarning:Xs,isDirectory:Qs,isExpectedUnmanagedExtension:Js,listItemDocumentPaths:Fh,normalizeEndpointForDisplay:ga,normalizeExtensionNameForMatch:Nn,parseTelemetryQueue:Wh,probeTelemetryEndpointHealth:Gh,projectHealthResult:Yh,resolveActionableUnknownAuthorEventCount:tc,resolveHealthSkipPolicy:Vh,resolveUnknownAuthorEventCount:ec,resolveVectorRefreshPolicy:Bh,selectStaleItemDetail:Ys,summarizeHealthCheckDetails:zh,summarizeExtensionList:ha,summarizeRecordList:it,summarizeStringList:q,telemetryEnvFlagEnabled:_a,warningCode:Zs};(function(){try{var e=typeof window<"u"?window:typeof 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 Zh(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!eu(e,t).ok)return{reason:"unverified_history"};let r=al(),i={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(r.metadata.status));r=Sl(r,o.patch,a+1,o.op),n.has(String(r.metadata.status))?s||(i=["create","close","cancel","update","update_audit"].includes(o.op)&&At(o.ts)?{timestamp:o.ts,source_index:a+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function Qh(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function e_(e,t,n,r,i){let a=Qh(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 st(Ht(e,d.id),d.id),{body:m,...f}=d;l=Zh(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 t_(e,t){let n=L(process.cwd(),t.path),r=await T(n),i=ge(r.schema);await lt({pmRoot:n,settings:r,id:e.item_id,op:"update",author:G(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(a){if(a.metadata.closed_at)return{changedFields:[]};let o=await st(Ht(n,a.metadata.id),a.metadata.id),s=Qh(i),c=Zh(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 JA(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function n_(e){return`${e.item_id} ${e.link_kind}`}function r_(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=JA(i.classification,r.classification),i.owners.set(n_(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[n_(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 i_(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=r_(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=ri(f.status,r)??f.status;r.terminal_statuses.has(p)?(u.push(f),p===r.close_status&&(s.legacy_closed_missing_linked_links_count+=1)):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 Ln from"node:fs/promises";import Mn 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 KA(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let a;try{a=await Ln.readdir(Mn.join(e,i))}catch{return}for(let o of a)for(let s of qn)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 YA(e,t){let{id:n,relativePath:r,liveItemIds:i,out:a}=e,o=Me(t);if(o){a.conflictMarkers.push({id:n,path:r,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=XA(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 XA(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 nc(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 ZA(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Ln.readdir(Mn.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 Ln.readFile(Mn.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:nc("history stream",o)});continue}YA({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},a)}return n}function a_(e){let t=Me(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function QA(e){let t=[],n=0,r=null;try{r=await V(Ut(e))}catch(a){n+=1,t.push({path:"settings.json",detail:nc("configuration file",a)})}if(r!==null){n+=1;let a=a_(r);a!==null&&t.push({path:"settings.json",detail:a})}let i;try{i=await Ln.readdir(Mn.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 Ln.readFile(Mn.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:nc("configuration file",c)});continue}let s=a_(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function o_(e,t,n,r={}){let i=await KA(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=Mn.join(e,u.relativePath);return It(await Ln.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 ZA(e,a),l=await QA(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 Rc from"node:fs/promises";import{realpathSync as mR}from"node:fs";import{execFile as pR}from"node:child_process";import xe 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]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();var eI=["metadata","resolution"],rc=["metadata","resolution","estimates","timestamps","lifecycle"],tI="completed";function ic(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function s_(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function c_(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=s_(n.close_reason)??tI;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${ic(r)}`,gate:"resolution"})}return t}function d_(e){let t=[];for(let n of e){let r=s_(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 ${ic(r)}`,gate:"metadata"})}return t}function l_(e,t){return e.map(n=>{let r=ul(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 u_(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 m_(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 ${ic(n.path)}`})}return t}function p_(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: ${rc.join(", ")}.`,g.USAGE);return new Set(eI)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(rc.includes(i)){n.add(i);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${rc.join(", ")}.`,g.USAGE)}return n}function f_(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function Rr(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();var nI=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function rI(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=nI.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 h_(e){return typeof e=="string"&&e.trim().length>0}function iI(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 __(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||h_(i.duplicate_of))continue;let a=rI(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:h_(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=iI(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 g_(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 y_(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function w_(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=y_(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(y_(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 v_(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 aI=/^[a-z][a-z0-9+.-]+:\/\//i;function Cr(e){return aI.test(e.trim())}import oI from"node:fs/promises";import Ee from"node:path";import{glob as sI}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 cI=["path","scope","note"],dI=["pattern","glob","path","scope","note"],lI=["path"],uI=["from","to"],mI=new Set(["note","scope"]);function k_(e){let t=e??"project";if(!ja.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${ja.join(", ")} (default: project).`,g.USAGE);return t}function ac(e){if(e.startsWith("```")||e.includes(`
67
- `)||/^(?:[-*+]\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("=")||_l(e)}function pI(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function fI(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!ac(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&&pI(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 hI(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let a=fI(r);if(a!==void 0)return[a]}gl(r,"--add",`${t} path`,ac(r));let i=ac(r)?Vn(n,"--add"):{path:r};if(Jn(i,"--add",cI),!i.path)throw new y(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return[{path:i.path,scope:k_(i.scope),note:i.note?.trim()||void 0}]}):[]}function _I(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=Vn(n,"--add-glob");Jn(r,"--add-glob",dI);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:k_(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function gI(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=Vn(n,"--remove"),i=Object.keys(r).filter(a=>mI.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(Jn(r,"--remove",lI),!r.path)throw new y("--remove key/value form requires path=<value>",g.USAGE);return r.path}return n}):[]}function yI(e){return e?e.map(t=>{let n=Vn(t,"--migrate");Jn(n,"--migrate",uI);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new y("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:r,to:i}}):[]}function Tr(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function wI(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(a=>Tr(a.path,n))),i=[...new Set(t.map(a=>Tr(a,n)).filter(a=>r.has(a)))].sort((a,o)=>a.localeCompare(o));if(i.length!==0)throw new y(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,g.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function St(e){return e.split(Ee.sep).join("/")}function oc(e,t,n=process.cwd()){let r=e.trim();if(Cr(r))return r;if(Ee.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return St(r.replaceAll("\\",Ee.sep));let i=Ee.relative(t,n);return i.startsWith(`..${Ee.sep}`)||i===".."||Ee.isAbsolute(i)?St(Ee.normalize(r)):St(Ee.relative(t,Ee.resolve(n,r)))}async function vI(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){if(Ee.resolve(n,i.pattern)===Ee.resolve(n))continue;let a=Ee.isAbsolute(i.pattern),o=await sI(i.pattern,{cwd:n,absolute:a,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),s=[...new Set(o.map(c=>oc(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 bI(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 kI(e){return`${e.path}::${e.scope}`}function sc(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function cc(e){return[...new Map(e.map(t=>[kI(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function SI(e,t=process.cwd()){let n=[...new Set(e)].sort((s,c)=>s.localeCompare(c)),r=[],i=[],a=[],o=[];for(let s of n){if(Cr(s)){o.push(s.trim());continue}let c=Ee.isAbsolute(s)?s:Ee.resolve(t,s);try{(await oI.stat(c)).isFile()?r.push(s):a.push(s)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&Et(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 EI(e,t,n,r){let i=0;for(let a=0;a<e.length;a+=1){let o=Tr(e[a].path,r);o!==e[a].path&&(e[a]={...e[a],path:o},i+=1)}return{adds:t.map(a=>{let o=Tr(a.path,r);return o!==a.path&&(i+=1),{...a,path:o}}),removes:n.map(a=>Tr(a,r)),count:i}}function xI(e,t,n,r){let i=cc(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:sc(i)}async function b_(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 SI(t,e.workspaceRoot):void 0}}async function ya(e,t,n,r){let{metadataKey:i}=r,a=vl(),o=L(process.cwd(),n.path),s=Be(o),c=process.cwd();await ne(o);let d=await T(o),l=W(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=hI(u,r.bareNoun).map(A=>({...A,path:oc(A.path,s,c)})),_=_I(m),w=await vI(_,s,c),v=bI([...h,...w],t.note,h.length>0||_.length>0),S=gI(f).map(A=>oc(A,s,c)),k=yI(p);if(wI(v,S,k),!(v.length>0||S.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 b_({id:A.id,artifacts:R,changed:!1,options:t,workspaceRoot:s})}let x=G(t.author,d.author_default),D=await lt({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=EI(Ae,v,S,k),_e=xI(Ae,we.adds,we.removes,r.supportsAppendStable&&t.appendStable===!0);_e.length>0?R[i]=_e:delete R[i];let Ue=!dd(Q,_e);return{changedFields:Ue?[i]:[],warnings:Ue&&we.count>0?[`path_migrations_applied:${we.count}`]:[]}}}),E=D.item[i]??[],b=D.warnings.find(A=>A.startsWith("path_migrations_applied:")),N=b?Number(b.slice(24)):0;return b_({id:D.item.id,artifacts:E,changed:D.changedFields.includes(i),migrationsApplied:N,options:t,workspaceRoot:s})}function wa(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 S_(e,t,n){let r=await ya(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return wa(r,"docs")}import E_ from"node:fs/promises";import Fe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="06b0bd73-d282-5473-a1da-f11c61a0a086")}catch{}})();var AI=32768;function dc(e){return St(Fe.normalize(e))}async function va(e){try{return await E_.realpath(e)}catch{return Fe.resolve(e)}}function jn(e,t){let n=Fe.isAbsolute(e.path)?Fe.resolve(e.path):Fe.resolve(t,e.path);return`${dc(n)}::${e.scope}`}function ba(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)=>ba(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))ba(i,t?`${t}.${r}`:r,n)}function II(e){let t=[];return ba(e.metadata,"metadata",t),ba(e.body,"body",t),t}function RI(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 CI(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,AI);for(let[s,c]of[[n,i.value],[r,o]]){s.lastIndex=0;for(let d of c.matchAll(s)){let l=RI(d[0]);!l||a.has(l)||(a.add(l),t.push({field:i.field,value:l}))}}}return t}async function TI(e,t,n=t){let r=Fe.isAbsolute(e)?Fe.resolve(e):Fe.resolve(n,e),i;try{i=await E_.stat(r)}catch{return}if(!i.isFile())return;let[a,o]=await Promise.all([va(t),va(r)]);if(fe(a,o)){let s=Fe.relative(a,o);return!s||s.startsWith("..")||Fe.isAbsolute(s)?void 0:{path:dc(s),scope:"project"}}return{path:dc(r),scope:"global"}}async function $I(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>jn(c,t))),i=new Map,a=CI(II(e)),o=new Map;await Promise.all([...new Set(a.map(c=>c.value))].map(async c=>{o.set(c,await TI(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=jn(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 x_(e,t,n){let r=await ya(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return wa(r,"files")}async function OI(e,t){let n=await va(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(!Fe.isAbsolute(o))return St(o);let s=await va(o);return fe(n,s)?St(Fe.relative(n,s)):St(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 DI(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 A_(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function I_(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 PI(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(St(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(I_)}async function NI(e){if(e.explain)return Gu({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 LI(e){if([e.strictRead,e.noTruncate,e.explain,Md()].includes(!0))return null;let t=await hi(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Tl({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function MI(e){let t=[],n=await _i(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=PI({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 NI({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:I_(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:A_(s.item),files:s.files,...a?{traceability:a.explanations.get(s.item.id)}:{}})),...a?{traceability_receipt:a.receipt}:{}}}async function uz(e,t){let n=L(process.cwd(),t.path),r=Be(n);await ne(n);let i=await OI(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=W(a,H()),{offset:s,limit:c}=DI(e),d=await LI({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:A_(l.item),files:l.files}))}:MI({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 mz(e,t,n){let r=L(process.cwd(),n.path),i=Be(r);await ne(r);let a=await T(r),o=W(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 $I(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=G(t.author,a.author_default),h=l.map(b=>({path:b.path,scope:b.scope,note:f})),_=[],w=new Set,v=await lt({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=>jn(Ae,i)));_=[],w.clear();for(let[Ae,we]of h.entries()){let _e=jn(we,i);A.has(_e)||(N.push(we),A.add(_e),_.push(we),w.add(Ae))}let R=cc(N),Q=t.appendStable?R:sc(R);return Q.length>0?b.metadata.files=Q:delete b.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==h.length?[`files_discover_skipped_existing:${h.length-_.length}`]:[]}}}),S=v.item.files??[],k=new Set(_.map(b=>jn(b,i))),x=S.filter(b=>k.has(jn(b,i))),D=l.filter((b,N)=>!w.has(N)),E=[...u,...D];return{id:v.item.id,files:S,changed:x.length>0,apply:!0,count:S.length,candidate_count:d.length,addable_count:l.length,added_count:x.length,skipped_existing_count:E.length,candidates:d,added:x,skipped_existing:E}}import{readFileSync as jI}from"node:fs";import ka 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 FI=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),lc=new Set(["--pm-path","--path","--author"]),UI={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"])},HI=new Set(["-p","--package"]),zI=new Set(["-c","--call"]),WI=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),GI=new Set(["-C","--prefix","--userconfig","--cache"]),_z=new Set(["--cwd"]),gz=new Set(["--cwd"]),qI=new Set(["exec","x"]),yz=new Set(["run","run-script"]),wz=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function BI(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function VI(e,t=process.cwd()){let n=JI(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[r,...i]=n;if(R_(r)||C_(r,t))return i;if(r==="node"&&i[0]&&C_(i[0],t))return i.slice(1);let a=r==="npx"||r==="bunx"?uc(i):r==="pnpm"?XI(i):r==="npm"?ZI(i):null;return a&&(R_(a.command)||YI(a.command))?a.args:null}var T_=(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 BI(a)){let c=VI(s),d=c?QI(c):null,l=d&&FI.has(d.subcommand)?eR(d.remaining,UI[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 JI(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 vz(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(lc.has(n)){t+=2;continue}t+=1;continue}return n}}function R_(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function KI(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 YI(e){let t=KI(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function C_(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=ka.resolve(t,e);try{return JSON.parse(jI(ka.join(ka.dirname(ka.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function uc(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+=HI.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function $_(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 XI(e){let t=$_(e,WI);return t?.subcommand!=="dlx"?null:uc(t.args)}function ZI(e){let t=$_(e,GI);return!t||!qI.has(t.subcommand)?null:uc(t.args)}function QI(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(lc.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function eR(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("=")&&(lc.has(r)||t.has(r))&&(n+=1)}}import{execFile as tR}from"node:child_process";import{readFile as nR}from"node:fs/promises";import D_ from"node:path";import{promisify as rR}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="574bbc1f-493b-5c51-9c93-97234779a3ce")}catch{}})();var iR=rR(tR),mc=1,aR="linked-test-trust.json";function pc(e){return D_.join(ad(e),aR)}function O_(){return{version:mc,acknowledged:{}}}async function fc(e){try{let t=JSON.parse(await nR(pc(e),"utf8"));return t.version!==mc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?O_():{version:mc,acknowledged:t.acknowledged}}catch{return O_()}}async function hc(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 iR("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 _c(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function oR(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Ud(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function $r(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function sR(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function Tz(e,t,n){if(!e||e.length===0)return e;let r=_c();return sR(e,t,n,await hc(r))}function P_(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 $z(e,t,n){let r=await fc(e);return N_(t,n,r)}function N_(e,t,n){let r=P_(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||!oR(e.provenance)?a?{fingerprint:r,trusted:!0,reason:"acknowledged",...$r(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...$r(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...$r(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:a?{fingerprint:r,trusted:!0,reason:"acknowledged",...$r(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...$r(i,t)}}async function L_(e,t,n){let r=await fc(e);return t.map(i=>N_(i,n,r))}async function Oz(e,t,n){let r=await fc(e),i=t.filter(a=>typeof a.command=="string"&&a.command.length>0).map(P_);for(let a of i)r.acknowledged[a]={acknowledged_at:n};return await Gn(D_.dirname(pc(e))),await Z(pc(e),`${JSON.stringify(r,null,2)}
68
- `),{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 Sa(e){return e.includeBody?dt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):_i(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 cR=5;async function dR(e,t){let n=t.hashMismatches.filter(a=>a!==ce);if(n.length===0)return;let r=await T(e),i=W(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 xm(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 Ea(e,t,n){let r=await Jt(e,t);await dR(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:cR,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 xa(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 lR(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function uR(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 gc(e,t=Yn()){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=lR(i.parent,n);o&&a.push(o),uR(i,r,n,t)}for(let[i,a]of r)r.set(i,[...new Set(a)].sort());return r}function yc(e,t,n=Yn()){let r=yi(e,o=>t?Ed(o,t):o==="closed"||o==="canceled",n),i=gc(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=>xa(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 jt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function wc(e){return jt(e).replace(/\/+$/,"")}function Ge(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 vc(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9b5e620c-ce82-5e2d-9866-2de6882bbb0c")}catch{}})();var hR=["src","tests","docs"],_R=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],gR=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),yR=["resolution","expected_result","actual_result"],wR=["default","tracked-all","tracked-all-strict"],M_=["core","strict","custom"],Ra=["off","warn","error"],Sc=["author","acceptance_criteria","estimated_minutes","close_reason"],U_=[...Sc,"reviewer","risk","confidence","sprint","release"],Ec=Array.from(new Set(U_)),vR={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"},bR={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"},kR={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"},SR={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"},ER={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"},xR=32*1024*1024,AR=1e4,xc=40,qe=5,IR=4096,RR=255,CR=fR(pR);function H_(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?H_(r):r);return t}function TR(e){return{...e,checks:e.checks.map(t=>({...t,details:H_(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 Ta(e,t){return ri(e,t)??e}function Or(e,t){return t.terminal_statuses.has(Ta(e,t))}function Ft(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Aa(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function $R(e){let t=Ft(Kc),n={blocked_reason:Ft(zr.blocked_reason),resolution:Ft(zr.resolution),actual_result:Ft(zr.actual_result)},r=Ft(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:Ft(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Ft(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Ft(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Aa(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Aa(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Aa(i.resolution,n.resolution)?"default":"settings",actual_result:Aa(i.actual_result,n.actual_result)?"default":"settings"}}}function z_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(M_.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${M_.join(", ")}.`,g.USAGE)}function W_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ra.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Ra.join(", ")}.`,g.USAGE)}function G_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ra.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Ra.join(", ")}.`,g.USAGE)}function OR(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>vR[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function DR(e,t,n){let r=OR(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Sc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...U_],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:[...Sc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var PR=new Set(["acceptance_criteria","estimated_minutes"]);function q_(e,t,n,r){return!r&&PR.has(t)&&Or(e.status,n)?!1:t==="author"?!ee(e.author):t==="acceptance_criteria"?!ee(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ta(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 B_(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: ${wR.join(", ")}.`,g.USAGE)}function V_(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 mR.native(e)}catch{return xe.resolve(e)}}function NR(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Cc(e,t,n){let r=t.length>0?xe.join(e,t):e,i;try{i=await Rc.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(gR.has(a.name))continue;await Cc(e,o,n);continue}a.isFile()&&n.push(jt(o))}}async function Ac(e){let t=[];for(let n of hR)await Cc(e,n,t);for(let n of _R){let r=xe.join(e,n);try{(await Rc.stat(r)).isFile()&&t.push(jt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function J_(e){try{let{stdout:t}=await CR("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:xR,windowsHide:!0,timeout:AR}),n=t.split("\0").map(r=>jt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function LR(e,t){let n=new Set,r=wc(Bc);r.length>0&&n.add(r);let i=wc(xe.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((a,o)=>a.localeCompare(o))}function F_(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function MR(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await J_(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Ac(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Ac(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ae(e,t=qe){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function nn(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ae(e,xc);return{values:n.values,truncated:n.truncated,total:e.length}}var jR={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},FR={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function UR(e){let t=e.missing_fields.map(n=>`${jR[n]} "${FR[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function K_(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"):Cm(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 Y_(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 HR="validate_metadata_duplicate_issue_codes";function X_(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:qe,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:[`${HR}:${e.length}`]}}function zR(e,t,n){let r=Object.fromEntries(Ec.map(i=>[i,[]]));for(let i of e)for(let a of Ec)q_(i,a,t,n)&&r[a].push(i.id);return r}function WR(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let a=t[i];a.length>0&&r.push(`${bR[i]}:${a.length}`)}return r.push(...n),r}function Z_(e,t){let n={};for(let r of e.required_fields){let i=t[r],a=i?i.length:0,o=kR[r];n[o]=a}return n}function Q_(e,t,n){let r=[];for(let i of e.required_fields){let a=t[i];if(a)for(let o of a){let s=n.get(o)?.type,c=typeof s=="string"&&s.length>0?s:"Unknown";r.push({item_type:c,field:i})}}return r}function GR(e,t,n,r){for(let i of t.required_fields){let a=n[i];if(!a||a.length===0)continue;let o=SR[i],s=ER[i];if(!o||!s)continue;let c=ae(a,r?a.length:qe);e[o]=c.values,e[s]=c.truncated}}function eg(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 tg(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 qR(e,t,n,r,i){let a=new Map(e.map(w=>[w.id,w])),o=t.profile==="strict",s=zR(e,n,o),c=__(e,{configuredPrefixes:i}),d=X_(c,r),l=WR(t,s,d.warnings),u=Z_(t,s),m=Q_(t,s,a),f=g_(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:[...Ec],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]),GR(p,t,s,r);let h=eg(t,s,a),_=tg(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 BR(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Ta(m.status,t))),a=[],o=[];for(let m of i){let f=yR.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:qe,d=ae(a.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=a.map(m=>UR(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 ng(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rg(e,t="pm",n=Zc()){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=Ge(a.blocked_by);s&&r.has(s)&&o.add(s),(a.dependencies??[]).filter(d=>{let l=Ge(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ge(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>o.add(d));let c=Ge(a.definition_of_ready);return ag(c??"",t).filter(d=>r.has(d)).forEach(d=>o.add(d)),[a.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function ig(e,t,n){let r=Yl(e,n?l=>Or(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:qe,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 ag(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${ng(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 og(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 sg(e,t="pm"){let n=rg(e,t),r=og(n),i=[...new Set(r.flat())].sort((o,s)=>o.localeCompare(s)),a=r.map(o=>xa(o,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:a}}function cg(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 Ca(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function dg(e,t){let n=Ca(e).split("/").filter(Boolean),r=Ca(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function VR(e,t){let n=Ca(t),r=Ca(e),i=t.endsWith("/")?t:`${t}/`,a=e.startsWith(i),o=n.length>0&&n===r,s=dg(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 JR(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function KR(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=jt(o.path);if(s.length===0||s===e)return;let c=VR(e,s);c!==null&&JR(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 lg(e,t){return e.map(n=>{let r=cg(n),i=r==="docs_unowned"?"docs":"files",a=KR(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 ug(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function YR(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Ge(e[n]);return i?r.some(a=>i.toLowerCase().includes(a)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function XR(e,t,n,r,i){let a=Ge(t.parent),o=a?n.get(r.get(a.toLowerCase())??a):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!Or(o.status,i)}}function ZR(e,t,n,r){let i=Ge(e.blocked_by),a=Ge(e.blocked_reason),o=a?.toLowerCase(),s=Ta(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 QR(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),a=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),s={activeItems:e.filter(c=>!Or(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of s.activeItems){let d=YR(c,r);d.length>0&&s.closureLikeRows.push({id:c.id,fields:d});let l=Ge(c.parent),u=l?i.get(a.get(l.toLowerCase())??l):void 0;if(u&&Or(u.status,n)&&(s.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),s.terminalParentFixRows.push(XR(c,u,i,a,n))),t){let m=ZR(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 eC(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 Ia(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function bc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function tC(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=Ia("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),s=Ia("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=Ia("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=Ia("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=bc("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=bc("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=bc("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 mg(e){let t=jt(e);return t.length>IR||t.split(/[\\/]/).some(n=>n.length>RR)}async function nC(e,t){let n=xe.isAbsolute(t)?t:xe.resolve(e,t);if(mg(n))return!1;try{let r=await Rc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return NR(r,["ENOENT","ENOTDIR"])}}async function rC(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(a=>({item:i,artifact:a,link_kind:"files"})),...(i.docs??[]).map(a=>({item:i,artifact:a,link_kind:"docs"}))]);for(let{item:i,artifact:a,link_kind:o}of r){if(a.scope!=="project")continue;if(Cr(a.path)){n.remoteLinkedPaths.add(a.path.trim());continue}let s=jt(a.path);s.length!==0&&(n.linkedProjectPaths.add(s),await nC(t,a.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:i.id,path:s,link_kind:o})))}return n}function iC(e,t,n,r,i,a){let o=r==="tracked-all-strict",s=o&&!i,c=i||o,d=c?[]:LR(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>F_(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!F_(f,d)),m={};if(l.length>0){let f=nn(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 pg(e,t,n,r,i,a,o,s="pm"){let c=QR(e,t,i,a);eC(c);let d=sg(c.activeItems,s),l=yc(e,i),u=Di(i,e,o?Number.POSITIVE_INFINITY:qe),m=[...tC(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}),...Pi(u)],f=o?Number.POSITIVE_INFINITY:qe,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),S=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),E=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:E?"error":m.length===0?"ok":"warn",ok:!E&&m.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:p.values,active_closure_like_metadata_rows_truncated:p.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:_.values,stale_blocker_rows_truncated:_.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count: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:S.values,parent_cycle_item_ids_truncated:S.truncated,parent_cycle_sample_paths:k.values,parent_cycle_sample_paths_truncated:k.truncated,hierarchy_cardinality_violation_count: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 fg(e,t,n,r,i,a,o=ge(Yc.schema)){let s=await rC(e,t),c=new Map(e.map(R=>[R.id,R])),d=[...new Set(s.missingLinkedPaths)].sort((R,Q)=>R.localeCompare(Q)),l=await MR(t,r),u=iC(l,n,t,r,i,a),m=u.candidateFiles.filter(R=>!s.linkedProjectPaths.has(R)),f=lg(m,e),p=w_(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 S=[...s.remoteLinkedPaths].sort((R,Q)=>R.localeCompare(Q)),k=nn(S,a),x=nn(d,a),D=nn(m,a),E=nn(f.map(R=>`${R.path}:${R.classification}:owner_candidate=${R.owner_candidate?.id??"unowned"}`),a),b=a?f:nn(ug(f),!1).values,N=nn(v_(p),a),A=i_(w,p,R=>c.get(R),o,a?1/0:xc);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:xc,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:S.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:E.values,orphaned_path_classifications_truncated:E.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:b}},warnings:v,staleLinkPruneRows:w}}function aC(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},a)=>{let o=t[a];if(o.trusted)return;let s=vc(i.command??"");n.push(`${r.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${s}`)}),n}async function hg(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 hc(_c()),u=await L_(r,d.map(({linkedTest:x})=>x),l),m=aC(d,u);for(let{item:x,linkedTest:D}of d){if(typeof D.command!="string"||D.command.trim().length===0)continue;a+=1;let E=T_(D.command,t);if(E.length!==0){o+=E.length;for(let b of E)s.add(b),i.has(b.toLowerCase())||c.push(`${x.id}:${b}:${vc(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:qe,w=ae(f,_),v=ae(p,_),S=ae([...s].sort((x,D)=>x.localeCompare(D)),_),k=ae(m,_);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:a,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:S.values,unique_referenced_pm_ids_truncated:S.truncated,linked_test_trust_current_source_ref: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 oC(e,t){let n=ni(e.map(c=>({ref:c.id,version:ti(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:qe,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:Vd,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 Ic="pm validate auto-fix";async function _g(e,t,n){switch(e.kind){case"set_closed_at":await t_(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Ic};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 kc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function gg(e,t,n){let r=[],i=[],a=new Map;for(let o of e.filter(s=>kc(s)===null))try{await _g(o,t,n),r.push(o)}catch(s){i.push({fix:o,error:s})}for(let o of e.filter(s=>kc(s)!==null)){let s=kc(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 x_(s.item_id,{remove:c,message:Ic},t):await S_(s.item_id,{remove:c,message:Ic},t),r.push(...o)}catch(d){i.push(...o.map(l=>({fix:l,error:d})))}}return{applied:r,failed:i}}var WW={applyValidateFix:_g,applyValidateFixes:gg,attachValidateFixHints:K_,buildCommandReferencesCheck:hg,buildDependencyReferencesCheck:ig,buildCloseReasonBackfillRows:eg,buildFilesCheck:fg,buildLifecycleCheck:pg,buildLifecycleDependencyGraph:rg,buildLifecycleParentGraph:gc,buildEstimateBackfillRows:tg,buildMetadataCounts:Z_,buildMissingFieldOccurrences:Q_,buildOrphanedPathRows:lg,classifyOrphanedPath:cg,collectDefaultProjectFileCandidates:Ac,collectTrackedGitFileCandidates:J_,detectLifecycleDependencyCycles:sg,detectLifecycleParentCycles:yc,escapeRegExp:ng,extractItemIds:ag,findLifecycleDependencyCycleComponents:og,isMetadataFieldMissing:q_,linkedArtifactPathExceedsFilesystemLimits:mg,listFilesRecursive:Cc,resolveDependencyCycleSeverity:W_,resolveParentCycleSeverity:G_,resolveFileScanMode:B_,resolveLifecycleDependencyCycleSamplePath:xa,resolveRequestedChecks:Y_,resolveValidateMetadataProfile:z_,resolveWorkspaceRoot:V_,sharedDirectoryPrefixLength:dg,summarizeOrphanedPathRows:ug,summarizeDuplicateIssueCodes:X_,toMeaningfulString:Ge};function sC(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function cC(e,t,n,r){let i=await o_(e,new Set(t.map(_=>_.id)),n,{schema:r.schema,extensionFieldNames:rn(H())}),a=[];i.unreadable_item_files.length>0&&a.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&a.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&a.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&a.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&a.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&a.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let o=a.length,s=await ia(e);s.tracked_path_count>0&&a.push(`validate_storage_tracked_runtime_cache_files:${s.tracked_path_count}`);let c=await En(e,$t(r));c.status==="drift"&&a.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await et(e),l=d===null?null:await xn(d);l!==null&&l.status!=="ok"&&a.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await vt(d??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:f,lossless:p}=Dn(m);f.length>0&&a.push(`validate_merge_decisions_unreviewed:${f.length}`),sC(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 at(e,t,n){n&&K_(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function dC(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 vu(e.pmRoot,e.items,r?1/0:qe,e.sourceIncomplete);at(t,i,n)}if(e.requestedChecks.has("metadata")){let i=qR(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let a=await e_(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,r?1/0:qe);t.closureTimestampFixes=a.fixes,Object.assign(i.check.details,a.details),i.warnings.push(...a.warnings),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",at(t,i,n)}if(e.requestedChecks.has("resolution")){let i=BR(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,at(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=pg(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,at(t,i,n),at(t,ig(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await fg(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,at(t,i,n)}return e.requestedChecks.has("command_references")&&at(t,await hg(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&at(t,await Ea(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&at(t,oC(e.items,r),n),e.requestedChecks.has("storage_integrity")&&at(t,await cC(e.pmRoot,e.items,W(e.settings,H()).type_to_folder,e.settings),n),t}function lC(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...d_(t.closeReasonBackfillRows)),r.push(...c_(t.resolutionBackfillRows)),r.push(...l_(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...u_(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...m_(t.staleLinkPruneRows)),r}async function uC(e,t,n,r,i,a){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=lC(e,t,n),{applicable:s,gated:c}=f_(o,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await gg(s,i,a);l.push(...m.applied.map(Rr)),u.push(...m.failed.map(({fix:f,error:p})=>({...Rr(f),error:p instanceof Error?p.message:String(p)})))}return{mode: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(Rr),applied_fixes:l,gated_fixes:c.map(m=>({...Rr(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function yg(e,t,n={}){Fd(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=p_(e.fixScope),a=L(process.cwd(),t.path);await ne(a);let o=await T(a),s=ge(o.schema),c=W(o,H()),d=Y_(e),l=[],u=await Sa({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 rr(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=DR(p,f,o.validation.metadata_required_fields),_=$R(o),w=W_(e.dependencyCycleSeverity),v=G_(e.parentCycleSeverity),S=B_(e.scanMode),k=V_(a),x=await dC({requestedChecks:d,options:e,global:t,pmRoot:a,workspaceRoot:k,settings:o,items:u,statusRegistry:s,metadataPolicy:h,lifecyclePatternPolicy:_,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:S,initialWarnings:[...new Set(l)],sourceIncomplete:m}),D=r?await uC(e,x,o,i,t,n):void 0,E=[...new Set(x.warnings)].sort((N,A)=>N.localeCompare(A)),b={ok:!x.checks.some(N=>N.status==="error"),has_warnings:E.length>0,checks:x.checks,warnings:E,...D!==void 0?{fixes:D}:{},generated_at:$(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...TR(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as mC}from"node:child_process";import{promisify as pC}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 fC=pC(mC),hC=16,_C=3e4;function gC(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 yC(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 wC(e,t,n,r){let i=yC(e,t),a=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Ld(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 gC(e,t.key,s)}finally{clearTimeout(o)}}function vg(e,t,n,r){let i=e;for(let a of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new Xe(`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 Xe(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function wg(e,t,n,r){let i=e.checks.find(a=>a.name===t);if(!i)throw new Xe(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:vg(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function vC(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await fC("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function bC(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(hC,t.length)},async()=>{for(;r<t.length;){let a=r;r+=1;let o=t[a],s=await st(Ht(e,o.id),o.id);n[a]=s.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function Dr(e,t={}){let n=await T(e),r=W(n),i=ge(n.schema),a=(t.strict_read===!0?(await Zl(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await dt(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 vC(e,t.tree_id),items:a,history:t.include_history===!1?[]:await bC(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&&(_=tu(m.operation,void 0,void 0,{...m.parameters,full:!0},o),d.set(h,_));let w=await _;return{value:vg(w,m.field,m.kind),population_size:a.length,cost:a.length}}if(m.kind==="validate"){l??=yg({counts:!0},o);let h=await l;return wg(h,m.check,m.field,m.kind)}if(m.kind==="health"){u??=Xh(o,{checkOnly:!0,full:!0});let h=await u;return wg(h,m.check,m.field,m.kind)}let f=t.providers?.[m.provider];if(f)return f(m);let p=pl(s,m.provider);if(!p)throw new TypeError(`assurance provider ${m.provider} is not registered`);return wC(p.runtime_definition,m,e,t.trigger??"sdk")}}}import{createHash as kC}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 bg(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:i}=Zr({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function SC(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 EC(e,t,n,r,i,a){let o=Object.fromEntries(Ya.map(f=>[f,0])),s=0,c=0,d=0,l=0,u=[],m=kC("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&&Ya.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 kg(e,t,n={}){qd(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let i=new Set,a=new Map;for(let k of t){if(i.has(k.id))throw new TypeError(`Duplicate recurrence item ${k.id}`);i.add(k.id);let x=Xr(k);x!==void 0&&a.set(k.id,x)}let o=zd(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}=EC(o,a,i,s,c,n.uncoveredOnly===!0),_=SC(n.cursor,h);if(_>p.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=p.slice(_,_+r).map(k=>{let x=o.membership.get(k),D=i.has(k);return{item_id:k,lineage_id:x.id,lineage_item_count:x.item_ids.length,family_ids:x.family_ids,present:D,...D?x.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=_+w.length,S=s.length===0?null: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?S:null,escape_rate_lower_bound:S},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as xC}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0311387c-c7c3-598c-961c-489e8a94ad29")}catch{}})();var Tc,Sg=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],$c=["measurement","assertion","gate"];function AC(e){if(Sg.includes(e))return e;throw ui({command_path:"assurance",token:e,allowed:Sg,display_name:"assurance action"})}function Fn(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 IC(e){if(!e)return Fn("kind",`Assurance declaration kind is required. Expected: ${$c.join(", ")}`,"pm assurance list measurement");if($c.includes(e))return e;throw new y(`Assurance declaration kind is required. Expected: ${$c.join(", ")}`,g.USAGE)}function Eg(e){if(!e)return Fn("preset",`Assurance preset is required. Expected: ${ir.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(ir.includes(e))return e;throw new y(`Assurance preset is required. Expected: ${ir.join(", ")}`,g.USAGE)}function Oc(e){return e.owner?.trim()?e.owner.trim():Fn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function RC(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 CC(e){let[t,n,r]=await Promise.all([Qn(e,"measurement"),Qn(e,"assertion"),Qn(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function xg(e,t){return t===!0?{id:e.id}:e}async function TC(e,t){let n=t.authorization_decision;if(!n)return[];let r=await Dr(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(o=>o.id===n),a=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!a.has(i.status))throw new y(`Assurance authorization ${n} must name a terminal Decision item`,g.USAGE);return[i.id]}async function $C(e,t){let n=ko(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>yn))throw new y(`assurance verdict limit must be an integer from 1 through ${yn}`,g.USAGE);let r=await yu(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 OC(e,t,n){if(e==="presets"){if(t.preset??t.id)return $i(Eg(t.preset??t.id),Oc(t));let i=ir.map(a=>{let o=$i(a,"pm-owner");return{id:a,title:o.title,description:o.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return gn(()=>Bu(n,Eg(t.preset??t.id),Oc(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await Vu(await Dr(n,{resolve_tree:!1,trigger:"derive"}),Oc(t)),a=t.apply?await gn(()=>Ju(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 Fn("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 yo(n,"assertion",t.id);return gn(()=>Ku(n,r,t.enforcement,{author:t.author,message:t.message}))}async function DC(e,t,n){if(!e.id)return Fn("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(!Bt.includes(e.trigger))throw new y(`Unknown assurance trigger ${e.trigger}. Expected: ${Bt.join(", ")}`,g.USAGE);let i=e.trigger,[a,o]=await Promise.all([CC(t),Dr(t,{...n.workspace,tree_id:e.tree,trigger:i})]),s=await nu(()=>fu(r,a,o,{trigger:i,dry_run:e.dry_run===!0}));return s.dry_run||await gu(t,s,{author:e.author,message:e.message}),s}function Ag(e){throw e instanceof y?e:new y(e instanceof Error?e.message:"assurance risk request is invalid",g.USAGE)}function PC(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"?bg(t):Zr(t)}catch(n){return Ag(n)}}function NC(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 LC(e,t,n){let r=C(t.policy),i=Tc?.pm_root===e?Tc:void 0,a=new Map(n.map(d=>[d.id,xC("sha256").update(C([Hd(d),Xr(d)])).digest("hex")])),o=i?.policy_serialized===r?i:void 0,s=o?NC(o,a):new Set,c=Wd(t.policy,o?n.filter(d=>s.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...s]}:{});return Tc={pm_root:e,policy_serialized:r,item_fingerprints:a,index:c},c}async function MC(e,t){let n=PC(e),r=await Dr(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?Gd(LC(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):kg(n.policy,r.items,n)}catch(i){return Ag(i)}}async function jC(e,t={},n={}){let r=AC(e.action),i=L(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return OC(r,e,i);if(r==="verdicts")return $C(e,i);if(r==="run")return DC(e,i,n);if(["risk","lineages"].includes(r))return MC(e,i);let a=IC(e.kind);if(r==="list")return Qn(i,a);if(!e.id)return Fn("id",`assurance ${r} requires an id`,`pm assurance ${r} ${a} <id>`);let o=e.id;if(r==="show")return yo(i,a,o);if(r==="remove"){let l=await gn(()=>_u(i,a,o,{author:e.author,message:e.message}));return xg(l,e.idOnly)}let s=RC(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 TC(i,s)}:{}},d=await gn(()=>Ei(i,a,s,c));return xg(d,e.idOnly)}function xG(e,t,n){let r={...e,...t};return jC({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:ko(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 Un from"node:fs/promises";import Oa from"node:path";import $a from"node:fs/promises";import Dc 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 FC=864e5;function UC(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 HC(e,t){let n;try{n=await $a.readdir(e,{withFileTypes:!0})}catch(i){if(F(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let a=Dc.join(e,i.name),o;try{o=await $a.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 Ig(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*FC,o=Dc.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await HC(o,s.warnings);for(let d of c){let l=Dc.join(o,d),u=`checkpoints/${d}`;s.scanned+=1,r?.onRead&&s.warnings.push(...await r.onRead(l));let m;try{m=await $a.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=UC(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 $a.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 Pc from"node:fs/promises";import Rg 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 zC=1440*60*1e3,WC=new Set(["committed","compensated"]);function GC(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 qC(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 WC.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 BC(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],a=GC(await Pc.readFile(e,"utf8")),o=qC(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 Pc.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:o,warnings:i}}async function Cg(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*zC,o=Rg.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Pc.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=Rg.join(o,d),u=`transactions/sdk/${d}`,m=await BC(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 Pr=["index","embeddings","runtime","locks","checkpoints","transactions"],VC=1440*60*1e3,JC=[{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 KC(e,t,n){let r=t.relativePath,i=Oa.join(e,r),a=await He({path:i,scope:"project"});try{let o=await Un.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 Un.unlink(i):await Un.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 YC(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],a=[],o=Date.now()-VC;for(let s of n){let c=Oa.join(e,s.relativePath);if(!await O(c))continue;let d=(await Un.readdir(c)).filter(l=>l.startsWith(s.prefix)).sort();for(let l of d){let u=Oa.posix.join(s.relativePath,l),m=Oa.join(c,l);a.push(...await He({path:m,scope:"project"}));let f=await Un.stat(m).catch(p=>{if(!F(p))throw p});if(f){if(f.mtimeMs>o){i.push(u);continue}r.push(u),!t&&(await Un.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 XC(e){if(!e||e.length===0)return[...Pr];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new y(`--scope requires at least one value (${Pr.join(",")})`,g.USAGE);let n=new Set;for(let r of t){if(!Pr.includes(r))throw new y(`Invalid --scope value "${r}". Expected one or more of: ${Pr.join(", ")}`,g.USAGE);n.add(r)}return Pr.filter(r=>n.has(r))}function ZC(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 JG(e,t={}){let n=L(process.cwd(),e.path);await ne(n);let r=await T(n),i=t.dryRun===!0,a=XC(t.scope),o=JC.filter(p=>a.includes(p.scope)),s=[],c=[],d=[];for(let p of o){let h=await KC(n,p,i);h.removed?s.push(p.relativePath):c.push(p.relativePath),d.push(...h.warnings)}if(a.includes("runtime")){let p=await YC(n,i);s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(a.includes("locks")){let p=await Rm(n,{dryRun:i,hooks:{onRead:h=>He({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 Cg(n,{dryRun:i,retentionDays:p,hooks:{onRead:_=>He({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 Ig(n,{dryRun:i,retentionDays:p,hooks:{onRead:_=>He({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 Yr({mode:i?"gc:dry-run":"gc",total_items:o.length}));let f=ZC({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 QC}from"node:child_process";import eT from"node:path";import{promisify as tT}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 nT=tT(QC),$g="@unbrained/pm-cli",rT="latest",iT={global:["--global"],project:[]};function Tg(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 Pa(e){return e.trim().toLowerCase()}function Og(e,t){let n=Pa(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"&&Pa(r)===n)}function aT(e,t){let n=L(process.cwd(),t.path),r=an(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function oT(e,t,n){try{let r=await nT(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(" ")}
69
- ${a}`,g.GENERIC_FAILURE)}}function Na(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():rT}function Da(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():$g}async function sT(e,t){let n=e.commandRunner??oT,r=Da(e),i=Na(e),a=`${r}@${i}`,o=["npm","install","-g",a];e.repair===!0&&o.push("--force");let s=Qc(import.meta.url,["../../.."]),c={requested:!0,status:"planned",package:r,target:a,command:o,before_version:s,...r===$g?{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 cT(e){return eT.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function dT(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!cT(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 lT(e,t){let n=dT(e,t);return e.kind!=="local"||await O(n)?n:await O(e.location)?e.location:n}function uT(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 Dg(e,t){let n=aT(e,t);return(await ye(n.selected_root)).state.entries.filter(r=>r.scope===e)}async function mT(e,t,n){let r=await Dg(e,t);return r.find(i=>Og(i,n.name))??r.find(i=>Pa(i.directory)===Pa(n.directory))}async function pT(e,t,n,r,i){let a=Na(t),o=await lT(e.source,a),s=uT(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 Is(o,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await mT(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 fT(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 nq(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",...iT[Tg(t)]];throw new y('Options "--cli-only" and "--packages-only" are mutually exclusive.',g.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:Ye(m),suggested_retry_args:m}})}let i=Tg(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 sT(t,a):{requested:!1,status:"skipped",package:Da(t),target:`${Da(t)}@${Na(t)}`,command:["npm","install","-g",`${Da(t)}@${Na(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await Dg(i,n):[];if(r&&(d=d.filter(m=>Og(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 pT(m,t,n,i,a));let u=fT(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 hT}from"node:crypto";import{isUtf8 as _T}from"node:buffer";import Nr from"node:fs/promises";import Nc 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 Pg(e){try{return(await Nr.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(F(t))return[];throw t}}function gT(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 yT(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 Bn(r).ok?gT(e,r,t.length,n):null}catch{return null}}async function Lc(e,t){if(!(await Nr.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let n=Nc.join(e,"history"),r=await Pg(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=Nc.join(n,o);try{let l=await Nr.lstat(d);if(i.set(o,C([l.ino,l.size,l.mtimeMs,l.ctimeMs])),!l.isFile())continue;let u=await Nr.readFile(d);c.digest=hT(t).update(u).digest("hex"),c.stream=yT(s,u,c.digest)}catch{}}if(C(r)!==C(await Pg(n)))throw new TypeError("attestation history inventory changed during read; retry");for(let[o,s]of i){let c=await Nr.lstat(Nc.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 Mc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jc(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function Hn(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function wT(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:Hn(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||Hn(e.latest_record_hash,e.latest_hash_algorithm))}function vT(e){return e===null?!0:!Mc(e)||!jc(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"&&At(e.ts)&&(e.record_hash===null||Hn(e.record_hash,"sha256")||Hn(e.record_hash,"sha512"))}function bT(e,t){return!Mc(e)||!jc(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)&&Hn(e.stream_digest,t)&&wT(e)&&(e.checkpoint_digest===null||Hn(e.checkpoint_digest,"sha256"))&&vT(e.last_maintenance)}function Ng(e){if(!Mc(e)||!jc(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==Za.format||e.version!==1||typeof e.generated_at!="string"||!At(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(!bT(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(Qa(C(i),t)!==r)throw new TypeError("History attestation rollup mismatch");return e}async function Lg(e={}){let t=Ce(e.hashAlgorithm),n=e.generatedAt??$();if(!At(n))throw new TypeError("Invalid history attestation timestamp");let r=await Lc(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:Za.format,version:1,hash_algorithm:t,generated_at:n,streams:r.map(o=>o.stream)};return Ng({...a,workspace_digest:Qa(C(a),t)})}async function Mg(e,t={}){let n=Ng(e),r=await Lc(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 Aq(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 Mg(r,{pmRoot:t.path})}let n=await Lg({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)}
70
- `,{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 Fg(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 Ug(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?Ye([...r,"merge","report"],n):e==="history_evidence_invalid"?Ye([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?Ye([...r,"merge","reconcile"],n):e==="history_repair_required"?Ye([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?Ye([...r,"merge","install"],n):null}function Hg(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 Fq(e){let t=L(process.cwd(),e.path);await ne(t);let n=await T(t),r=W(n,H()),i=[],a=await Sa({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),o=await et(t),[s,c,d,l]=await Promise.all([En(t,$t(n)),o===null?Promise.resolve(null):xn(o),vt(o??t,{includeLossless:!0,pmRoot:t}),Ea(t,a,!1)]),{pendingDecisions:u,lossless:m}=Dn(d.receipts),f=[...new Set(u.map(w=>w.item_id))].sort((w,v)=>w.localeCompare(v)),p=l.check.details,h=Hg(p),_=Fg({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:Ug(_,t),reason:_},warnings:[...new Set(i)].sort((w,v)=>w.localeCompare(v)),generated_at:$()}}function Uq(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(`
71
- `)}var Hq={commandForWorkspacePositionState:Ug,normalizeWorkspaceHistoryDrift:Hg,selectWorkspacePositionState:Fg};import kT from"node:fs/promises";import Lr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f02db25d-bedb-5411-b50a-de0fea51a117")}catch{}})();var Fc="index/manifest.json",Uc="search/embeddings.jsonl",ST="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function ET(e){return e.progress===!0||process.stderr.isTTY===!0}function de(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
72
- `)}catch{}}function xT(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 AT(e,t,n,r){let i=[];return{candidates:await $l(e,t,n,i,r),warnings:i}}async function zc(e,t,n,r,i){let a=rn(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 kT.readFile(s.item_path,"utf8"),d=It(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:${Lr.relative(e,s.item_path)}`),o.push({metadata:s.metadata,body:""})}}return o}function IT(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:Pl(e,{fields:n})}}var zn=ee;function RT(e){let t=H(),n=zn(e.search?.provider);if(!n)return null;let r=fl(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,a=zn(i.name)??zn(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 CT(e){let t=H(),n=zn(e.vector_store?.adapter);if(!n)return null;let r=hl(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,a=zn(i.name)??zn(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 Hc(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 TT(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)=>Hc(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(Hc(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 Wg(e,t,n){let r=n?qt(n.name,zg(e)):t?qt(t.name,t.model):null;if(!r)throw new y("No embedding identity available for semantic reindex mode",g.USAGE);return r}function $T(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function Gg(e,t,n,r,i,a,o,s){let c=r?.name??n?.name,d=Nl(c,e.search.embedding_corpus_max_characters).maxCharacters,l=ao(e),u=i.map(p=>Ll(p,{providerName:c,maxCharacters:d,fields:l})),m=[],f=null;if(r)try{m=await TT(r,e,u),f=qt(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 Ml(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=qt(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 OT(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 Ul(e,o,{},a)}async function qg(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 Fl(e,n)}}function DT(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function PT(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 NT(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Kn(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=gi(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 LT(e){let t=W(e.settings,H()),n=await AT(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 MT(e){let t=await _n(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return Wg(e.settings,Kn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&hn(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(ST))}async function jT(e){let t=await _n(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=Wg(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(d=>d.metadata.id)),i=$T(t.entries,r),a=hn(t.embedding,n);e.forceFullSemantic&&!a&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let o=e.forceFullSemantic||a?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),s=new Set(o.map(d=>d.metadata.id)),c=s.size>0?await zc(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 FT(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await zc(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 Gg(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:oo(r.vectors,"Reindex embeddings")}}async function UT(e){let t=await Gg(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=oo(n,"Reindex embeddings");if(!(!e.resetRequired&&(hn(e.ledgerEmbedding,r)||zl(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let a=await FT(e);return n=a.vectors,r=a.embeddingIdentity,i=a.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:a.staleDocuments,vectorDimension:i,resetRequired:!0}}async function HT(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 zT(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:Hc(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 WT(e){de(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await UT({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 OT(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 qg(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=zT(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await HT({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:Hl(t.embeddingIdentity,t.vectorDimension)}}async function GT(e){let t=await jT(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 qg(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await WT({...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 qT(e){let t=Lr.join(e.pmRoot,Fc),n=Lr.join(e.pmRoot,Uc),r=ao(e.settings),i=e.documentsForKeywordArtifacts.map(o=>JSON.stringify(IT(o,e.mode,r))).join(`
59
+ `}function C0(e){return e.map((t,n)=>({...t,sequence:n+1}))}function P1(e,t,n){Ds(e,"base");let r=Ds(t,"ours"),i=Ds(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:ca(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:ca(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:ca(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=C0([...r.slice(0,o),...l]);return{merged:ca(u),strategy:"union_reanchor",common_entries:o,entries_from_ours:s.length,entries_from_theirs:d.length,entries_total:u.length,reanchored:!0}}var T0=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],$0=["acceptance_criteria"],O0=["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 Ir(e){if(typeof e!="object"||e===null||Array.isArray(e))return C(e);let{provenance:t,...n}=e;return C(n)}function D0(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function P0(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(D0(l))}return d}function N0(e,t){return qt(String(e),String(t))>=0?e:t}function uh(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 mh(e,t,n,r,i,a,o){let s=uh(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 Ps(e){return{...e.metadata}}function Ns(e,t,n){try{let r=el(Ct(e,n),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 new y(`Item merge input (${t}) is not a readable item document: ${String(r)}`,g.GENERIC_FAILURE)}}function L0(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?P0(e.baseValue,e.oursValue,e.theirsValue):e.field==="acceptance_criteria"?lh(hi(e.baseValue),hi(e.oursValue),hi(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 M0(e){let t=mh(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 j0(e,t,n,r,i,a,o){let s=new Set([...T0,...$0]),c=new Set(O0),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(!L0({field:u,baseValue:m,oursValue:f,theirsValue:p,unionFieldSet:s,accumulator:l})){if(c.has(u)){l.merged[u]=N0(f,p);continue}M0({field:u,baseValue:m,oursValue:f,theirsValue:p,preferred:r,conflictResolution:i,oursUpdatedAt:a,theirsUpdatedAt:o,accumulator:l})}}return l}function N1(e,t,n,r={}){let i=r.preferred??"ours",a=r.conflictResolution??"preferred_side",o=Ns(t,"ours",r),s=Ns(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=Ns(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=Ps(c),l=Ps(o),u=Ps(s),{merged:m,conflictFields:f,fieldsFromTheirs:p,unionFields:h,conflictDecisions:_}=j0(d,l,u,i,a,o.metadata.updated_at,s.metadata.updated_at),w=mh(c.body,o.body,s.body,i,a,o.metadata.updated_at,s.metadata.updated_at);return w.conflict?(f.push("body"),_.push({field:"body",base:Y(c.body),ours:Y(o.body),theirs:Y(s.body),retained:Y(w.value),discarded:Y(w.from_theirs?o.body:s.body),retained_side:w.retained_side,resolution_basis:w.resolution_basis})):w.from_theirs&&p.push("body"),{merged:Qd({metadata:m,body:w.value},r),conflict_fields:f,fields_from_theirs:p,union_fields:h,conflict_decisions:_,requested_preference:i,requested_preference_applied:a==="preferred_side",conflict_resolution:a}}function Ls(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ms(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(!Ls(t)||!Ls(n))return null;let s=Ls(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 ph(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=uh(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 ph(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 L1(e,t,n,r={}){let i=r.preferred??"ours",a=Ms(e,"base"),o=Ms(t,"ours"),s=Ms(n,"theirs"),c=[],d=[],l=ph(a,o,s,i,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
60
+ `,conflict_paths:c,paths_from_theirs:d,preferred:i}}import{constants as fh}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 Rr(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,fh.O_RDONLY|q0(fh));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 la from"node:path";import{execFile as B0}from"node:child_process";import{createHash as hh}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),da=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function V1(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||!da.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||!da.test(o))return;let{stdout:c}=await vt("git",["rev-parse","--verify",`${o}:${i}`],{cwd:e,timeout:1e4}),d=c.trim(),l=hh(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 _h(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"&&da.test(t.original_head)&&typeof t.original_blob=="string"&&da.test(t.original_blob)}async function gh(e,t,n,r){if(r!==void 0&&hh(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,ma=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"]),pa="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"]),wh=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 it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vh(e,t){return Object.keys(e).every(n=>t.has(n))}function ua(e){return Array.isArray(e)&&e.length<=ma&&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>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(it(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function bh(e){if(!it(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[vh(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"),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 ax(e){if(!it(e))return!1;let t=Object.entries(e);return t.length<=ma&&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("\\")||la.posix.isAbsolute(e))return!1;let n=la.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&la.posix.basename(n,la.posix.extname(n))===t}function sx(e){return!ua(e.fields_from_theirs)||!ua(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>ma||!e.decisions.every(bh)?!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===pa)&&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 yh(e,t){if(!it(t)||fa(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||wh.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&&yh(r.field,r.retained)&&yh(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,i)=>r+(it(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(it(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===pa)}function ux(e){return e.operation!==void 0&&!_h(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||!vh(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 js(e,t){if(!it(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 Fs(e){if(!it(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=>!it(r)||!Object.hasOwn(r,"retained")||!Object.hasOwn(r,"discarded")?r:{base:Y(void 0),ours:Y(void 0),theirs:Y(void 0),...r})}}function kh(e){if(!it(e))return;if(!ua(e.fields_from_theirs))return"fields_from_theirs";if(!ua(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>ma)return"decisions";let t=e.decisions.findIndex(n=>!bh(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function Us(e,t){return js(e,t)===null}function fa(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 zs(e,t){let n=Pn(t),r=Ft(n?void 0:t);return!n&&(t===null||wh.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),xh=16*1024*1024,ha=100;async function Hs(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 Ah(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 Gs(e){return he.join(e,"merge-receipts")}function Nn(e){return`${e}.json`}async function Eh(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await Rr(e.receiptPath,xh)}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=Fs(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!Us(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:Ws(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
61
+ `}}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)))})):_a(e).decisions}))}function Ws(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 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 ct(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({..._a(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 _a(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:fa(t.retained)??Ft(Pn(t.retained)?void 0:t.retained),discarded_hash:fa(t.discarded)??Ft(Pn(t.discarded)?void 0:t.discarded)}))}}async function hF(e){let t=await Hs(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)}
62
+ `);let o=await Ah(e.cwd,a.item_path);if(o!==null){let s=Gs(o),c=a.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:zs(u.field,u.retained),discarded:zs(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:pa};await Vn(s),await Z(he.join(s,Nn(a.id)),`${JSON.stringify(l,null,2)}
63
+ `)}return a}async function Sh(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>=ha)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 Rr(he.join(e,t),xh)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=Fs(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let a=js(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:kh(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 Hs(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await Sh(n,"clone_local"),i=t.pmRoot??he.join(e,".agents","pm"),a=await Sh(Gs(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?Ws(d):[Tr(d)]).includes(Tr(l))){o.delete(d.id),s+=1,r.invalid_evidence.length+a.invalid_evidence.length+c.length<ha&&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,ha),invalid_evidence_truncated:r.invalid_evidence_truncated||a.invalid_evidence_truncated||r.invalid_evidence_count+a.invalid_evidence_count+s>ha,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 _F(e,t,n={}){let r=await Hs(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(!Us(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=$(),o=he.join(r,Nn(t.id)),s=await Ah(e,t.item_path),c=s===null?null:he.join(Gs(s),Nn(t.id)),d=(await Promise.all([Eh({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[Eh({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)]:Ws(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 gF(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 ga 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",Rh=Symbol("pre-durable-disposition-eligible");function Et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qs(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 Ih(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 Ch(e,t){if(typeof e!="string")return!1;let n=ga.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!ga.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(ga.posix.basename(n)===`${t}.toon`||ga.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&&Ch(e.item_path,t)}function Th(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=>Ih(o)?[o.field]:[])):new Set;return qs(t)&&qs(n)&&qs(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(Ih)&&a.size===i.length&&t.length===a.size&&t.every(o=>a.has(o))}function Ax(e,t){return xx(e,t)&&Th(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&&Ch(e.item_path,t)&&Th(e)}function Rx(e){return e[Rh]===!0}function $h(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),[Rh]:Ix(r,t),...typeof e.ts=="string"&&fn(e.ts)?{eventTimestamp:e.ts}:{}}])}function Oh(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 Dh(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(`
64
+ `).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 Ml(e.located,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n}}async function Ph(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 Nh(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 Ph(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=Cl(o.entries,o.entries.length-1),c=ll(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=$o({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 Ph(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=ci({...sl({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 Ni({historyPath:t.historyPath,historyRawUnderLock:a,nextHistoryRaw:`${o.prefix}${JSON.stringify(v)}
65
+ `}),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 Fh}from"node:fs/promises";import Bs from"node:path";import Uh 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]="289c841a-1355-54a5-a3e3-f59de2abd58c")}catch{}})();function Lh(e,t){return t==="body"?e.body:e.metadata[t]}function Vs(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)&&Vs(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)&&Vs(i,n[r]))}function Mh(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 ml(a.patch))o.add(_i(c.path)),c.from&&o.add(_i(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 Px(e,t,n){let r=Uh.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(_i(p.path));let a=new Set([...i].filter(p=>Vs(Lh(t,p),Lh(n,p)))),o=new Set([...i].filter(p=>!a.has(p))),s=Mh(e,o),c=Mh(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 Nx(e){try{return await Fh(e)}catch{return null}}async function Lx(e){if(await Nx(Bs.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 Mx(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 Fh(e.itemPath),r=[];for(let o of t){let s=await Lx({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 jh(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:Bs.relative(a,t.currentItemPath).split(Bs.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 gh(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 jx(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 Mx({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(_a)}}:e.options.auditContext}}function Fx(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=ul(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 Ux(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 zx(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?Uh.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(ci({...c,event_class:nl(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function Hx(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 Js(e,t,n){let{pmRoot:r,settings:i,typeRegistry:a}=await mo(n.path),o=await iu(r,e,i,a.type_to_folder);return t.salvageTail===!0?Nh({pmRoot:r,subject:o,settings:i,typeRegistry:a,options:t,author:W(t.author,i.author_default)}):mm({pmRoot:r,subject:o,settings:i,typeRegistry:a,operation:"history-repair",options:t,transform:s=>Wx({pmRoot:r,subject:o,options:t},s)})}function Gx(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 Wx(e,t){let{pmRoot:n,subject:r,options:i}=e,a=t.entries,o=t.verification,s=Tt(a),c=i.normalizeProvenance?om(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=pl(c.entries),l=new Set(c.entries.map(A=>A.item_hash_version).filter(A=>A!==void 0)),u=di(c.entries,d),m=Fx(r,t,d);await jh(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?Px(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await jx({options:i,pmRoot:n,subjectId:r.id,itemReplayContext:m,reconciliation:_}),E=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,Gx(i,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,x=!!i.dryRun,D=Ux({message:i.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=zx({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=Hx(E,u.skippedOps,_);return{changed:E,rewrittenEntries:S,beforeWrite:async()=>jh(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 lU(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 uU(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 mo(t.path),a=[],o=await lt(n,r.item_format,i.type_to_folder,a,r.schema,{forceSourceScan:!0}),s=await Xt(n,o),c=e.normalizeProvenance?await sm(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 Js(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 rl(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]="1c246528-8709-5f7c-a813-6e2894763d3c")}catch{}})();var qx=new Set(Yl),Hh=25,Mn=8,an=100,Bx=Ee.join("runtime","telemetry","events.jsonl"),Vx=Ee.join("runtime","telemetry","state.json"),Jx=2500,Kx=500,Gh=eu-3,Yx=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function ec(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 tc(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function jn(e){return e.trim().toLowerCase()}function Xs(e,t){let n=jn(e),r=jn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function nc(e){try{return(await St.stat(e)).isDirectory()}catch{return!1}}async function Xx(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 Zx(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 Qx(e,t,n){let r=Ee.join(e,"history");if(!await nc(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 Zx(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 Zs(e,t){return Ee.relative(e,t).replaceAll("\\","/")}async function Wh(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)=>Zs(e,i).localeCompare(Zs(e,a))),r}function eA(e){return!(typeof e=="object"&&e!==null&&"code"in e&&F(e))}async function tA(e,t,n){let r=await Wh(e,t),i=[],a=[],o=[],s=[],c=sn(z());for(let d of r){let l=Zs(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:cd(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:ii(f.metadata)})}catch{o.push(l)}}return{paths:r,unreadable:i,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function nA(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){eA(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(...$h(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Oh(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 qh(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 rA(e,t,n,r,i,a){let o=await tA(e,t,n),s=await nA(e),c=ai(o.formatVersions),d=ge(n),l=bi(a,A=>Zd(A,d),Qn()),u=await sa(e),m=await tt(e),f=await ch(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=Dh(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}`),...qh(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}`]:[],...dh({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:at(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 iA(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function aA(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:iA(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function oA(e,t){return ee(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function sA(e){let t=ee(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function cA(e){return ee(e.reason)??ee(e.error)??ee(e.message)}function Ks(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 dA(e){let t=[],n=[],r=[];e.forEach((a,o)=>{let s=oA(a.definition,o),c=sA(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:cA(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(Ks),n.sort(Ks),r.sort(Ks);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 Bh(e,t,n,r,i,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>tc(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=[],h=ws(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 lA(e,t,n){let r=await As(Je(e)),i=await Ke({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=i.loaded.map(S=>aA(S)),o=await im(i.loaded,Je(e)),s=await Ye({...i,loaded:i.loaded}),[c,d]=await Promise.all([ye(i.roots.project),ye(i.roots.global)]);await xs(e,s.registrations.migrations);let l=dA(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=>Xs(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=p.filter(S=>!Xs(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=Bh(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 uA(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function at(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function mA(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 ya(e,t){let n=at(e,t);return{...n,sample:n.sample.map(r=>mA(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 pA(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 fA={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:ya(e.discovered,t),effective:ya(e.effective,t),loaded:ya(e.loaded,t),failed:at(e.failed,t),warnings:q(e.warnings,t),activation:{failed:at(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:pA(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:at(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:at(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:at(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:at(e.history_conflict_markers,t),history_invalid_json:at(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 Vh(e,t){let n=fA[e.name];return n?n(e.details,t):e.details}function hA(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:Vh(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 zh(e){return e.details.skipped===!0}function _A(e){let t=q(e.warnings,Mn),n=e.checks.filter(zh).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!zh(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 Qs(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=uA(e,Hh);return{values:n.values,truncated:n.truncated,total:e.length}}function wa(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function gA(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return qx.has(e)?e:null}function va(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 Jh(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e.split(`
66
+ `)){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>=Gh&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:a}}function yA(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function wA(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 vA(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||uo().telemetry_disabled?void 0:{attempted:!0,...await Kh(n)}}function bA(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>=Kx;return(o||s||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function kA(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function EA(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Ql?[`telemetry_schema_version_behind:${t}`]:[]}function SA(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 xA(){return{...uo(),pm_no_telemetry:wa("PM_NO_TELEMETRY"),telemetry_otel_disabled:wa("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:wa("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:gA()}}function AA(e,t){return e.telemetry.enabled&&t.validEntries>0}function IA(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Kh(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(Jx)});return{probe_url:va(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of Yx){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:va(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function RA(e,t){let n=Br(process.cwd()),r=Ee.join(n,Bx),i=Ee.join(n,Vx),a=await V(r),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?Jh(a):yA(),d=await V(i),{runtimeState:l,stateParseFailed:u}=wA(d),m=e.telemetry.endpoint.trim(),f=va(m),p=await vA(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...bA(e,c,l),...kA(p),...EA(p),...SA(e,l));let _=AA(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:IA(_,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:Gh,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:xA()}},warnings:h}}async function CA(e){let t;try{t=await Om(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 TA(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 lt(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 $A(e,t){let n=gi(e),r=Zn(n.settings),i=vi(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 OA(){return{refreshed:[],skipped:[],warnings:[]}}async function DA(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?OA():Kl(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function PA(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&yn(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function NA(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 LA(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Yh(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:so(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:so(r,e.vector_store?.adapter??null)}}function MA(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function jA(e,t,n){return e.enabled&&n.length>0&&t}async function FA(e,t,n,r,i){let a=$A(t,e),o=await wn(e),s=a.semanticRuntimeAvailable?po(n,o.entries):[],c=await DA({pmRoot:e,snapshot:a,refreshPolicy:r,staleBefore:s}),d=await wn(e),l=a.semanticRuntimeAvailable?po(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=PA({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=NA({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=Qs(s,i),h=Qs(l,i),_=jA(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:MA(r),...Yh(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:Hh,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:LA(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 UA(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 Xh(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 zA=new Set(["extensions","locks","search"]);function HA(e){let t=new Set(Xc.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(Zc));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of zA)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 GA(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:a}=HA(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 nc(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 Zh(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 WA(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?dt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):lt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Ys(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function qA(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 BA(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 VA(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 rc=e=>e.unknown_event_count??0,ic=e=>e.actionable_unknown_event_count??rc(e);function JA(e,t,n,r,i,a){let o=rc(r),s=ic(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 Qh(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function KA(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 YA(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function XA(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 e_(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=Lo(r)?.code??tc(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=ec(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 ZA(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 QA(e){for(let t of e.checks){let n=Mo(e.remediationSources[t.name]);ZA({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function eI(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 Js(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 tI(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 t_(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?_A(i):t.brief===!0?hA(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 n_(e,t={}){let n=L(process.cwd(),e.path);await ne(n);let r=Ht(n),{settings:i,warnings:a}=await _l(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=Xh(t),m=await GA(n,s,c),f=UA(i),p=await RA(i,{checkTelemetry:t.checkTelemetry===!0}),h=await lA(n,i,!!e.noExtensions),_=Zh(t),w=[],v=await WA({pmRoot:n,settings:i,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),E=v,k=Li(ge(i.schema),v),x=[...(await bm({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,...Mi(k)],D=_.skipDrift?{warnings:[]}:await Al({pmRoot:n,settings:i,itemIds:v.map(pe=>pe.id),commandLabel:"health"}),S=await Qx(n,i.history.compact_policy,await Xx(n)),b=await or(n,20,t.verboseAuthorEvents===!0),N=ic(b),A=N>0?[`history_unknown_author_events:${N}`]:[],R=Qh(await Xl(n,v,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),Q=await lm(n),Ae=Q.warnings,we=await CA(n),_e=_.skipIntegrity&&!l?{...Ys("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await rA(n,s.type_to_folder,i.schema,i,l,v),He=_.skipDrift?Ys("history_drift"):await TA({pmRoot:n,items:E,settings:i,typeRegistry:s,itemReadWarnings:w}),Ur=[...new Set(w)],Bn=await eI({gitWorkspaceRoot:_e.gitWorkspaceRoot,pendingMergeReceipts:_e.pendingMergeReceipts,historyDriftCheck:He,global:e});tI(He,Bn);let H=_.skipVectors?Ys("vectorization"):await FA(n,i,E,u,t.verboseStaleItems===!0),B=[qA(r,i,o),BA(m,c),VA(x,k),p.check,h.check,JA(v,i,S,b,R.scan,Q),we.check,_e.check,He.check,H.check],zr=KA({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:He,vectorizationCheck:H}),Hr=XA({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:He,vectorizationCheck:H});QA({checks:B,remediationSources:Hr,historyDriftedCount:YA(He),overThresholdCount:S.over_threshold.length});let Fa=zr.filter(pe=>!ec(pe,l)),Ua=e_({warnings:zr,checks:B,remediationSources:Hr,requireMergeDrivers:l}),Zg=new Set(Ua.filter(pe=>pe.severity==="gate_failing").map(pe=>pe.check)),Qg=new Set(Ua.map(pe=>pe.check));for(let pe of B)pe.ok=!Zg.has(pe.name),Qg.has(pe.name)&&(pe.status="warn");let ey={ok:Fa.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Fa.length>0?g.GENERIC_FAILURE:0},checks:B,warnings:zr,findings:Ua,failed_because:Fa,generated_at:$()};return t_(ey,t,_.summaryMode)}var dz={buildHierarchyIntegrityWarnings:qh,buildExtensionHealthTriageSummary:Bh,buildHealthFindings:e_,buildCapabilityContractMetadata:Sr,buildStaleInProgressHealthSummary:Qh,buildVectorizationProviderDetails:Yh,collectUnknownCapabilityGuidance:Er,isAdvisoryHealthWarning:ec,isDirectory:nc,isExpectedUnmanagedExtension:Xs,listItemDocumentPaths:Wh,normalizeEndpointForDisplay:va,normalizeExtensionNameForMatch:jn,parseTelemetryQueue:Jh,probeTelemetryEndpointHealth:Kh,projectHealthResult:t_,resolveActionableUnknownAuthorEventCount:ic,resolveHealthSkipPolicy:Zh,resolveUnknownAuthorEventCount:rc,resolveVectorRefreshPolicy:Xh,selectStaleItemDetail:Qs,summarizeHealthCheckDetails:Vh,summarizeExtensionList:ya,summarizeRecordList:at,summarizeStringList:q,telemetryEnvFlagEnabled:wa,warningCode:tc};(function(){try{var e=typeof window<"u"?window:typeof 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 r_(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!au(e,t).ok)return{reason:"unverified_history"};let r=dl(),i={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(r.metadata.status));r=Rl(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 i_(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function a_(e,t,n,r,i){let a=i_(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 ct(Gt(e,d.id),d.id),{body:m,...f}=d;l=r_(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 o_(e,t){let n=L(process.cwd(),t.path),r=await T(n),i=ge(r.schema);await ut({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 ct(Gt(n,a.metadata.id),a.metadata.id),s=i_(i),c=r_(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 nI(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function s_(e){return`${e.item_id} ${e.link_kind}`}function c_(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=nI(i.classification,r.classification),i.owners.set(s_(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[s_(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 d_(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=c_(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=oi(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 rI(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 iI(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=aI(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 aI(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 ac(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 oI(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:ac("history stream",o)});continue}iI({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},a)}return n}function l_(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 sI(e){let t=[],n=0,r=null;try{r=await V(Ht(e))}catch(a){n+=1,t.push({path:"settings.json",detail:ac("configuration file",a)})}if(r!==null){n+=1;let a=l_(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:ac("configuration file",c)});continue}let s=l_(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function u_(e,t,n,r={}){let i=await rI(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 oI(e,a),l=await sI(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 Oc from"node:fs/promises";import{realpathSync as bR}from"node:fs";import{execFile as kR}from"node:child_process";import xe from"node:path";import{promisify as ER}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 cI=["metadata","resolution"],oc=["metadata","resolution","estimates","timestamps","lifecycle"],dI="completed";function sc(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function m_(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function p_(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=m_(n.close_reason)??dI;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${sc(r)}`,gate:"resolution"})}return t}function f_(e){let t=[];for(let n of e){let r=m_(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 ${sc(r)}`,gate:"metadata"})}return t}function h_(e,t){return e.map(n=>{let r=hl(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){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 g_(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 ${sc(n.path)}`})}return t}function y_(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: ${oc.join(", ")}.`,g.USAGE);return new Set(cI)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(oc.includes(i)){n.add(i);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${oc.join(", ")}.`,g.USAGE)}return n}function w_(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 lI=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function uI(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=lI.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 v_(e){return typeof e=="string"&&e.trim().length>0}function mI(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 b_(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||v_(i.duplicate_of))continue;let a=uI(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:v_(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=mI(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 k_(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 E_(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function S_(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=E_(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(E_(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 x_(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 pI=/^[a-z][a-z0-9+.-]+:\/\//i;function Or(e){return pI.test(e.trim())}import fI from"node:fs/promises";import Se from"node:path";import{glob as hI}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 _I=["path","scope","note"],gI=["pattern","glob","path","scope","note"],yI=["path"],wI=["from","to"],vI=new Set(["note","scope"]);function I_(e){let t=e??"project";if(!za.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${za.join(", ")} (default: project).`,g.USAGE);return t}function cc(e){if(e.startsWith("```")||e.includes(`
67
+ `)||/^(?:[-*+]\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("=")||bl(e)}function bI(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function kI(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!cc(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&&bI(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 EI(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let a=kI(r);if(a!==void 0)return[a]}kl(r,"--add",`${t} path`,cc(r));let i=cc(r)?Yn(n,"--add"):{path:r};if(Xn(i,"--add",_I),!i.path)throw new y(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return[{path:i.path,scope:I_(i.scope),note:i.note?.trim()||void 0}]}):[]}function SI(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=Yn(n,"--add-glob");Xn(r,"--add-glob",gI);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:I_(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function xI(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=Yn(n,"--remove"),i=Object.keys(r).filter(a=>vI.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(Xn(r,"--remove",yI),!r.path)throw new y("--remove key/value form requires path=<value>",g.USAGE);return r.path}return n}):[]}function AI(e){return e?e.map(t=>{let n=Yn(t,"--migrate");Xn(n,"--migrate",wI);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 II(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 dc(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 RI(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 hI(i.pattern,{cwd:n,absolute:a,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),s=[...new Set(o.map(c=>dc(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 CI(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 TI(e){return`${e.path}::${e.scope}`}function lc(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function uc(e){return[...new Map(e.map(t=>[TI(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function $I(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 fI.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 OI(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 DI(e,t,n,r){let i=uc(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:lc(i)}async function A_(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 $I(t,e.workspaceRoot):void 0}}async function ba(e,t,n,r){let{metadataKey:i}=r,a=xl(),o=L(process.cwd(),n.path),s=Je(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=EI(u,r.bareNoun).map(A=>({...A,path:dc(A.path,s,c)})),_=SI(m),w=await RI(_,s,c),v=CI([...h,...w],t.note,h.length>0||_.length>0),E=xI(f).map(A=>dc(A,s,c)),k=AI(p);if(II(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 A_({id:A.id,artifacts:R,changed:!1,options:t,workspaceRoot:s})}let x=W(t.author,d.author_default),D=await ut({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=OI(Ae,v,E,k),_e=DI(Ae,we.adds,we.removes,r.supportsAppendStable&&t.appendStable===!0);_e.length>0?R[i]=_e:delete R[i];let He=!pd(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 A_({id:D.item.id,artifacts:S,changed:D.changedFields.includes(i),migrationsApplied:N,options:t,workspaceRoot:s})}function ka(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 R_(e,t,n){let r=await ba(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return ka(r,"docs")}import C_ 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 PI=32768;function mc(e){return xt(ze.normalize(e))}async function Ea(e){try{return await C_.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`${mc(n)}::${e.scope}`}function Sa(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)=>Sa(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))Sa(i,t?`${t}.${r}`:r,n)}function NI(e){let t=[];return Sa(e.metadata,"metadata",t),Sa(e.body,"body",t),t}function LI(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 MI(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,PI);for(let[s,c]of[[n,i.value],[r,o]]){s.lastIndex=0;for(let d of c.matchAll(s)){let l=LI(d[0]);!l||a.has(l)||(a.add(l),t.push({field:i.field,value:l}))}}}return t}async function jI(e,t,n=t){let r=ze.isAbsolute(e)?ze.resolve(e):ze.resolve(n,e),i;try{i=await C_.stat(r)}catch{return}if(!i.isFile())return;let[a,o]=await Promise.all([Ea(t),Ea(r)]);if(fe(a,o)){let s=ze.relative(a,o);return!s||s.startsWith("..")||ze.isAbsolute(s)?void 0:{path:mc(s),scope:"project"}}return{path:mc(r),scope:"global"}}async function FI(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>zn(c,t))),i=new Map,a=MI(NI(e)),o=new Map;await Promise.all([...new Set(a.map(c=>c.value))].map(async c=>{o.set(c,await jI(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 T_(e,t,n){let r=await ba(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return ka(r,"files")}async function UI(e,t){let n=await Ea(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 Ea(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 zI(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 $_(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function O_(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 HI(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(O_)}async function GI(e){if(e.explain)return Ku({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 WI(e){if([e.strictRead,e.noTruncate,e.explain,zd()].includes(!0))return null;let t=await yi(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Nl({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function qI(e){let t=[],n=await wi(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=HI({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 GI({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:O_(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:$_(s.item),files:s.files,...a?{traceability:a.explanations.get(s.item.id)}:{}})),...a?{traceability_receipt:a.receipt}:{}}}async function EH(e,t){let n=L(process.cwd(),t.path),r=Je(n);await ne(n);let i=await UI(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}=zI(e),d=await WI({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:$_(l.item),files:l.files}))}:qI({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 SH(e,t,n){let r=L(process.cwd(),n.path),i=Je(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 FI(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 ut({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=uc(N),Q=t.appendStable?R:lc(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 BI}from"node:fs";import xa 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 VI=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),pc=new Set(["--pm-path","--path","--author"]),JI={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"])},KI=new Set(["-p","--package"]),YI=new Set(["-c","--call"]),XI=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),ZI=new Set(["-C","--prefix","--userconfig","--cache"]),RH=new Set(["--cwd"]),CH=new Set(["--cwd"]),QI=new Set(["exec","x"]),TH=new Set(["run","run-script"]),$H=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function eR(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function tR(e,t=process.cwd()){let n=nR(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[r,...i]=n;if(D_(r)||P_(r,t))return i;if(r==="node"&&i[0]&&P_(i[0],t))return i.slice(1);let a=r==="npx"||r==="bunx"?fc(i):r==="pnpm"?aR(i):r==="npm"?oR(i):null;return a&&(D_(a.command)||iR(a.command))?a.args:null}var N_=(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 eR(a)){let c=tR(s),d=c?sR(c):null,l=d&&VI.has(d.subcommand)?cR(d.remaining,JI[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 nR(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 OH(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(pc.has(n)){t+=2;continue}t+=1;continue}return n}}function D_(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function rR(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 iR(e){let t=rR(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function P_(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=xa.resolve(t,e);try{return JSON.parse(BI(xa.join(xa.dirname(xa.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function fc(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(YI.has(r)){t+=1;break}t+=KI.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function L_(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 aR(e){let t=L_(e,XI);return t?.subcommand!=="dlx"?null:fc(t.args)}function oR(e){let t=L_(e,ZI);return!t||!QI.has(t.subcommand)?null:fc(t.args)}function sR(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(pc.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function cR(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("=")&&(pc.has(r)||t.has(r))&&(n+=1)}}import{execFile as lR}from"node:child_process";import{readFile as uR}from"node:fs/promises";import F_ from"node:path";import{promisify as mR}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 M_(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 hc=["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"],dR=new Set(hc);function jH(e){return vl(e,hc)}function FH(e,t){let n={},r=[];for(let[i,a]of Object.entries(e)){let o=i.toLowerCase();if(!dR.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: ${hc.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 pR=mR(lR),_c=1,fR="linked-test-trust.json";function gc(e){return F_.join(dd(e),fR)}function j_(){return{version:_c,acknowledged:{}}}async function yc(e){try{let t=JSON.parse(await uR(gc(e),"utf8"));return t.version!==_c||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?j_():{version:_c,acknowledged:t.acknowledged}}catch{return j_()}}async function wc(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 pR("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 vc(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function hR(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Wd(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 _R(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 YH(e,t,n){if(!e||e.length===0)return e;for(let i of e)M_(i);let r=vc();return _R(e,t,n,await wc(r))}function U_(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 XH(e,t,n){let r=await yc(e);return z_(t,n,r)}function z_(e,t,n){let r=U_(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||!hR(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 H_(e,t,n){let r=await yc(e);return t.map(i=>z_(i,n,r))}async function ZH(e,t,n){let r=await yc(e),i=t.filter(a=>typeof a.command=="string"&&a.command.length>0).map(U_);for(let a of i)r.acknowledged[a]={acknowledged_at:n};return await Vn(F_.dirname(gc(e))),await Z(gc(e),`${JSON.stringify(r,null,2)}
68
+ `),{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 Aa(e){return e.includeBody?lt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):wi(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 gR=5;async function yR(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 Tm(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 Ia(e,t,n){let r=await Xt(e,t);await yR(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:gR,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 Ra(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 wR(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function vR(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 bc(e,t=Qn()){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=wR(i.parent,n);o&&a.push(o),vR(i,r,n,t)}for(let[i,a]of r)r.set(i,[...new Set(a)].sort());return r}function kc(e,t,n=Qn()){let r=bi(e,o=>t?Rd(o,t):o==="closed"||o==="canceled",n),i=bc(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=>Ra(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 Ec(e){return Ut(e).replace(/\/+$/,"")}function Be(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 Sc(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9b5e620c-ce82-5e2d-9866-2de6882bbb0c")}catch{}})();var SR=["src","tests","docs"],xR=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],AR=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),IR=["resolution","expected_result","actual_result"],RR=["default","tracked-all","tracked-all-strict"],G_=["core","strict","custom"],$a=["off","warn","error"],Ic=["author","acceptance_criteria","estimated_minutes","close_reason"],B_=[...Ic,"reviewer","risk","confidence","sprint","release"],Rc=Array.from(new Set(B_)),CR={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"},TR={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"},$R={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"},OR={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"},DR={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"},PR=32*1024*1024,NR=1e4,Cc=40,Ve=5,LR=4096,MR=255,jR=ER(kR);function V_(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?V_(r):r);return t}function FR(e){return{...e,checks:e.checks.map(t=>({...t,details:V_(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 Da(e,t){return oi(e,t)??e}function Nr(e,t){return t.terminal_statuses.has(Da(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 Ca(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function UR(e){let t=zt(Qc),n={blocked_reason:zt(qr.blocked_reason),resolution:zt(qr.resolution),actual_result:zt(qr.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:Ca(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Ca(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Ca(i.resolution,n.resolution)?"default":"settings",actual_result:Ca(i.actual_result,n.actual_result)?"default":"settings"}}}function J_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(G_.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${G_.join(", ")}.`,g.USAGE)}function K_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if($a.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${$a.join(", ")}.`,g.USAGE)}function Y_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if($a.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${$a.join(", ")}.`,g.USAGE)}function zR(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>CR[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function HR(e,t,n){let r=zR(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Ic],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...B_],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:[...Ic],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var GR=new Set(["acceptance_criteria","estimated_minutes"]);function X_(e,t,n,r){return!r&&GR.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"?Da(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 Z_(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: ${RR.join(", ")}.`,g.USAGE)}function Q_(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=W_(n),a=W_(r),o=xe.relative(i,a);return o.length===0||!o.startsWith("..")&&!xe.isAbsolute(o)?n:r}function W_(e){try{return bR.native(e)}catch{return xe.resolve(e)}}function WR(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Dc(e,t,n){let r=t.length>0?xe.join(e,t):e,i;try{i=await Oc.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(AR.has(a.name))continue;await Dc(e,o,n);continue}a.isFile()&&n.push(Ut(o))}}async function Tc(e){let t=[];for(let n of SR)await Dc(e,n,t);for(let n of xR){let r=xe.join(e,n);try{(await Oc.stat(r)).isFile()&&t.push(Ut(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function eg(e){try{let{stdout:t}=await jR("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:PR,windowsHide:!0,timeout:NR}),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 qR(e,t){let n=new Set,r=Ec(Yc);r.length>0&&n.add(r);let i=Ec(xe.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((a,o)=>a.localeCompare(o))}function q_(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function BR(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await eg(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Tc(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Tc(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ae(e,t=Ve){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,Cc);return{values:n.values,truncated:n.truncated,total:e.length}}var VR={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},JR={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function KR(e){let t=e.missing_fields.map(n=>`${VR[n]} "${JR[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function tg(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"):Pm(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 ng(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 YR="validate_metadata_duplicate_issue_codes";function rg(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Ve,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:[`${YR}:${e.length}`]}}function XR(e,t,n){let r=Object.fromEntries(Rc.map(i=>[i,[]]));for(let i of e)for(let a of Rc)X_(i,a,t,n)&&r[a].push(i.id);return r}function ZR(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let a=t[i];a.length>0&&r.push(`${TR[i]}:${a.length}`)}return r.push(...n),r}function ig(e,t){let n={};for(let r of e.required_fields){let i=t[r],a=i?i.length:0,o=$R[r];n[o]=a}return n}function ag(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 QR(e,t,n,r){for(let i of t.required_fields){let a=n[i];if(!a||a.length===0)continue;let o=OR[i],s=DR[i];if(!o||!s)continue;let c=ae(a,r?a.length:Ve);e[o]=c.values,e[s]=c.truncated}}function og(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 sg(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 eC(e,t,n,r,i){let a=new Map(e.map(w=>[w.id,w])),o=t.profile==="strict",s=XR(e,n,o),c=b_(e,{configuredPrefixes:i}),d=rg(c,r),l=ZR(t,s,d.warnings),u=ig(t,s),m=ag(t,s,a),f=k_(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:[...Rc],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]),QR(p,t,s,r);let h=og(t,s,a),_=sg(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 tC(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Da(m.status,t))),a=[],o=[];for(let m of i){let f=IR.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:Ve,d=ae(a.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=a.map(m=>KR(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 cg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dg(e,t="pm",n=nd()){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=Be(a.blocked_by);s&&r.has(s)&&o.add(s),(a.dependencies??[]).filter(d=>{let l=Be(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Be(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>o.add(d));let c=Be(a.definition_of_ready);return ug(c??"",t).filter(d=>r.has(d)).forEach(d=>o.add(d)),[a.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function lg(e,t,n){let r=tu(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:Ve,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 ug(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${cg(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 mg(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 pg(e,t="pm"){let n=dg(e,t),r=mg(n),i=[...new Set(r.flat())].sort((o,s)=>o.localeCompare(s)),a=r.map(o=>Ra(o,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:a}}function fg(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 Oa(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function hg(e,t){let n=Oa(e).split("/").filter(Boolean),r=Oa(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function nC(e,t){let n=Oa(t),r=Oa(e),i=t.endsWith("/")?t:`${t}/`,a=e.startsWith(i),o=n.length>0&&n===r,s=hg(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 rC(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function iC(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=nC(e,s);c!==null&&rC(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 _g(e,t){return e.map(n=>{let r=fg(n),i=r==="docs_unowned"?"docs":"files",a=iC(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 gg(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function aC(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Be(e[n]);return i?r.some(a=>i.toLowerCase().includes(a)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function oC(e,t,n,r,i){let a=Be(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 sC(e,t,n,r){let i=Be(e.blocked_by),a=Be(e.blocked_reason),o=a?.toLowerCase(),s=Da(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 cC(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=aC(c,r);d.length>0&&s.closureLikeRows.push({id:c.id,fields:d});let l=Be(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(oC(c,u,i,a,n))),t){let m=sC(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 dC(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 Ta(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function xc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function lC(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=Ta("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),s=Ta("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=Ta("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=Ta("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=xc("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=xc("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=xc("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 yg(e){let t=Ut(e);return t.length>LR||t.split(/[\\/]/).some(n=>n.length>MR)}async function uC(e,t){let n=xe.isAbsolute(t)?t:xe.resolve(e,t);if(yg(n))return!1;try{let r=await Oc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return WR(r,["ENOENT","ENOTDIR"])}}async function mC(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 uC(t,a.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:i.id,path:s,link_kind:o})))}return n}function pC(e,t,n,r,i,a){let o=r==="tracked-all-strict",s=o&&!i,c=i||o,d=c?[]:qR(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>q_(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!q_(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 wg(e,t,n,r,i,a,o,s="pm"){let c=cC(e,t,i,a);dC(c);let d=pg(c.activeItems,s),l=kc(e,i),u=Li(i,e,o?Number.POSITIVE_INFINITY:Ve),m=[...lC(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}),...Mi(u)],f=o?Number.POSITIVE_INFINITY:Ve,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 vg(e,t,n,r,i,a,o=ge(ed.schema)){let s=await mC(e,t),c=new Map(e.map(R=>[R.id,R])),d=[...new Set(s.missingLinkedPaths)].sort((R,Q)=>R.localeCompare(Q)),l=await BR(t,r),u=pC(l,n,t,r,i,a),m=u.candidateFiles.filter(R=>!s.linkedProjectPaths.has(R)),f=_g(m,e),p=S_(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(gg(f),!1).values,N=on(x_(p),a),A=d_(w,p,R=>c.get(R),o,a?1/0:Cc);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:Cc,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 fC(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},a)=>{let o=t[a];if(o.trusted)return;let s=Sc(i.command??"");n.push(`${r.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${s}`)}),n}async function bg(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 wc(vc()),u=await H_(r,d.map(({linkedTest:x})=>x),l),m=fC(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=N_(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}:${Sc(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:Ve,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 hC(e,t){let n=ai(e.map(c=>({ref:c.id,version:ii(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:Ve,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:Xd,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 $c="pm validate auto-fix";async function kg(e,t,n){switch(e.kind){case"set_closed_at":await o_(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:$c};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 Ac(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Eg(e,t,n){let r=[],i=[],a=new Map;for(let o of e.filter(s=>Ac(s)===null))try{await kg(o,t,n),r.push(o)}catch(s){i.push({fix:o,error:s})}for(let o of e.filter(s=>Ac(s)!==null)){let s=Ac(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 T_(s.item_id,{remove:c,message:$c},t):await R_(s.item_id,{remove:c,message:$c},t),r.push(...o)}catch(d){i.push(...o.map(l=>({fix:l,error:d})))}}return{applied:r,failed:i}}var dW={applyValidateFix:kg,applyValidateFixes:Eg,attachValidateFixHints:tg,buildCommandReferencesCheck:bg,buildDependencyReferencesCheck:lg,buildCloseReasonBackfillRows:og,buildFilesCheck:vg,buildLifecycleCheck:wg,buildLifecycleDependencyGraph:dg,buildLifecycleParentGraph:bc,buildEstimateBackfillRows:sg,buildMetadataCounts:ig,buildMissingFieldOccurrences:ag,buildOrphanedPathRows:_g,classifyOrphanedPath:fg,collectDefaultProjectFileCandidates:Tc,collectTrackedGitFileCandidates:eg,detectLifecycleDependencyCycles:pg,detectLifecycleParentCycles:kc,escapeRegExp:cg,extractItemIds:ug,findLifecycleDependencyCycleComponents:mg,isMetadataFieldMissing:X_,linkedArtifactPathExceedsFilesystemLimits:yg,listFilesRecursive:Dc,resolveDependencyCycleSeverity:K_,resolveParentCycleSeverity:Y_,resolveFileScanMode:Z_,resolveLifecycleDependencyCycleSamplePath:Ra,resolveRequestedChecks:ng,resolveValidateMetadataProfile:J_,resolveWorkspaceRoot:Q_,sharedDirectoryPrefixLength:hg,summarizeOrphanedPathRows:gg,summarizeDuplicateIssueCodes:rg,toMeaningfulString:Be};function _C(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function gC(e,t,n,r){let i=await u_(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 sa(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 tt(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}`),_C(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 ot(e,t,n){n&&tg(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function yC(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 xu(e.pmRoot,e.items,r?1/0:Ve,e.sourceIncomplete);ot(t,i,n)}if(e.requestedChecks.has("metadata")){let i=eC(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let a=await a_(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,r?1/0:Ve);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",ot(t,i,n)}if(e.requestedChecks.has("resolution")){let i=tC(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,ot(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=wg(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,ot(t,i,n),ot(t,lg(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await vg(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,ot(t,i,n)}return e.requestedChecks.has("command_references")&&ot(t,await bg(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&ot(t,await Ia(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&ot(t,hC(e.items,r),n),e.requestedChecks.has("storage_integrity")&&ot(t,await gC(e.pmRoot,e.items,G(e.settings,z()).type_to_folder,e.settings),n),t}function wC(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...f_(t.closeReasonBackfillRows)),r.push(...p_(t.resolutionBackfillRows)),r.push(...h_(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...__(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...g_(t.staleLinkPruneRows)),r}async function vC(e,t,n,r,i,a){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=wC(e,t,n),{applicable:s,gated:c}=w_(o,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await Eg(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 Sg(e,t,n={}){Gd(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=y_(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=ng(e),l=[],u=await Aa({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 or(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=J_(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),h=HR(p,f,o.validation.metadata_required_fields),_=UR(o),w=K_(e.dependencyCycleSeverity),v=Y_(e.parentCycleSeverity),E=Z_(e.scanMode),k=Q_(a),x=await yC({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 vC(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:{...FR(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as bC}from"node:child_process";import{promisify as kC}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 EC=kC(bC),SC=16,xC=3e4;function AC(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 IC(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 RC(e,t,n,r){let i=IC(e,t),a=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Ud(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??xC),o.unref?.()})]);return AC(e,t.key,s)}finally{clearTimeout(o)}}function Ag(e,t,n,r){let i=e;for(let a of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new Ze(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[a]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(a=>typeof a=="string"))return i;throw new Ze(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function xg(e,t,n,r){let i=e.checks.find(a=>a.name===t);if(!i)throw new Ze(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:Ag(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function CC(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await EC("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function TC(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(SC,t.length)},async()=>{for(;r<t.length;){let a=r;r+=1;let o=t[a],s=await ct(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 ru(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await lt(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 CC(e,t.tree_id),items:a,history:t.include_history===!1?[]:await TC(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&&(_=ou(m.operation,void 0,void 0,{...m.parameters,full:!0},o),d.set(h,_));let w=await _;return{value:Ag(w,m.field,m.kind),population_size:a.length,cost:a.length}}if(m.kind==="validate"){l??=Sg({counts:!0},o);let h=await l;return xg(h,m.check,m.field,m.kind)}if(m.kind==="health"){u??=n_(o,{checkOnly:!0,full:!0});let h=await u;return xg(h,m.check,m.field,m.kind)}let f=t.providers?.[m.provider];if(f)return f(m);let p=gl(s,m.provider);if(!p)throw new TypeError(`assurance provider ${m.provider} is not registered`);return RC(p.runtime_definition,m,e,t.trigger??"sdk")}}}import{createHash as $C}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 Ig(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 OC(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 DC(e,t,n,r,i,a){let o=Object.fromEntries(Qa.map(f=>[f,0])),s=0,c=0,d=0,l=0,u=[],m=$C("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&&Qa.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 Rg(e,t,n={}){Kd(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=Bd(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}=DC(o,a,i,s,c,n.uncoveredOnly===!0),_=OC(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 PC}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0311387c-c7c3-598c-961c-489e8a94ad29")}catch{}})();var Pc,Cg=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],Nc=["measurement","assertion","gate"];function NC(e){if(Cg.includes(e))return e;throw fi({command_path:"assurance",token:e,allowed:Cg,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 LC(e){if(!e)return Hn("kind",`Assurance declaration kind is required. Expected: ${Nc.join(", ")}`,"pm assurance list measurement");if(Nc.includes(e))return e;throw new y(`Assurance declaration kind is required. Expected: ${Nc.join(", ")}`,g.USAGE)}function Tg(e){if(!e)return Hn("preset",`Assurance preset is required. Expected: ${sr.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(sr.includes(e))return e;throw new y(`Assurance preset is required. Expected: ${sr.join(", ")}`,g.USAGE)}function Lc(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 MC(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 jC(e){let[t,n,r]=await Promise.all([nr(e,"measurement"),nr(e,"assertion"),nr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function $g(e,t){return t===!0?{id:e.id}:e}async function FC(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 UC(e,t){let n=xo(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 Eu(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 zC(e,t,n){if(e==="presets"){if(t.preset??t.id)return Pi(Tg(t.preset??t.id),Lc(t));let i=sr.map(a=>{let o=Pi(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(()=>Xu(n,Tg(t.preset??t.id),Lc(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await Zu(await Lr(n,{resolve_tree:!1,trigger:"derive"}),Lc(t)),a=t.apply?await vn(()=>Qu(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 bo(n,"assertion",t.id);return vn(()=>em(n,r,t.enforcement,{author:t.author,message:t.message}))}async function HC(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([jC(t),Lr(t,{...n.workspace,tree_id:e.tree,trigger:i})]),s=await su(()=>wu(r,a,o,{trigger:i,dry_run:e.dry_run===!0}));return s.dry_run||await ku(t,s,{author:e.author,message:e.message}),s}function Og(e){throw e instanceof y?e:new y(e instanceof Error?e.message:"assurance risk request is invalid",g.USAGE)}function GC(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"?Ig(t):ti(t)}catch(n){return Og(n)}}function WC(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 qC(e,t,n){let r=C(t.policy),i=Pc?.pm_root===e?Pc:void 0,a=new Map(n.map(d=>[d.id,PC("sha256").update(C([qd(d),ei(d)])).digest("hex")])),o=i?.policy_serialized===r?i:void 0,s=o?WC(o,a):new Set,c=Vd(t.policy,o?n.filter(d=>s.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...s]}:{});return Pc={pm_root:e,policy_serialized:r,item_fingerprints:a,index:c},c}async function BC(e,t){let n=GC(e),r=await Lr(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?Jd(qC(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):Rg(n.policy,r.items,n)}catch(i){return Og(i)}}async function VC(e,t={},n={}){let r=NC(e.action),i=L(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return zC(r,e,i);if(r==="verdicts")return UC(e,i);if(r==="run")return HC(e,i,n);if(["risk","lineages"].includes(r))return BC(e,i);let a=LC(e.kind);if(r==="list")return nr(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 bo(i,a,o);if(r==="remove"){let l=await vn(()=>bu(i,a,o,{author:e.author,message:e.message}));return $g(l,e.idOnly)}let s=MC(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 FC(i,s)}:{}},d=await vn(()=>Ii(i,a,s,c));return $g(d,e.idOnly)}function qW(e,t,n){let r={...e,...t};return VC({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:xo(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 Na from"node:path";import Pa from"node:fs/promises";import Mc 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 JC=864e5;function KC(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 YC(e,t){let n;try{n=await Pa.readdir(e,{withFileTypes:!0})}catch(i){if(F(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let a=Mc.join(e,i.name),o;try{o=await Pa.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 Dg(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*JC,o=Mc.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await YC(o,s.warnings);for(let d of c){let l=Mc.join(o,d),u=`checkpoints/${d}`;s.scanned+=1,r?.onRead&&s.warnings.push(...await r.onRead(l));let m;try{m=await Pa.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=KC(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 Pa.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 jc from"node:fs/promises";import Pg 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 XC=1440*60*1e3,ZC=new Set(["committed","compensated"]);function QC(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 eT(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 ZC.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 tT(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],a=QC(await jc.readFile(e,"utf8")),o=eT(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 jc.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:o,warnings:i}}async function Ng(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*XC,o=Pg.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await jc.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=Pg.join(o,d),u=`transactions/sdk/${d}`,m=await tT(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"],nT=1440*60*1e3,rT=[{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 iT(e,t,n){let r=t.relativePath,i=Na.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 aT(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],a=[],o=Date.now()-nT;for(let s of n){let c=Na.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=Na.posix.join(s.relativePath,l),m=Na.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 oT(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 sT(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 fq(e,t={}){let n=L(process.cwd(),e.path);await ne(n);let r=await T(n),i=t.dryRun===!0,a=oT(t.scope),o=rT.filter(p=>a.includes(p.scope)),s=[],c=[],d=[];for(let p of o){let h=await iT(n,p,i);h.removed?s.push(p.relativePath):c.push(p.relativePath),d.push(...h.warnings)}if(a.includes("runtime")){let p=await aT(n,i);s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(a.includes("locks")){let p=await Dm(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 Ng(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 Dg(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=sT({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 cT}from"node:child_process";import dT from"node:path";import{promisify as lT}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 uT=lT(cT),Mg="@unbrained/pm-cli",mT="latest",pT={global:["--global"],project:[]};function Lg(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 Ma(e){return e.trim().toLowerCase()}function jg(e,t){let n=Ma(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"&&Ma(r)===n)}function fT(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 hT(e,t,n){try{let r=await uT(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(" ")}
69
+ ${a}`,g.GENERIC_FAILURE)}}function ja(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():mT}function La(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():Mg}async function _T(e,t){let n=e.commandRunner??hT,r=La(e),i=ja(e),a=`${r}@${i}`,o=["npm","install","-g",a];e.repair===!0&&o.push("--force");let s=rd(import.meta.url,["../../.."]),c={requested:!0,status:"planned",package:r,target:a,command:o,before_version:s,...r===Mg?{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 gT(e){return dT.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function yT(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!gT(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 wT(e,t){let n=yT(e,t);return e.kind!=="local"||await O(n)?n:await O(e.location)?e.location:n}function vT(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 Fg(e,t){let n=fT(e,t);return(await ye(n.selected_root)).state.entries.filter(r=>r.scope===e)}async function bT(e,t,n){let r=await Fg(e,t);return r.find(i=>jg(i,n.name))??r.find(i=>Ma(i.directory)===Ma(n.directory))}async function kT(e,t,n,r,i){let a=ja(t),o=await wT(e.source,a),s=vT(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 Ts(o,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await bT(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 ET(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 kq(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",...pT[Lg(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=Lg(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 _T(t,a):{requested:!1,status:"skipped",package:La(t),target:`${La(t)}@${ja(t)}`,command:["npm","install","-g",`${La(t)}@${ja(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await Fg(i,n):[];if(r&&(d=d.filter(m=>jg(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 kT(m,t,n,i,a));let u=ET(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 ST}from"node:crypto";import{isUtf8 as xT}from"node:buffer";import jr 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]="a049f799-3807-59b5-96de-51e900798779")}catch{}})();async function Ug(e){try{return(await jr.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(F(t))return[];throw t}}function AT(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 IT(e,t,n){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!xT(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 Kn(r).ok?AT(e,r,t.length,n):null}catch{return null}}async function Uc(e,t){if(!(await jr.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let n=Fc.join(e,"history"),r=await Ug(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=Fc.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=ST(t).update(u).digest("hex"),c.stream=IT(s,u,c.digest)}catch{}}if(C(r)!==C(await Ug(n)))throw new TypeError("attestation history inventory changed during read; retry");for(let[o,s]of i){let c=await jr.lstat(Fc.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 zc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hc(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 RT(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 CT(e){return e===null?!0:!zc(e)||!Hc(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 TT(e,t){return!zc(e)||!Hc(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)&&RT(e)&&(e.checkpoint_digest===null||Wn(e.checkpoint_digest,"sha256"))&&CT(e.last_maintenance)}function zg(e){if(!zc(e)||!Hc(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==to.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(!TT(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(no(C(i),t)!==r)throw new TypeError("History attestation rollup mismatch");return e}async function Hg(e={}){let t=Ce(e.hashAlgorithm),n=e.generatedAt??$();if(!Rt(n))throw new TypeError("Invalid history attestation timestamp");let r=await Uc(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:to.format,version:1,hash_algorithm:t,generated_at:n,streams:r.map(o=>o.stream)};return zg({...a,workspace_digest:no(C(a),t)})}async function Gg(e,t={}){let n=zg(e),r=await Uc(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 Wg 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 Bq(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 Wg.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 Gg(r,{pmRoot:t.path})}let n=await Hg({pmRoot:t.path,hashAlgorithm:Ce(e.hashAlgorithm)});if(e.output===void 0)return n;try{await Wg.writeFile(e.output,`${JSON.stringify(n,null,2)}
70
+ `,{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 qg(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 Bg(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 Vg(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 a2(e){let t=L(process.cwd(),e.path);await ne(t);let n=await T(t),r=G(n,z()),i=[],a=await Aa({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),o=await tt(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}),Ia(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=Vg(p),_=qg({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:Bg(_,t),reason:_},warnings:[...new Set(i)].sort((w,v)=>w.localeCompare(v)),generated_at:$()}}function o2(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(`
71
+ `)}var s2={commandForWorkspacePositionState:Bg,normalizeWorkspaceHistoryDrift:Vg,selectWorkspacePositionState:qg};import $T 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 Gc="index/manifest.json",Wc="search/embeddings.jsonl",OT="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function DT(e){return e.progress===!0||process.stderr.isTTY===!0}function de(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
72
+ `)}catch{}}function PT(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 NT(e,t,n,r){let i=[];return{candidates:await Ll(e,t,n,i,r),warnings:i}}async function Bc(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 $T.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 LT(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:Fl(e,{fields:n})}}var qn=ee;function MT(e){let t=z(),n=qn(e.search?.provider);if(!n)return null;let r=yl(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 jT(e){let t=z(),n=qn(e.vector_store?.adapter);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.upsert,s=i.delete;return{adapterName:a,...typeof o=="function"?{upsert:o}:{},...typeof s=="function"?{delete:s}:{}}}function qc(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 FT(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)=>qc(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(qc(s,`extension search provider "${e.name}" embed output at index ${a}`))}return i}function Jg(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function Kg(e,t,n){let r=n?Vt(n.name,Jg(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 UT(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function Yg(e,t,n,r,i,a,o,s){let c=r?.name??n?.name,d=Ul(c,e.search.embedding_corpus_max_characters).maxCharacters,l=co(e),u=i.map(p=>zl(p,{providerName:c,maxCharacters:d,fields:l})),m=[],f=null;if(r)try{m=await FT(r,e,u),f=Vt(r.name,Jg(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 Hl(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 zT(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 ql(e,o,{},a)}async function Xg(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 Wl(e,n)}}function HT(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function GT(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 WT(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Zn(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=vi(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 qT(e){let t=G(e.settings,z()),n=await NT(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 BT(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 Kg(e.settings,Zn(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(OT))}async function VT(e){let t=await wn(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=Kg(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(d=>d.metadata.id)),i=UT(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 Bc(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 JT(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await Bc(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 Yg(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:lo(r.vectors,"Reindex embeddings")}}async function KT(e){let t=await Yg(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=lo(n,"Reindex embeddings");if(!(!e.resetRequired&&(yn(e.ledgerEmbedding,r)||Vl(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let a=await JT(e);return n=a.vectors,r=a.embeddingIdentity,i=a.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:a.staleDocuments,vectorDimension:i,resetRequired:!0}}async function YT(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 Gl(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 XT(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:qc(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 ZT(e){de(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await KT({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 zT(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 Xg(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=XT(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await YT({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:Bl(t.embeddingIdentity,t.vectorDimension)}}async function QT(e){let t=await VT(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 Xg(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await ZT({...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 e$(e){let t=Fr.join(e.pmRoot,Gc),n=Fr.join(e.pmRoot,Wc),r=co(e.settings),i=e.documentsForKeywordArtifacts.map(o=>JSON.stringify(LT(o,e.mode,r))).join(`
73
73
  `);de(e.progressEnabled,"writing keyword artifacts"),await Z(t,`${JSON.stringify(e.manifest,null,2)}
74
74
  `),await Z(n,`${i}
75
- `);let a=[];if(e.mode!=="keyword")try{de(e.progressEnabled,"writing vectorization status ledger"),await Wl(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 Vq(e,t){let n=xT(e.mode),r=ET(e),i=e.full===!0;de(r,`start mode=${n}`);let a=L(process.cwd(),t.path);await ne(a);let o=fi(await T(a)).settings,s=null;try{s=await te(a,kl,o.locks.ttl_seconds,G(void 0,"pm-reindex"),!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms)}catch(c){throw c instanceof y&&c.exitCode===g.CONFLICT?new y("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",g.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=RT(o),d=CT(o),l=NT({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;de(r,"loading item corpus");let m=await LT({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;de(r,`loaded_items=${h.length}`);let _=$(),w=PT(u,_,h),v=Lr.join(a,Fc),S=Lr.join(a,Uc),k=u==="keyword"?await zc(a,p,o.schema,f):h,x=[],D={},E=null,b=DT(u);if(u==="keyword"&&await MT({pmRoot:a,settings:o,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let R=await GT({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,E=R.vectorizationEmbeddingMetadata}let N=await qT({pmRoot:a,mode:u,manifest:w,documentsForKeywordArtifacts:k,settings:o,vectorizationLedgerEntries:D,vectorizationEmbeddingMetadata:E,progressEnabled:r}),A=[...await X({path:v,scope:"project",op:"reindex:manifest"}),...await X({path:S,scope:"project",op:"reindex:embeddings"}),...await Yr({mode:u,total_items:h.length})];return de(r,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:Fc,embeddings:Uc},warnings:[...f,...x,...N,...A],generated_at:_}}finally{await s?.()}}export{M as a,$e as b,Xe as c,gn as d,nu as e,iu as f,Bt as g,uo as h,ny as i,fo as j,ho as k,cu as l,wn as m,Zn as n,go as o,by as p,fu as q,Qn as r,yo as s,Ei as t,wo as u,_u as v,gu as w,yu as x,ip as y,qD as z,uv as A,mv as B,et as C,xP as D,Nv as E,Ey as F,o$ as G,bu as H,Iy as I,A$ as J,Sb as K,CN as L,ON as M,DN as N,ur as O,PN as P,NN as Q,LN as R,MN as S,jN as T,FN as U,UN as V,HN as W,zN as X,WN as Y,GN as Z,ws as _,Is as $,vD as aa,_m as ba,Ri as ca,iO as da,P as ea,oe as fa,aO as ga,ko as ha,oO as ia,sO as ja,Ou as ka,cO as la,dO as ma,lO as na,Gy as oa,uO as pa,mO as qa,So as ra,pO as sa,fO as ta,bo as ua,hO as va,_O as wa,Pu as xa,gO as ya,By as za,Mu as Aa,IO as Ba,rr as Ca,RO as Da,Qy as Ea,ew as Fa,CO as Ga,tw as Ha,S_ as Ia,PO as Ja,Gu as Ka,x_ as La,uz as Ma,mz as Na,ir as Oa,$i as Pa,Bu as Qa,Vu as Ra,Ju as Sa,Ku as Ta,Qu as Ua,tm as Va,nm as Wa,am as Xa,Mt as Ya,b1 as Za,k1 as _a,S1 as $a,E1 as ab,N1 as bb,mh as cb,pa as db,rF as eb,vt as fb,iF as gb,aF as hb,_x as ib,vx as jb,Ah as kb,bw as lb,sm as mb,qs as nb,ZF as ob,QF as pb,Di as qb,Pi as rb,Xh as sb,XU as tb,Zh as ub,e_ as vb,t_ as wb,i_ as xb,o_ as yb,WI as zb,GI as Ab,_z as Bb,gz as Cb,yz as Db,wz as Eb,BI as Fb,VI as Gb,JI as Hb,vz as Ib,R_ as Jb,YI as Kb,C_ as Lb,uc as Mb,$_ as Nb,XI as Ob,ZI as Pb,QI as Qb,hc as Rb,_c as Sb,Tz as Tb,$z as Ub,Oz as Vb,TR as Wb,WW as Xb,yg as Yb,Dr as Zb,bg as _b,kg as $b,Sg as ac,$c as bc,jC as cc,xG as dc,JG as ec,nq as fc,Ng as gc,Lg as hc,Mg as ic,Aq as jc,Fq as kc,Uq as lc,Hq as mc,Vq as nc};
76
- //# sourceMappingURL=chunk-KNJR2WUO.js.map
75
+ `);let a=[];if(e.mode!=="keyword")try{de(e.progressEnabled,"writing vectorization status ledger"),await Jl(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 p2(e,t){let n=PT(e.mode),r=DT(e),i=e.full===!0;de(r,`start mode=${n}`);let a=L(process.cwd(),t.path);await ne(a);let o=gi(await T(a)).settings,s=null;try{s=await te(a,Il,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=MT(o),d=jT(o),l=WT({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;de(r,"loading item corpus");let m=await qT({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;de(r,`loaded_items=${h.length}`);let _=$(),w=GT(u,_,h),v=Fr.join(a,Gc),E=Fr.join(a,Wc),k=u==="keyword"?await Bc(a,p,o.schema,f):h,x=[],D={},S=null,b=HT(u);if(u==="keyword"&&await BT({pmRoot:a,settings:o,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let R=await QT({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 e$({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:Gc,embeddings:Wc},warnings:[...f,...x,...N,...A],generated_at:_}}finally{await s?.()}}export{M as a,$e as b,Ze as c,vn as d,su as e,du as f,Jt as g,fo as h,cy as i,go as j,yo as k,pu as l,kn as m,tr as n,vo as o,Iy as p,wu as q,nr as r,bo as s,Ii as t,ko as u,bu as v,ku as w,Eu as x,dp as y,rP as z,wv as A,vv as B,tt as C,MP as D,Gv as E,Ty as F,h$ as G,Au as H,Dy as I,N$ as J,$b as K,zN as L,WN as M,qN as N,fr as O,BN as P,VN as Q,JN as R,KN as S,YN as T,XN as U,ZN as V,QN as W,eL as X,tL as Y,nL as Z,ks as _,Ts as $,OD as aa,bm as ba,My as ca,$i as da,_O as ea,P as fa,oe as ga,gO as ha,xo as ia,yO as ja,wO as ka,Mu as la,vO as ma,bO as na,kO as oa,Zy as pa,EO as qa,SO as ra,Ao as sa,xO as ta,AO as ua,So as va,IO as wa,RO as xa,Fu as ya,CO as za,ew as Aa,Hu as Ba,FO as Ca,or as Da,UO as Ea,sw as Fa,cw as Ga,zO as Ha,dw as Ia,R_ as Ja,BO as Ka,Ku as La,T_ as Ma,EH as Na,SH as Oa,sr as Pa,Pi as Qa,Xu as Ra,Zu as Sa,Qu as Ta,em as Ua,im as Va,om as Wa,sm as Xa,lm as Ya,Ft as Za,D1 as _a,P1 as $a,N1 as ab,L1 as bb,V1 as cb,gh as db,_a as eb,hF as fb,kt as gb,_F as hb,gF as ib,Sx as jb,Rx as kb,$h as lb,Cw as mb,mm as nb,Js as ob,lU as pb,uU as qb,Li as rb,Mi as sb,n_ as tb,dz as ub,r_ as vb,a_ as wb,o_ as xb,d_ as yb,u_ as zb,XI as Ab,ZI as Bb,RH as Cb,CH as Db,TH as Eb,$H as Fb,eR as Gb,tR as Hb,nR as Ib,OH as Jb,D_ as Kb,iR as Lb,P_ as Mb,fc as Nb,L_ as Ob,aR as Pb,oR as Qb,sR as Rb,M_ as Sb,hc as Tb,jH as Ub,FH as Vb,wc as Wb,vc as Xb,YH as Yb,XH as Zb,ZH as _b,FR as $b,dW as ac,Sg as bc,Lr as cc,Ig as dc,Rg as ec,Cg as fc,Nc as gc,VC as hc,qW as ic,fq as jc,kq as kc,zg as lc,Hg as mc,Gg as nc,Bq as oc,a2 as pc,o2 as qc,s2 as rc,p2 as sc};
76
+ //# sourceMappingURL=chunk-VBTLX5SN.js.map