@unbrained/pm-cli 2026.9.27 → 2026.9.28

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 (127) hide show
  1. package/.claude-plugin/marketplace.json +4 -6
  2. package/CHANGELOG.md +26 -0
  3. package/dist/cli/help-json-payload.js +1 -1
  4. package/dist/cli/register-operations.js +1 -1
  5. package/dist/cli-bundle/bundle-manifest.json +154 -154
  6. package/dist/cli-bundle/chunks/{chunk-OKVDVERQ.js → chunk-35DME35A.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-AUS6USO4.js → chunk-A2G5OG6W.js} +2 -2
  8. package/dist/cli-bundle/chunks/chunk-CPOWTIIS.js +2 -0
  9. package/dist/cli-bundle/chunks/{chunk-7TAGYNFP.js → chunk-GLH2LNRH.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-3BTJ66CB.js → chunk-NBDB3SRC.js} +48 -48
  11. package/dist/cli-bundle/chunks/{chunk-JX6WCCHL.js → chunk-NEUIVBFO.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-6OJVQ7SW.js → chunk-OYCCWPBM.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-LKGQUZ5M.js → chunk-PLNNUAFZ.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-4SLLCDFL.js → chunk-PR4UAMI5.js} +8 -8
  15. package/dist/cli-bundle/chunks/{chunk-TSF2LPIH.js → chunk-UT7GRGHY.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-V5UGBYHN.js → chunk-VMJLM7P2.js} +62 -62
  17. package/dist/cli-bundle/chunks/{chunk-IEP3VAT5.js → chunk-YERBAGQD.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-ZFHJP7YD.js +29 -0
  19. package/dist/cli-bundle/chunks/{register-list-query-6PAJ4PBU.js → register-list-query-N6RP6PSP.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-mutation-RZCXZXYS.js → register-mutation-CY7JGQE6.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-operations-GK6VU2H2.js → register-operations-53HAD3QP.js} +2 -2
  22. package/dist/cli-bundle/chunks/{register-setup-ASEMNMBF.js → register-setup-NVX6374E.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-OJRX6G22.js → chunk-5KJXX2TZ.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-MILJCOFJ.js → chunk-6IVQPNYN.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-NETVXIH5.js → chunk-A5O3VYWV.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/chunk-AZA4AEOR.js +75 -0
  27. package/dist/cli-bundle/focused-chunks/chunk-BGWF6CMP.js +2 -0
  28. package/dist/cli-bundle/focused-chunks/{chunk-PDVL7QYU.js → chunk-BRLXKRI2.js} +15 -15
  29. package/dist/cli-bundle/focused-chunks/{chunk-SMADBUPL.js → chunk-DTLRXY77.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-6UNKK3UH.js → chunk-IJXZQE3D.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-NWRVNHAD.js → chunk-IWLMQLBO.js} +6 -6
  32. package/dist/cli-bundle/focused-chunks/chunk-K7GSZ7YZ.js +2 -0
  33. package/dist/cli-bundle/focused-chunks/{chunk-OJKJFDIG.js → chunk-ONDNR3VU.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-NZAG7OKB.js → chunk-OVVCXTIE.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-GZD4ZYIB.js → chunk-V7OPZRL6.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-LBDWUHQD.js → chunk-Y5Z3XNGY.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-QO4MTAEA.js → chunk-YZB7IPR6.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-DQ3MB7BO.js → chunk-ZMQTIS3L.js} +2 -2
  39. package/dist/cli-bundle/main.js +21 -21
  40. package/dist/cli-bundle/sdk-authoring.js +1 -1
  41. package/dist/cli-bundle/sdk-contracts.js +1 -1
  42. package/dist/cli-bundle/sdk-core.js +18 -18
  43. package/dist/cli-bundle/sdk-governance.js +1 -1
  44. package/dist/cli-bundle/sdk-graph.js +1 -1
  45. package/dist/cli-bundle/sdk-merge.js +51 -51
  46. package/dist/cli-bundle/sdk-query.js +1 -1
  47. package/dist/cli-bundle/sdk-runtime.js +1 -1
  48. package/dist/cli-bundle/sdk-testing.js +1 -1
  49. package/dist/cli-bundle/sdk.js +1 -1
  50. package/dist/core/diagnostics/remediation.js +1 -1
  51. package/dist/core/item/item-format.js +1 -1
  52. package/dist/core/store/settings.js +3 -3
  53. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  54. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  55. package/dist/sdk/completion/fish.js +3 -3
  56. package/dist/sdk/completion/zsh.js +3 -3
  57. package/dist/sdk/extension/copy-scope.d.ts +2 -2
  58. package/dist/sdk/extension/copy-scope.js +1 -1
  59. package/dist/sdk/extension/install-plan.js +1 -1
  60. package/dist/sdk/extension/install-runtime.js +2 -2
  61. package/dist/sdk/extension/static-inventory.js +1 -1
  62. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  63. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  64. package/dist/sdk/governance/health-merge-evidence.d.ts +18 -0
  65. package/dist/sdk/governance/health-merge-evidence.js +2 -0
  66. package/dist/sdk/governance/health.js +1 -1
  67. package/dist/sdk/merge/install.js +2 -2
  68. package/dist/sdk/output-projection.d.ts +1 -1
  69. package/dist/sdk/output-projection.js +1 -1
  70. package/dist/sdk/public-surface.json +1 -1
  71. package/dist/sdk/read-output-budget.d.ts +1 -1
  72. package/dist/sdk/read-output-budget.js +1 -1
  73. package/dist/sdk/read-output-contracts.js +1 -1
  74. package/dist/sdk/test/execution.d.ts +11 -0
  75. package/dist/sdk/test/execution.js +2 -2
  76. package/dist/sdk/test/parsers.d.ts +1 -1
  77. package/dist/sdk/test/parsers.js +1 -1
  78. package/dist/types.d.ts +3 -3
  79. package/dist/types.js +1 -1
  80. package/docs/AGENT_READ_AND_TEST_RECEIPTS.md +21 -0
  81. package/docs/CLAUDE_CODE_PLUGIN.md +12 -7
  82. package/docs/CONFIGURATION.md +2 -0
  83. package/docs/PACKAGE_EVIDENCE.md +18 -7
  84. package/docs/README.md +1 -0
  85. package/docs/TESTING.md +14 -3
  86. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +7 -3
  87. package/marketplace.json +4 -6
  88. package/package.json +5 -5
  89. package/packages/pm-beads/package.json +1 -1
  90. package/packages/pm-calendar/package.json +1 -1
  91. package/packages/pm-command-kit/package.json +1 -1
  92. package/packages/pm-digital-twin/package.json +1 -1
  93. package/packages/pm-governance-audit/package.json +1 -1
  94. package/packages/pm-guide-shell/package.json +1 -1
  95. package/packages/pm-kanban/package.json +1 -1
  96. package/packages/pm-lifecycle-hooks/package.json +1 -1
  97. package/packages/pm-linked-test-adapters/package.json +1 -1
  98. package/packages/pm-search-advanced/package.json +1 -1
  99. package/packages/pm-templates/package.json +1 -1
  100. package/packages/pm-todos/package.json +1 -1
  101. package/packages/pm-vcs/package.json +1 -1
  102. package/plugins/pm-claude/.claude-plugin/plugin.json +4 -2
  103. package/plugins/pm-claude/.mcp.json +1 -2
  104. package/plugins/pm-claude/README.md +7 -7
  105. package/plugins/pm-claude/package.json +2 -2
  106. package/plugins/pm-claude/{commands/pm-calendar.md → skills/pm-calendar/SKILL.md} +1 -0
  107. package/plugins/pm-claude/{commands/pm-close-task.md → skills/pm-close-task/SKILL.md} +1 -0
  108. package/plugins/pm-claude/{commands/pm-init.md → skills/pm-init/SKILL.md} +2 -1
  109. package/plugins/pm-claude/{commands/pm-list.md → skills/pm-list/SKILL.md} +2 -1
  110. package/plugins/pm-claude/{commands/pm-new.md → skills/pm-new/SKILL.md} +1 -0
  111. package/plugins/pm-claude/{commands/pm-search.md → skills/pm-search/SKILL.md} +1 -0
  112. package/plugins/pm-claude/{commands/pm-start-task.md → skills/pm-start-task/SKILL.md} +1 -0
  113. package/plugins/pm-claude/{commands/pm-status.md → skills/pm-status/SKILL.md} +1 -0
  114. package/plugins/pm-claude/{commands/pm-triage.md → skills/pm-triage/SKILL.md} +1 -0
  115. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  116. package/plugins/pm-codex/package.json +2 -2
  117. package/plugins/pm-codex/plugin.json +1 -1
  118. package/dist/cli-bundle/chunks/chunk-4UPZLUT2.js +0 -29
  119. package/dist/cli-bundle/chunks/chunk-LC6WEA5U.js +0 -2
  120. package/dist/cli-bundle/focused-chunks/chunk-6J2YCGSN.js +0 -75
  121. package/dist/cli-bundle/focused-chunks/chunk-E7LYK7V5.js +0 -2
  122. package/dist/cli-bundle/focused-chunks/chunk-KMPKKSA6.js +0 -2
  123. package/plugins/pm-claude/commands/pm-audit.md +0 -38
  124. package/plugins/pm-claude/commands/pm-developer.md +0 -38
  125. package/plugins/pm-claude/commands/pm-planner.md +0 -54
  126. package/plugins/pm-claude/commands/pm-release.md +0 -41
  127. package/plugins/pm-claude/commands/pm-workflow.md +0 -49
@@ -1,75 +0,0 @@
1
- import{a as Ho,c as zr,d as Hr,e as hl,g as _l,h as Go,i as gl,j as sn,k as an,l as yl,m as wl,n as qo,o as kl,p as cn,q as ln,r as Sl,s as El,t as Bo}from"./chunk-NETVXIH5.js";import{e as Xr,f as Xo,h as Zo}from"./chunk-DQ3MB7BO.js";import{B as jl,C as Jr,D as Fl,E as Yo,G as Ul,H as zl,J as Hl,K as Kr,M as Yr,a as cl,g as zo,i as ll}from"./chunk-E7LYK7V5.js";import{K as Zd}from"./chunk-6UNKK3UH.js";import{D as rs,E as di,Ha as Wd,Ia as Gd,Ma as qd,Na as Bd,T as ui,U as wd,V as is,W as Zn,Y as os,aa as $d,ba as Od,ca as Dd,da as Pd,ea as fi,f as dd,g as ud,ga as Nd,h as md,ha as Ld,ia as Md,ja as Ht,k as li,ka as jd,kb as Kd,la as _n,ma as Fd,mb as cs,na as ss,nb as Yd,o as Yn,oa as gn,ob as Xd,p as fd,pa as Ud,q as pd,qa as zd,r as Xn,ra as Hd,s as hd,sa as as,u as ns,v as _d,wb as ls,z as gd}from"./chunk-GZD4ZYIB.js";import{a as ul,b as on,c as Wo,d as ml,e as fl,f as at,g as Wr,h as pl,i as St}from"./chunk-QO4MTAEA.js";import{$ as Ft,Aa as od,Ab as ct,Bb as zt,C as q,Ca as fn,D as Wl,Da as Kn,Ea as sd,Eb as Td,Fa as ri,Fb as lt,G as Ee,Ga as Ut,H as Qo,Ha as fe,Ia as ii,Ja as ad,Ka as ts,La as oi,Ma as pn,N as Gl,Na as si,O as Zr,Oa as cd,Qa as xe,R as Qr,Ra as ld,S as ei,Sa as T,Ta as ai,Tb as Qn,U as ql,Ua as ci,V as De,Vb as pi,Wa as yd,X as xt,Y as Bl,Z as Vl,_ as Jl,aa as Kl,ac as Vd,bb as vd,cb as bd,dc as Jd,eb as kd,fa as Yl,fb as Sd,ga as es,gb as It,ha as ti,hb as Ed,ia as un,ib as xd,ka as ni,la as Xl,lb as Id,ma as Zl,mb as Ad,oa as Ql,qa as ed,rb as mi,sa as td,tb as Rd,ua as nd,vb as te,wa as mn,wb as Pe,xa as rd,xb as Ne,yb as Cd,za as id,zb as hn}from"./chunk-NWRVNHAD.js";import{b as nn,e as de,g as Oe,i as Se,j as Ye,n as _e,o as vl,p as Gr,r as bl}from"./chunk-LBDWUHQD.js";import{$ as g,$a as Nt,Aa as $e,Ab as Ke,Ba as Yc,Bc as Dl,Da as ee,Ga as Xc,Jc as H,Ka as Zc,Kb as dl,Mc as X,Oc as He,Pb as qr,Pc as Pl,Qa as Qc,Qb as xl,Qc as Vr,Ra as el,Rb as Vo,S as Wc,Sa as G,Sb as Jo,T as Gc,Tb as Ko,Td as C,Ud as Ml,V as qc,Vb as Il,Vd as dn,Wb as Al,Wd as Et,X as Bc,Xa as Jn,Xc as Nl,Xd as jt,Y as Fr,Ya as N,Yc as Xe,Z as Vc,Za as Ve,Zb as Rl,_a as Ur,_c as Ll,a as Mr,aa as y,ae as ce,bb as tl,cb as Lt,d as jr,eb as nl,ec as Cl,fb as rl,gb as il,ha as Jc,i as Uc,ka as Kc,l as zc,m as Hc,ma as Fo,ob as ol,pb as Mt,qb as R,ra as Vn,rb as sl,sa as $,sb as ke,ta as kt,ua as j,ub as Uo,va as K,vb as al,vc as Tl,w as jo,wa as ne,wb as rn,xc as Br,yb as Je,yc as $l,za as he,zc as Ol}from"./chunk-PDVL7QYU.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]="00d2200c-d308-51a6-acc4-8da90afaf6d6")}catch{}})();var L=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Ie=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 yn(e){try{return await e()}catch(t){throw t instanceof L?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Qd(e){try{return await e()}catch(t){throw t instanceof Ie?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as Mg}from"node:crypto";import jg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var wn=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]="00ad9b34-4feb-5812-8755-801869cce3ad")}catch{}})();var tu=1,Wt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],ds=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Fg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Ug=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,hi=30,_i=5e3,nu=4,zg=50;function dt(e,t){if(!Ug.test(e))throw new L(`${t} must be a stable lowercase id`)}function Hg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function er(e){let t=Fg.filter(i=>e[i]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function ms(e,t){return R(e)===R(t)}function ru(e,t){if(t.polarity==="equals")return ms(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 iu(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=>ru(r.observed,t)===(r.expected==="pass"))}function Wg(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!ms(e.value,t.value)}function Gg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||R(e.scope)!==R(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Wg(er(e),er(t))||n[t.enforcement]<n[e.enforcement]||r}function qg(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new L("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 L("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new L("items source equals/state requires field")}function Bg(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(n=>n!==void 0).length>1)throw new L("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 L("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 L("dependency_kind source source_kind_state must be present or missing")}function Vg(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new L("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 L("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 L("prose_edge_gap exemption selectors must not be empty")}}function fs(e){dt(e.id,"measurement.id"),e.max_cost!==void 0&&Hg(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new L(`measurement.source.kind must be one of ${ds.join(", ")}`);let n=Reflect.get(t,"kind");if(!ds.includes(n))throw new L(`measurement.source.kind must be one of ${ds.join(", ")}`);let r=t;if(r.kind==="items"&&qg(r),r.kind==="dependency_kind"&&Bg(r),r.kind==="prose_edge_gap"&&Vg(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new L(`${r.kind} source requires field`);return r.kind==="provider"&&(dt(r.provider,"provider source provider"),dt(r.key,"provider source key")),e}function ps(e){if(dt(e.id,"assertion.id"),dt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new L("assertion.owner_item_id is required");let t=er(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new L(`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 L("retired assertion requires retire_reason");e.scope.kind==="filter"&&dt(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 L("assertion negative control requires pass and fail cases");if(!iu(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function Jg(e){if(!Array.isArray(e.allowed_providers))throw new L("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)dt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Wt.includes(t))throw new L(`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 L(`gate provider policy trigger ${t} is invalid`)}}function ou(e){if(dt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new L("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new L("gate requires at least one assertion");for(let t of e.assertion_ids)dt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${Wt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!Wt.includes(t))throw new L(`gate trigger must be one of ${Wt.join(", ")}`);return e.provider_policy&&Jg(e.provider_policy),e}function vn(e){if(e.version!==tu)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(fs(r),t.has(`measurement:${r.id}`))throw new L(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(ps(r),t.has(`assertion:${r.id}`))throw new L(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){ou(r);let i=r.assertion_ids.filter(o=>!e.assertions.some(s=>s.id===o));if(i.length>0)throw new L(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new L(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of su(e))if(!n.has(r))throw new L(`${i.join(", ")} references missing measurement ${r}`);return e}function hs(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)hs(n,t)}function su(e){let t=new Map,n=(r,i)=>{let o=t.get(r)??[];o.push(i),t.set(r,o)};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=[];hs(r.source.expression,i);for(let o of i)n(o,`derived measurement ${r.id}`)}return t}function Kg(e,t){let n=e.assertion_ids.flatMap(o=>{let s=t.assertions.find(a=>a.id===o);return[s.measurement_id,...s.scope.kind==="filter"?[s.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let o=n.pop();if(r.has(o))continue;r.add(o);let s=t.measurements.find(a=>a.id===o);s.source.kind==="provider"?i.add(s.source.provider):s.source.kind==="derived"&&hs(s.source.expression,n)}return i}function tr(){return{version:tu,measurements:[],assertions:[],gates:[]}}function Yg(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 o=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?o:!o}return ms(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Xg(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 Zg(e,t){let n=[],r=Fo(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let o of i.dependencies??[]){let s=Fo(o.kind)??o.kind.trim().toLowerCase(),a=o.source_kind?.trim();s===r&&Xg(e,a)&&n.push(`${i.id}->${o.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Qg(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 o=Reflect.get(i,"text");typeof o=="string"&&t.push(o)}}}return t}function ey(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 us(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function ty(e){let t=new Map,n=new Set,r=[],i=/\b[a-z][a-z0-9]*-[a-z0-9]+\b/giu,o=0;for(let s of e){t.set(s.id.toLowerCase(),s.id);for(let a of s.dependencies??[])n.add(us(s.id,a.id));for(let a of[s.parent,s.blocked_by])typeof a=="string"&&n.add(us(s.id,a));for(let a of Qg(s)){let c=[...a.matchAll(i)].map(l=>l[0]);o+=c.length,r.push({holder_id:s.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:o}}function ny(e,t){let n=ty(t.items),r=new Map;for(let s of n.prose_mentions){let a=s.mentioned_ids.map(l=>n.canonical_ids.get(l.toLowerCase())).filter(l=>l!==void 0&&l!==s.holder_id),c=[...new Set(a)];for(let l of c){let d=us(s.holder_id,l);if(n.linked_pairs.has(d)||ey(e.exemptions??[],s.holder_id,l,s.segment))continue;let u=c.some(m=>m!==l);r.get(d)?.explicit===!0&&!u||r.set(d,{contributor:`${s.holder_id}->${l}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],o=i.map(s=>s.contributor).sort();return{value:o.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:o.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(s=>s.explicit).length,implicit_subject:i.filter(s=>!s.explicit).length}}}function ry(e,t){return{value:t.history.filter(r=>(e.op===void 0||r.op===e.op)&&(e.author===void 0||r.author===e.author)&&(e.harness===void 0||r.agent_harness===e.harness)&&(e.model===void 0||r.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function iy(e,t){let n=t.items.filter(r=>{let i=r[e.link],o=Array.isArray(i)&&i.length>0;return e.state==="present"?o:!o});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function oy(e,t){let n=e.source;return n.kind==="items"?Yg(n,t):n.kind==="dependency_kind"?Zg(n,t):n.kind==="prose_edge_gap"?ny(n,t):n.kind==="history"?ry(n,t):n.kind==="links"?iy(n,t):null}function au(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function 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 cu(e,t,n){let r=new Array(e.length),i=0,o=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let s=i;i+=1,r[s]=await n(e[s],s)}});return await Promise.all(o),r}async function lu(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let s=n.find(l=>l.id===e.measurement);if(!s)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await du(s,t,n,r,i);if(typeof a.value!="number")throw new TypeError(`derived measurement ${s.id} is not numeric`);let c=i.charged.has(s.id)?[]:[a.cost];return i.charged.add(s.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let o=await cu(e.operands,nu,s=>lu(s,t,n,r,i));return{value:sy(e.operator,o.map(s=>s.value)),costs:o.flatMap(s=>s.costs),population_size:Math.max(0,...o.map(s=>s.population_size)),contributors:[...new Set(o.flatMap(s=>s.contributors))]}}async function ay(e,t,n,r,i){fs(e);let o=Date.now(),s,a=[],c=0;if(e.source.kind==="derived"){let u=await lu(e.source.expression,t,n,[...r,e.id],i);s={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=oy(e,t);u!==null?s=u:(s=await t.external(e.source),c=1)}let l={units:s.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()-o},d=au([...a,l],Date.now()-o);if(e.max_cost!==void 0&&d.units>e.max_cost)throw new Ie(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${d.units}`);return{id:e.id,definition_fingerprint:`sha256:${Mg("sha256").update(R(e)).digest("hex")}`,value:s.value,population_size:s.population_size,cost:d,contributors:s.contributors??[],...s.partitions?{partitions:s.partitions}:{}}}function du(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let o=i.cache.get(e.id);if(o)return o;let s=ay(e,t,n,r,i).catch(a=>{if(a instanceof Ze&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},l=new Ze(a.message,c);throw l.cause=a,l}throw a});return i.cache.set(e.id,s),s}async function _s(e,t,n=[e]){return du(e,t,n,[],{cache:new Map,charged:new Set})}function cy(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==="monotone_nondecreasing",e-t.value)}function ly(e,t,n={}){ps(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:cy(t.value,r),verdict:i?"retired":ru(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:iu(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function dy(e,t,n,r){let i=Kg(e,t);if(i.size===0)return;let o=e.provider_policy,s=o?.triggers[r];if(!o||!s)throw new Ie(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let a=new Set(o.allowed_providers),c={low:0,medium:1,high:2};for(let l of i){if(!a.has(l))throw new Ie(`assurance gate ${e.id} refuses provider ${l}`);let d=n.provider_capabilities?.[l];if(!d)throw new Ie(`assurance provider ${l} has no declared capabilities`);if(c[d.cost_class]>c[s.max_cost_class])throw new Ie(`assurance gate ${e.id} refuses ${d.cost_class}-cost provider ${l} at trigger ${r}`);if(d.network&&!s.allow_network)throw new Ie(`assurance gate ${e.id} refuses network provider ${l} at trigger ${r}`)}}async function eu(e,t,n,r,i){try{return await _s(n,r,i)}catch(o){if(o instanceof Ze){let s=o.check?` check ${o.check}`:"",a=o.measurement_id??n.id,c=new Ie(`assurance gate ${e} assertion ${t} measurement ${a} source ${o.source_kind}${s} field ${o.field} could not resolve: ${o.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}});throw c.cause=o,c}throw o}}async function uu(e,t,n,r){vn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new Ie(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new Ie(`assurance gate ${e} does not declare trigger ${r.trigger}`);dy(i,t,n,r.trigger);let o=await cu(i.assertion_ids,nu,async c=>{let l=t.assertions.find(p=>p.id===c),d=t.measurements.find(p=>p.id===l.measurement_id),u=n;if(l.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(_=>!p.has(_.status))}}else if(l.scope.kind==="filter"){let p=l.scope.measurement_id,_=t.measurements.find(v=>v.id===p),h=await eu(i.id,l.id,_,n,t.measurements),w=new Set(h.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===l.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return ly(l,await eu(i.id,l.id,d,u,t.measurements),{owner_terminal:f})}),s=o.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=o.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:s?"block":a?"warn":"pass",exit_code:s?1:0,assertions:o,assertions_total:o.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:au(o.map(c=>c.cost),Math.max(0,...o.map(c=>c.cost.duration_ms)))}}function gi(e){return jg.join(e,"assurance.json")}async function mu(e){let t=await K(gi(e));return t===null?tr():yi(t)}function yi(e){try{return vn(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 wi(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function uy(e,t){e==="measurement"?fs(t):e==="assertion"?ps(t):ou(t)}async function nr(e,t){let n=structuredClone(wi(await mu(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function gs(e,t,n){let r=wi(await mu(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function vi(e,t,n,r={}){uy(t,n);let i=await T(e),o=q(r.author,i.author_default),s=await pn({pmRoot:e,filePath:gi(e),op:`assurance:${t}:put`,author:o,message:r.message,lockTtlSeconds:hi,lockWaitMs:_i,mutate:a=>{let c=a===null?tr():yi(a),l=wi(c,t),d=l.findIndex(m=>m.id===n.id),u=d<0?"created":"updated";if(t==="assertion"&&d>=0&&Gg(l[d],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new L(`loosening assertion ${n.id} requires a verified authorization_decision`)}return d<0?l.push(structuredClone(n)):l[d]=structuredClone(n),vn(c),{raw:`${JSON.stringify(c,null,2)}
2
- `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...s.result,changed:s.changed}}async function ys(e,t,n={}){let r=tr();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),vn(r);let i=await T(e),o=q(n.author,i.author_default),s=await pn({pmRoot:e,filePath:gi(e),op:"assurance:bundle:apply",author:o,message:n.message,lockTtlSeconds:hi,lockWaitMs:_i,mutate:a=>{let c=a===null?tr():yi(a),l=[],d=[],u=(m,f,p)=>{for(let _ of f){let h=m.find(w=>w.id===_.id);if(!h){m.push(structuredClone(_)),l.push(`${p}:${_.id}`);continue}if(R(h)!==R(_))throw new L(`assurance bundle refuses to replace divergent ${p} ${_.id}`);d.push(`${p}:${_.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),vn(c),{raw:`${JSON.stringify(c,null,2)}
3
- `,result:{changed:l.length>0,created_ids:l,unchanged_ids:d}}}});return{...s.result,changed:s.changed}}async function fu(e,t,n,r={}){let i=await T(e),o=q(r.author,i.author_default),s=await pn({pmRoot:e,filePath:gi(e),op:`assurance:${t}:remove`,author:o,message:r.message,lockTtlSeconds:hi,lockWaitMs:_i,mutate:a=>{let c=a===null?tr():yi(a);if(t==="measurement"){let u=su(c).get(n);if(u&&u.length>0)throw new L(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new L(`assurance assertion ${n} is referenced by gate`);let l=wi(c,t),d=l.findIndex(u=>u.id===n);if(d<0)throw new L(`assurance ${t} ${n} not found`);return l.splice(d,1),vn(c),{raw:`${JSON.stringify(c,null,2)}
4
- `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...s.result,changed:s.changed}}async function pu(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await T(e);await oi({pmRoot:e,op:"assurance:gate:verdict",author:q(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:hi,lockWaitMs:_i})}async function hu(e,t={}){let n=t.limit??zg;if(!Number.isInteger(n)||n<1||n>wn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${wn}`);return(await Ft(ii(e),fe)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.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]="0daf7c89-abc5-5c35-ba3f-9772a50408c0")}catch{}})();var rr={type:"string",minLength:1,maxLength:128,pattern:"\\S"},bi={type:"array",minItems:1,maxItems:Vo,items:rr},_u={...bi,items:{...rr,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},my={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,bi])),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:_u}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:bi}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:_u,authors:bi}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Vo,items:{type:"array",minItems:2,maxItems:2,items:rr}}}}]}}},UT={$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:xl,items:my}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42dee0a5-d003-5e44-8b2d-d74a23d3f2ce")}catch{}})();async function gu(e,t,n,r){let i=await It(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"]}:yu(i,t,n,r)}function fy(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function yu(e,t,n=5,r=!1){let i=[],o=new Map,s=e.policies.filter(h=>h.rule.kind==="require_fields"),a=s.filter(h=>h.subject?.operations===void 0),c=new Set,l=0,d=0,u=0,m=0,f=0,p=Rl(e);for(let h of t){let w=p({operation:"",author:"",before:h,after:h,completeness_only:!0});l+=+(w.decisions.length>0),d+=w.decisions.length,w.decisions.forEach(S=>c.add(S.policy_id));let v=w.decisions.filter(S=>!S.satisfied);if(v.length===0)continue;m+=1;let k=o.get(h.type)??{items:0,violations:0,missing_fields:0};k.items+=1;for(let S of v)u+=1,k.violations+=1,k.missing_fields+=S.missing_fields.length,S.effect==="refuse"&&(f+=1),i.length<n&&i.push({id:h.id,type:h.type,status:h.status,decision:S});o.set(h.type,k)}let _=r||f>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:_,ok:_==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:s.length,state_requirement_count:a.length,applicable_requirement_count:c.size,requirement_application_count:d,governed_items:l,ungoverned_items:t.length-l,contract_status:fy(s.length,t.length,l),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:u,refused_violations:f,missing_by_type:Object.fromEntries(o),violations:i,violations_truncated:i.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}import py 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]="f54fe358-8f4c-5bf4-ae2a-9c92cd08c953")}catch{}})();function hy(){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(([t,n])=>({id:`completeness-${t.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${t} work reaches completion.`,subject:{types:[t],statuses:["closed"]},rule:{kind:"require_fields",fields:[...n]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function bu(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 _y(e,t){let n=N(process.cwd(),e.path);await te(n);let r=await T(n);return{pmRoot:n,settings:r,author:q(t,r.author_default)}}function wu(e,t,n,r){if(e==="policy-mode")return Ko({...n,enforcement:t});let i=n.policies.filter(a=>a.id!==t);if(e==="policy-remove")return{...n,policies:i};let o=Jo(r.definition),s=Ko({...n,policies:[...i,o].sort((a,c)=>a.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(s,null,2)}
5
- `)>kd)throw new y("Policy registry exceeds its byte ceiling.",g.USAGE);return s}async function vu(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:wu(e,t,await It(r.pmRoot),n)};let i=await pn({pmRoot:r.pmRoot,filePath:py.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(o){let s=wu(e,t,Sd(o),n);return{raw:`${JSON.stringify(s,null,2)}
6
- `,result:s}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function gy(e,t,n){let r,i=await Td({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(o){let a=(await It(n.pmRoot)).policies.find(c=>c.id===t.policy);if(!a||a.rule.kind!=="approval")throw new y("--policy must name an approval rule.",g.USAGE);if(!a.rule.authors.includes(n.author))throw new y("This actor is not a declared approver.",g.CONFLICT);return await Ed(n.pmRoot,o.metadata.id),r={policy_id:a.id,policy_fingerprint:Il(a),content_fingerprint:Al(a,{...o.metadata,body:o.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...r,warnings:i.warnings}}}function yy(e,t){let n=bu(t),r=Jo({...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 s$(e,t,n={},r={}){if(!qr.includes(e))throw new y("Unknown workflow policy action.",g.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:hy()};let i=await _y(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await It(i.pmRoot)};if(e==="policy-put"){let d=yy(t,n.definition);return vu(e,d.id,{...n,definition:d},i)}if(!t?.trim())throw new y(`schema ${e} requires an operand.`,g.USAGE);if(["policy-remove","policy-mode"].includes(e))return vu(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 gy(t,n,i)}let o=G(i.settings,H()),s=await Pe(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,o.type_to_folder);if(!s)throw new y(`Item ${t} not found.`,g.NOT_FOUND);let{document:a}=await Ne(s,{schema:i.settings.schema}),c={...a.metadata,body:a.body},l=n.definition===void 0?c:{...c,...bu(n.definition)};if(l.id!==c.id)throw new y("Policy preview cannot change the item id.",g.USAGE);return{policy_result:!0,action:e,changed:!1,result:await xd(i.pmRoot,await It(i.pmRoot),{operation:"update",author:i.author,before:c,after:l,completeness_only:n.definition===void 0})}}import{createHash as Du}from"node:crypto";import ir from"node:fs/promises";import or from"node:path";import{Option as I$}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]="7ffd5046-9154-52e7-94ce-192b07b8ceae")}catch{}})();function wy(e,t){let n=[],r=new Set;for(let i of t.keys){if(!Object.hasOwn(e,i))continue;let o=e[i];if(o!=null){if(typeof o=="string"){n.push(o);continue}if(!Array.isArray(o)||!o.every(s=>typeof s=="string"))return;r.has(o)||(r.add(o),n.push(...o))}}return n.length>0?n.join("; "):void 0}function ki(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function F(e,t){return e[t]===!0?!0:void 0}function ut(e,t){return e[t]===!1?!0:void 0}function ku(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Su(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function Eu(e){let t=i=>zo(e,ki(Xr,i)),n=i=>ll(e,ki(Xo,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:wy(e,ki(Xo,"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:ku(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:F(e,"replaceDeps"),replaceTests:F(e,"replaceTests"),replaceFiles:F(e,"replaceFiles"),replaceDocs:F(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:F(e,"clearDeps"),clearComments:F(e,"clearComments"),clearNotes:F(e,"clearNotes"),clearLearnings:F(e,"clearLearnings"),clearFiles:F(e,"clearFiles"),clearTests:F(e,"clearTests"),clearDocs:F(e,"clearDocs"),clearReminders:F(e,"clearReminders"),clearEvents:F(e,"clearEvents"),clearTypeOptions:F(e,"clearTypeOptions")};return Su(r,e),r}function re(e,t){let n=ki(cl,t),r=zo(e,n);if(r!==void 0)return r;for(let i of n.keys){let o=e[i];if(Array.isArray(o)){let s=o.filter(a=>typeof a=="string");if(s.length>0)return s.join(",")}if(t==="ids"&&typeof o=="string")return o;if(typeof o=="number"&&Number.isFinite(o))return String(o)}}function vy(e){let t=F(e,"filterFilesMissing"),n=F(e,"filterDocsMissing");return{filterReviewerMissing:F(e,"filterReviewerMissing"),filterRiskMissing:F(e,"filterRiskMissing"),filterConfidenceMissing:F(e,"filterConfidenceMissing"),filterSprintMissing:F(e,"filterSprintMissing"),filterReleaseMissing:F(e,"filterReleaseMissing"),hasNotes:F(e,"hasNotes"),hasLearnings:F(e,"hasLearnings"),hasFiles:F(e,"hasFiles"),hasDocs:F(e,"hasDocs"),hasTests:F(e,"hasTests"),hasComments:F(e,"hasComments"),hasDeps:F(e,"hasDeps"),hasBody:F(e,"hasBody"),hasLinkedCommand:F(e,"hasLinkedCommand"),noNotes:ut(e,"notes"),noLearnings:ut(e,"learnings"),noFiles:ut(e,"files")??t,filterFilesMissing:t,noDocs:ut(e,"docs")??n,filterDocsMissing:n,noTests:ut(e,"tests"),noComments:ut(e,"comments"),noDeps:ut(e,"deps"),emptyBody:F(e,"emptyBody"),noLinkedCommand:ut(e,"linkedCommand")}}function xu(e){let t={status:re(e,"status"),type:re(e,"type"),tag:re(e,"tag"),priority:re(e,"priority"),deadlineBefore:re(e,"deadlineBefore"),deadlineAfter:re(e,"deadlineAfter"),updatedAfter:re(e,"updatedAfter"),updatedBefore:re(e,"updatedBefore"),createdAfter:re(e,"createdAfter"),createdBefore:re(e,"createdBefore"),today:F(e,"today"),recent:F(e,"recent"),ids:re(e,"ids"),assignee:re(e,"assignee"),assigneeFilter:re(e,"assigneeFilter"),parent:re(e,"parent"),sprint:re(e,"sprint"),release:re(e,"release"),limit:re(e,"limit"),offset:re(e,"offset"),noTruncate:ut(e,"truncate"),includeBody:F(e,"includeBody"),strictRead:F(e,"strictRead"),compact:F(e,"compact"),brief:F(e,"brief"),full:F(e,"full"),fields:re(e,"fields"),sort:re(e,"sort"),order:re(e,"order"),tree:F(e,"tree"),treeDepth:re(e,"treeDepth"),filterAcMissing:F(e,"filterAcMissing"),filterEstimatesMissing:ku(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:F(e,"filterResolutionMissing"),filterMetadataMissing:F(e,"filterMetadataMissing"),...vy(e)};return Su(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]="17883200-00ba-51ef-8a6b-ab0ce2ad2029")}catch{}})();var by=Symbol("pm.mcp-mutation-transport"),ky=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function Ei(e){return by in e}function xi(e,t){return Ei(e)?hd(t):ns(e,t)}function j$(e,t,n=[]){let r=ns(e,{...e,...t});for(let i of n)Reflect.deleteProperty(r,i);return r}function O(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function se(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 F$(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function bn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bs(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 U$(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:O(e,"limit")??O(t,"limit")}function z$(e){let t=O(e,"outputFormat");return{json:!0,quiet:!0,author:O(e,"author"),path:O(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:O(e,"outputInclude"),outputLimit:se(e,"outputLimit"),outputBudget:se(e,"outputBudget"),outputSession:O(e,"outputSession"),outputCursor:O(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Sy=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Au=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"]),Ey=new Set([...Au].filter(e=>e!=="file")),xy=new Set(["files","files-discover","docs","test","test-all"]),Ru=new Set(["comments","notes","learnings"]);function Iy(e,t){if(!(!Ru.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 Ay=new Set(["claim","release","start-task","pause-task","close-task"]),Ry={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun"],package:["dryRun"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Cy=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Cu(e,t=""){let n={},r=xy.has(t),i=t==="files"||t==="files-discover"||t==="docs",o=Ru.has(t)?Ey:Au;for(let[s,a]of Object.entries(e)){if(Array.isArray(a)&&Sy.has(s)){n[s]=a.join(",");continue}if(s==="note"&&i){n[s]=a;continue}if(typeof a=="string"&&o.has(s)){n[s]=[a];continue}if(typeof a=="string"&&r&&(s==="add"||s==="remove")){n[s]=[a];continue}n[s]=a}return Object.assign(n,Object.fromEntries(Object.getOwnPropertySymbols(e).map(s=>[s,Reflect.get(e,s)]))),n}function Ty(e,t,n){let r=O(e,"author");return r!==void 0?r:n!==void 0&&Ay.has(n)?O(e,"assignee")??O(t,"assignee"):void 0}function $y(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function H$(e,t){let n=bn(e.options)?e.options:void 0,r=Zc(e.options),i={},o=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of Ry[t??""]??[])o(c);for(let c of Cy)o(c);t!==void 0&&Ei(e)&&Iy(t,r);let s=Cu({...i,...r},t);if(t==="history-attest"&&Ei(e)&&(s.output!==void 0||typeof s.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 a=Ei(e)?e:n??e;return xi(a,$y(s,Ty(e,s,t)))}function W$(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 G$(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 Oy(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 q$(e){return!ky.has(Oy(e))}function B$(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function ks(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function V$(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[o,s]of Object.entries(e))n.has(o)||(r[o]=s);let i={...r,...t};return delete i.args,i}function J$(e,t){let n=xi(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function vs(e){return{type:se(e,"filterType"),tag:se(e,"filterTag"),priority:se(e,"filterPriority"),deadlineBefore:se(e,"filterDeadlineBefore"),deadlineAfter:se(e,"filterDeadlineAfter"),updatedAfter:se(e,"filterUpdatedAfter"),updatedBefore:se(e,"filterUpdatedBefore"),createdAfter:se(e,"filterCreatedAfter"),createdBefore:se(e,"filterCreatedBefore"),ids:rs(e.ids),assignee:se(e,"filterAssignee"),assigneeFilter:se(e,"filterAssigneeFilter")??se(e,"filterAssignee_filter"),parent:se(e,"filterParent"),sprint:se(e,"filterSprint"),release:se(e,"filterRelease"),limit:se(e,"limit"),offset:se(e,"offset")}}function ws(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return ks(e)}function Si(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function K$(e){let t=ws(e.kind),n=ws(e.exemptIsolate),r=ws(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Si(e.maxDepth),limit:Si(e.limit),after:O(e,"after"),direction:O(e,"direction"),maxPaths:Si(e.maxPaths),sample:Si(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 Tu(e){let t=xu(e);return e.ids!==void 0&&(t.ids=rs(e.ids)),t}function Y$(e){return{status:O(e,"filterStatus"),list:bn(e.list)?Tu(e.list):vs(e),reason:O(e,"reason"),resolution:O(e,"resolution"),expectedResult:O(e,"expectedResult")??O(e,"expected_result")??O(e,"expected"),actualResult:O(e,"actualResult")??O(e,"actual_result")??O(e,"actual"),validateClose:O(e,"validateClose")??O(e,"validate_close"),author:O(e,"author"),message:O(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:O(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var Dy=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 Iu(e){let t={};for(let[n,r]of Object.entries(e))Dy.has(n)||(t[n]=r);return $u(t)}function $u(e){let t=Cu(e,"update-many");for(let n of Xr)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return Eu(t)}function X$(e){if(bn(e.list)||bn(e.update)){let t=bn(e.update)?e.update:Iu(e),n=xi(e,$u(t));return{status:se(e,"filterStatus"),list:bn(e.list)?Tu(e.list):vs(e),update:_d(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:O(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:se(e,"filterStatus"),list:vs(e),update:xi(e,Iu(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:O(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]="fd8c4c35-98bb-5f3b-927d-8696125af703")}catch{}})();function Le(e,t){throw new y(e,g.USAGE,t)}var Py="2026-07-15T06:22:12.276Z",Ny=Date.parse(Py),Ly=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Ou=e=>typeof e=="string"?e:"",Pu=e=>{let t=e??{},n=Ou(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Ou(t.ts))>=Ny);return Ly[r][i]};function Nu(e,t,n=20,r=new Set,i=!1){let o=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}l+=1;let _=Pu(p);if(_!=="attributed"){if(d+=1,_==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}a[_]+=1,i&&_==="actionable_unknown"&&s.push({item_id:e,line:m+1}),o.length<c&&o.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:a.legacy_unknown+a.actionable_unknown>o.length,actionable_events:s}}var aO=(e,t,n=20,r=new Set)=>Nu(e,t,n,r);function Lu(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let o=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof o!="object"||o===null||!Array.isArray(o.events)))for(let s of o.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var sr=async(e,t=20,n=!1)=>{let r=or.join(e,"history"),i;try{i=(await ir.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let o=new Set,s=[],a=[],c=0,l=0,d=0,u=0,m=0,f=0,p="_workspace.jsonl",_=new Set;if(i.includes(p))try{_=Lu(await ir.readFile(or.join(r,p),"utf8"))}catch{_=new Set}for(let w of i){let v;try{v=await ir.readFile(or.join(r,w),"utf8")}catch{continue}let k=w.slice(0,-6),S=Nu(k,v,t-s.length,_,n);c+=1,l+=S.checked_events,d+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,f+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&o.add(k),s.push(...S.samples),n&&a.push(...S.actionable_events)}let h=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...o].sort((w,v)=>w.localeCompare(v)),samples:s,samples_truncated:h>s.length,...n?{actionable_events:a}:{}}};function My(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 jy(e){try{return Lu(await ir.readFile(or.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function Fy(e){return(e.item_id===fe||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function Uy(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Le(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Pu(i)!=="actionable_unknown"&&Le(`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:Du("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Mu(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Le("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Le("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Le("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let o=My(t.all_actionable===!0?(await sr(e,0,!0)).actionable_events:r),s=await jy(e),a=new Map;for(let m of o)if(Fy(m)||Le(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(m.item_id))try{a.set(m.item_id,(await ir.readFile(or.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Le(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=o.map(m=>Uy(m,s,a.get(m.item_id))),l=t.all_actionable===!0?"all_actionable":"events",d=Du("sha256").update(JSON.stringify({version:1,selection:l,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:l},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:d},completeCoordinates:c}}async function cO(e,t,n=50){return(await Mu(e,t,n)).plan}function zy(e,t){let n=e.length>0;return n&&t&&Le("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&&Le("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:Hy(e),all_actionable:t}}function Hy(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),o=r===fe||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!o||!Number.isSafeInteger(i)||i<1)&&Le(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function lO(e,t){let n=zy(ks(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Wy(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:O(t,"planFingerprint")??O(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:O(t,"attributedAuthor")??O(t,"attributed_author")??void 0,reviewer:O(t,"reviewer"),reason:O(t,"reason")})}async function Wy(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",o=await Mu(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:o.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Le("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Le("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()!==o.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 a=o.completeCoordinates.filter(({disposition:u})=>o.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:m})=>({item_id:u,line:m}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:g.NO_EFFECT,plan:o.plan};let c=await T(e),l=await oi({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:r}},message:i,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),d=o.plan.actionable_count>0&&o.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:a.length,...d,plan:o.plan,history_path:l.historyPath}}import{execFile as Gy}from"node:child_process";import ju from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1d4534aa-5a56-5a76-8971-aa3ba6c52e59")}catch{}})();function Fu(e,t){return new Promise((n,r)=>{Gy("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,o)=>{i?r(i):n(o)})})}function Uu(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(Uu(n),!n)throw new RangeError("Source line range must use start:end.");return n}function qy(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 By(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 o=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((s,a)=>s.localeCompare(a));n.set(i,o)}return n}async function Vy(e){let t=ju.relative(e.workspaceRoot,ju.resolve(e.workspaceRoot,e.sourcePath)),n=await Fu(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Fu(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:qy(n),commitItems:By(r),available:!0}}function Jy(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let o=i.source===t,s=o?i.target:i.source;if((e.visitedDepth.get(s)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(s,n);let a=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,s],kinds:[...e.current.kinds,o?i.kind:a.inverse??i.kind]};e.details.get(s)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function Ky(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let o=t.shift(),s=o.kinds.length;i!==void 0&&s>=i||s>=e.maxDepth||(i=Jy({current:o,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((o,s)=>o.nodes.join("\0").localeCompare(s.nodes.join("\0"))),r}function Yy(e,t,n){let r=Jd(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=Ky({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(a=>[a.id,a]))}),o=i[0];if(!o)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let s=[...new Set(i.map(a=>a.nodes.at(-1)))];return{status:s.length===1?"found":"ambiguous",nodes:o.nodes,kinds:o.kinds,alternative_decision_ids:s.slice(1)}}async function Xy(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await Vy({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function Zy(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 Qy(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function zu(e){Uu(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 Xy(e),r=Qy(n),i=new Map;for(let o of e.candidates){let s=[...n.commitLines.entries()].filter(([d])=>n.commitItems.get(d)?.includes(o.item.id)),a=s.reduce((d,[,u])=>d+u,0),c=Yy(o.item.id,e.corpus,t),l=Zy({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});i.set(o.item.id,{score:a*100+o.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(o.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...o.files.map(d=>({kind:"linked_file",reference:d.path})),...s.map(([d,u])=>({kind:"git_commit",reference:d.slice(0,12),contribution_lines:u}))],rationale:{value:o.item.value?.trim()||null,why_now:o.item.why_now?.trim()||null,outcome:o.item.outcome?.trim()||null,objective:o.item.objective?.trim()||null},decision_path:c,ambiguities:l})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7470da18-4b85-5090-8ede-7de708b1f4ff")}catch{}})();var ar=["software-delivery","research","agent-evaluation","operations"];function Hu(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 Ii(e,t,n,r,i){let o=`preset-${e}`,s=i.map(c=>({id:`${o}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),a=s.map(c=>Hu(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:s,assertions:a,gates:[{id:`${o}-readiness`,description:n,assertion_ids:a.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Ai(e,t){return e==="software-delivery"?Ii(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Ii(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Ii(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Ii(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function Wu(e,t,n,r={}){return ys(e,Ai(t,n).declarations,r)}async function Gu(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(o=>!n.has(o.status))};return await Promise.all(["files","tests","docs"].map(async o=>{let s={id:`derived-active-missing-${o}`,description:`Observed active items missing ${o} evidence.`,source:{kind:"links",link:o,state:"missing"}},c=(await _s(s,r)).value,l=Hu(`${s.id}-ceiling`,s.id,t,c,"observe"),d=`active-missing-${o}`;return{id:d,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[s],assertions:[l],gates:[{id:`derived-${d}`,description:`Observe the accepted ${o} evidence baseline.`,assertion_ids:[l.id],triggers:["ci","scheduled"]}]}}}))}function qu(e,t,n={}){return ys(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 Bu(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 vi(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Ku from"node:fs/promises";import{createRequire as ew}from"node:module";import Ae 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]="a0014621-9e3d-5620-8f36-081811054843")}catch{}})();function Vu(e,t){let n=Ae.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Ae.sep}`)&&!Ae.isAbsolute(n))return n.split(Ae.sep).join("/");let r=Ae.resolve(e),i=0xcbf29ce484222325n;for(let s=0;s<r.length;s+=1)i^=BigInt(r.charCodeAt(s)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Ae.basename(Ae.dirname(e))}/package.json`}function tw(e){return e.includes(`${Ae.sep}.pnpm${Ae.sep}`)?"pnpm":e.includes(`${Ae.sep}node_modules${Ae.sep}`)?"npm":"other"}async function Ju(e){try{let t=JSON.parse(await Ku.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 Ss(e){try{return await Ku.realpath(e)}catch{return Ae.resolve(e)}}async function Yu(e,t,n=$e(import.meta.url,["../../.."])){let r=await Ss(t),i=await Ss(Ae.join(n,"package.json")),o=await Ju(i),s=new Map;o!==void 0&&s.set(i,{version:o,path:Vu(i,r),layout:"host",consumers:["pm-cli-host"]});for(let l of e)try{let d=ew(l.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await Ss(d),m=await Ju(u);if(m===void 0)continue;let f=u,p=s.get(f);if(p){p.consumers.includes(l.name)||(p.consumers.push(l.name),p.consumers.sort((_,h)=>_.localeCompare(h)));continue}s.set(f,{version:m,path:Vu(u,r),layout:tw(u),consumers:[l.name]})}catch{}let a=[...s.values()].sort((l,d)=>l.path.localeCompare(d.path)),c=o===void 0?[]:a.filter(l=>l.version!==o);return{host_version:o??null,copies:a,mismatches:c,warnings:c.map(l=>`extension_host_pm_cli_version_skew:${o}:${l.version}:${l.consumers.join("+")}`)}}import Es from"node:fs/promises";import xs 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]="86c82880-d6c1-5d03-b786-222421f1146d")}catch{}})();var Xu=8388608,nw=new Set(["resolved","failed"]),rw=[{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 Is(e){return rw.find(t=>t.matches(e))?.kind}function Zu(e){let t=new Map,n=0,r=0;return{entries:e.map(o=>{let s=Qe(o.agent_provenance)?o.agent_provenance:void 0;if(s===void 0||!Xl(o).ok)return o;let a={},c=!1;for(let[d,u]of Object.entries(s)){let m=Qe(u)?Is(u.value):void 0;if(m===void 0){a[d]=u;continue}c=!0,r+=1;let f=o.agent_harness??"unknown",p=`${f}\0${d}\0${m}`,_=t.get(p)??{harness:f,dimension:d,kind:m,count:0};_.count+=1,t.set(p,_)}if(!c)return o;n+=1;let l={...o};return Object.keys(a).length===0?delete l.agent_provenance:l.agent_provenance=a,Zl(o,l,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((o,s)=>o.harness.localeCompare(s.harness)||o.dimension.localeCompare(s.dimension)||o.kind.localeCompare(s.kind))}}}async function Qu(e){let t=[];for(let n of await em(e)??[])try{let r=await Es.readFile(xs.join(e,"history",n),"utf8");for(let i of r.split(`
8
- `)){if(i.trim().length===0)continue;let o=tm(i);if(o===null||!Qe(o.agent_provenance))continue;if(Object.values(o.agent_provenance).some(a=>Qe(a)&&Is(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function em(e){try{return(await Es.readdir(xs.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function iw(e,t,n){let r;try{r=await Es.open(xs.join(e,"history",t),"r");let i=(await r.stat()).size,o=Math.min(i,Math.max(0,n)),s=Buffer.alloc(o),{bytesRead:a}=await r.read(s,0,o,0),c=s.subarray(0,a).toString("utf8"),l=a>=i,d=c.lastIndexOf(`
9
- `),u=c;return l||(u=d===-1?"":c.slice(0,d+1)),{content:u,bytesRead:a,complete:l}}catch{return null}finally{await r?.close()}}function tm(e){try{let t=JSON.parse(e);return Qe(t)?t:null}catch{return null}}function ow(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=Qe(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([s,a])=>{if(!Qe(a))return;let c=Is(a.value);if(!c)return;let l=`${r}\0${s}\0${c}`,d=n.get(l)??{harness:r,dimension:s,kind:c,count:0};d.count+=1,n.set(l,d)}),!Qe(e.context))return;let o=e.context.agent_provenance_outcomes;Qe(o)&&Object.entries(o).forEach(([s,a])=>{if(!Qe(a)||typeof a.resolver!="string"||!nw.has(String(a.status)))return;let c=`${r}\0${s}\0${a.resolver}`,l=t.get(c)??{harness:r,dimension:s,resolver:a.resolver,attempts:0,successes:0};l.attempts+=1,a.status==="resolved"&&(l.successes+=1),t.set(c,l)})}function sw(e,t,n,r,i,o){let s=i;for(let a of e.split(`
10
- `)){if(a.trim().length===0)continue;if(s>=r)return{eventsRead:s,truncated:!0};s+=1;let c=tm(a);if(c===null){o.malformed_events+=1;continue}if(typeof c.ts=="string"&&Et(c.ts)){let l=new Date(c.ts).toISOString();(o.earliest_event_at===null||l<o.earliest_event_at)&&(o.earliest_event_at=l),(o.latest_event_at===null||l>o.latest_event_at)&&(o.latest_event_at=l)}ow(c,t,n)}return{eventsRead:s,truncated:!1}}function aw(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 nm(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:Xu,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,o=0,s=0,a=!1,c=await em(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await iw(e,u,Math.max(0,Xu-s));if(m===null){n.unreadable_sources+=1;continue}s+=m.bytesRead;let f=sw(m.content,r,i,t,o,n);if(o=f.eventsRead,f.truncated){a=!0;break}if(!m.complete){a=!0;break}}let l=[...r.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.resolver.localeCompare(m.resolver)),d=[...i.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.kind.localeCompare(m.kind));return n.bytes_read=s,n.events_read=o,n.truncated=a,n.complete=!a&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:l,sample:n,invalid_values:d,warnings:aw(l,d,n.complete),events_read:o,truncated:a}}import cw 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]="cd8981b8-f6f7-5911-9951-799e68cecb9b")}catch{}})();function As(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=xe(e.settings);if(n.ownership_enforcement==="strict")throw new y(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,g.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function lw(e){let t=await K(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 Pe(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 Ne(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 Ri(e){let t=e.writeHistoryRaw??ne;try{await t(e.historyPath,e.nextHistoryRaw),await es(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await cw.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await es(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function rm(e){let t=[...As({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await ce(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let r=await lw({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(r),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await n()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7bab0f96-b67f-5523-9d1f-7426e1d58fbd")}catch{}})();async function im(e){let{subject:t,settings:n,operation:r,options:i}=e,o=await Jl(t.historyPath,t.id);if(o.raw===null)throw new y(`No history stream exists for ${t.id}.`,g.NOT_FOUND);if(o.entries.length===0)throw new y(`No history entries exist for ${t.id}; nothing to ${r.slice(8)}.`,g.USAGE);let s=t.located?await Ne(t.located,{schema:n.schema}):null,a=q(i.author,n.author_default),c=await e.transform({raw:o.raw,entries:o.entries,verification:Kn(o.entries),loadedItem:s,author:a}),l=Kn(c.rewrittenEntries);if(!l.ok)throw new y(`${r} produced an invalid rewritten chain (${l.errors.join(", ")}).`,g.GENERIC_FAILURE);let d=c.changed&&!i.dryRun?await rm({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:o.raw,currentItemRawBeforeLock:s?.raw??null,operation:r,author:a,force:i.force,itemDocument:s?.document??null,applyRewrite:async u=>{await c.beforeWrite?.(),c.applyRewrite?await c.applyRewrite(u):await Ri({historyPath:t.historyPath,nextHistoryRaw:Ut(c.rewrittenEntries),historyRawUnderLock:u.historyRawUnderLock})},applyPostRewrite:c.afterWrite??(async()=>X({path:t.historyPath,scope:"project",op:`${r.replace("-","_")}:history`}))}):[];return c.report({verification:l,warnings:d})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77ccea6e-a118-53df-94b7-a740bb3d7681")}catch{}})();function Ci(e,t,n=25){let r=e.definitions.filter(s=>s.roles.length===0).map(s=>s.id).sort((s,a)=>s.localeCompare(a)),i=new Set(r),o=t.filter(s=>{let a=vl(s.status,e);return a!==void 0&&i.has(a)}).map(s=>s.id).sort((s,a)=>s.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:o.length,affected_item_ids:o.slice(0,n),affected_item_ids_truncated:o.length>n}}function Ti(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}import Cs from"node:fs/promises";import ue from"node:path";import dw from"node:readline/promises";import{stdin as uw,stdout as $i}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]="f0c60332-623f-52c0-b217-acb15fcd2218")}catch{}})();var eD=["ask","add","skip","status"],mw=["AGENTS.md","CLAUDE.md"],fw=["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,Ts=1,hw="<!-- pm-cli:agent-guidance:start:",_w=`<!-- pm-cli:agent-guidance:start:v${Ts} -->`,Rs="<!-- pm-cli:agent-guidance:end -->",lr="Add workflow guidance later: pm init --agent-guidance add";var gw=()=>dw.createInterface({input:uw,output:$i});function kn(e,t){let n=ue.relative(e,t);return n.length===0?ue.basename(t):n.split(ue.sep).join("/")}function om(e){return e.endsWith(`
11
- `)?e:`${e}
12
- `}function yw(e){return e.includes(`\r
13
- `)?`\r
14
- `:`
15
- `}function sm(e){let t=e.indexOf(hw);if(t===-1)return null;let n=e.indexOf(Rs,t);return n===-1?null:{start_index:t,end_index:n+Rs.length}}function ww(e){return sm(e)!==null}function vw(e,t="<your project test command>"){return[_w,"## 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.","",Rs,""].join(e)}function am(e,t="<your project test command>"){let n=yw(e),r=vw(n,t),i=sm(e);if(i){let a=e.slice(i.end_index),c=a.startsWith(`\r
16
- `)?a.slice(2):a.startsWith(`
17
- `)?a.slice(1):a,l=om(`${e.slice(0,i.start_index)}${r}${c}`);return{next_content:l,changed:l!==e}}let o=e.length===0?"":e.endsWith(`
18
- `)?`
19
- `:`
20
-
21
- `,s=om(`${e}${o}${r}`);return{next_content:s,changed:s!==e}}async function cm(e){if(await $(ue.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Cs.readFile(ue.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=bw(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 $(ue.join(e,"pnpm-lock.yaml"))?"pnpm test":await $(ue.join(e,"bun.lock"))||await $(ue.join(e,"bun.lockb"))?"bun run test":await $(ue.join(e,"yarn.lock"))?"yarn test":"npm test"}function bw(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 kw(e,t){let n=ue.dirname(e);return ue.basename(e)==="pm"&&ue.basename(n)===".agents"?ue.dirname(n):ue.resolve(t,e)}function Sw(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 Ew(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 xw(e){let t=gw();try{$i.write(`
22
- Agent guidance check
23
- `),$i.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 $i.write(`
25
- `),Ew(n,!0)}finally{t.close()}}function lm(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:Ts,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 dm(e){let t=[],n=await cm(e);for(let r of mw){let i=ue.join(e,r),o=await $(i);if(!o){t.push({file_path:i,exists:o,has_guidance:!1,has_marker:!1});continue}let s=await Cs.readFile(i,"utf8"),a=s.toLowerCase(),c=fw.filter(d=>a.includes(d)),l=ww(s);t.push({file_path:i,exists:o,has_guidance:l||c.length>=pw,has_marker:l,outdated:l&&am(s,n).changed})}return t}function Sn(e,t){e.includes(t)||e.push(t)}function Iw(e,t){let n=lm(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function um(e,t=ue.dirname(e)){let r=await $(e)?await Cs.readFile(e,"utf8"):"",i=am(r,await cm(t));return i.changed?(await ne(e,i.next_content),{changed:!0,warnings:await X({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function Aw(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=>kn(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>kn(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>kn(e.projectRoot,t.file_path))}}async function Rw(e,t,n){return e?await dm(n):t}function cr(e,t,n){e.state={...e.state,...n,template_version:Ts,last_checked_files:t}}async function mm(e,t){if(t.presentBefore)return;let n=await um(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Cw(e,t){t||(e.warnings.push("agent_guidance:missing"),Sn(e.nextSteps,lr))}function Tw(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"),Sn(e.nextSteps,lr)}async function $w(e,t){await mm(e,t),cr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Ow(e,t){e.state.declined&&cr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Dw(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Sn(e.nextSteps,lr)}async function Pw(e,t){if(e.prompted=!0,await xw(t.targetRelativePath)){await mm(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"),Sn(e.nextSteps,lr)}function Nw(e){e.warnings.push("agent_guidance:missing_non_interactive"),Sn(e.nextSteps,lr)}async function Lw(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Cw(n,t.presentBefore),n):t.mode==="skip"?(Tw(n,t.checkedFiles),n):t.mode==="add"?(await $w(n,t),n):t.presentBefore?(Ow(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Dw(n),n):t.interactive?(await Pw(n,t),n):(Nw(n),n)}async function fm(e){let t=kw(e.pm_root,e.cwd),n=await dm(t),r=Sw(n,t),i=kn(t,r),o=n.map(u=>kn(t,u.file_path)),s=n.some(u=>u.has_guidance),a=await Lw(lm(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:i,checkedFiles:o,presentBefore:s,projectRoot:t});if(e.mode==="add")for(let u of n.filter(m=>m.outdated)){let m=await um(u.file_path,t);a.applied||=m.changed,a.warnings.push(...m.warnings)}let c=Iw(e.settings,a.state);n=await Rw(a.applied,n,t);let l=n.filter(u=>u.outdated).map(u=>kn(t,u.file_path));return l.length>0&&(a.warnings.push(`agent_guidance_outdated:${l.join(",")}`),Sn(a.nextSteps,"pm init --agent-guidance add")),{summary:Aw({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:a.prompted,applied:a.applied,skipped:a.skipped,state:a.state}),warnings:a.warnings,next_steps:a.nextSteps,settings_changed:c.changed}}import vt from"node:fs/promises";import ve from"node:path";import dr from"node:fs/promises";import{createHash as Mw}from"node:crypto";import hm 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]="d876d1ab-2de0-5c32-b999-721038adafcd")}catch{}})();var $s=new Set([void 0,...Wl]),_m=11,jw="history-drift-cache.json";function gm(e){return hm.join(e,"runtime",jw)}async function Fw(e){try{let t=await dr.readFile(gm(e),"utf8"),n=JSON.parse(t);return n.version!==_m||n.history_item_hash_version!==ti||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!$s.has(r.hash_algorithm)||!un.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&un.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}async function Uw(e,t,n,r,i){let o=ii(e),s;try{s=await dr.stat(o)}catch(l){return j(l)||i.unreadableStreams.push(fe),!1}let a=i.missingStreams.length,c=await ym({itemId:fe,historyPath:o,stat:s,cached:t[fe],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(fe),c.verification.chainOk||i.chainMismatches.push(fe),n[fe]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.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(a),c.cacheDirty)}function zw(e){return Mw("sha256").update(e).digest("hex")}function Hw(e){return!$s.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!un.includes(e.item_hash_version)}async function Ww(e){let t=await dr.readFile(e,"utf8"),n=zw(t);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 o=fn(r),s=r.some(Hw),a=r[r.length-1],c=$s.has(a.hash_algorithm),l=a.item_hash_version,d=l!==void 0&&un.includes(l),u=d?l:o.item_hash_version;return{latestAfterHash:i,hashAlgorithm:c?Ee(a.hash_algorithm):void 0,identityDiscontinuities:td(r),chainOk:o.ok,versionSkew:s,latestHashComparable:c&&u!==void 0&&(!s||d||l===void 0),contentHash:n,itemHashVersion:u??ti}}function Gw(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function pm(e,t,n){try{let r=await Ww(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function qw(e,t){return e!==null&&e.contentHash===t.content_hash&&e.latestAfterHash===t.latest_after_hash&&e.chainOk===t.chain_ok&&e.versionSkew===(t.version_skew===!0)&&e.latestHashComparable===t.latest_hash_comparable&&e.itemHashVersion===t.item_hash_version&&e.hashAlgorithm===t.hash_algorithm}async function ym(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Gw(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await pm(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let r=await pm(e.itemId,e.historyPath,e.accumulator);return{verification:r,cacheDirty:!qw(r,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&&un.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function Bw(e,t,n,r){let i,o;try{i=Lt(e,t.id),o=await dr.stat(i)}catch(d){return(j(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await ym({itemId:t.id,historyPath:i,stat:o,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!s.verification)return s.cacheDirty;s.verification.identityDiscontinuities.length>0&&(r.identityDiscontinuities??=[]).push(...s.verification.identityDiscontinuities.map(d=>({...d,item_id:t.id}))),s.verification.versionSkew&&r.versionSkews.push(t.id),s.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:s.verification.contentHash,latest_after_hash:s.verification.latestAfterHash,chain_ok:s.verification.chainOk,version_skew:s.verification.versionSkew,latest_hash_comparable:s.verification.latestHashComparable,item_hash_version:s.verification.itemHashVersion,hash_algorithm:s.verification.hashAlgorithm};let{body:a,...c}=t;return s.verification.latestHashComparable&&(Ql({metadata:c,body:a},s.verification.itemHashVersion,s.verification.hashAlgorithm).includes(s.verification.latestAfterHash)||r.hashMismatches.push(t.id)),s.cacheDirty}async function Vw(e,t){if(!(t.unreadableStreams.includes(fe)||t.chainMismatches.includes(fe)||t.versionSkews.includes(fe)))try{let n=await ad(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(fe)}}async function Gt(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},o=(await Fw(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:o,nextEntries:s,verifyCacheHitByContent:c};for(let m of t)await Bw(e,m,l,r)&&(a=!0);let d=await Uw(e,o,s,c,r);if(a||=d,await Vw(e,r),a||Object.keys(o).length!==Object.keys(s).length){let m=gm(e);try{await dr.mkdir(hm.dirname(m),{recursive:!0}),await ne(m,JSON.stringify({version:_m,history_item_hash_version:ti,entries:s}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.versionSkews,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[fe]:[]])].sort((m,f)=>m.localeCompare(f));return{...r,driftedItems:u}}import ur from"node:fs/promises";import Oi 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]="84aca8e9-b9a8-59dd-8e11-aa9f67184ec4")}catch{}})();function Jw(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:o,ttl_seconds:s}=n;return typeof r!="string"||typeof i!="string"||typeof o!="string"||typeof s!="number"||!Number.isFinite(s)?null:{id:r,owner:i,created_at:o,ttl_seconds:s}}function wm(e,t,n){let r=Jw(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 o=n-i,s=Math.floor(o/1e3),a=o>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:s,stale:a,reason:a?"expired":"active"}}}async function vm(e,t){let n=t??Date.now(),r=Oi.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await ur.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(s){if(j(s))return i;throw s}for(let s of o){let a;try{a=await ur.readFile(Oi.join(r,s),"utf8")}catch(l){if(j(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=wm(s,a,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function bm(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Oi.join(e,"locks"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},a;try{a=(await ur.readdir(o)).filter(l=>l.endsWith(".lock")).sort()}catch(c){if(j(c))return s;throw c}for(let c of a){s.scanned+=1;let l=Oi.join(o,c),d=`locks/${c}`;if(r?.onRead){let f=await r.onRead(l);s.warnings.push(...f)}let u;try{u=await ur.readFile(l,"utf8")}catch(f){if(j(f)){s.scanned-=1;continue}s.warnings.push(`lock_unreadable:${c}`),s.retained.push(d),s.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=wm(c,u,i);if(m.detail==="unparseable_json"){s.warnings.push(`lock_unparseable:${c}`),s.retained.push(d),s.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){s.warnings.push(`lock_invalid_timestamp:${c}`),s.retained.push(d),s.entries.push(m.entry);continue}if(m.detail==="active"){s.retained.push(d),s.entries.push(m.entry);continue}if(!n){try{await ur.unlink(l)}catch(f){if(!j(f)){s.warnings.push(`lock_remove_failed:${c}`),s.retained.push(d),s.entries.push(m.entry);continue}}if(r?.onWrite){let f=await r.onWrite(l);s.warnings.push(...f)}}s.removed.push(d),s.entries.push(m.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]="a236314b-1a3b-5499-bed3-364a2cb034a5")}catch{}})();var Kw=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:"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 Os(e){if(typeof e!="string")return;let t=e.trim();for(let n of Kw)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Ds(e){let t={};for(let n of e){let r=Os(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function km(e){return Object.values(Ds(e))}import $t from"node:fs/promises";import Te 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]="f7999053-cf48-5588-b8c8-570789086dac")}catch{}})();var Yw=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function En(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Br(t.extensionName));for(let h of t.extensionNames??[])n.add(Br(h));let r=h=>n.size===0||n.has(Br(h)),i=(h,w)=>Sm(h.filter(v=>r(v.name)).map(w)),o=(h,w)=>Sm(h.filter(v=>r(v.name)).flatMap(w)),{registrations:s,commands:a,parsers:c,preflight:l,services:d,renderers:u,hooks:m}=e,f=o(s.relationship_kinds??[],h=>h.definitions.map(w=>w.kind)),p=u.overrides.filter(h=>r(h.name)&&((h.commands?.length??0)>0||h.resultDiscriminator!==void 0)).map(h=>({format:h.format,commands:[...h.commands??[]],result_discriminator:h.resultDiscriminator!==void 0})).sort((h,w)=>h.format.localeCompare(w.format)),_=i(s.assurance_providers??[],h=>h.definition.id);return{capabilities:$l(e,t),commands:i(s.commands,h=>h.command),command_overrides:i(a.overrides,h=>h.command),command_handlers:i(a.handlers,h=>h.command),hooks:Yw.filter(([h])=>m[h].some(w=>r(w.name))).map(([,h])=>h),flag_commands:i(s.flags,h=>h.target_command),item_types:o(s.item_types,h=>h.types.map(w=>w.name)),item_fields:o(s.item_fields,h=>h.fields.map(w=>w.name)),...f.length>0?{relationship_kinds:f}:{},migrations:o(s.migrations,h=>typeof h.definition.id=="string"?[h.definition.id]:[]),profiles:i(s.profiles,h=>h.profile.name),importers:i(s.importers,h=>h.importer),exporters:i(s.exporters,h=>h.exporter),search_providers:i(s.search_providers,h=>h.definition.name),vector_store_adapters:i(s.vector_store_adapters,h=>h.definition.name),..._.length>0?{assurance_providers:_}:{},parser_overrides:i(c.overrides,h=>h.command),service_overrides:i(d.overrides,h=>h.service),renderer_overrides:i(u.overrides,h=>h.format),...p.length>0?{renderer_ownership:p}:{},preflight_overrides:l.overrides.filter(h=>r(h.name)).length,preflight_ownership:l.overrides.filter(h=>r(h.name)).map(h=>({commands:[...h.commands??[]]}))}}function Sm(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import lb from"node:path";import{mkdir as db}from"node:fs/promises";import{access as uv,readFile as Li,realpath as qt,writeFile as mv}from"node:fs/promises";import{constants as fv}from"node:fs";import{execFile as pv}from"node:child_process";import Z from"node:path";import{promisify as hv}from"node:util";import{readFile as Xw,writeFile as Zw}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]="5b131b40-e139-5a7d-a6ef-633fe2cbee64")}catch{}})();var xm="# pm-cli:runtime-cache:start",Ps="# pm-cli:runtime-cache:end",Im=".agents/pm",Ns=["runtime/","search/","locks/","transactions/","checkpoints/"],Qw=["search/eval-queries.json"];async function Em(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 Am(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function Ls(e){let t=e.replaceAll("\\","/");return mr.isAbsolute(e)||t===".."||t.startsWith("../")}function ev(e=Im){let t=Am(e);return[xm,...Ns.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Qw.map(n=>`!${t}/${n}`),Ps].join(`
26
- `)}async function xD(e,t={}){let n=mr.join(e,".gitignore"),r=Im;if(t.pmRoot!==void 0){let d=Am(mr.relative(mr.resolve(e),mr.resolve(t.pmRoot)));if(Ls(d))return{path:n,changed:!1};d.length>0&&(r=d)}let i="";try{i=await Em(()=>Xw(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&j(d)))throw d}let o=i.indexOf(xm),s=i.indexOf(Ps),c=(o>=0&&s>=o?`${i.slice(0,o)}${i.slice(s+Ps.length)}`:i).trimEnd(),l=`${c.length>0?`${c}
27
-
28
- `:""}${ev(r)}
29
- `;return l===i?{path:n,changed:!1}:(await Em(()=>Zw(n,l,"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]="8d1a6b35-70e8-5a61-8ce6-3bea9ed8170b")}catch{}})();var tv="PM_SOURCE_CONTEXT_ACCESS",nv="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Rm(e){let t=e[tv],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[nv]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}import{execFile as rv}from"node:child_process";import iv from"node:path";import{promisify as ov}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]="725f175b-c548-5700-8e85-ea0b5dce3747")}catch{}})();var xn=ov(rv);function We(){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 Ms(e,t){try{return(await xn("git",["config","--local",...t==="core.bare"||t==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",t],{cwd:e,env:We(),timeout:1e4})).stdout.trim()}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code===1)return;throw n}}async function Cm(e){if(await Ms(e,"extensions.worktreeConfig")==="true")return"--worktree";let{stdout:t}=await xn("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"],{cwd:e,env:We(),timeout:1e4}),[n,r]=t.trim().split(/\r?\n/);if(n===r)return"--local";let i=iv.join(r,"config.worktree");for(let o of["core.bare","core.worktree"]){let s=await Ms(e,o);s===void 0||o==="core.bare"&&s!=="true"||(await xn("git",["config","--file",i,o,s],{cwd:e,env:We(),timeout:1e4}),await xn("git",["config","--local","--unset-all",o],{cwd:e,env:We(),timeout:1e4}))}for(let o of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(let s of["name","driver"]){let a=`merge.${o}.${s}`,c=await Ms(e,a);c!==void 0&&await xn("git",["config","--file",i,a,c],{cwd:e,env:We(),timeout:1e4})}return await xn("git",["config","--local","extensions.worktreeConfig","true"],{cwd:e,env:We(),timeout:1e4}),"--worktree"}import Tm from"node:fs";import Di 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]="7ab9180f-dfcb-579d-bc0c-dbba2e4ad77e")}catch{}})();var $m="@unbrained/pm-cli";var Us=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,zs="2026.8.31";function Pi(e){let t=e.match(Us);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function Hs(e,t){let n=Pi(e),r=Pi(t);if(!n||!r)return null;for(let i=0;i<n.length;i+=1){let o=n[i]-r[i];if(o!==0)return Math.sign(o)}return 0}function js(e){return Hs(e,zs)!==-1?3:2}function Fs(e){try{let t=JSON.parse(Tm.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function sv(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=>sv(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(r=>{let i=Hs(zs,r.version);return i!==null&&(r.inclusive?i!==1:i===-1)}))}}function cv(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let r=n[$m],i=typeof r=="string"?r.trim():"",o=/^[<!]/u.test(i)?void 0:i.match(Us)?.[0];if(!o)return[];let s=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(i),a=av(i);return[{version:o,constraint:s?"exact":a.bounded?"range":"minimum",...s?{}:{declaration:i},history_epoch_compatible:s?Hs(o,zs)!==-1:a.compatible}]})}function lv(e){let n=Fs(Di.join(e,"package-lock.json"))?.packages;if(typeof n!="object"||n===null)return;let r=n["node_modules/@unbrained/pm-cli"];if(typeof r!="object"||r===null)return;let i=r.version;return typeof i=="string"?i:void 0}function dv(e,t){try{let n=Tm.readFileSync(Di.join(e,t),"utf8").split(/\r?\n/u),r=n.findIndex(c=>c.includes($m));if(r<0)return;let i=n[r].match(/^\s*/u)[0].length,o=[n[r]];for(let c=r+1;c<n.length;c+=1){let l=n[c],d=l.trim(),u=l.match(/^\s*/u)[0].length;if(d.length>0&&u<=i)break;o.push(l)}return o.join(`
30
- `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??o[0].match(Us)?.[0]}catch{return}}function Om(e){let t=[],n=Fs(Di.join(e,"package.json"));n&&t.push(...cv(n).map(s=>({...s,source:"package.json"})));let i=Fs(Di.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof i=="string"&&Pi(i)&&t.push({version:i,source:"installed-package",constraint:"exact",history_epoch_compatible:js(i)===3});let o=lv(e);o&&Pi(o)&&t.push({version:o,source:"package-lock.json",constraint:"exact",history_epoch_compatible:js(o)===3});for(let s of["pnpm-lock.yaml","yarn.lock"]){let a=dv(e,s);a&&t.push({version:a,source:s,constraint:"exact",history_epoch_compatible:js(a)===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]="8f999825-ace7-55cd-b83c-8c6c4b94fd9f")}catch{}})();var Mi=hv(pv),Ni="# pm-cli:merge-drivers:start",Lm="# pm-cli:merge-drivers:end",In="# pm-cli:merge-drivers:v2:start",Ws="# pm-cli:merge-drivers:v2:end",_v="merge-fence";function Dm(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function gv(){let e=$e(import.meta.url,["../../.."]),t=process.execPath,n=await qt(process.execPath);for(let r of(process.env.PATH??"").split(Z.delimiter)){if(!Z.isAbsolute(r))continue;let i=Z.join(r,Z.basename(process.execPath));try{if(await uv(i,fv.X_OK),i!==n&&await qt(i)===n){t=i;break}}catch{}}return`${Dm(t)} ${Dm(Z.join(e,"dist","cli.js"))}`}var Mm=[{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 yv(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=Rm(e.environment),o=!!(n&&r),s=t===void 0&&o&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let a=N(e.cwd,t);return{pm_root:a,workspace_start:a,source_coordinates_available:o,source_context_selected:!1,source_policy:i}}return s?{pm_root:Z.resolve(r),workspace_start:Z.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:o?N(e.cwd,".agents/pm"):N(e.cwd),workspace_start:e.cwd,source_coordinates_available:o,source_context_selected:!1,source_policy:i}}async function tt(e){try{let{stdout:t}=await Mi("git",["rev-parse","--show-toplevel"],{cwd:e,env:We(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await qt(t.trim())}catch{return null}}async function jm(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 Gs(e,t){return Z.relative(e,t).replaceAll("\\","/")}function et(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Pm(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 wv(e,t,n){if(Om(t).filter(o=>o.constraint==="exact").some(o=>o.version!==n))return!1;let i=await tt(e);if(i!==null&&i!==await qt(t)){let o=await Promise.all([i,t].map(async s=>{let a=await Mi("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:s,env:We(),timeout:1e4});return qt(a.stdout.trim())}));if(o[0]===o[1])return!1}return!0}async function vv(e,t,n){let r=Pm(e,0);if(r===null||e[r.nextOffset]!==" ")return!1;let i=Pm(e,r.nextOffset+1);if(i===null||e.slice(i.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(Z.basename(r.value))||Z.basename(i.value)!=="cli.js"||Z.basename(Z.dirname(i.value))!=="dist"||!await $(r.value)||!await $(i.value))return!1;try{let o=Z.dirname(Z.dirname(i.value)),s=JSON.parse(await Li(Z.join(o,"package.json"),"utf8")),a=typeof s.bin=="string"?s.bin:s.bin?.pm;return await wv(o,n,s.version)?s.name==="@unbrained/pm-cli"&&a==="dist/cli.js":!1}catch{return!1}}function qs(e,t){let n=e.length>0?`${e}/`:"",r=[`${et(`${n}**/*.toon`)} merge=pm-item-toon`,`${et(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${et(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${et(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${et(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${et(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${et(`${n}settings.json`)} merge=pm-json`),r.push(`${et(`${n}**/*.json`)} merge=pm-json`),r.push(`${et(`${n}extensions/**`)} -merge`),r.push(`${et(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function Nm(e,t,n){let r=e.indexOf(t),i=e.indexOf(n);return r>=0&&i>r?`${e.slice(0,r)}${e.slice(i+n.length)}`:e.replace(t,"").replace(n,"")}async function Fm(e,t,n){let r=Z.join(e,".gitattributes"),i="";try{i=await Li(r,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&j(l)))throw l}let o=[In,...t,Ws].join(`
31
- `),a=Nm(Nm(i,In,Ws),Ni,Lm).trimEnd(),c=`${a.length>0?`${a}
32
-
33
- `:""}${o}
34
- `;return c===i?{path:r,changed:!1}:(n||await mv(r,c,"utf8"),{path:r,changed:!0})}function An(e){let t=G(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function ji(e,t){let n=Z.resolve(e),r=null,i="",o=n;for(let v=0;v<8;v+=1){let k=Z.join(o,".gitattributes");try{let x=await Li(k,"utf8");if(x.includes(In)||x.includes(Ni)){r=o,i=x;break}}catch{}let S=Z.dirname(o);if(S===o)break;o=S}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=Z.join(r,".gitattributes"),a=i.includes(In),c=a?In:Ni,l=a?Ws:Lm,d=i.indexOf(c),u=i.indexOf(l),m=u>d?i.slice(d+c.length,u).split(`
35
- `).map(v=>v.trim()).filter(v=>v.length>0):[],f=qs(Gs(r,n),t),p=new Set(m),_=new Set(f),h=f.filter(v=>!p.has(v)),w=m.filter(v=>!_.has(v));return{status:h.length>0||w.length>0?"drift":"ok",path:s,missing_patterns:h,stale_patterns:w,schema_scope:"project"}}async function Rn(e){let t=[],n=[];for(let r of Mm){let i=`merge.${r.key}.driver`,o=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`;try{let{stdout:s}=await Mi("git",["config","--get",i],{cwd:e,env:We(),encoding:"utf8",windowsHide:!0,timeout:1e4}),a=s.trim();await vv(a,o,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 Um(e){let t;try{t=await jm(Z.resolve(e))}catch{return{status:"no_git"}}let n=Gs(t,Z.resolve(e)),r=await T(e),i=q(void 0,r.author_default),o=await ce(e,_v,r.locks.ttl_seconds,i,!1,xe(r).force_required_for_stale_lock,r.locks.wait_ms);try{let s=Z.join(t,".gitattributes"),a;try{a=await Li(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&j(u))return{status:"not_installed",path:s};throw u}if(!a.includes(In)&&!a.includes(Ni))return{status:"not_installed",path:s};let c=await T(e),l=An(c),d=await Fm(t,qs(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await o()}}async function iP(e,t){let n=yv({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await te(r);let i=await jm(n.workspace_start);return bv({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function bv(e){let t=Z.resolve(e.pmRoot),n=Z.resolve(e.workspaceRoot),r=e.dryRun===!0,i,o;try{[i,o]=await Promise.all([qt(t),qt(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 s=Gs(o,i);if(Ls(s))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let a=await T(i),c=An(a),l=qs(s,c),d=[],u=await gv();for(let f of Mm)d.push({key:`merge.${f.key}.name`,value:f.name}),d.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!r)try{let f=await Cm(o);for(let p of d)await Mi("git",["config",f,p.key,p.value],{cwd:o,env:We(),encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new y(`Cannot install repository-local merge drivers in ${o}. 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 Fm(o,l,r);return{ok:!0,dry_run:r,workspace_root:o,pm_root:i,gitattributes:{path:m.path,changed:m.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:C()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96cec314-edb6-5c51-abc4-d028bdc4f10c")}catch{}})();var kv=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Sv(e){let t=kv.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Ev(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function zm(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 s of e){let a=typeof s=="string"?s.trim():"";if(a.length===0)continue;let c=Sv(a);if(c===void 0)continue;let l=i.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<r&&l.examples.push(a),i.set(c,l)}let o=[];for(let[s,a]of i.entries()){if(a.count<n)continue;let c=Ev(s);o.push({name:c,prefix:s,count:a.count,examples:a.examples,shadows_builtin:ul(c)!==void 0})}return o.sort((s,a)=>a.count-s.count||s.name.localeCompare(a.name)),o}import{createHash as Qm}from"node:crypto";import Vt from"node:fs/promises";import Tn from"node:path";import{mkdir as xv,readFile as Iv}from"node:fs/promises";import Vm 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]="4d7f490a-03a3-512c-ba3c-b19fcc9a1270")}catch{}})();var Bs=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Av="sdk-workspace-transaction",Rv=/^[a-zA-Z0-9._-]+$/,Cv=30,Tv=3e3;function Hm(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Rv.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Wm(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 Gm(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 Jm(e,t){return Vm.join(e,"transactions","sdk",`${t}.json`)}async function At(e,t){t.updatedAt=C();let n=Jm(e,t.transactionId);await xv(Vm.dirname(n),{recursive:!0}),await ne(n,`${JSON.stringify(t,null,2)}
36
- `)}function $v(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Bt(e){return Object.assign(Object.create(null),e)}function Ov(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 Vs(e,t){return e===void 0?void 0:Ov(e,t)}function Js(e,t,n,r){let i=Vs(n,r);i===void 0?delete e[t]:e[t]=i}function qm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Bm(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Dv(e,t){if(!Bm(e.startedStepIds,t)||!Bm(e.completedStepIds,t)||!qm(e.results)||!qm(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,o=new Set(i);return Object.keys(e.compensationData).some(s=>!r.has(s))||Object.keys(e.results).some(s=>!o.has(s))?!1:e.status==="committed"?t.every(s=>o.has(s)):e.status!=="compensated"||o.size===0&&r.size===0}function Pv(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,o=i.schemaVersion===1&&i.transactionId===t,s=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((d,u)=>d===n[u]),a=Dv(i,n),c=$v(i),l=["applying","compensating","compensated","committed"].includes(String(i.status));if(!o||!s||!a||!c||!l)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...i,results:Bt(i.results),compensationData:Bt(i.compensationData)}}async function Nv(e,t,n,r,i){let o=i,s=o!==void 0;if(o?.status==="compensating"&&await Km(e,o),o===void 0||o.status==="compensated"){let a=C();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??a,updatedAt:a,stepIds:r,startedStepIds:[],completedStepIds:[],results:Bt(),compensationData:Bt()},await At(e.pmRoot,o),await mt(e,o,"prepared")}return{journal:o,recovered:s}}async function Lv(e,t,n){try{await jv(t,e.steps),await At(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let o of e.steps){if(r.has(o.id))continue;let s=await o.inspect(),a=Vs(s.result,`Step ${o.id} result`);if(s.state!=="applied"){let c=await o.prepareCompensation?.();Js(t.compensationData,o.id,c,`Step ${o.id} compensation data`),i.add(o.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>i.has(d)),await At(e.pmRoot,t);let l=await o.apply();a=Vs(l,`Step ${o.id} result`)}await mt(e,t,"step_applied",o.id),r.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),Js(t.results,o.id,a,`Step ${o.id} result`),await At(e.pmRoot,t),await mt(e,t,"step_recorded",o.id)}return await mt(e,t,"committing"),t.status="committed",await At(e.pmRoot,t),await mt(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Bt(t.results)}}catch(r){if(r instanceof Bs||t.status==="committed")throw r;try{await Km(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function Mv(e,t,n){try{return Pv(await Iv(Jm(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&j(r))return;throw r}}async function mt(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function jv(e,t){let n=new Set,r=Bt();for(let i of t){let o=await i.inspect();o.state==="applied"&&(n.add(i.id),Js(r,i.id,o.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function Km(e,t){t.status="compensating",await At(e.pmRoot,t),await mt(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 o;try{o=r.has(i.id)&&(await i.inspect()).state==="applied"}catch{o=r.has(i.id)}o&&(await mt(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(s=>s.id).filter(s=>n.has(s)),t.startedStepIds=e.steps.map(s=>s.id).filter(s=>r.has(s)),delete t.results[i.id],delete t.compensationData[i.id],await At(e.pmRoot,t),await mt(e,t,"step_compensated",i.id)}t.status="compensated",await At(e.pmRoot,t),await mt(e,t,"compensated")}async function Ym(e){let t=Wm(e.pmRoot,"Transaction pmRoot"),n=Hm(e.transactionId,"Transaction id"),r=Wm(e.author,"Transaction author"),i=Gm(e.lockTtlSeconds,Cv,"Transaction lock TTL"),o=Gm(e.lockWaitMs,Tv,"Transaction lock wait"),s=[...e.steps];if(s.length===0)throw new TypeError("Workspace transaction requires at least one step");let a=s.map(d=>{let u=Hm(d.id,"Transaction step id");if(u!==d.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return u});if(new Set(a).size!==a.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:s,lockTtlSeconds:i,lockWaitMs:o},l=await ce(t,Av,i,r,!1,!1,o);try{let d=await Mv(t,n,a),u=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Bt(d.results)};let m=await Nv(c,n,r,a,d);return await Lv(c,m.journal,u||m.recovered)}finally{await l()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9052af10-ff8c-55db-8a35-b45e1e23a901")}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 ef(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 tf(e,t){let n=Ys(e),r=ft(t,"migrationScope");return`auto-${Qm("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function Ys(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:de(ft(e.from,"source")),to:de(ft(e.to,"target")),...e.type===void 0?{}:{type:ft(e.type,"type")}}:{kind:e.kind,from:de(ft(e.from,"source")),to:de(ft(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Fv(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Uv(e,t,n){let r=Se(t.schema),i=Fv(n);return Ye(e,r.files[i],Oe[i])}function nf(e,t){return Tn.join(e,"transactions","schema",`${t}-plan.json`)}function Fi(e){return e.length===0?null:JSON.parse(e)}async function Cn(e){let t=await K(e);return{exists:t!==null,raw:t??""}}async function rf(e,t){t.exists?await ne(e,t.raw):await Vt.rm(e,{force:!0})}function zv(e,t,n){let r=at(e),i=r.definitions.findIndex(s=>s.name.trim().toLowerCase()===t.from.toLowerCase()),o=r.definitions.findIndex(s=>s.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return St(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 St(r)}function Hv(e,t,n){let r=sn(e),i=r.fields.findIndex(s=>s.key===t.from),o=r.fields.findIndex(s=>s.key===t.to);if(n==="stage"){if(o>=0)return an(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let s=r.fields[i];r.fields.push({...s,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 an(r)}function Wv(e,t,n){let r=cn(e),i=r.statuses.findIndex(s=>s.id===t.from),o=r.statuses.findIndex(s=>s.id===t.to);if(n==="stage"){if(o>=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 Gv(e,t,n){return t.kind==="rename-type"?zv(e,t,n):t.kind==="rename-field"?Hv(e,t,n):Wv(e,t,n)}function Rt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Xs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function $n(e){return Array.isArray(e)?e.map(t=>Xs(t)).filter(t=>t!==void 0):[]}function qv(e,t){for(let n of $n(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>Rt(r,t)));for(let n of $n(e.type_workflows))n.type=Rt(n.type,t)}function Bv(e,t){for(let r of $n(e.definitions))r.default_status=Rt(r.default_status,t);let n=Xs(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=Rt(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(o=>Rt(o,t)):i))}function Vv(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=>Rt(i,t)));for(let r of["options","command_option_policies"])for(let i of $n(n[r])){let o=r==="options"?"key":"option";i[o]=Rt(i[o],t)}}}function Jv(e,t){let n=Xs(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]=Rt(n[r],t)}function Ks(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"?qv(r,t):t.kind==="rename-field"?Vv(r,t):Bv(r,t),Jv(r,t),`${JSON.stringify(r,null,2)}
37
- `}function of(e,t){if(t.kind==="rename-type"){let r=at(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=cn(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function Kv(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 Yv(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 sf(e,t){let n=Ys(t.request),r=t.migrationId===void 0?tf(n,t.migrationScope??"plan"):ef(t.migrationId),i=e.map(c=>Yv(c,n)).filter(c=>c!==null).sort((c,l)=>c.id.localeCompare(l.id)),o=Qm("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),s=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),a=i.filter(c=>!s.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:o,affected_item_count:i.length,pending_item_count:a.length,skipped_completed_count:i.length-a.length,items:Object.freeze(a)})}async function Xv(e){let t=G(e.settings,H()),n=[...new Set(Object.values(t.type_to_folder))],r=await mi(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]}},o=r?await Id({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:i}):null;return o?{items:o.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 Zv(e,t){let n=await K(nf(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: ${Xc(r)}`,g.GENERIC_FAILURE)}}async function Qv(e,t){let n=nf(e,t.migration_id);await Vt.mkdir(Tn.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await ne(n,`${JSON.stringify(r,null,2)}
38
- `)}function eb(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function tb(e){let t=await Pe(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 Ne(t,{schema:e.settings.schema})).document.metadata}function Xm(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 o=e.metadata;if(Object.prototype.hasOwnProperty.call(o,i)&&!Object.prototype.hasOwnProperty.call(o,r))return[];if(!Object.prototype.hasOwnProperty.call(o,r)||Object.prototype.hasOwnProperty.call(o,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return o[i]=o[r],delete o[r],[r,i]}function Zm(e){return{id:e.id,inspect:async()=>{let t=await Cn(e.filePath),n=of(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 ne(e.filePath,Gv(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 rf(e.filePath,{exists:t.exists,raw:t.raw})}}}function nb(e){return{id:e.stepId,inspect:async()=>{let t=await Cn(e.filePath);return{state:Ks(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 ne(e.filePath,Ks(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 rf(e.filePath,{exists:t.exists,raw:t.raw})}}}function rb(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await T(e.pmRoot),n=G(t,H()).type_to_folder,r=await tb({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=Kv(r,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await T(e.pmRoot),n=G(t,H()).type_to_folder,r=await 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:Xm(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await T(e.pmRoot),n=G(t,H()).type_to_folder;await 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:Xm(r,e.request,"reverse")}}})}}}async function ib(e){let t=await Zv(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 Xv({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...sf(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function ob(e){let t=of(await K(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 Qv(e.pmRoot,e.plan)}async function sb(e){let t=Se(e.settings.schema),n=[...new Set([["types",Oe.types],["fields",Oe.fields],["workflows",Oe.workflows]].map(([i,o])=>Ye(e.pmRoot,t.files[i],o)).filter(i=>i!==e.schemaPath))];try{let i=Tn.join(e.pmRoot,"templates"),o=await Vt.readdir(i,{withFileTypes:!0});n.push(...o.filter(s=>s.isFile()&&s.name.toLowerCase().endsWith(".json")).map(s=>Tn.join(i,s.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!j(i))throw i}n.sort((i,o)=>i.localeCompare(o));let r=[];for(let i of n){let o=await K(i);o!==null&&Ks(o,e.request)!==o&&r.push({filePath:i,beforeRaw:o})}return{paths:n,snapshots:r}}async function ab(e){for(let t of e.snapshots){let n=await Vt.readFile(t.filePath,"utf8"),r=Tn.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await ts({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Fi(t.beforeRaw),after:Fi(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function cb(e,t,n){let r=Ys(e),i=N(process.cwd(),n.path);await te(i);let o=t.migrationId===void 0?tf(r,await Vt.realpath(i)):ef(t.migrationId),s=await T(i),a=q(t.author,s.author_default),c=await ib({pmRoot:i,settings:s,migrationId:o,request:r}),l=c.plan;if(t.dryRun===!0)return{...l,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=Uv(i,s,r),u=await Vt.readFile(d,"utf8");c.stored||await ob({pmRoot:i,schemaPath:d,request:r,plan:l});let m=await sb({pmRoot:i,schemaPath:d,settings:s,request:r}),f=[Zm({id:"stage-schema",filePath:d,request:r,phase:"stage"}),...m.paths.map((w,v)=>nb({filePath:w,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...l.items.map(w=>rb({pmRoot:i,id:w.id,request:r,author:a,force:t.force===!0})),Zm({id:"retire-source",filePath:d,request:r,phase:"retire"})],p=await Ym({pmRoot:i,transactionId:`schema-${o}`,author:a,steps:f,lockTtlSeconds:Math.max(s.locks.ttl_seconds,300),lockWaitMs:s.locks.wait_ms}),_=await Vt.readFile(d,"utf8"),{historyPath:h}=await ts({pmRoot:i,author:a,documentPath:Tn.relative(i,d).replaceAll("\\","/"),before:Fi(u),after:Fi(_),op:"schema_migration",idempotencyKey:`${l.migration_id}:${l.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${l.affected_item_count}`,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms});return await ab({pmRoot:i,author:a,settings:s,request:r,plan:l,snapshots:m.snapshots}),{...l,action:r.kind,applied:!0,recovered:p.recovered,migrated_item_count:l.affected_item_count,workspace_history_path:h}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1805dfab-5dc5-5be4-ad32-cbd8b3e37f8c")}catch{}})();var cN=[...qr,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Ui="schema-types",af="schema-statuses",cf="schema-fields";function Ct(e){return si({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 uN(e,t,n){let r=N(process.cwd(),n.path);await pt(r);let i;try{i=Wo({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 o=await T(r),s=Se(o.schema),a=Ye(r,s.files.types,Oe.types),c=[],l=q(t.author,o.author_default),d=xe(o),u=await ce(r,Ui,o.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms),m;try{let f=await K(a),p;try{p=at(f)}catch(_){throw new y(_ instanceof Error?_.message:String(_),g.GENERIC_FAILURE)}try{ml(i,p);let _=new Map,h=G(o,H());for(let[w,v]of Object.entries(h.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!_.has(k)&&_.set(k,w)}fl(i,p,_)}catch(_){throw new y(_ instanceof Error?_.message:String(_),g.USAGE)}m=Wr(p,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await Ct({pmRoot:r,filePath:a,raw:St(m.file),op:"schema:add-type",author:l,settings:o}),await fr(r,[m.definition],c,"schema:add-type-folder"),c.push(...await X({path:a,scope:"project",op:"schema:add-type"}))}finally{await u()}return await lf(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:a,definitions:m.file.definitions.length},warnings:Tt(c),generated_at:C()}}async function pt(e){await te(e)}async function lf(e,t){try{let n=await Um(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 Tt(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function ub(e,t,n,r){let i=G(t,H()),o=r.trim().toLowerCase();return(await ct(e,t.item_format,i.type_to_folder,[],n)).filter(a=>typeof a.type=="string"&&a.type.toLowerCase()===o).length}async function mb(e,t,n,r){let i=G(t,H()),o=_e(n),s=de(r);return(await ct(e,t.item_format,i.type_to_folder,[],n)).filter(c=>{let l=typeof c.status=="string"?c.status:"";return(o.alias_to_id.get(de(l))??de(l))===s}).length}async function fb(e,t,n,r,i){if(i.length===0||qo.has(i))return;let o=await mb(t,n,r,i);o>0&&e.push(`items_using_status:${o}`);let s=pb(r.workflow,i);s.length>0&&e.push(`status_referenced_by_workflow:${s.join(",")}`)}function pb(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(([,r])=>r!==void 0&&de(r)===t).map(([r])=>r)}async function mN(e,t,n){let r=N(process.cwd(),n.path);await pt(r);let i=await T(r),o=Se(i.schema),s=Ye(r,o.files.types,Oe.types),a=[],c=q(t.author,i.author_default),l=xe(i),d=await ce(r,Ui,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await K(s),f;try{f=at(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=pl(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 _=await ub(r,i,o,p);_>0&&a.push(`items_using_type:${_}`)}await Ct({pmRoot:r,filePath:s,raw:St(u.file),op:"schema:remove-type",author:c,settings:i}),a.push(...await X({path:s,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return u.removed&&await lf(r,a),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:s,definitions:u.file.definitions.length},warnings:Tt(a),generated_at:C()}}function Zs(e,t){return Ye(e,t.files.statuses,Oe.statuses)}function zi(e,t){return Ye(e,t.files.fields,Oe.fields)}function df(e,t){return Ye(e,t.files.types,Oe.types)}async function fr(e,t,n,r){for(let i of t){let o=el(i.folder??Qc(i.name)),s=lb.join(e,o);await $(s)||(await db(s,{recursive:!0}),n.push(...await X({path:s,scope:"project",op:r})))}}function Qs(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 hb(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=de(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let o=de(i);o.length>0&&!t.has(o)&&t.set(o,r)}}}return t}async function fN(e,t,n){let r=N(process.cwd(),n.path);await pt(r);let i;try{i=kl({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 o=await T(r),s=Se(o.schema),a=Zs(r,s),c=_e(s);try{Bo(i,c.alias_to_id)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}let l=hb(c.by_id.get(i.id));if((i.roles??l?.roles??[]).length===0)throw new y(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,g.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${on(i.id)}" --role active`,`pm schema add-status "${on(i.id)}" --role blocked`]});let u=[],m=q(t.author,o.author_default),f=xe(o),p=await ce(r,af,o.locks.ttl_seconds,m,!!t.force,f.force_required_for_stale_lock,o.locks.wait_ms),_;try{let h=await K(a),w;try{w=cn(h)}catch(k){throw new y(k instanceof Error?k.message:String(k),g.GENERIC_FAILURE)}let v=_b(w.statuses);try{Bo(i,v)}catch(k){throw new y(k instanceof Error?k.message:String(k),g.USAGE)}_=Sl(w,i,l),await Ct({pmRoot:r,filePath:a,raw:ln(_.file),op:"schema:add-status",author:m,settings:o}),u.push(...await X({path:a,scope:"project",op:"schema:add-status"}))}finally{await p()}return{action:"add-status",registered:!0,replaced:_.replaced,status:_.definition,file:{path:a,statuses:_.file.statuses.length},warnings:Tt(u),generated_at:C()}}async function pN(e,t,n){let r=N(process.cwd(),n.path);await pt(r);let i=await T(r),o=Se(i.schema),s=Zs(r,o),a=[],c=q(t.author,i.author_default),l=xe(i),d=await ce(r,af,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await K(s),f;try{f=cn(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=El(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=de(u.definition?.id??e);await fb(a,r,i,o,p),await Ct({pmRoot:r,filePath:s,raw:ln(u.file),op:"schema:remove-status",author:c,settings:i}),a.push(...await X({path:s,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:s,statuses:u.file.statuses.length},warnings:Tt(a),generated_at:C()}}function uf(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 gb(e,t,n){return{...uf(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 mf(e){return{id:e.id,source:qo.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 ff(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function yb(){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 o=i.name;typeof o=="string"&&o.trim().length>0&&e.set(o.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function wb(e){let t=_e(e),n=[],r=[];for(let i of t.definitions){let o=mf(i);o.source==="builtin"?n.push(o):r.push(o)}return{builtin:n,custom:r}}async function pr(e){let t=N(process.cwd(),e.path);await pt(t);let n=await T(t),r=Se(n.schema),i=Ye(t,r.files.types,Oe.types),o=Zs(t,r),s=G(n,H()),a=yb(),c=new Set((n.item_types?.definitions??[]).map(l=>l.name.trim().toLowerCase()).filter(l=>l.length>0&&!a.has(l)));return{pmRoot:t,typesPath:i,statusesPath:o,byType:s.by_type,customNames:c,extensionProvenance:a,schema:r}}async function hN(e){let t=await pr(e),n=[],r=[],i=[];for(let a of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=ff(a.name,t.customNames,new Set(t.extensionProvenance.keys())),l=uf(a);c==="extension"?i.push(l):c==="custom"?r.push(l):n.push(l)}let o=wb(t.schema),s=Gr(t.schema).definitions.map(Qs);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:o.builtin,custom:o.custom,counts:{builtin:o.builtin.length,custom:o.custom.length,total:o.builtin.length+o.custom.length}},fields:{custom:s,counts:{total:s.length}},file:{path:t.typesPath},generated_at:C()}}async function _N(e,t){let n=(e??"").trim();if(n.length===0)throw new y("Type name must not be empty.",g.USAGE);let r=await pr(t),i=Object.values(r.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(s=>s.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:gb(i,ff(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:C()}}async function gN(e,t){let n=de(e);if(n.length===0)throw new y("Status id must not be empty.",g.USAGE);let r=await pr(t),i=_e(r.schema),o=i.alias_to_id.get(n)??n,s=i.by_id.get(o);if(!s)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:mf(s),file:{path:r.statusesPath},generated_at:C()}}async function yN(e,t,n){let r=N(process.cwd(),n.path);await pt(r);let i;try{i=gl({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 o=await T(r),s=Se(o.schema),a=zi(r,s),c=[],l=Yr(i.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let d=q(t.author,o.author_default),u=xe(o),m=await ce(r,cf,o.locks.ttl_seconds,d,!!t.force,u.force_required_for_stale_lock,o.locks.wait_ms),f;try{let p=await K(a),_;try{_=sn(p)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.GENERIC_FAILURE)}f=yl(_,i),await Ct({pmRoot:r,filePath:a,raw:an(f.file),op:"schema:add-field",author:d,settings:o}),c.push(...await X({path:a,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:a,fields:f.file.fields.length},warnings:Tt(c),generated_at:C()}}async function vb(e,t,n,r){let i=G(t,H());return(await ct(e,t.item_format,i.type_to_folder,[],n)).filter(s=>{let a=s[r];return a==null?!1:Array.isArray(a)?a.length>0:typeof a=="string"?a.trim().length>0:!0}).length}async function wN(e,t,n){let r=N(process.cwd(),n.path);await pt(r);let i=await T(r),o=Se(i.schema),s=zi(r,o),a=[],c=q(t.author,i.author_default),l=xe(i),d=await ce(r,cf,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await K(s),f;try{f=sn(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=wl(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=de(u.definition?.key??e),_=de(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(_.length>0){let h=await vb(r,i,o,_);h>0&&a.push(`items_using_field:${h}`)}await Ct({pmRoot:r,filePath:s,raw:an(u.file),op:"schema:remove-field",author:c,settings:i}),a.push(...await X({path:s,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:s,fields:u.file.fields.length},warnings:Tt(a),generated_at:C()}}async function vN(e){let t=await pr(e),n=Gr(t.schema).definitions.map(Qs);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:zi(t.pmRoot,t.schema)},generated_at:C()}}async function bN(e,t){let n=de(e);if(n.length===0)throw new y("Field key must not be empty.",g.USAGE);let r=await pr(t),i=Gr(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:Qs(i),file:{path:zi(r.pmRoot,r.schema)},generated_at:C()}}async function kN(e,t,n){let r=N(process.cwd(),n.path);await pt(r);let i;try{let _=_l(e);if(_===void 0)throw new Error(`Type preset name is required. Allowed: ${hl.join(", ")}.`);i=_}catch(_){throw new y(_ instanceof Error?_.message:String(_),g.USAGE)}let o=await T(r),s=Se(o.schema),a=df(r,s),c=[],l=q(t.author,o.author_default),d=xe(o),u=[],m=[],f,p=await ce(r,Ui,o.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms);try{let _=await K(a),h;try{h=at(_)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=h;for(let v of Go(i)){let k=Wr(w,v);w=k.file,(k.replaced?m:u).push(k.definition.name)}f=w.definitions.length,await Ct({pmRoot:r,filePath:a,raw:St(w),op:"schema:apply-preset",author:l,settings:o}),await fr(r,Go(i),c,"schema:apply-preset-folder"),c.push(...await X({path:a,scope:"project",op:"schema:apply-preset"}))}finally{await p()}return{action:"apply-preset",preset:i,registered:u,replaced:m,file:{path:a,definitions:f},warnings:Tt(c),generated_at:C()}}function bb(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 SN(e,t){let n=N(process.cwd(),t.path);await pt(n);let r=await T(n),i=Se(r.schema),o=df(n,i),s=bb(e.minCount),a=G(r,H()),l=(await ct(n,r.item_format,a.type_to_folder,[],i)).map(k=>typeof k.title=="string"?k.title:""),d=zm(l,{minCount:s}),u=[],m=[],f=[],p=[],_;if(!e.apply){let k;try{k=at(await K(o))}catch(S){throw new y(S instanceof Error?S.message:String(S),g.GENERIC_FAILURE)}return _=k.definitions.length,{action:"infer-types",applied:!1,min_count:s,candidates:d,registered:m,replaced:f,skipped:p,file:{path:o,definitions:_},warnings:u,generated_at:C()}}let h=q(e.author,r.author_default),w=xe(r),v=await ce(n,Ui,r.locks.ttl_seconds,h,!!e.force,w.force_required_for_stale_lock,r.locks.wait_ms);try{let k=await K(o),S;try{S=at(k)}catch(A){throw new y(A instanceof Error?A.message:String(A),g.GENERIC_FAILURE)}let x=S;for(let A of d){if(A.shadows_builtin){p.push({name:A.name,reason:"shadows_builtin"});continue}let E;try{E=Wo({name:A.name})}catch{p.push({name:A.name,reason:"invalid_type_token"});continue}let b=Wr(x,E);x=b.file,(b.replaced?f:m).push(b.definition.name)}_=x.definitions.length,await Ct({pmRoot:n,filePath:o,raw:St(x),op:"schema:infer-types",author:h,settings:r}),await fr(n,x.definitions.filter(A=>m.includes(A.name)||f.includes(A.name)),u,"schema:infer-types-folder"),u.push(...await X({path:o,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:s,candidates:d,registered:m,replaced:f,skipped:p,file:{path:o,definitions:_},warnings:Tt(u),generated_at:C()}}import pf 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]="decec6f3-3795-5353-bf48-75aa61dd79d4")}catch{}})();function Re(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 Hi(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 ta(e){return ol(e)}async function kb(e){try{let t=JSON.parse(await pf.readFile(ea.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 Sb(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 kb(n.source_root),i=r.package_name?`pm install npm:${r.package_name}`:void 0,o=n.source_input??n.source_root;return new y(`Extension entry "${e.entry}" is absent from GitHub source "${o}". 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 ${o}`,normalized_args:["install",o],...i?{next_best_command:i}:{}}})}async function On(e,t={}){let n=ea.join(e,"manifest.json");if(!await $(n))throw new y(`Extension manifest is missing at "${n}".`,g.USAGE);let r;try{r=JSON.parse(await pf.readFile(n,"utf8"))}catch(s){throw new y(`Failed to parse extension manifest at "${n}": ${Eb(s)}`,g.USAGE)}let i=ta(r);if(!i)throw new y(`Extension manifest at "${n}" is invalid.`,g.USAGE);let o=ea.resolve(e,i.entry);if(!he(e,o))throw new y(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await $(o))throw await Sb(i,o,t);if(!await al(e,o))throw new y(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:o,manifest:i}}function Eb(e){return e instanceof Error?e.message:String(e)}import na from"node:fs/promises";import xb 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]="33b7f318-cc64-55d6-8b57-19a618efe6c0")}catch{}})();var Ib=".managed-extensions.json",Wi=1;function hr(e){return xb.join(e,Ib)}function Ab(){return{version:Wi,updated_at:C(),entries:[]}}function _r(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 hf(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 Ce(e){return typeof e=="string"?e:void 0}function Rb(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 Cb(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:Ce(t.name),package:Ce(t.package),version:Ce(t.version),repository:Ce(t.repository),owner:Ce(t.owner),repo:Ce(t.repo),ref:Ce(t.ref),subpath:Ce(t.subpath),commit:Ce(t.commit)}}function Tb(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Rb(t))return null;let n=Cb(t.source);if(!n)return null;let r=rl(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:Re(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Ce(t.last_update_check_at),last_update_remote_commit:Ce(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Ce(t.update_error)}}function $b(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Wi||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=Tb(r);i&&n.push(i)}return{version:Wi,updated_at:Ce(t.updated_at)??C(),entries:_r(n)}}async function we(e){let t=hr(e),n=Ab();try{let r=await na.readFile(t,"utf8"),i=JSON.parse(r),o=$b(i);if(!o)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:o,warnings:[]}}catch(r){if(r instanceof y)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&j(r))return{path:t,state:n,warnings:[]};throw new y(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE)}}async function Jt(e,t){let n=hr(e),r={version:Wi,updated_at:C(),entries:_r(t.entries)};await na.mkdir(e,{recursive:!0}),await na.writeFile(n,`${JSON.stringify(r,null,2)}
39
- `,"utf8")}function gr(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:C(),entries:_r(n)}}async function _f(e,t,n,r){let i=t.entries.find(s=>I(s.name)===I(n));if(!i)return t;let o=gr(t,{...i,contributions:r});return await Jt(e,o),o}import{execFile as Hb}from"node:child_process";import J from"node:fs/promises";import ca from"node:os";import M from"node:path";import{fileURLToPath as Wb}from"node:url";import{promisify as Gb}from"node:util";import qb from"npm-package-arg";import{extract as Bb,list as Vb}from"tar";import Ob 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]="96c5708d-1f4d-5f94-9945-7f8baa337106")}catch{}})();var Db="PM_CLI_PACKAGE_ROOT",gf={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Pb=new Set(["*","all"]);function ra(){let e=[],t=process.env[Db];return typeof t=="string"&&t.trim().length>0&&e.push(Ge.resolve(t.trim())),e.push($e(import.meta.url,["../../.."])),[...new Set(e)]}async function yr(e){let t=e.trim().toLowerCase(),n=await wf(t);if(n)return n;let r=gf[t];if(!r)return null;for(let i of ra()){let o=Ge.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await $(Ge.join(o,"manifest.json")))return o}return null}function yf(e){return Pb.has(e.trim().toLowerCase())}function Nb(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Lb(e,t){let n=await Ob.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=Ge.join(e,r.name);if(!await $(Ge.join(i,"package.json")))continue;let o=await zr(i),s=o.aliases&&o.aliases.length>0?o.aliases:[Nb(r.name)];for(let a of s){let c=a.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:i,package_name:o.package_name??null})}}}async function ia(){let e=new Map;for(let t of ra()){let n=Ge.join(t,"packages");await $(n)&&await Lb(n,e)}for(let[t,n]of Object.entries(gf))if(!e.has(t))for(let r of ra()){let i=Ge.join(r,"packages",n.package_directory);if(await $(Ge.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Gi(){return(await ia()).map(e=>e.alias)}async function wf(e){let t=e.trim().toLowerCase();return(await ia()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function vf(e){let t=await wf(e);return t?(await zr(t)).package_name??null:null}async function bf(e){let t=await yr(e);if(!t)return null;try{let n=await Hr(t);return n.length!==1?null:(await On(n[0])).manifest.name}catch{return null}}function Mb(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 jb(e,t,n,r,i,o){let s=r==="global"?"--global":"--project",a=Object.fromEntries(Ho.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))||o.has(Ge.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${s}`,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:a,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:Mb(e),media:e.catalog?.media}}}async function kf(e,t,n={}){let r=rn(N(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,o=await we(i),s=new Set(o.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>Ge.resolve(m.source.location))),a=new Set(o.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),c=[],l=new Map;for(let m of await ia()){let f=Ge.resolve(m.package_root),p=l.get(f)??[];p.push(m),l.set(f,p)}for(let m of l.values()){let f=m[0],p=m.map(h=>h.alias).sort((h,w)=>h.localeCompare(w)),_=await zr(f.package_root);c.push(jb(_,f,p,e,a,s))}let d=Ub(n.fields),u=d?c.map(m=>zb(m,d)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Ho.filter(m=>m!=="extensions"),packages:u}}var Fb=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 Ub(e){if(e===void 0)return;let t=Gd(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=>!Fb.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 zb(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]="68a37ea1-3571-59ab-b72c-0195efa84e3c")}catch{}})();var Ef=Gb(Hb),Bi="@unbrained/pm-cli",Jb={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},oa;async function xf(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=M.resolve(t);for(;;){let i=M.join(r,"node_modules",...n.split("/")),o=M.join(i,"package.json");if(await $(o))try{let a=JSON.parse(await J.readFile(o,"utf8"));if(a.name===n)return{package:n,...typeof a.version=="string"?{version:a.version}:{},directory:i}}catch{return null}let s=M.dirname(r);if(s===r)return null;r=s}}function sa(e,t,n){let r=e.split("/").map(l=>l.trim()).filter(l=>l.length>0);if(r.length<2)return null;let i=r[0],o=r[1].replace(/\.git$/i,"");if(i.length===0||o.length===0)return null;let s=r.slice(2),a,c;return s[0]==="tree"&&s.length>=2?(a=s[1],c=s.slice(2).join("/")):s.length>0&&(c=s.join("/")),typeof n=="string"&&n.trim().length>0&&(a=n.trim()),{kind:"github",input:t,owner:i,repo:o,repository:`https://github.com/${i}/${o}.git`,ref:a,subpath:c&&c.length>0?c:void 0}}function Kb(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new y('npm package source must include a package spec after "npm:".',g.USAGE);if(t)throw new y('Options "--gh/--github" cannot be combined with npm: package sources.',g.USAGE);if(n)throw new y('Option "--ref" cannot be combined with npm: package sources.',g.USAGE);return{kind:"npm",input:e,spec:r}}function Vi(e,t={}){let n=e.trim();if(n.length===0)throw new y("Extension source is required for --install.",g.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Kb(n,t.forceGithub===!0,r);let i=(()=>{try{let s=new URL(n);if(s.hostname!=="github.com")return null;let a=s.pathname.replace(/^\/+/,"");return sa(a,n,r)}catch{return null}})();if(i)return i;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let s=sa(o,n,r);if(!s)throw new y(`Invalid GitHub source "${n}".`,g.USAGE);return s}if(t.forceGithub){let s=sa(n,n,r);if(!s)throw new y(`Invalid GitHub shorthand "${n}".`,g.USAGE);return s}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:M.resolve(process.cwd(),n)}}async function qi(e,t=Ef,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):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new y(`Git command failed: git ${e.join(" ")}
40
- ${o}`,g.GENERIC_FAILURE)}}function Yb(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Xb(e=process.platform){return e==="win32"}async function If(e,t,n=Ef,r=process.platform,i=process.env){let o=Yb(r),s=Object.fromEntries(Object.entries(i).filter(([a])=>a.toLowerCase()!=="npm_config_allow_scripts"));s.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(o,e,{cwd:t,encoding:"utf8",env:s,shell:Xb(r)})).stdout??"").trim()}catch(a){let c=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr):"",l=c.trim().length>0?c.trim():a instanceof Error?a.message:String(a);throw new y(`npm command failed: ${o} ${e.join(" ")}
41
- ${l}`,g.GENERIC_FAILURE)}}function Af(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 Rf(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 Zb(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("npm err! code e404")||n.includes("404 not found")||n.includes("is not in this registry")}function Qb(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return Zb(e)||n.includes("not found")}function ek(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function tk(e){let t=Af(e),n=ek(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,o=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:o?[o,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:o?[`Try ${o} 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&&o?{fallback_candidates:[{source:i,command:o,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:o}:{}}}}}function nk(e,t){if(!Qb(t))return null;let n=tk(e);return new y(n.message,g.NOT_FOUND,n.context)}async function Cf(e){if(M.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=M.resolve(process.cwd(),e);return await $(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=Wb(t);return await $(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=M.resolve(process.cwd(),e);if(await $(t))return t}return null}async function rk(e){let t=await Cf(e);if(t)return t;let n=ik(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function ik(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!Rf(e))return e;let i=e.slice(0,r),o=e.slice(r+n.length);if(o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${i}@${M.resolve(t,o)}`;let s;try{s=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let a=/^\/[A-Za-z]:/.test(s)?s.slice(1):s;return`${i}@${a}`}function Sf(e,t){let n=M.resolve(e,t),r=M.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${M.sep}`)||M.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 ok(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 sk(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]).flatMap(({key:n,value:r})=>{let i=ok(r,n);return i?[i]:[]})}function ak(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(s=>{let a=s.name?.trim().toLowerCase();return a!==void 0?a===n:s.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let i=e[0],o=i.name??i.key;return n&&o!==void 0&&o.trim().toLowerCase()!==n?void 0:i}function ck(e,t,n){let r;try{r=JSON.parse(e)}catch{let s=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0).at(-1);if(!s)throw new y("npm pack did not report a tarball filename.",g.GENERIC_FAILURE);return{tarball:Sf(t,s)}}let i=sk(r),o=ak(i,n);if(!o)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:Sf(t,o.filename),package:o.name??o.key,version:o.version}}async function lk(e){return dk(e,If)}async function dk(e,t){let n=await Cf(e.spec);if(n){if((await J.stat(n)).isFile()&&Tf(n))return aa(n);let s=M.join(n,"package.json"),a=await $(s)?JSON.parse(await J.readFile(s,"utf8")):{};return{directory:await Ji(n,e.input),package:typeof a.name=="string"?a.name:void 0,version:typeof a.version=="string"?a.version:void 0,cleanup:async()=>{}}}let r=await J.mkdtemp(M.join(ca.tmpdir(),"pm-npm-package-source-")),i=M.join(r,"pack");await J.mkdir(i,{recursive:!0});try{let o=await rk(e.spec),s=await t(["pack",o,"--json","--pack-destination",i]),a=ck(s,i,Rf(e.spec)?void 0:Af(e.spec));if(!await $(a.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 aa(a.tarball);return{directory:c.directory,package:a.package??c.package,version:a.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await J.rm(r,{recursive:!0,force:!0})}}}}catch(o){await J.rm(r,{recursive:!0,force:!0});let s=nk(e.spec,o);throw s||o}}function Tf(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ht(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 uk(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&ht(`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(o=>o===".."))&&ht(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&ht(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ht(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ht(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ht(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&ht(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function aa(e,t=Jb){(await J.stat(e)).size>t.maxArchiveBytes&&ht(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await J.mkdtemp(M.join(ca.tmpdir(),"pm-local-package-archive-")),i=M.join(r,"extract");await J.mkdir(i,{recursive:!0});let o={entries:0,expandedBytes:0,packageJsonEntries:0},s;try{if(await Vb({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(s===void 0)try{uk(d,t,o)}catch(u){s=u}}}),s!==void 0)throw s;o.packageJsonEntries!==1&&ht(`Local package archive must contain exactly one package/package.json entry; found ${o.packageJsonEntries}.`),await Bb({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let a=M.join(i,"package"),c=M.join(a,"package.json"),l=JSON.parse(await J.readFile(c,"utf8"));return await mk(a),{directory:await Ji(a,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.version:void 0,cleanup:async()=>{await J.rm(r,{recursive:!0,force:!0})}}}catch(a){throw await J.rm(r,{recursive:!0,force:!0}),a}}async function mk(e,t=If){let n=M.join(e,"package.json");if(!await $(n))return;let r;try{r=JSON.parse(await J.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,o=yk(i),s=fk(i);if(o.length===0&&!s)return;let a={...r};delete a.devDependencies;let c={...a};pk(c),await J.writeFile(n,`${JSON.stringify(c,null,2)}
42
- `,"utf8");try{await Promise.all([J.rm(M.join(e,"package-lock.json"),{force:!0}),J.rm(M.join(e,"npm-shrinkwrap.json"),{force:!0})]),o.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),s&&await hk(e)}finally{await J.writeFile(n,`${JSON.stringify(a,null,2)}
43
- `,"utf8")}}function fk(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Bi in t)return!0;return!1}function pk(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Bi],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function hk(e){let t=$e(import.meta.url,["../../.."]),[n,r]=Bi.split("/"),i=M.join(e,"node_modules",n),o=M.join(i,r);await J.mkdir(i,{recursive:!0}),await J.rm(o,{recursive:!0,force:!0}),await J.symlink(t,o,_k(process.platform))}function _k(e){return e==="win32"?"junction":"dir"}function gk(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(r=>{let i=r.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(r)}))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{qb.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 yk(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===Bi||typeof i!="string"||i.trim().length===0||t.has(r))continue;let o=i.trim();t.set(r,gk(r,o))}return[...t.values()]}async function Ji(e,t){let n=await Hr(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>M.relative(e,i).replaceAll(M.sep,"/")).sort((i,o)=>i.localeCompare(o));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 wk(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(M.posix.join(".agents/pm/extensions",t.subpath)),n.push(M.posix.join(".custom/pm-extensions",t.subpath)),n.push(M.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let o=M.resolve(e,i);if(he(e,o)&&await $(M.join(o,"manifest.json")))return{directory:o,resolved_subpath:i}}if(await $(M.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await Ji(e,t.input);return{directory:r,resolved_subpath:M.relative(e,r).replaceAll(M.sep,"/")}}function vk(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 bk(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!vk(n))return new y(t,g.NOT_FOUND);let r=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,s=typeof o=="string"&&o.trim().length>0?M.resolve(o.trim()):"";oa?.key!==s&&(oa={key:s,aliases:await Gi()}),r=oa.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 $f(e){if(e.kind==="local"){let r;try{r=await J.stat(e.absolute_path)}catch{throw await bk(e)}if(r.isFile()&&Tf(e.absolute_path)){let o=await aa(e.absolute_path);return{source:e,directory:o.directory,source_root:M.dirname(o.directory),resolved_subpath:M.relative(M.dirname(o.directory),o.directory).replaceAll(M.sep,"/"),npm_package:o.package,npm_version:o.version,cleanup:o.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 lk(e);return{source:e,directory:r.directory,source_root:M.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:M.relative(M.dirname(r.directory),r.directory).replaceAll(M.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await J.mkdtemp(M.join(ca.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await qi(n);let r=await qi(["-C",t,"rev-parse","HEAD"]),i=await wk(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await J.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await J.rm(t,{recursive:!0,force:!0}),r}}async function Ki(e,t){if(!await $(e)||!await $(t))return!1;let[n,r]=await Promise.all([J.realpath(e),J.realpath(t)]);return n===r}import wr from"node:fs/promises";import vr 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]="60ab864f-43c5-512c-b33f-456de96f8090")}catch{}})();var la=1,Kt="2026.6.24",kk=">=22.18.0",Sk={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Of=new Set([...Cl.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(dl).map(e=>e.toLowerCase()),"scaffold"]),Ek="^6.0.0",xk="^22.0.0",Nf=["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 Df(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Lf(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 Mf(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 Ik={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Pf=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],jf={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"]},Ak={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"]'},Rk={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."},Ck={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."},Ff="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Tk={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."]},$k={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."]},Ok={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`."]},Dk={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 Uf(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 zf(e,t){return e==="schema"?Ok[t]:e==="profile"?Dk[t]:$k[t]}function Pk(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.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(),o=r>0&&(r===t.length||i!==void 0&&Of.has(i));return`${(Of.has(n)||o?["starter",...t]:t).join(" ")} ping`}function Hf(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],o=`${e.replace(/-/g,"_")}_owner`,s="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(s)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(o)},`,' 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(s)}],`,` [${JSON.stringify(s)}, "in_progress"],`,` [${JSON.stringify(s)}, "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 Nk(e,t,n){let r=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=[" 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 s;if(n==="search")return[...s,""," // 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 a=e,c=`${e}s`,l=e.replace(/-/g,""),d=l===a?[]:[l],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...s,""," // 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(a)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...s,""," // 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({",...Hf(e).map(a=>` ${a}`)," });"]:n==="importers"?[...s,""," // 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(o)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} 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(o)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} 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"?[...s,""," // 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"?[...s,""," // 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"?[...s,""," // 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 };`," });"]:[...s,""," // 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 Lk(e,t,n){let r=n==="hooks",i=n==="search",o=n==="importers",s=n==="schema",a=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",u=n==="services",m=Ak[n],f=e,p=`${e}s`,_=`${e.replace(/-/g,"_")}_note`,h=`${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,"});",""]:[],k=i?da(e,t,"search",m):[],S=o?da(e,t,"importers",m):[],x=s?[`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 {",...Df(Lf({extensionName:e,itemTypeName:f,itemTypeFolder:p,fieldName:_,migrationId:h,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...nt,"});",""]:[],A=a?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Df(Mf(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...nt,"});",""]:[],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;",...nt,"});",""]:[],b=l?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...nt,"});",""]:[],P=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...nt,"});",""]:[],U=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";',"",...Nf,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...l?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...nt,"});","",...v,...k,...S,...x,...A,...E,...b,...P,...U,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
44
- `)}function Mk(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 jk={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"},Fk={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 Uk(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 zk(e,t,n){let r=[],i=[...Uk(e,t,n)],o=[" commands: [pingCommand],"],s=`${e}-search`,a=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,l=e,d=`${e}s`,u=e.replace(/-/g,""),m=u===l?[]:[u],f=`${e.replace(/-/g,"_")}_note`,p=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),o.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(s)},`," 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(a)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),o.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,","}));"),o.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(f)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(l)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(p)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),o.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({",...Hf(e),"});"),o.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);`," },","});"),o.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 };","});"),o.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,","});"),o.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 };`,"});"),o.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:o}}function Hk(e,t,n){let r=zk(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((o,s)=>o.localeCompare(s)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
45
- `)}function da(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,o=`${e}-vector`,s=`${e.replace(/-/g," ")} items`,a=e,c=`${e}s`,l=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],m=f=>[...u," let deactivated = false;"," try {",...f.map(p=>p===""?p:` ${p}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...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(o)}, 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(o)},`,' 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(s)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(s)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(s)},`,' 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(s)},`,' 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(Lf({extensionName:e,itemTypeName:a,itemTypeFolder:c,fieldName:l,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Mf(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 Wk(e,t,n){let r=n==="parser",i=JSON.stringify([...jf[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" };',"",...Nf,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(Kt)},`," },",` target: { pmVersion: ${JSON.stringify(Kt)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...nt,"});","",...da(e,t,n,i)].join(`
46
- `)}function Gk(e,t,n){let r=Uf(n,"package"),i=zf(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 (${jk[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`.",Ff,"- `.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 ${Fk[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 \`${la}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Kt}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
47
- `)}function qk(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 Bk(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 Vk(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 Jk(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 Kk(e,t,n,r="commands",i=!1){let o=`pm-${e}`,s=jf[r],a=Mk(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:la,pm_min_version:Kt,trusted:!0,sandbox_profile:"strict",permissions:{...Sk},capabilities:s,...a.length>0?{activation:{commands:a}}:{}},null,2)}
48
- `,l=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Nk(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
49
- `),d=`${JSON.stringify(Ik,null,2)}
50
- `,u=Rk[r],m=Uf(r,"package"),f=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:kk},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Kt}`},devDependencies:{"@types/node":xk,typescript:Ek},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
51
- `,p=Lk(e,t,r),_=Ck[r],h=["node_modules/","*.log","*.tsbuildinfo",""].join(`
52
- `),w=qk(e),k=["```ts",`import { ${Bk(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Vk(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Jk(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],S=[`# ${o}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,_,Ff,"- `.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:",...k,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Tk[r],...zf(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Kt}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${la}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Kt}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
53
- `);return{"package.json":f,"manifest.json":c,"index.ts":i?Hk(e,t,r):l,"index.test.ts":i?Wk(e,t,r):p,"tsconfig.json":d,".gitignore":h,"README.md":i?Gk(o,t,r):S}}async function Wf(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!Pf.includes(i))throw new y(`Unknown scaffold capability "${n}". Supported capabilities: ${Pf.join(", ")}.`,g.USAGE);let o=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 s=r?"declarative":"imperative",a=e.trim(),c=vr.resolve(process.cwd(),a),l=Hi(vr.basename(c)).replace(/^(?:pm-)+/u,""),d=Pk(l),u=Kk(l,d,t,o,r),m=!1;if(await $(c)){if(!(await wr.stat(c)).isDirectory())throw new y(`Scaffold target "${c}" exists and is not a directory.`,g.CONFLICT)}else await wr.mkdir(c,{recursive:!0}),m=!0;for(let[p,_]of Object.entries(u)){let h=vr.join(c,p);if(!await $(h))continue;if(await wr.readFile(h,"utf8")!==_)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,_]of Object.entries(u)){let h=vr.join(c,p);if(await $(h)){f.push({path:p,status:"unchanged"});continue}await wr.mkdir(vr.dirname(h),{recursive:!0}),await wr.writeFile(h,_,"utf8"),f.push({path:p,status:"created"})}return{extension_name:l,package_name:`pm-${l}`,command_name:d,invocation_command:`pm ${d}`,capability:o,style:s,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]="6c9e36f8-0f95-5768-8893-bf33bbb4d848")}catch{}})();function Gf(e,t){return`${e}:${I(t)}`}function Yk(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let s of i){let a=o.get(s.command)??[];o.set(s.command,[...a,s])}for(let[s,a]of o){if(t!==null&&!a.some(l=>t.has(I(l.name))))continue;let c=a.at(-1);n.push({command:s,surface:r,policy:"last_activated_wins",collision:a.length>1,claimants:a.map(l=>({name:l.name,layer:l.layer,winner:l===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function qf(e,t,n){let r=new Set(n.failed.map(l=>Gf(l.layer,l.name))),i=[...t.loaded.map(l=>({name:l.name,layer:l.layer,version:l.version,activation_status:r.has(Gf(l.layer,l.name))?"failed":"ok",surfaces:En(n,{extensionName:l.name})})),...t.failed.map(l=>({name:l.name,layer:l.layer,version:"unknown",activation_status:"not_loaded",surfaces:En(n,{extensionName:l.name})}))].sort((l,d)=>l.name.localeCompare(d.name)||l.layer.localeCompare(d.layer)),o=typeof e=="string"?I(e):null,s=o===null?null:new Set(t.loaded.filter(l=>I(l.name)===o||typeof l.source_package=="string"&&I(l.source_package)===o||(l.source_aliases??[]).some(d=>I(d)===o)).map(l=>I(l.name)).concat(o)),a=s===null?i:i.filter(l=>s.has(I(l.name))),c=s===null?{}:{extensionNames:[...s]};return{target:typeof e=="string"?e.trim():null,total:a.length,extensions:a,union:En(n,c),command_ownership:Yk(n,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]="df60255d-fdd6-594a-9e17-547d53f7b3bb")}catch{}})();function ua(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 o=e.get(r)??new Set;o.add(i),e.set(r,o)}function Xk(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 Bf(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Zk(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:o}=e;return t?i.has(n)||o.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))),o=new Set(n.failed.map(c=>I(c.name))),{commandPathsByExtension:s,actionPathsByExtension:a}=Xk(n);return e.map(c=>{let l=I(c.name),d=Bf(s.get(l)),u=Bf(a.get(l)),m={...d?{command_paths:d}:{},...u?{action_paths:u}:{}},f=Zk({enabled:c.enabled,normalizedName:l,loadedNames:r,loadFailedNames:i,activationFailedNames:o});return{...c,...f,...m}})}function Qk(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 Kf=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 eS(e){return Kf.has(tp(e))}function Vf(e){return e==="project"||e==="global"}function Yf(e){let t=e.split(":"),n=t[0];if(!n||!Kf.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),o=t.at(-2),s=t.at(-1)?.trim();return!Vf(r)||!Vf(o)||!i||!s?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:o,name:s}}}function tS(e){let t=new Set;for(let n of e){let r=Yf(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function ma(e,t){let n=e.filter(eS);if(n.length===0)return null;let r=tS(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 nS(e,t,n,r){let i=t.map(u=>Yf(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 o=e==="global"?"--global":"--project",s=me(r,"deactivate"),a=`${me(r,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(u=>[I(u.name),u])),l=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let f=I(m);l.set(f,(l.get(f)??0)+1)}let d=[...l.entries()].map(([u,m])=>{let f=c.get(u),p=f?.name??u,_=f?.command_paths??[],h=f?.action_paths??[];return{action:"deactivate",extension:p,command:`${s} ${p} ${o}`,affected_collisions:m,feature_loss:{command_paths:[..._].sort((w,v)=>w.localeCompare(v)),action_paths:[...h].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,_=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return p!==_?p-_:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:l.size,next_best_command:a,collisions:i,remediation_candidates:d}}function Xf(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 Zf(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 Qf(e,t){let n=[];for(let r of Ol(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 rS=[{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: ${Mr.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 iS(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:s,unmanagedActionRequiredTotal:a,notCheckedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,u=[],m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:s};if(t.length>0){let f=ma(t,{deactivate:`${me(n,"deactivate")} <name> ${i}`,doctor:`${me(n,"doctor")} ${i} --detail deep --trace`});f&&u.push(f);for(let p of rS)p.matches(t,m)&&u.push(p.build(m))}return a>0&&u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${me(n,"manage")} ${i} --fix-managed-state (or ${me(n,"adopt-all")} ${i}, ${me(n,"adopt")} <name> ${i}, or reinstall via ${me(n,"install")} ${i} <source>).`),l>0&&u.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&u.push(`Update-check coverage is partial: some sources have no completed check. Run ${me(n,"manage")} ${i} to request update checks.`),d>0&&u.push(`Update available managed extensions via ${me(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${me(n,"manage")} ${i} after extension changes.`),u}function Zi(e,t,n,r={}){let i=[...new Set(t)].sort((b,P)=>b.localeCompare(P)),o=n.filter(b=>b.managed).length,s=n.filter(b=>b.enabled).length,a=n.filter(b=>b.active).length,c=n.filter(b=>b.update_check_status==="checked"&&b.update_available===!0).length,l=n.filter(b=>b.managed===!1),d=l.filter(b=>Jf(b)).map(b=>b.name).sort((b,P)=>b.localeCompare(P)),u=l.filter(b=>!Jf(b)).map(b=>b.name).sort((b,P)=>b.localeCompare(P)),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,_=Object.entries({skipped_unmanaged:u.length,skipped_non_github:p,failed:f,not_checked:m.not_checked}).filter(([,b])=>b>0).map(([b,P])=>`extension_update_health_partial_coverage:${b}:${P}`),h=_.length>0,w=h?"partial":"full",v=[...new Set([...i,..._])].sort((b,P)=>b.localeCompare(P)),k=[...new Set(v.map(b=>tp(b)))].sort((b,P)=>b.localeCompare(P)),S=Qk(v),x=e==="global"?"--global":"--project",A=nS(e,i,n,r),E=iS({normalizedWarnings:v,options:r,scope:e,scopeFlag:x,updateCheckFailedTotal:f,policyWarningCount:S.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:k,warnings:v,policy_warning_count:S.warning_count,policy_violation_count:S.violation_count,policy_blocked_count:S.blocked_count,total_extensions:n.length,managed_total:o,enabled_total:s,active_total:a,update_available_total:c,update_health_coverage:w,update_health_partial:h,unmanaged_loaded_extension_count:l.length,unmanaged_loaded_extensions:l.map(b=>b.name).sort((b,P)=>b.localeCompare(P)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:f,top_warnings:v.slice(0,8),remediation:E,...A?{collision_plan:A}:{}}}function ep(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 tp(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function br(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let o=zc(r);return o?[o]:Hc(r)})();for(let o of i){let s=`${o.layer}:${o.name}:${o.capability}`;t.has(s)||(t.add(s),n.push(o))}}return n}function kr(){return{version:jr.version,capabilities:[...jr.capabilities],legacy_aliases:{...jr.legacy_aliases}}}function Jf(e){let t=I(e.name),n=I(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function np(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 o=[...new Set(t.filter(d=>d.active).map(d=>I(d.name)))].sort((d,u)=>d.localeCompare(u)),s=[...new Set(n.filter(d=>d.layer==="project").map(d=>I(d.name)))].sort((d,u)=>d.localeCompare(u)),a=new Set(r.map(d=>I(d.name))),c=o.filter(d=>!s.includes(d)&&!a.has(d)).sort((d,u)=>d.localeCompare(u));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:o.length,loaded_project_count:s.length,active_project_names:o,loaded_project_names:s,missing_active_project_names:c}}}import rp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a77d8d8d-f429-5154-ab3a-2caddc44472e")}catch{}})();function Qi(e,t,n){let r=rp.relative(e,n);return r!==""&&!he(e,n)||n===t||he(t,n)?!1:!r.split(rp.sep).some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-"))}import{randomUUID as oS}from"node:crypto";import ae from"node:fs/promises";import sS from"node:os";import ie 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]="9b04c14b-8049-52ef-b7e8-dc87a0fb7629")}catch{}})();var ip=3,aS=120,op=250,cS=12e4,lS=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),sp=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,ap=e=>lS.has(String(sp(e))),eo=(e,t)=>sp(e)===t,cp=e=>new Promise(t=>{setTimeout(t,e)}),lp=async e=>{let t=ie.join(e,"package.json");await $(t)||await ae.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
54
- `,"utf8")},dp=async e=>{let t=$e(import.meta.url,["../../.."]),n=ie.join(e,"node_modules","@unbrained"),r=ie.join(n,"pm-cli");await ae.mkdir(n,{recursive:!0}),await ae.rm(r,{recursive:!0,force:!0}),await ae.symlink(t,r,process.platform==="win32"?"junction":"dir")},Sr=async e=>{let t=ie.resolve(e),n=ie.dirname(t),r=ie.parse(n).root,i=await ae.realpath(r).catch(()=>r),o=ie.relative(r,n),s=o===""?[]:o.split(ie.sep);for(let[a,c]of s.entries()){let l=ie.join(i,c);try{i=await ae.realpath(l)}catch{i=ie.join(i,...s.slice(a));break}}return ie.join(i,ie.basename(t))},up=async(e,t,n,r=sS.tmpdir())=>Mt("extension_install_copy",async()=>{let i=ie.resolve(e),o=await ae.realpath(i).catch(()=>i),s=await Sr(t);if(o===s)return;if(!he(o,s)){await n(o,t,{recursive:!0,force:!0});return}let a=await ae.realpath(ie.resolve(r)).catch(()=>Sr(r)),c=he(o,a)?ie.dirname(o):a;if(he(o,c))throw new y(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,g.USAGE,{code:"extension_install_source_contains_destination"});let l=await ae.mkdtemp(ie.join(c,"pm-extension-copy-")),d=ie.join(l,"extension");try{await n(o,d,{recursive:!0,force:!0,filter:u=>Qi(o,s,ie.resolve(u))}),await n(d,t,{recursive:!0,force:!0})}finally{await ae.rm(l,{recursive:!0,force:!0})}}),mp=async(e,t,n=ae.cp)=>{for(let r=1;r<=ip;r+=1)try{await Mt("extension_install_copy",async()=>{await ae.rm(t,{recursive:!0,force:!0}),await up(e,t,n)});return}catch(i){if(!ap(i)||r===ip)throw i;await cp(op)}},fa=async e=>{let t;try{t=await ae.readFile(ie.join(e,"owner.json"),"utf8")}catch(i){if(!kt(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},fp=async(e,t)=>await fa(e)!==t?!1:(await ae.rm(e,{recursive:!0,force:!0}),!0),dS=async(e,t)=>{let n;try{n=await ae.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await fa(e);return r===null?(await ae.rm(e,{recursive:!0,force:!0}),!0):fp(e,r)},uS=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await fa(e)!==t)return;let o=new Date;await ae.utimes(e,o,o)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},mS=async(e,t)=>{await ae.mkdir(e);try{await ae.writeFile(ie.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
55
- `,"utf8")}catch(n){throw await ae.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},fS=async(e,t,n,r,i)=>{for(let o=1;o<=n;o+=1)try{return await mS(e,t),!0}catch(s){if(!eo(s,"EEXIST"))throw s;await dS(e,i)?o-=1:await cp(r)}return!1},pa=async(e,t,n,r)=>Mt("extension_install",async()=>{let i=ie.join(e,"runtime","extension-install-locks"),o=ie.join(i,"scope.lock");await ae.mkdir(i,{recursive:!0});let{attempts:s=aS,delay_ms:a=op,stale_ms:c=cS,heartbeat_ms:l}=r??{};if(![s,a,c,l].filter(v=>v!==void 0).every(Number.isFinite))throw new y("Extension install lock timings must be finite numbers.",g.USAGE);let d=Math.max(1,Math.floor(s)),u=Math.max(0,Math.floor(a)),m=Math.floor(c),f=Math.floor(l??m/3);if(m<=0||f<=0||f>=m)throw new y("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",g.USAGE);let p={pid:process.pid,token:oS(),created_at:C(),destination:t};if(!await fS(o,p,d,u,m))throw new y(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let h=uS(o,p.token,f),w=!1;try{let v=await n();return w=!0,v}finally{await h(),await fp(o,p.token).catch(v=>{if(w)throw v})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96a05fa4-b833-56ca-b501-40a427d03201")}catch{}})();var pp=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,o=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let s=i;i+=1,r[s]=await n(e[s])}});return await Promise.all(o),r};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="37f2dced-3b93-5c64-85ae-56e62c95e8eb")}catch{}})();function hp(e,t){let n=I(e),r=t.find(i=>I(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,o)=>i.localeCompare(o)),action_paths:[...r?.action_paths??[]].sort((i,o)=>i.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]="fcc97434-1ef5-5c47-b491-f00e9d19b2c6")}catch{}})();function _p(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${I(o.name)}`]:[])),r=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>o.passThrough!==!0).filter(o=>!n.has(`${o.layer}:${I(o.name)}`)).map(o=>`extension_output_service_override_global:${o.service}:${o.layer}:${o.name}`),i=e.renderers.overrides.filter(o=>(o.commands?.length??0)===0&&o.resultDiscriminator===void 0).map(o=>`extension_output_renderer_override_global:${o.format}:${o.layer}:${o.name}`);return[...new Set([...r,...i])].sort((o,s)=>o.localeCompare(s))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var gp=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=Yr(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8507f364-e079-5743-a54b-bb3a68ab66d0")}catch{}})();var pS=1e4,hS=(e,t,n)=>{let r=e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).map(s=>{let[a,c=""]=s.split(/\s+/);return{commit:a,ref:c}}),i=r.find(s=>s.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let o=t?.trim();return o?{checked_at:n,remote_commit:i.commit,available:i.commit!==o}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},yp=async(e,t=qi)=>{let n=C();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,pS);return hS(i,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import _S from"node:fs/promises";import gS 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]="c4dc16d1-672a-5b1c-b681-97a7b3febd69")}catch{}})();function ha(e){return gS.join(e,"extension-migrations.json")}function wp(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 vp(e,t){return`${e.layer}:${e.name}:${t}`}async function yS(e){let t=ha(e);if(!await $(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await _S.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 _a(e,t){let n=await yS(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let s=wp(i,o),a=r.get(vp(i,s));a&&(i.definition.status=a.status,a.status==="failed"?i.definition.reason=a.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function wS(e){let t=await _a(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),r=[],i=!1,o=e.migrations.map((d,u)=>({migration:d,index:u})).filter(({migration:d})=>e.scope===void 0||d.layer===e.scope);for(let{migration:d,index:u}of o){let m=wp(d,u),f=vp(d,m),p=n.get(f),_=String(d.definition.status??"pending").toLowerCase(),h=p?.status??(_==="applied"||_==="failed"?_:"pending");if(h==="applied"){r.push({key:f,layer:d.layer,extension:d.name,id:m,before:h,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:f,layer:d.layer,extension:d.name,id:m,before:h,outcome:"pending"});continue}let w=d.runtime_definition?.run??d.definition.run;if(typeof w!="function"){r.push({key:f,layer:d.layer,extension:d.name,id:m,before:h,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:h}));let k={key:f,layer:d.layer,extension:d.name,id:m,status:"applied",attempted_at:v};n.set(f,k),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,r.push({key:f,layer:d.layer,extension:d.name,id:m,before:h,outcome:"applied"}),i=!0}catch(k){let S=k instanceof Error?k.message:String(k),x={key:f,layer:d.layer,extension:d.name,id:m,status:"failed",attempted_at:v,error:S};n.set(f,x),d.definition.status="failed",d.definition.reason=S,r.push({key:f,layer:d.layer,extension:d.name,id:m,before:h,outcome:"failed",error:S}),i=!0}}if(i){let d=await T(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,f)=>m.key.localeCompare(f.key))};await si({pmRoot:e.pmRoot,filePath:ha(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
56
- `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let s=r.filter(d=>d.outcome==="pending").length,a=r.filter(d=>d.outcome==="applied").length,c=r.filter(d=>d.outcome==="skipped").length,l=r.filter(d=>d.outcome==="failed").length;return{ok:l===0,dry_run:e.dryRun===!0,state_path:ha(e.pmRoot),total:r.length,pending_count:s,applied_count:a,skipped_count:c,failed_count:l,migrations:r}}async function bp(e){let t=await T(e.resolvedRoots.settings_root),n=await Je({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Ke(n);e.warnings.push(...n.warnings,...r.warnings);let i=await wS({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]="ee1bfa77-6687-578c-9cd6-639fc702c48c")}catch{}})();function kp(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 o=i.details;return{alias:r,ok:i.ok,extension:o.extension,source:o.source,source_resolution:o.source_resolution,install_plan:o.install_plan,dry_run:o.dry_run,destination_path:o.destination_path,activated:o.activated,settings_changed:o.settings_changed,command_paths:o.command_paths,action_paths:o.action_paths,command_discovery:o.command_discovery,verification:o.verification,runtime_activation_status:o.runtime_activation_status,activation_diagnostics:o.activation_diagnostics,warnings:i.warnings}})}}import no from"node:fs/promises";import to 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]="f4b9502f-f742-5f11-b341-56763bbed7c2")}catch{}})();var vS=new Set(["node_modules",".git","dist","build","coverage"]);async function Sp(e,t,n,r){let i=e.source.kind==="local"?await no.stat(e.source.absolute_path):void 0,o=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,s=await bS(e.directory,t,r),a={source_mode:o,...o==="archive"?{archive_bytes:i.size}:{},copy:s},c=e.source_root??e.directory;return o==="directory"&&(!s.complete||s.development_entries>0||s.bytes>=16*1024*1024)&&await $(to.join(c,"package.json"))&&(a.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}async function bS(e,t,n={}){let{maxEntries:r=1e4,maxDepth:i=64,signal:o}=n;if(![r,i].every(u=>Number.isSafeInteger(u)&&u>0))throw new y("maxEntries and maxDepth must be positive safe integers.",g.USAGE);o?.throwIfAborted();let s=await no.realpath(e),a=await Sr(t),c=await Ki(s,a);o?.throwIfAborted();let l=c?"in_place":he(s,a)?"nested_filtered_snapshot":"directory_snapshot",d={copy_scope:l,source_directory:s,destination_directory:a,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:r,max_depth:i};return l==="in_place"||await Ep(s,0,d,o),d}async function Ep(e,t,n,r){r?.throwIfAborted();let i=await no.opendir(e);for await(let o 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 s=to.join(e,o.name);if(n.copy_scope==="nested_filtered_snapshot"&&!Qi(n.source_directory,n.destination_directory,s)){n.excluded_entries+=1;continue}if(to.relative(n.source_directory,s).split(to.sep).some(a=>vS.has(a))&&(n.development_entries+=1),await kS(s,t,n,r),!n.complete)return}}async function kS(e,t,n,r){let i=await no.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 Ep(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 SS from"node:fs/promises";import ES 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]="b1bf79a0-1f04-590f-b613-45ca1b534d5d")}catch{}})();function xS(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function IS(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 ga(e){let t=ES.join(e,"manifest.json"),n;try{n=await SS.readFile(t,"utf8")}catch(a){if(kt(a))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw a}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,o=Jc(i),s=xS(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:o.findings,warnings:o.findings.map(a=>IS(s,a)),remediation:o.findings.map(a=>a.message)}}function xp(e){return ga(Ve(e))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcdfdabd-8862-502f-8cd1-298c08825985")}catch{}})();async function Ip(e,t,n){let r=typeof t=="string"?null:await yr(e),i=r===null?null:e.trim().toLowerCase(),o=i===null?null:await vf(i),s=Vi(r??e,{forceGithub:typeof t=="string",ref:n}),a=i===null?null:await xf(e);return{bundledAliasName:i,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:i===null?s.kind:"builtin",input:i??s.input,...o===null?{}:{package:o}},ambiguous:a!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...o===null?{}:{package:o},command:`pm install ${i}`}],...a===null?[]:[{kind:"npm",input:`npm:${a.package}`,package:a.package,...a.version===void 0?{}:{version:a.version},directory:a.directory,command:`pm install npm:${a.package}`}]]}}}import Yt 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]="d7afb9a1-be35-5dfd-a52e-2525598b68d8")}catch{}})();var ya=async e=>Yt.readFile(e).catch(t=>{if(eo(t,"ENOENT"))return null;throw t}),Ap=async(e,t,n,r,i)=>Mt("extension_install_backup",async()=>{let o=hr(e),s=Nt(t),[a,c]=await Promise.all([ya(o),ya(s)]);return r&&await Yt.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:o,managedStateContents:a,settingsPath:s,settingsContents:c}}),Rp=async e=>Mt("extension_install_rollback",async()=>{await Yt.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Yt.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await Yt.rm(t,{force:!0}):(await Yt.mkdir(AS.dirname(t),{recursive:!0}),await Yt.writeFile(t,n))});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f8fc1a7-748d-559d-9de8-835d0428c6a7")}catch{}})();var RS=4,Op=[["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"]],CS=Op.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),TS={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"},$S="__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"],Dp=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],DS=["disabled","require_trusted","require_provenance"],Pp={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:[]},PS=e=>{let t=e??Pp,n={};for(let r of OS)n[r]=Re(t[r]??[]);return n},NS=(e,t)=>{for(let n of Dp)t[n].length>0&&(e[n]=t[n]);return e},LS=(e,t)=>{for(let n of DS)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},MS=e=>{let t={};for(let n of Dp)t[n]=Re(e[n]??[]);return t},jS=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:NS(LS({name:t},e),MS(e))},FS=e=>(e??[]).map(t=>jS(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),US=e=>{let t=Object.assign({},Pp,e??{}),n=PS(e),r=FS(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}},Np=async(e,t)=>{let n=[t],r=await bf(t);r&&n.push(r);let i=[...new Set(n.map(o=>I(o)).filter(o=>o.length>0))];for(let o of i){let s=e.find(c=>I(c.name)===o);if(s)return s;let a=e.find(c=>I(c.directory)===o);if(a)return a}},Lp=(e,t)=>{let n=t.trim(),r=new Set(Re(e.extensions.enabled));return new Set(Re(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},Mp=(e,t)=>{let n=t.trim(),r=new Set(Re(e.extensions.enabled)),i=new Set(Re(e.extensions.disabled)),o=[...r],s=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},zS=(e,t)=>{let n=t.trim(),r=new Set(Re(e.extensions.enabled)),i=new Set(Re(e.extensions.disabled)),o=[...r],s=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},HS=(e,t)=>{let n=t.trim(),r=new Set(Re(e.extensions.enabled)),i=new Set(Re(e.extensions.disabled)),o=[...r],s=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},WS=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=Op.map(([i,o,s])=>({action:o,flag:s,distance:Uc(t,i,n)})).filter(i=>i.distance!==null).sort((i,o)=>i.distance-o.distance)[0];return r?{action:r.action,flag:r.flag}:null},GS=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=WS(e);if(!r)return new y(`One action flag is required. Use one of: ${CS}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let i=`pm ${n} ${r.flag}`;return ci({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(jp),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},qS=[["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"]],jp={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},BS=e=>jp[e]??null,VS=(e,t)=>{let n=[...new Set(qS.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=BS(e.trim().toLowerCase());if(r)return r;throw GS(e,t)}if(n.length>1)throw new y("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},JS=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"},KS=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&e.source.kind!=="github"?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],Fp=e=>{for(let t of KS){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Up=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,update_error:i.update_error,update_check_status:r.status,update_check_reason:r.reason}},YS=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),o=r?Lp(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Up({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:o},t,r,Fp(r))}},XS=async(e,t,n,r,i,o)=>{let s=Te.join(e,t),a=Te.join(s,"manifest.json"),c=o.get(I(t));if(!await $(a))return YS(t,n,r,c);let l=Symbol("invalid-extension-manifest-json"),d=await $t.readFile(a,"utf8").then(f=>JSON.parse(f)).catch(()=>l);if(d===l)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=ta(d);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(I(u.name))??o.get(I(t));return{summary:Up({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:Lp(r,u.name)},n,m,Fp(m))}},rt=async(e,t,n,r)=>{if(!await $(e))return{extensions:[],warnings:[]};let o=(await $t.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,u)=>d.localeCompare(u)),s=new Map(r.entries.map(d=>[I(d.name),d])),a=new Map(r.entries.map(d=>[I(d.directory),d])),c=[],l=[];for(let d of o){let u=await XS(e,d,t,n,s,a);u.warning&&c.push(u.warning),u.summary&&l.push(u.summary)}return{extensions:l.sort((d,u)=>d.name.localeCompare(u.name)),warnings:c.sort((d,u)=>d.localeCompare(u))}},ZS=Tl(),QS=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,eE=(e,t,n,r)=>{let i=n.command_paths.map(a=>`pm ${a} --help`),o=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,s=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&s.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:QS(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:s,...o?{sdk_dependency_status:"missing"}:{}}},tE=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},zp=e=>e.map(t=>tE(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),Hp=(e,t,n)=>{let r=I(e);return t.find(i=>(n===void 0||i.layer===n)&&I(i.name)===r)},nE=(e,t,n,r)=>n.find(o=>o.scope===t&&I(o.name)===I(e))?.activation_status??(r?"failed":"unknown"),Wp=(e,t,n,r,i)=>ZS.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,s=await $t.mkdtemp(Te.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=$e(import.meta.url,["../.."]);try{let a=await Je({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:Uo(),cache_bust:!0,module_graph_snapshot_root:s}),c=await Ke({...a}),l=[...a.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...zp(c.failed)],d=Object.fromEntries(a.loaded.map(u=>[I(u.name),il(En(c,{extensionName:u.name}))]));return{installed:Xi(r,a,c),warnings:[...a.warnings,...c.warnings],activation_failures:l,extensions_disabled:a.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:d}}finally{await $t.rm(s,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),va=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),o=[...i].sort((c,l)=>{let d=c.name.localeCompare(l.name);return d!==0?d:c.directory.localeCompare(l.directory)}),s=r,a=[];for(let c of o){let l=Te.join(e,c.directory),d=await On(l),u=C(),m={kind:"local",input:c.name,location:l};s=gr(s,{name:d.manifest.name,directory:c.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:u,updated_at:u,source:m}),a.push({name:d.manifest.name,directory:c.directory,version:d.manifest.version,entry:d.manifest.entry,source:m})}return a.length>0&&await Jt(e,s),{state:s,adopted_entries:a,unmanaged_candidates:o,already_managed_count:n.length-i.length}},rE=(e,t)=>{let n=N(process.cwd(),t.path),r=rn(n,process.cwd()),i=e==="global"?Ur(process.cwd()):n,o=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:o,roots:r}},ro=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]},iE=e=>TS[e],oE=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,o=iE(e),s=`<${r}>`,a=`pm ${n} ${o} ${s}`;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} ${s}`,a,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:a,fallback_candidates:[{source:"lifecycle_action",command:a,reason:`flag-form ${e} command with required ${r} target`}]}})},io=(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 oE(t,n)},sE=(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,o)=>o.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},aE=(e,t)=>{let r=[{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(i=>i.triggered&&!i.allowed);if(r)throw new y(r.message,g.USAGE)},cE=(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},lE=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},dE=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:lE(e),warnings:[...new Set(e.warnings)].sort((i,o)=>i.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(r,$S,{value:!0,enumerable:!1,configurable:!1}),r},ba=async(e,t,n)=>{let r=VS(e,t);aE(r,t);let i=cE(e,r,t),o=JS(t),s=rE(o,n),c={action:r,normalizedTarget:i,scope:o,resolvedRoots:s,warnings:[],options:t,global:n},d={...c,withResult:(u,m=!0)=>dE(c,u,m)};return await WE(d)},uE=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=Nl(r),o={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"`},s={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"`},a=[];return[n==="package",t.declarative===!0].every(Boolean)&&a.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[o[n],...a,`Install the scaffold: ${Xe(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,s[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},mE=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([ro(r),r.ref].filter(l=>typeof l=="string").map(l=>l.trim()).filter(Boolean).length>0)throw new y('Action "init" does not accept --gh/--github/--ref options.',g.USAGE);let a=io(n,t,r),c=await Wf(a,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:c.created_directory||c.files.some(l=>l.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:uE(c,r)})},fE=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:o,withResult:s}=e;if(t!==void 0)throw new y('Action "reload" does not accept a target argument.',g.USAGE);let a=await T(n.settings_root),c=Uo(),l=await Je({pmRoot:n.settings_root,settings:a,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});r.push(...l.warnings);let d=await Ke(l);r.push(...d.warnings);let u={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:l.loaded.length,failed_count:l.failed.length,activated_count:Math.max(0,l.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:l.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),s(u)},pE=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:o}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new y('Action "catalog" does not accept a package target.',g.USAGE);return o(await kf(n,i,r))},hE=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),_E=e=>({kind:"local",input:e.input,location:e.absolute_path}),gE=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),yE=(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}),wE=(e,t,n,r)=>e?hE(e,t):n.kind==="local"?_E(n):n.kind==="npm"?gE(n,r):yE(n,r),vE=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:hf(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},bE=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:o,destinationDirectoryName:s}=t,a=await T(r.settings_root),c=await we(r.selected_root);i.push(...c.warnings);let l=Te.join(r.selected_root,s),d=await $(l),u=await Ki(o.directory,l);await $t.mkdir(r.selected_root,{recursive:!0});let m=await $t.mkdtemp(Te.join(r.selected_root,".pm-extension-install-backup-")),f=Te.join(m,"destination");try{let p=await Ap(r.selected_root,r.settings_root,l,d,f),_=wE(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),h=c.state.entries.find(S=>I(S.name)===I(o.manifest.name)),w=vE(h,o.manifest.version,_,C()),v=gr(c.state,{name:o.manifest.name,directory:s,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,...w,source:_}),k=Mp(a,o.manifest.name);try{u||await mp(o.directory,l),await lp(l),await dp(l),await Jt(r.selected_root,v),k&&await ai(r.settings_root,a,"settings:write")}catch(S){try{await Rp(p)}catch(x){throw new AggregateError([S,x],`Extension install failed: ${String(S)}; rollback failed: ${String(x)}`,{cause:x})}throw S}return{settings:a,managedState:v,sourceRecord:_,destinationDirectory:l,destinationExists:d,installInPlace:u,activationChanged:k}}finally{await $t.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},kE=async(e,t,n)=>{let r=n.filter(i=>I(i.name)===I(t)).flatMap(i=>i.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&r.length>0&&await fr(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},SE=(e,t,n,r,i)=>{let o=Hp(t,n.activation_failures,e.scope),s=nE(t,e.scope,n.installed,o),a=[!n.extensions_disabled,s==="ok"].every(Boolean);a||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${s}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:a,status:s,failure:o,verification:{status:c[String(a)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:s,activated:a,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(a)]}}},EE=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:o,withResult:s}=e,{validated:a,destinationDirectoryName:c}=t,l=await bE(e,t),d=await rt(r.selected_root,n,l.settings,l.managedState);i.push(...d.warnings);let u=await Wp(r.pm_root,Te.dirname(r.selected_root),l.settings,d.extensions,o);i.push(...u.warnings);let m=await kE(e,a.manifest.name,u.item_type_registrations),f=hp(a.manifest.name,u.installed),p=SE(e,a.manifest.name,u,f,m),_=u.contribution_inventories[I(a.manifest.name)];return _&&(l.managedState=await _f(r.selected_root,l.managedState,a.manifest.name,_)),s({extension:{name:a.manifest.name,version:a.manifest.version,entry:a.manifest.entry,capabilities:a.manifest.capabilities,directory:c},source:l.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:l.destinationDirectory,overwritten:[l.destinationExists,!l.installInPlace].every(Boolean),installed_in_place:l.installInPlace,activated:p.activated,settings_changed:l.activationChanged,runtime_activation_status:p.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:_,command_discovery:eE(a.manifest.name,l.sourceRecord,f,p.failure),verification:p.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:p.failure??null}},p.activated)},xE=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 o=[],s=new Map;for(let a of await Gi()){let c=await yr(a),l=Te.resolve(c),d=s.get(l);d===void 0&&(d=await ba(a,{...t,install:!0},n),s.set(l,d)),o.push({alias:a,result:d})}return r.push(...o.flatMap(a=>a.result.warnings)),i(kp(o,t.dryRun===!0),o.every(a=>a.result.ok))},IE=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:o,installSource:s,sourceResolution:a}=await Ip(t,n,e.options.ref);if(a.ambiguous){let l=a.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${l.package}`)}let c=await $f(s);try{let l=await On(c.directory,{source_kind:s.kind,source_input:s.input,source_root:c.source_root}),d=Hi(l.manifest.name),u=e.options.dryRun===!0||s.kind==="local"&&i===null?await Sp(c,Te.join(r.selected_root,d),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:l.manifest.name,version:l.manifest.version},source_resolution:a,install_plan:u}):await pa(r.settings_root,d,()=>EE(e,{validated:l,destinationDirectoryName:d,bundledAliasName:i,bundledPackageName:o,sourceResolution:a,installSource:s,resolvedSource:c,installPlan:u}))}finally{c.cleanup&&await c.cleanup()}},AE=async e=>{let t=ro(e.options),n=t??io(e.normalizedTarget,e.action,e.options);return[t===void 0,yf(n)].every(Boolean)?xE(e):IE(e,n,t)},RE=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:s}=e;if(t!==void 0)throw new y('Action "adopt-all" does not accept a target argument.',g.USAGE);if(ro(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new y('Action "adopt-all" does not accept --gh/--github/--ref options.',g.USAGE);let c=await T(r.settings_root),l=await we(r.selected_root);i.push(...l.warnings);let d=await rt(r.selected_root,n,c,l.state);i.push(...d.warnings);let u=await va(r.selected_root,n,d.extensions,l.state),m=await rt(r.selected_root,n,c,u.state);i.push(...m.warnings);let f=Zi(n,i,m.extensions,o);i.push(...f.warnings);let p=new Map(m.extensions.map(w=>[`${I(w.name)}:${I(w.directory)}`,w])),_=new Map(m.extensions.map(w=>[I(w.directory),w])),h=u.adopted_entries.map(w=>{let v=I(w.directory),k=p.get(`${I(w.name)}:${v}`)??_.get(v);return{...w,...Gp(k)}});return s({adopted_all:h.length>0,adopted_count:h.length,already_managed_count:u.already_managed_count,extensions:h,triage:f,warning_codes:f.warning_codes,update_health_partial:f.update_health_partial,update_health_coverage:f.update_health_coverage})},Gp=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),CE=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=Vi(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new y(`Invalid GitHub shorthand "${e}".`,g.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},TE=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:s,withResult:a}=e,c=io(n,t,s),l=ro(s),d=await T(i.settings_root),u=await we(i.selected_root);o.push(...u.warnings);let m=await rt(i.selected_root,r,d,u.state);o.push(...m.warnings);let f=await Np(m.extensions,c);if(!f)throw new y(`Installed extension "${c}" was not found in ${r} scope.`,g.NOT_FOUND);if(f.managed)return a({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let p=Te.join(i.selected_root,f.directory),_=await On(p),h=C(),w=CE(l,c,p,s.ref),v=gr(u.state,{name:_.manifest.name,directory:f.directory,scope:r,manifest_version:_.manifest.version,manifest_entry:_.manifest.entry,capabilities:[..._.manifest.capabilities],contributions:_.manifest.contributions,installed_at:h,updated_at:h,source:w});await Jt(i.selected_root,v);let k=await rt(i.selected_root,r,d,v);o.push(...k.warnings);let S=k.extensions.find(x=>I(x.name)===I(_.manifest.name))??k.extensions.find(x=>I(x.directory)===I(f.directory));return a({adopted:!0,extension:{name:_.manifest.name,directory:f.directory,version:_.manifest.version,entry:_.manifest.entry},source:w,...Gp(S)})},qp=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:s}=e,a=io(n,t,s),c=await T(i.settings_root),l=await we(i.selected_root);o.push(...l.warnings);let d=await rt(i.selected_root,r,c,l.state);o.push(...d.warnings);let u=await Np(d.extensions,a);if(!u)throw new y(`Installed extension "${a}" was not found in ${r} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:l,candidate:u}},$E=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:o}=await qp(e),s=Te.join(t.selected_root,o.directory);await $t.rm(s,{recursive:!0,force:!0});let a={...i.state,updated_at:C(),entries:i.state.entries.filter(l=>I(l.name)!==I(o.name)&&I(l.directory)!==I(o.directory))};await Jt(t.selected_root,a);let c=HS(r,o.name);return c&&await ai(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:s,settings_changed:c})},Cp=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:o}=e,{settings:s,candidate:a}=await qp(e),c=t==="activate"?Mp(s,a.name):zS(s,a.name);c&&await ai(n.settings_root,s,"settings:write");let l=t==="activate"?await Wp(n.pm_root,Te.dirname(n.selected_root),s,[a],i).then(d=>(r.push(...d.warnings),Hp(a.name,d.activation_failures,e.scope))):void 0;return l&&r.push(`extension_activate_failed:${e.scope}:${a.name}`),o({extension:{name:a.name,directory:a.directory},active:t==="activate"&&l===void 0,runtime_active:t==="activate"&&l===void 0,activation_failure:l??null,settings_changed:c,settings:{enabled:[...s.extensions.enabled],disabled:[...s.extensions.disabled]}},l===void 0)},OE=(e,t,n,r,i,o)=>{let s=r==="package"?"package":"extension",a={package:"doctor",extension:"--doctor"}[s],c=i?.adopted_entries.length??0,l=[[o!==null,o??""],[t>0,`Run pm ${s} explore --project and pm ${s} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${s} ${a} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...l.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},wa=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),DE=(e,t,n,r)=>{if(e!=="project"||t||!wa(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.`},PE=(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=ep(n.detail),o=n.trace===!0;if([o,i!=="deep"].every(Boolean))throw new y("--trace requires --detail deep with --doctor.",g.USAGE);return{isolated:r,detailMode:i,includeTrace:o}},NE=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await va(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},LE=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:wa(r),rerun_command:null,pm_global_path_recipe:null};let o=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:wa(r),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},ME=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:s,withResult:a}=e,{isolated:c,detailMode:l,includeTrace:d}=PE(t,n,o),u=await T(r.settings_root),m=await we(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:_}=await NE(e,f.extensions,m.state),h=await rt(r.selected_root,n,u,p);i.push(...h.warnings);let w=await Je({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:s.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Ke({...w,loaded:w.loaded}),k=await xp(r.pm_root);i.push(...k.warnings,...w.warnings),i.push(...Xf(w.failed)),i.push(...v.warnings),i.push(...Zf(v.failed)),i.push(...Qf(w,v)),i.push(..._p(v,w)),i.push(...sE(w,v)),i.push(...gp(v));let S=Xi(h.extensions,w,v),x=np(n,S,w.loaded.map(W=>({layer:W.layer,name:W.name})),w.failed.map(W=>({name:W.name})),w.disabled_by_flag);i.push(...x.warnings);let A=S.filter(W=>W.update_check_status==="failed").map(W=>`extension_update_check_failed:${W.name}`);i.push(...A);let E=Zi(n,i,S,o);i.push(...E.warnings);let b=[...E.warnings],P={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},U=br(b),z=kr(),D=E.warning_codes,Q=DE(n,c,o.vocabulary,w),Fe=OE(E.remediation,w.failed.length,v.failed.length,o.vocabulary,_,Q),ye=LE(n,c,o.vocabulary,w),Ue={status:E.status,scope:n,warning_count:E.warning_count,warning_codes:D,total_extensions:S.length,managed_total:S.filter(W=>W.managed).length,enabled_total:S.filter(W=>W.enabled).length,active_total:S.filter(W=>W.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:S.filter(W=>W.runtime_active===!0).length,activation_status_totals:{ok:S.filter(W=>W.activation_status==="ok").length,failed:S.filter(W=>W.activation_status==="failed").length,not_loaded:S.filter(W=>W.activation_status==="not_loaded").length,unknown:S.filter(W=>W.activation_status==="unknown").length},unknown_capability_count:U.length,capability_contract_version:z.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:S.filter(W=>W.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:ua(w.failed),activation_failures:ua(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:x.warnings.length,trace_enabled:d,isolation:ye,policy:P,remediation:Fe},ze=_?{requested:!0,applied:_.adopted_entries.length>0,adopted_count:_.adopted_entries.length,already_managed_count:_.already_managed_count,adopted_extensions:_.adopted_entries.map(W=>W.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:h.extensions.filter(W=>W.managed).length,adopted_extensions:[]},tn={mode:l,summary:Ue,triage:E,trace_enabled:d,capability_contract:z,capability_guidance:U,managed_state_fix:ze,author_manifest:k,isolation:ye,policy:w.policy};if(l==="deep"){let W=d?v.failed:v.failed.map(V=>{let{trace:qn,...Bn}=V;return Bn});tn.deep={warnings:b,warning_codes:D,capability_contract:z,capability_guidance:U,trace_enabled:d,managed_state:{path:m.path,count:p.entries.length,entries:p.entries},installed_extensions:S,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(V=>({layer:V.layer,directory:V.directory,name:V.name,version:V.version,entry:V.entry,priority:V.priority}))},activation:{failed:W,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:x.summary},d&&(tn.deep.trace={activation_failures:v.failed.filter(V=>V.trace!==void 0).map(V=>({layer:V.layer,name:V.name,entry_path:V.entry_path,error:V.error,method:V.trace.method,command:V.trace.command,capability:V.trace.capability,missing_capability:V.trace.missing_capability,registration_index:V.trace.registration_index,expected_schema:V.trace.expected_schema,hint:V.trace.hint,received:V.trace.received}))})}return a(tn)},jE=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:s,withResult:a}=e,c=await T(r.settings_root),l=await Je({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:s.noExtensions===!0}),d=await Ke(l);i.push(...l.warnings),i.push(...d.warnings);let u=qf(t,l,d);if(t!==void 0&&u.extensions.length===0){let m=o.vocabulary==="package"?"package":"extension",f=[...new Set(l.loaded.map(_=>o.vocabulary==="package"&&typeof _.source_package=="string"&&_.source_package.trim().length>0?_.source_package.trim():_.name))].sort((_,h)=>_.localeCompare(h)),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 a({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},FE=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await va(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let o=await pp(r.entries,RS,async s=>{if(s.source.kind!=="github")return s;let a=await yp(s.source);return{...s,last_update_check_at:a.checked_at,last_update_remote_commit:a.remote_commit,update_available:a.available,update_error:a.error}});r={...r,updated_at:C(),entries:_r(o)},await Jt(e.resolvedRoots.selected_root,r)}return{state:r,fix:i}},UE=async(e,t,n)=>{let r=await Je({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Ke({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:Xi(n,r,i),failures:zp(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}}},zE=(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},Tp=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:s}=e,a=await T(r.settings_root),c=US(a.extensions.policy),l=await we(r.selected_root);i.push(...l.warnings);let d=await rt(r.selected_root,n,a,l.state);i.push(...d.warnings);let{state:u,fix:m}=await FE(e,d.extensions,l.state),f=await rt(r.selected_root,n,a,u);if(i.push(...f.warnings),t==="manage"){let v=f.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);i.push(...v)}let p=await UE(e,a,f.extensions),_=p.installed,h=Zi(n,i,_,o);i.push(...h.warnings);let w={total:_.length,managed_total:_.filter(v=>v.managed).length,enabled_total:_.filter(v=>v.enabled).length,active_total:_.filter(v=>v.active).length,extensions:_,triage:h,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=zE(m,_)),s(w)},$p={init:mE,install:AE,uninstall:$E,explore:Tp,manage:Tp,describe:jE,reload:fE,doctor:ME,catalog:pE,adopt:TE,"adopt-all":RE,activate:Cp,deactivate:Cp,migrate:bp},HE=e=>[e.action==="uninstall",e.action==="manage",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[e.action==="doctor",e.options.fixManagedState===!0].every(Boolean)].some(Boolean),WE=e=>HE(e)?pa(e.resolvedRoots.settings_root,`${e.action}-state`,()=>$p[e.action](e)):$p[e.action](e);import{execFile as GE}from"node:child_process";import{realpath as qE}from"node:fs/promises";import Bp from"node:path";import{promisify as BE}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]="be96ba6f-f848-58bf-8a3b-b6e3d6ab4b7a")}catch{}})();var VE=BE(GE),JE=32*1024*1024,KE=1e4,YE=["search/eval-queries.json"];function ka(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function XE(e){return`'${e.replaceAll("'","'\\''")}'`}async function ZE(e,t=qE){return t(e).catch(()=>Bp.resolve(e))}async function oo(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 ZE(e),r=ka(Bp.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=Ns.map(o=>`${r}/${ka(o)}`);try{let{stdout:o}=await VE("git",["ls-files","-z","--",...i.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:JE,windowsHide:!0,timeout:KE}),s=new Set(YE.map(l=>`${r}/${l}`)),a=[...new Set(o.split("\0").filter(l=>l.length>0&&!s.has(ka(l))))].sort((l,d)=>l.localeCompare(d)),c=i.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>XE(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import{execFile as Ux}from"node:child_process";import{randomUUID as zx}from"node:crypto";import{readdir as Hx,stat as Wx}from"node:fs/promises";import ge 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]="a917834c-52c2-54c6-af84-a57d4c4b3855")}catch{}})();var QE=Object.freeze({pm_item_scalar_missing:!0});function Dn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function Y(e){return e===void 0?QE:e}function Ot(e){return ke(R(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function Sa(e,t){let n=De(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,o]of e.split(/\r?\n/).entries()){let s=o.trim();if(s)try{let a=JSON.parse(s);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new y(`History merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}}return r}function _t(e){return R({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function ex(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&_t(e[r])===_t(t[r]);)r+=1;return r}function zj(e,t,n){let r=Sa(e,"base"),i=Sa(t,"ours"),o=Sa(n,"theirs"),s=[r,i,o].map(f=>f.filter(p=>p.op==="create"));if(s[0].length===0&&s.slice(1).every(f=>f.length>0)||s.some(f=>f.length>1)||new Set(s.flat().map(_t)).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 a=ex(i,o);if(a===i.length&&a===o.length)return{merged:Ut(i),strategy:"identical",common_entries:a,entries_from_ours:0,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(a===o.length)return{merged:Ut(i),strategy:"fast_forward_ours",common_entries:a,entries_from_ours:i.length-a,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(a===i.length)return{merged:Ut(o),strategy:"fast_forward_theirs",common_entries:a,entries_from_ours:0,entries_from_theirs:o.length-a,entries_total:o.length,reanchored:!1};let c=i.slice(a),l=new Set(c.map(_t)),d=o.slice(a).filter(f=>!l.has(_t(f))),u=[...c,...d].sort((f,p)=>{let _=jt(f.ts,p.ts);if(_!==0)return _;let h=l.has(_t(f)),w=l.has(_t(p));return h!==w?Number(w)-Number(h):_t(f).localeCompare(_t(p))}),m=ri([...i.slice(0,a),...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:Ut(m.entries),strategy:"union_reanchor",common_entries:a,entries_from_ours:c.length,entries_from_theirs:d.length,entries_total:m.entries.length,reanchored:!0}}function Ea(e,t){let n=De(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,o]of e.split(/\r?\n/).entries()){let s=o.trim();if(!s)continue;let a;try{a=JSON.parse(s)}catch{throw new y(`Relationship merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.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(a)}return r}function so(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
57
- `)}
58
- `}function tx(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Hj(e,t,n){Ea(e,"base");let r=Ea(t,"ours"),i=Ea(n,"theirs"),o=Math.min(r.length,i.length),s=0;for(;s<o&&r[s].eventId===i[s].eventId;)s+=1;if(s===r.length&&s===i.length)return{merged:so(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===i.length)return{merged:so(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:so(i),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:i.length-s,entries_total:i.length,reanchored:!1};let a=r.slice(s),c=new Set(a.map(m=>m.eventId)),l=i.slice(s).filter(m=>!c.has(m.eventId)),d=[...a,...l].sort((m,f)=>{if(m.timestamp!==void 0&&f.timestamp!==void 0){let h=jt(m.timestamp,f.timestamp);if(h!==0)return h}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),_=c.has(f.eventId);return p!==_?Number(_)-Number(p):0}),u=tx([...r.slice(0,s),...d]);return{merged:so(u),strategy:"union_reanchor",common_entries:s,entries_from_ours:a.length,entries_from_theirs:l.length,entries_total:u.length,reanchored:!0}}var nx=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],rx=["acceptance_criteria"],ix=["updated_at"];function Xt(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:R(e)===R(t)}function Vp(e,t,n){let r=d=>Array.isArray(d)?d:[],i=new Set(r(e).map(d=>R(d))),o=r(t),s=new Set(o.map(d=>R(d))),a=r(n),c=new Set(a.map(d=>R(d))),l=o.filter(d=>{let u=R(d);return!i.has(u)||c.has(u)});for(let d of a){let u=R(d);!s.has(u)&&!i.has(u)&&l.push(d)}return l}function Er(e){if(typeof e!="object"||e===null||Array.isArray(e))return R(e);let{provenance:t,...n}=e;return R(n)}function ox(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 sx(e,t,n){let r=d=>Array.isArray(d)?d:[],i=new Set(r(e).map(Er)),o=r(t),s=new Set(o.map(Er)),a=r(n),c=new Set(a.map(Er)),l=o.filter(d=>{let u=Er(d);return!i.has(u)||c.has(u)});for(let d of a){let u=Er(d);!s.has(u)&&!i.has(u)&&l.push(ox(d))}return l}function ax(e,t){return jt(String(e),String(t))>=0?e:t}function Jp(e,t,n,r){return Xt(t,n)?{value:t,from_theirs:!1,conflict:!1}:Xt(e,t)?{value:n,from_theirs:!0,conflict:!1}:Xt(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function Kp(e,t,n,r,i,o,s){let a=Jp(e,t,n,r);if(!a.conflict)return{...a,conflict:!1};if(i==="preferred_side")return{...a,resolution_basis:"requested_preference",retained_side:a.from_theirs?"theirs":"ours"};let c=jt(o,s);if(i==="latest_document_update"&&c!==0){let d=c<0;return{value:d?n:t,from_theirs:d,conflict:!0,resolution_basis:"document_updated_at",retained_side:d?"theirs":"ours"}}let l=R(Y(n)).localeCompare(R(Y(t)))<0;return{value:l?n:t,from_theirs:l,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:l?"theirs":"ours"}}function xa(e){return{...e.metadata}}function Ia(e,t,n){try{let r=Vl(xt(e,n),n),i=Object.entries(r.metadata).find(([,o])=>Dn(o))?.[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 cx(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?sx(e.baseValue,e.oursValue,e.theirsValue):e.field==="acceptance_criteria"?Vp(li(e.baseValue),li(e.oursValue),li(e.theirsValue)).join("; "):Vp(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,Xt(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function lx(e){let t=Kp(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 dx(e,t,n,r,i,o,s){let a=new Set([...nx,...rx]),c=new Set(ix),l=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,m)=>u.localeCompare(m)),d={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let u of l){let m=e[u],f=t[u],p=n[u];if(!cx({field:u,baseValue:m,oursValue:f,theirsValue:p,unionFieldSet:a,accumulator:d})){if(c.has(u)){d.merged[u]=ax(f,p);continue}lx({field:u,baseValue:m,oursValue:f,theirsValue:p,preferred:r,conflictResolution:i,oursUpdatedAt:o,theirsUpdatedAt:s,accumulator:d})}}return d}function Wj(e,t,n,r={}){let i=r.preferred??"ours",o=r.conflictResolution??"preferred_side",s=Ia(t,"ours",r),a=Ia(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:s.metadata.id});let c=Ia(e,"base",r);if(c.metadata.id!==s.metadata.id||c.metadata.id!==a.metadata.id)throw new y("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",g.CONFLICT,{code:"item_identity_conflict",item_id:c.metadata.id});let l=xa(c),d=xa(s),u=xa(a),{merged:m,conflictFields:f,fieldsFromTheirs:p,unionFields:_,conflictDecisions:h}=dx(l,d,u,i,o,s.metadata.updated_at,a.metadata.updated_at),w=Kp(c.body,s.body,a.body,i,o,s.metadata.updated_at,a.metadata.updated_at);return w.conflict?(f.push("body"),h.push({field:"body",base:Y(c.body),ours:Y(s.body),theirs:Y(a.body),retained:Y(w.value),discarded:Y(w.from_theirs?s.body:a.body),retained_side:w.retained_side,resolution_basis:w.resolution_basis})):w.from_theirs&&p.push("body"),{merged:Bl({metadata:m,body:w.value},r),conflict_fields:f,fields_from_theirs:p,union_fields:_,conflict_decisions:h,requested_preference:i,requested_preference_applied:o==="preferred_side",conflict_resolution:o}}function Aa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ra(e,t){let n=De(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 ux(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=l=>{let d=new Map;for(let u of l){let m=R(u);d.set(m,(d.get(m)??0)+1)}return d},i=r(e),o=r(t),s=r(n);for(let[l,d]of i)if((o.get(l)??0)<d||(s.get(l)??0)<d)return null;let a=new Map(o),c=[];for(let l of n){let d=R(l),u=a.get(d)??0;u>0?a.set(d,u-1):c.push(l)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function mx(e,t,n,r,i,o,s){if(!Aa(t)||!Aa(n))return null;let a=Aa(e)?e:{},c={},l=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((d,u)=>d.localeCompare(u));for(let d of l){let u=i.length>0?`${i}.${d}`:d,m=fx(a,t,n,d,r,u,o,s);m!==void 0&&(c[d]=m)}return c}function Yp(e,t,n,r,i,o,s){if(Xt(t,n))return t;let a=ux(e,t,n);if(a!==null)return a.acceptedTheirs&&s.push(i),a.merged;let c=mx(e,t,n,r,i,o,s);if(c!==null)return c;let l=Jp(e,t,n,r);return l.conflict?o.push(i):l.from_theirs&&s.push(i),l.value}function fx(e,t,n,r,i,o,s,a){let c=Object.prototype.hasOwnProperty.call(t,r),l=Object.prototype.hasOwnProperty.call(n,r),d=Object.prototype.hasOwnProperty.call(e,r);if(c&&l)return Yp(e[r],t[r],n[r],i,o,s,a);if(c){if(d&&Xt(e[r],t[r])){a.push(o);return}return d?(s.push(o),i==="theirs"?void 0:t[r]):t[r]}if(!(d&&Xt(e[r],n[r])))return d?(s.push(o),i==="theirs"?n[r]:void 0):(a.push(o),n[r])}function Gj(e,t,n,r={}){let i=r.preferred??"ours",o=Ra(e,"base"),s=Ra(t,"ours"),a=Ra(n,"theirs"),c=[],l=[],d=Yp(o,s,a,i,"",c,l);return{merged:`${JSON.stringify(d??null,null,2)}
59
- `,conflict_paths:c,paths_from_theirs:l,preferred:i}}import{constants as Xp}from"node:fs";import{lstat as px,open as hx}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]="b8cf81eb-6afd-5d5a-8a4d-b5b5fbd51ace")}catch{}})();var _x={lstat:px,open:hx};function gx(e){return e.O_NOFOLLOW??0}async function xr(e,t,n=_x){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let i=await n.open(e,Xp.O_RDONLY|gx(Xp));try{let o=await i.stat();if(!o.isFile()||o.size>t)return null;let s=Buffer.alloc(o.size),a=0;for(;a<s.length;){let{bytesRead:l}=await i.read(s,a,s.length-a,a);if(l===0)break;a+=l}return(await i.stat()).size===o.size&&a===o.size?s.toString("utf8",0,a):null}finally{await i.close()}}import ao from"node:path";import{execFile as yx}from"node:child_process";import{createHash as wx}from"node:crypto";import{readdir as vx}from"node:fs/promises";import bx from"node:path";import{promisify as kx}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]="b5dfe3ea-a457-5fb4-84b4-c03110f6b53a")}catch{}})();var Zt=kx(yx),Ca=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function tF(e,t){let n=t.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n;for(let i of["rebase-merge","rebase-apply"])try{let{stdout:o}=await Zt("git",["rev-parse","--path-format=absolute","--git-path",`${i}/orig-head`],{cwd:e,timeout:1e4}),s=(await xr(o.trim(),128))?.trim();if(s===void 0||!Ca.test(s))continue;let{stdout:a}=await Zt("git",["rev-parse","--verify",`${s}:${r}`],{cwd:e,timeout:1e4}),c=a.trim();return{kind:"rebase",original_head:s,original_blob:c}}catch{}}function Zp(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&t.kind==="rebase"&&typeof t.original_head=="string"&&Ca.test(t.original_head)&&typeof t.original_blob=="string"&&Ca.test(t.original_blob)}async function Qp(e,t,n,r){if(r!==void 0&&wx(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(r)}\0`).update(r).digest("hex")!==n.original_blob)return!1;try{let{stdout:i}=await Zt("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),o=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await vx(i.trim())).some(l=>o.has(l)))return!1;let{stdout:s}=await Zt("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(s.trim()!==n.original_head)return!1;let{stdout:a}=await Zt("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(a.trim()!==n.original_blob)return!1;let{stdout:c}=await Zt("git",["hash-object","--",bx.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await Zt("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0d215db3-1a51-5509-aa08-a3d0708aa3ef")}catch{}})();var Sx=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,Ex=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,lo=2048,xx=64,Ix=1e5,Ax=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 gt(e){return Sx.test(e)}var Rx=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),uo="bounded_non_sensitive_scalars_v1",Cx=new Set(["open","in_progress","blocked","closed","canceled"]),Tx=new Set(["risk","confidence","severity"]),$x=new Set(["low","medium","high","critical"]),th=new Map([["priority",new Set([0,1,2,3,4].map(R))],["status",new Set([...Cx].map(R))],...[...Tx].map(e=>[e,new Set([...$x].map(R))])]);function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nh(e,t){return Object.keys(e).every(n=>t.has(n))}function co(e){return Array.isArray(e)&&e.length<=lo&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Ir(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>Ix||r.depth>xx)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 rh(e){if(!it(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[nh(e,Rx),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),Ir(e.base),Ir(e.ours),Ir(e.theirs),Ir(e.retained),Ir(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function Ox(e){if(!it(e))return!1;let t=Object.entries(e);return t.length<=lo&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function Dx(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||ao.posix.isAbsolute(e))return!1;let n=ao.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&ao.posix.basename(n,ao.posix.extname(n))===t}function Px(e){return!co(e.fields_from_theirs)||!co(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>lo||!e.decisions.every(rh)?!1:e.merged_field_hashes===void 0||Ox(e.merged_field_hashes)}function Nx(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===uo)&&i.includes(e.evidence_source)}function Lx(e){return typeof e.created_at=="string"&&dn(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&dn(e.reconciled_at))}function eh(e,t){if(!it(t)||mo(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(o=>o==="pm_value_hash"||o==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let r=t.pm_value;return(r===null||th.get(e)?.has(R(r))===!0)&&Ot(r)===t.pm_value_hash}function Mx(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&eh(r.field,r.retained)&&eh(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===uo)}function jx(e){return e.operation!==void 0&&!Zp(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function Fx(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||!nh(e,Ax)?"required_fields":typeof e.id!="string"||!gt(e.id)?"receipt_id":typeof e.item_id!="string"||!Ex.test(e.item_id)?"item_id":Dx(e.item_path,e.item_id)?null:"item_path"}function Ta(e,t){if(!it(e))return"required_fields";let n=Fx(e);return n!==null?n:jx(e)?Px(e)?Nx(e)?Lx(e)?t==="durable"&&!Mx(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function $a(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 ih(e){if(!it(e))return;if(!co(e.fields_from_theirs))return"fields_from_theirs";if(!co(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>lo)return"decisions";let t=e.decisions.findIndex(n=>!rh(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function Oa(e,t){return Ta(e,t)===null}function mo(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 Da(e,t){let n=Dn(t),r=Ot(n?void 0:t);return!n&&(t===null||th.get(e)?.has(R(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]="7793ca52-14e7-544f-a5cf-ebea38bb1401")}catch{}})();var qx=Gx(Ux),ah=16*1024*1024,fo=100;async function Pa(e){try{let{stdout:t}=await qx("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function ch(e,t){let n=ge.dirname(ge.resolve(e,t));for(let r=0;r<12;r+=1){if(await $(ge.join(n,"settings.json")))return n;let i=ge.dirname(n);if(i===n)break;n=i}return null}function Na(e){return ge.join(e,"merge-receipts")}function Pn(e){return`${e}.json`}async function oh(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await xr(e.receiptPath,ah)}catch(o){if(kt(o))return null;throw o}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=$a(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!Oa(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||ge.basename(e.receiptPath)!==Pn(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprints:La(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
60
- `}}function Ar(e,t=!1){return ke(R({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:ke(R(Y(n.retained))),discarded_hash:ke(R(Y(n.discarded)))})):Ma(e).decisions}))}function La(e){let t=[Ar(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(Ar(e,!0)),t}function Bx(e,t){if(e.state==="reconciled"&&t.state==="reconciled"&&e.settlement===t.settlement)return e;let{reconciled_at:n,settlement:r,...i}=e;return{...i,state:"pending"}}function Ma(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:mo(t.retained)??Ot(Dn(t.retained)?void 0:t.retained),discarded_hash:mo(t.discarded)??Ot(Dn(t.discarded)?void 0:t.discarded)}))}}async function bF(e){let t=await Pa(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,i=ge.basename(r,ge.extname(r)),o={version:1,id:zx(),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(a=>({...a,base:Y(a.base),ours:Y(a.ours),theirs:Y(a.theirs),retained:Y(a.retained),discarded:Y(a.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:C(),value_availability:"clone_local"};await Vn(t),await ne(ge.join(t,Pn(o.id)),`${JSON.stringify(o,null,2)}
61
- `);let s=await ch(e.cwd,o.item_path);if(s!==null){let a=Na(s),c=o.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:Da(u.field,u.retained),discarded:Da(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),l=c.reduce((u,m)=>u+(Object.hasOwn(m.retained,"pm_value")?1:0)+(Object.hasOwn(m.discarded,"pm_value")?1:0),0),d={...o,decisions:c,value_availability:l===0?"hash_only":l===c.length*2?"bounded_inline":"mixed",value_policy:uo};await Vn(a),await ne(ge.join(a,Pn(o.id)),`${JSON.stringify(d,null,2)}
62
- `)}return o}async function sh(e,t){let n;try{n=await Hx(e)}catch(a){let c=await Vx(e,a);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,o=[],s=(a,c)=>{if(i+=1,o.length>=fo)return;let l=a.slice(0,-5);o.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},...gt(l)?{receipt_id:l}:{candidate_name_hash:ke(a)}})};for(let a of n.sort((c,l)=>c.localeCompare(l))){if(!a.endsWith(".json"))continue;let c=await Jx(e,a,t);c.receipt!==void 0?r.push(c.receipt):s(a,c)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:o,invalid_evidence_truncated:i>o.length}}async function Vx(e,t,n=Wx){if(!j(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!j(i))return!1;let o=ge.dirname(r);if(o===r)return!0;r=o}}async function Jx(e,t,n){let r;try{r=await xr(ge.join(e,t),ah)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=$a(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let o=Ta(i,n);if(o!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(o)?"identity_invalid":"schema_invalid",validation_error:o,...o==="collections"?{validation_path:ih(i)}:{}};let s=i;if(t!==Pn(s.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:a,evidence_source:c,...l}=s;return{receipt:{...l,requested_preference:s.requested_preference??a??"ours",requested_preference_applied:s.requested_preference_applied??(s.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:s.conflict_resolution??"preferred_side",evidence_source:n}}}async function yt(e,t={}){let n=await Pa(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await sh(n,"clone_local"),i=t.pmRoot??ge.join(e,".agents","pm"),o=await sh(Na(i),"durable"),s=new Map(o.receipts.map(l=>[l.id,l])),a=0,c=[];for(let l of r.receipts){let d=s.get(l.id);if(d!==void 0&&!(d.value_policy===void 0?La(l):[Ar(l)]).includes(Ar(d))){s.delete(l.id),a+=1,r.invalid_evidence.length+o.invalid_evidence.length+c.length<fo&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:l.id});continue}s.set(l.id,d===void 0?l:Bx(l,d))}return{receipts:[...s.values()].filter(l=>(t.includeReconciled||l.state==="pending")&&(t.includeLossless!==!1||l.decisions.length>0)).sort((l,d)=>l.created_at.localeCompare(d.created_at)),invalid_evidence_count:r.invalid_evidence_count+o.invalid_evidence_count+a,invalid_evidence:[...r.invalid_evidence,...o.invalid_evidence,...c].slice(0,fo),invalid_evidence_truncated:r.invalid_evidence_truncated||o.invalid_evidence_truncated||r.invalid_evidence_count+o.invalid_evidence_count+a>fo,clone_local_evidence_resolved:n!==null}}function Nn(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function kF(e,t,n={}){let r=await Pa(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(!Oa(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let o=C(),s=ge.join(r,Pn(t.id)),a=await ch(e,t.item_path),c=a===null?null:ge.join(Na(a),Pn(t.id)),d=(await Promise.all([oh({receiptPath:s,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:o,settlement:n.settlement}),...c===null?[]:[oh({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:o,settlement:n.settlement})]])).filter(m=>m!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(m=>m.modern)?[Ar(t)]:La(t)).some(m=>d.every(f=>f.fingerprints.includes(m))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let m of d)await ne(m.path,m.content)}async function SF(e){let t=await yt(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:C()}}import{createHash as Kx}from"node:crypto";import po from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5ba549f-1965-5c5e-98b3-bd0903210032")}catch{}})();var Yx="2026-08-09T16:15:18.000Z",dh=Symbol("pre-durable-disposition-eligible");function wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ja(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function lh(e){return wt(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 uh(e,t){if(typeof e!="string")return!1;let n=po.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!po.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(po.posix.basename(n)===`${t}.toon`||po.posix.basename(n)===`${t}.md`)}function Xx(e,t){return typeof e.receipt_id=="string"&&gt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&uh(e.item_path,t)}function mh(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,o=Array.isArray(i)?new Set(i.flatMap(s=>lh(s)?[s.field]:[])):new Set;return ja(t)&&ja(n)&&ja(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(lh)&&o.size===i.length&&t.length===o.size&&t.every(s=>o.has(s))}function Zx(e,t){return Xx(e,t)&&mh(e)}function Qx(e,t){return typeof e.receipt_id=="string"&&gt(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&&uh(e.item_path,t)&&mh(e)}function eI(e){return e[dh]===!0}function fh(e,t){if(!wt(e)||!wt(e.context))return[];let n=e.context.merge;return!wt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!wt(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:Zx(r,t),[dh]:Qx(r,t),...typeof e.ts=="string"&&dn(e.ts)?{eventTimestamp:e.ts}:{}}])}function ph(e,t,n){if(!wt(e)||e.op!=="merge_reconcile")return[];if(!wt(e.context)||!wt(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!wt(i)||typeof i.receipt_id!="string"||!gt(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"||!dn(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 hh(e,t,n=[]){let r=new Map;for(let s of n){let a=`${s.itemId}\0${s.originalHistoryLine}\0${s.receiptId}\0${s.originalEventTimestamp}`;r.set(a,Math.max(r.get(a)??0,s.auditHistoryLine))}let i=s=>eI(s)&&s.eventTimestamp!==void 0&&jt(s.eventTimestamp,Yx)<0&&(r.get(`${s.itemId}\0${s.line}\0${s.receiptId}\0${s.eventTimestamp}`)??0)>s.line;return{missing:e.filter(s=>!s.legacySummaryAccepted&&!t.has(s.receiptId)&&!i(s)).map(s=>({item_id:s.itemId,history_line:s.line,...gt(s.receiptId)?{receipt_id:s.receiptId}:{receipt_reference_hash:Kx("sha256").update(s.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(s=>s.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}import{isUtf8 as tI}from"node:buffer";import{readFile as nI}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]="c1778165-2763-5eab-80f3-d52e08547fc2")}catch{}})();function rI(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 iI(e){if(De(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[s,a]of e.split(`
63
- `).entries()){if(!a.trim()){n+=a.length+1;continue}let c=rI(a);if(c===null){r===void 0&&(r=n,i=s+1),n+=a.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+=a.length+1}let o=fn(t);if(!o.ok||o.item_hash_version===void 0)throw new y("History salvage requires a nonempty verified prefix.",g.CONFLICT,{code:"history_salvage_refused",verification_errors:o.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries:t,itemHashVersion:o.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:ke(e.slice(r)),retained_entries:t.length}}}async function oI(e,t,n){if(!e.located)return{itemRaw:null,document:n};let r=await Cd(e.located,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n}}async function _h(e){let t;try{t=await nI(e)}catch(n){if(j(n))return null;throw n}if(!tI(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 gh(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 o=await _h(t.historyPath);if(o===null)throw new y(`No history stream exists for ${t.id}.`,g.NOT_FOUND);await He({path:t.historyPath,scope:"project"});let s=iI(o),a=bd(s.entries,s.entries.length-1),c=rd(a);if(typeof a.metadata.id=="string"&&a.metadata.id!==t.id)throw new y("History belongs to another item; salvage refused.",g.CONFLICT,{code:"history_salvage_refused"});let l=await oI(t,n,c),d=As({itemDocument:l.document,subjectId:t.id,author:i,force:r.force,settings:n}),u=s.itemHashVersion,m=r.dryRun===!0,f=s.receipt!==null;if(f&&!m){let p=await ce(e.pmRoot,t.id,n.locks.ttl_seconds,i,!!r.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let _=await _h(t.historyPath),h=await Pe(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),w=h?await K(h.itemPath):null;if(_!==o||w!==l.itemRaw)throw new y("History or item changed while waiting for salvage lock; retry.",g.CONFLICT);let v=ni({...ed({hashAlgorithm:Ee(s.entries.at(-1).hash_algorithm),nowIso:C(),author:i,op:"history_salvage",before:c,after:c,message:r.message,context:{history_salvage:s.receipt}}),before_hash:s.entries.at(-1).after_hash,after_hash:s.entries.at(-1).after_hash,item_hash_version:u});await Ri({historyPath:t.historyPath,historyRawUnderLock:o,nextHistoryRaw:`${s.prefix}${JSON.stringify(v)}
64
- `}),d.push(...await X({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return{id:t.id,dry_run:m,changed:f,history:{path:t.historyPath,entries_scanned:s.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:[]},...s.receipt?{salvage:s.receipt}:{},warnings:d,generated_at:C()}}import{realpath as bh}from"node:fs/promises";import Fa from"node:path";import kh 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]="55e22181-7bbf-5fed-965c-219fe465ed72")}catch{}})();function yh(e,t){return t==="body"?e.body:e.metadata[t]}function Ua(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 o=t.findIndex((s,a)=>!r.has(a)&&Ua(i,s));return o<0?!1:(r.add(o),!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)&&Ua(i,n[r]))}function wh(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let o=e[i],s=new Set;for(let c of od(o.patch))s.add(di(c.path)),c.from&&s.add(di(c.from));let a=[...n].filter(c=>s.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:i+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,l)=>c.localeCompare(l))})}}return r.reverse()}function sI(e,t,n){let r=kh.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(di(p.path));let o=new Set([...i].filter(p=>Ua(yh(t,p),yh(n,p)))),s=new Set([...i].filter(p=>!o.has(p))),a=wh(e,s),c=wh(e,o),l=[...i].sort((p,_)=>p.localeCompare(_)),d=[...s].sort((p,_)=>p.localeCompare(_)),u=[...o].sort((p,_)=>p.localeCompare(_)),m=[...new Set(a.map(p=>p.author))].sort((p,_)=>p.localeCompare(_)),f=[...new Set(c.map(p=>p.author))].sort((p,_)=>p.localeCompare(_));return{reconciled_field_count:i.size,reconciled_fields:l,reverted_field_count:s.size,reverted_fields:d,discarded_events:a,discarded_authors:m,preserved_field_count:o.size,preserved_fields:u,preserved_events:c,preserved_authors:f,recovery_hint:a.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 aI(e){try{return await bh(e)}catch{return null}}async function cI(e){if(await aI(Fa.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let n=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let i=Object.keys(r).sort();if(n.length!==i.length||n.some((a,c)=>a!==i[c]))return null;let o=e.currentItemReplay.metadata;return n.every(a=>{let c=a==="body"?e.currentItemReplay.body:o[a];return[Ot(c),ke(R(Y(c)))].includes(r[a])})?{receipt:e.receipt,declaredFields:n}:null}async function lI(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(s=>s.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await bh(e.itemPath),r=[];for(let s of t){let a=await cI({receipt:s,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});a&&r.push(a)}let i=new Set(r.flatMap(({declaredFields:s})=>s)),o=e.reconciliation?.reconciled_fields;return r.length>0&&(o===void 0||o.length>0&&o.every(s=>i.has(s)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:s})=>s.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function vh(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:o}=e,s=t.currentItemPath===null?null:Fa.relative(o,t.currentItemPath).split(Fa.sep).join("/");if(!n||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||s!==i.item_path||i.operation===void 0||!await Qp(o,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 dI(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(s=>s.item_id===e.subjectId).map(s=>s.id)??[]),r=(e.options.mergeReceiptProof?await yt(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(s=>s.item_id===e.subjectId&&t.has(s.id))??[],i=e.options.mergeReceiptProof?await lI({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(i&&!i.trusted&&e.options.force!==!0)throw new y(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${i.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 o=i?.trusted?r.filter(s=>i.receipt_ids.includes(s.id)):[];return{mergeReceiptProof:i,effectiveAuditContext:o.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:o.map(Ma)}}:e.options.auditContext}}function uI(e,t,n){let r=e.located?.itemPath??null,i=t.loadedItem,o=t.entries;if(!i)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=id(i.document),a=o[o.length-1].after_hash;return{currentItemReplay:s,currentItemPath:r,matchedChainBefore:mn(s,n,Ee(o.at(-1)?.hash_algorithm)).includes(a),currentItemRawBeforeLock:i.raw,loadedItem:i}}function mI(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 fI(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=Ee(e.reanchorEntries.at(-1)?.hash_algorithm),i=mn(e.finalReplay,e.itemHashVersion,r),o=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,s=i.indexOf(o),a=mn(n,e.itemHashVersion,r),c={hash_algorithm:r,ts:C(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?kh.compare(e.finalReplay,e.currentItemReplay):[],before_hash:i[s],after_hash:a[s],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(ni({...c,event_class:Kl(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function pI(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 za(e,t,n){let{pmRoot:r,settings:i,typeRegistry:o}=await cs(n.path),s=await Yd(r,e,i,o.type_to_folder);return t.salvageTail===!0?gh({pmRoot:r,subject:s,settings:i,typeRegistry:o,options:t,author:q(t.author,i.author_default)}):im({pmRoot:r,subject:s,settings:i,typeRegistry:o,operation:"history-repair",options:t,transform:a=>_I({pmRoot:r,subject:s,options:t},a)})}function hI(e,t){let n=e.mergeAbandonmentProof!==void 0&&e.auditContext!==void 0&&t.some(r=>r.op==="merge_reconcile"&&R(r.context)===R(e.auditContext));return e.forceAuditEntry===!0&&!n}async function _I(e,t){let{pmRoot:n,subject:r,options:i}=e,o=t.entries,s=t.verification,a=fn(o),c=i.normalizeProvenance?Zu(o):{entries:o,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},l=sd(c.entries),d=new Set(c.entries.map(U=>U.item_hash_version).filter(U=>U!==void 0)),u=ri(c.entries,l),m=uI(r,t,l);await vh(i.mergeAbandonmentProof,m,s.ok,u);let f=u.finalDocument,p=mn(f,l),_=!1;if(m.currentItemReplay!==null){let U=mn(m.currentItemReplay,l);_=!p.some((z,D)=>z===U[D])}let h=_&&m.currentItemReplay?sI(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await dI({options:i,pmRoot:n,subjectId:r.id,itemReplayContext:m,reconciliation:h}),k=[u.entriesRehashed>0,u.entriesPatchRepaired>0,_,hI(i,o),c.receipt.changed].some(Boolean),S=t.author,x=!!i.dryRun,A=mI({message:i.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:_}),{rewrittenEntries:E,auditEntryAdded:b}=fI({reanchorEntries:u.entries,changed:k,reconcileNeeded:_,currentItemReplay:m.currentItemReplay,finalReplay:f,author:S,message:A,auditOperation:i.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:l,explicitItemHashVersion:u.explicitItemHashVersion}),P=pI(k,u.skippedOps,h);return{changed:k,rewrittenEntries:E,beforeWrite:async()=>vh(i.mergeAbandonmentProof,m,s.ok,u),report:({verification:U,warnings:z})=>({id:r.id,dry_run:x,changed:k,history:{path:r.historyPath,entries_scanned:o.length,chain_drift_before:!s.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:_,audit_entry_added:b,verify_ok:U.ok,verify_errors:U.errors,item_hash_version_before:a.item_hash_version??null,item_hash_version_after:l,version_disposition:d.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},provenance_normalization:{requested:i.normalizeProvenance===!0,...c.receipt},...h?{reconciliation:h}:{},...w?{merge_receipt_proof:w}:{},warnings:[...new Set([...P,...z])].sort((D,Q)=>D.localeCompare(Q)),generated_at:C()})}}function _1(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 g1(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 cs(t.path),o=[],s=await zt(n,r.item_format,i.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await Gt(n,s),c=e.normalizeProvenance?await Qu(n):[],l=[...new Set([...a.driftedItems,...c])].sort((f,p)=>f.localeCompare(p)),d=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let f of l)try{let p=await za(f,{...e,auditContext:e.auditContextById?.[f],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[f]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),_=p.changed?"repaired":"skipped_clean";m[_]+=1,u.push(...p.warnings.map(h=>`${f}:${h}`)),d.push({id:f,outcome:_,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,d.push({id:f,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await Yl(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:s.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:d,totals:m,warnings:[...new Set([...o,...u])].sort((f,p)=>f.localeCompare(p)),generated_at:C()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7386bc6e-f032-5faa-b6b0-1fbe9eee1420")}catch{}})();var gI=new Set(Hd),Eh=25,Ln=8,Qt=100,yI=ve.join("runtime","telemetry","events.jsonl"),wI=ve.join("runtime","telemetry","state.json"),vI=2500,bI=500,xh=Bd-3,kI=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Va(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 Ja(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Mn(e){return e.trim().toLowerCase()}function Ga(e,t){let n=Mn(e),r=Mn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function Ka(e){try{return(await vt.stat(e)).isDirectory()}catch{return!1}}async function SI(e){let t=(await vt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>vt.readdir(ve.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>Jn.some(o=>i.name.endsWith(o))).map(i=>ve.parse(i.name).name)))}async function EI(e,t,n,r){let i=await He({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:i,overThreshold:!1,classification:"live"};let s;try{s=await vt.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(o){let l=s.split(/\r?\n/).map(d=>d.trim()).filter(Boolean).at(-1);try{a=JSON.parse(l??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?s.split(/\r?\n/).filter(l=>l.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function xI(e,t,n){let r=ve.join(e,"history");if(!await Ka(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await vt.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),s=t.enabled?t.max_entries:null,a=[],c=[],l=[],d=[];for(let u of i){let m=ve.join(r,u),f=u.slice(0,-6),p=await EI(m,f,t,n);a.push(...p.warnings),p.classification==="tombstone"&&l.push(f),p.classification==="orphaned"&&d.push(f),p.overThreshold&&c.push(f)}return{count:i.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...d.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:s,tombstones:l,orphaned:d}}function qa(e,t){return ve.relative(e,t).replaceAll("\\","/")}async function Ih(e,t){let n=[...new Set(Object.values(t))].sort((i,o)=>i.localeCompare(o)),r=[];for(let i of n){let o=ve.join(e,i),s=[];try{s=await vt.readdir(o)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&j(a))continue;continue}for(let a of s)Jn.some(c=>a.toLowerCase().endsWith(c))&&r.push(ve.join(o,a))}return r.sort((i,o)=>qa(e,i).localeCompare(qa(e,o))),r}function II(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}async function AI(e,t,n){let r=await Ih(e,t),i=[],o=[],s=[],a=[],c=nn(H());for(let l of r){let d=qa(e,l),u;try{u=await vt.readFile(l,"utf8")}catch{i.push(d);continue}let m=De(u);if(m){o.push({path:d,...m});continue}try{let f=xt(u,{format:tl(l),schema:n,extensionFieldNames:c});a.push({ref:d,version:Zr(f.metadata)})}catch{s.push(d)}}return{paths:r,unreadable:i,conflictMarkers:o,parseFailures:s,formatVersions:a}}async function RI(e){let t=ve.join(e,"history"),n=[],r=[],i=[],o=[],s=[],a=[];try{a=(await vt.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,l)=>c.localeCompare(l))}catch(c){II(c)&&n.push("history")}for(let c of a){let l=c.slice(0,-6),d;try{d=await vt.readFile(ve.join(t,c),"utf8")}catch{n.push(l);continue}let u=De(d);if(u){r.push({id:l,...u});continue}d.split(/\r?\n/).forEach((m,f)=>{if(m.trim())try{let p=JSON.parse(m);o.push(...fh(p,l).map(_=>({itemId:l,line:f+1,..._}))),s.push(...ph(p,l,f+1))}catch{i.push({id:l,line:f+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:o,mergeReceiptDispositions:s}}function Ah(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}`)]}function CI(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}async function TI(e,t,n,r,i){let o=await AI(e,t,n),s=await RI(e),a=Qr(o.formatVersions),c=_e(n),l=pi(i,b=>ql(b,c),Qn()),d=await oo(e),u=await tt(e),m=u===null?null:await Rn(u),f=await yt(u??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),p=new Set(f.receipts.map(b=>b.id)),_=hh(s.mergeReceiptReferences,p,s.mergeReceiptDispositions),h=_.missing,w=f.receipts.filter(b=>b.state==="pending"),{pendingDecisions:v,lossless:k}=Nn(w),S=m?.status==="missing"&&m.missing_keys.length===5&&m.drifted_keys.length===0,x=[...o.unreadable.map(b=>`integrity_item_unreadable:${b}`),...o.conflictMarkers.map(b=>`integrity_item_conflict_marker:${b.path}:L${b.line}`),...o.parseFailures.map(b=>`integrity_item_parse_failed:${b}`),...s.unreadable.map(b=>`integrity_history_unreadable:${b}`),...s.conflictMarkers.map(b=>`integrity_history_conflict_marker:${b.id}:L${b.line}`),...s.invalidJson.map(b=>`integrity_history_invalid_json:${b.id}:L${b.line}`),...a.outdated.map(b=>`integrity_item_outdated_format_version:${b}`),...a.ahead.map(b=>`integrity_item_ahead_format_version:${b}`),...Ah(l),...d.tracked_path_count>0?[`tracked_runtime_cache_files:${d.tracked_path_count}`]:[],...m!==null&&m.status!=="ok"?[`merge_driver_configuration_${S?"missing":"drift"}:${m.missing_keys.length+m.drifted_keys.length}`]:[],...v.length>0?[`merge_decisions_unreviewed:${v.length}`]:[],...k.length>0?[`merge_receipts_pending:${k.length}`]:[],...CI({invalidEvidenceCount:f.invalid_evidence_count,missingHistoryReferenceCount:h.length})],A=[...new Set(x)].sort((b,P)=>b.localeCompare(P)),E=A.filter(b=>!b.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:E.length===0?"ok":"warn",ok:E.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:a.outdated.length,item_ahead_format_version:a.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:d.tracked_path_count,merge_driver_configuration:m===null||m.status==="ok"?0:m.missing_keys.length+m.drifted_keys.length,pending_merge_decisions:v.length,lossless_merge_receipts:k.length,invalid_merge_receipt_evidence:f.invalid_evidence_count,missing_merge_receipt_history_references:h.length,accepted_legacy_merge_receipt_references:_.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:_.acceptedDispositionCount},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:a.outdated,item_ahead_format_version:a.ahead,hierarchy_integrity:{...l,relations:ot(l.relations,Ln)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.invalidJson,tracked_runtime_cache:{tracker_relative_root:d.tracker_relative_root,tracked_paths:d.tracked_paths,tracked_path_count:d.tracked_path_count,remediation_command:d.remediation_command},merge_driver_configuration:m===null?null:{...m,required:r},pending_merge_decision_items:[...new Set(v.map(b=>b.item_id))].sort((b,P)=>b.localeCompare(P)),lossless_merge_receipt_items:[...new Set(k.map(b=>b.item_id))].sort((b,P)=>b.localeCompare(P)),invalid_merge_receipt_evidence_details:f.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:f.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:h.slice(0,Qt),missing_merge_receipt_history_reference_details_truncated:h.length>Qt}},warnings:A,gitWorkspaceRoot:u,pendingMergeReceipts:w}}function $I(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function OI(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:$I(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function DI(e,t){let n=ee(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function PI(e){let n=ee(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function NI(e){return ee(e.reason)??ee(e.error)??ee(e.message)}function Ha(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 LI(e){let t=[],n=[],r=[];e.forEach((o,s)=>{let a=DI(o.definition,s),c=PI(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:a,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:a,status:c,reason:NI(o.definition)});return}n.push({layer:o.layer,name:o.name,id:a,status:c})}),t.sort(Ha),n.sort(Ha),r.sort(Ha);let i=[...r.map(o=>`extension_migration_failed:${o.layer}:${o.name}:${o.id}`),...n.map(o=>`extension_migration_pending:${o.layer}:${o.name}:${o.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function Rh(e,t,n,r,i,o,s,a,c){let l=[...new Set(e)].sort((h,w)=>h.localeCompare(w)),d=[...new Set(l.map(h=>Ja(h)))].sort((h,w)=>h.localeCompare(w)),u=l.filter(h=>h.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=[],_=ma(l,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return _&&p.push(_),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: ${Mr.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),l.some(h=>h.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),l.some(h=>h.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>."):s.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:l.length===0?"ok":"warn",warning_count:l.length,warning_codes:d,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:o,unmanaged_loaded_extension_count:s.length,unmanaged_loaded_extensions:s,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:m,unknown_capability_count:u,top_warnings:l.slice(0,8),remediation:p}}async function MI(e,t,n){let r=await ga(Ve(e)),i=await Je({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),o=i.loaded.map(E=>OI(E)),s=await Yu(i.loaded,Ve(e)),a=await Ke({...i,loaded:i.loaded}),[c,l]=await Promise.all([we(i.roots.project),we(i.roots.global)]);await _a(e,a.registrations.migrations);let d=LI(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:d.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:l.path,count:l.state.entries.length,entries:l.state.entries}}},m=new Set(c.state.entries.map(E=>Mn(E.name))),f=new Set(l.state.entries.map(E=>Mn(E.name))),p=[...new Map(i.loaded.filter(E=>!(E.layer==="project"?m:f).has(Mn(E.name))).map(E=>[`${E.layer}:${E.name}`,{layer:E.layer,name:E.name,directory:E.directory}])).values()].sort((E,b)=>{let P=`${E.layer}:${E.name}`,U=`${b.layer}:${b.name}`;return P.localeCompare(U)}),_=p.map(E=>`${E.layer}:${E.name}`).sort((E,b)=>E.localeCompare(b)),h=p.filter(E=>Ga(E.name,E.directory)).map(E=>`${E.layer}:${E.name}`).sort((E,b)=>E.localeCompare(b)),w=p.filter(E=>!Ga(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}`]:[],k=[...r.warnings,...i.warnings,...u.warnings,...d.warnings,...c.warnings,...l.warnings,...v,...s.warnings],S=br(k),x=kr(),A=Rh(k,i.failed.length,a.failed.length,d.summary,c.warnings.length+l.warnings.length,c.state.entries.length+l.state.entries.length,_,h,w);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...i,loaded:o,warnings:k,activation:u,author_manifest:r,triage:A,...d.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:S,host_version_census:s}},warnings:k}}function jI(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function ot(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function FI(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 ho(e,t){let n=ot(e,t);return{...n,sample:n.sample.map(r=>FI(r))}}function B(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 UI(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 zI={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:B(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:B(e.missing_required,t),missing_optional:B(e.missing_optional,t),missing:B(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:B(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:ho(e.discovered,t),effective:ho(e.effective,t),loaded:ho(e.loaded,t),failed:ot(e.failed,t),warnings:B(e.warnings,t),activation:{failed:ot(n.failed,t),warnings:B(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:UI(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:ot(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:B(n.affected_item_ids,t),samples:ot(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:B(e.item_unreadable,t),item_conflict_markers:ot(e.item_conflict_markers,t),item_parse_failures:B(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:B(n.tracked_paths,t)},history_unreadable:B(e.history_unreadable,t),history_conflict_markers:ot(e.history_conflict_markers,t),history_invalid_json:ot(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:B(n.candidate_items,t),confirmed_items:B(n.confirmed_items,t),resolved_false_positive_items:B(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:B(e.drifted_items,t),merge_receipt_attributed_items:B(e.merge_receipt_attributed_items,t),missing_streams:B(e.missing_streams,t),unreadable_streams:B(e.unreadable_streams,t),hash_mismatches:B(e.hash_mismatches,t),chain_mismatches:B(e.chain_mismatches,t),version_skews:B(e.version_skews,t),workspace_state_mismatches:B(e.workspace_state_mismatches,t),workspace_state_missing:B(e.workspace_state_missing,t),workspace_state_unreadable:B(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:B(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:B(e.stale_items_after,t),skipped:e.skipped})};function Ch(e,t){let n=zI[e.name];return n?n(e.details,t):e.details}function HI(e){let t=B(e.warnings,Ln);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:Ch(n,Ln)})),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:Ln},generated_at:e.generated_at}}function Sh(e){return e.details.skipped===!0}function WI(e){let t=B(e.warnings,Ln),n=e.checks.filter(Sh).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!Sh(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:Ln,omitted_checks:n},generated_at:e.generated_at}}function Ba(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=jI(e,Eh);return{values:n.values,truncated:n.truncated,total:e.length}}function _o(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function GI(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return gI.has(e)?e:null}function go(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 Th(e){let t=0,n=0,r=0,i=0,o=0;for(let s of e.split(`
65
- `)){let a=s.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let l=Math.max(0,Math.trunc(c.attempts));t+=1,o=Math.max(o,l),l>=xh&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:o}}function qI(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function BI(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 VI(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||as().telemetry_disabled?void 0:{attempted:!0,...await $h(n)}}function JI(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,o=n.last_failed_flush_at,s=o&&(!i||o>i),a=!i,c=t.validEntries>=bI;return(s||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function KI(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function YI(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>qd?[`telemetry_schema_version_behind:${t}`]:[]}function XI(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 ZI(){return{...as(),pm_no_telemetry:_o("PM_NO_TELEMETRY"),telemetry_otel_disabled:_o("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:_o("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:GI()}}function QI(e,t){return e.telemetry.enabled&&t.validEntries>0}function eA(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function $h(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(vI)});return{probe_url:go(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of kI){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:go(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function tA(e,t){let n=Ur(process.cwd()),r=ve.join(n,yI),i=ve.join(n,wI),o=await K(r),s=o!==null,a=o?Buffer.byteLength(o,"utf8"):0,c=o?Th(o):qI(),l=await K(i),{runtimeState:d,stateParseFailed:u}=BI(l),m=e.telemetry.endpoint.trim(),f=go(m),p=await VI(e,t.checkTelemetry),_=[];u&&_.push("telemetry_state_invalid_json"),_.push(...JI(e,c,d),...KI(p),...YI(p),...XI(e,d));let h=QI(e,c),w=typeof d.pending_otel_spans=="number"?d.pending_otel_spans:0;return{check:{name:"telemetry",status:_.length===0?"ok":"warn",ok:_.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:f,global_pm_root:n,queue_path:r,queue_exists:s,queue_entries:c.validEntries,queue_draining:eA(h,_),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:a,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:xh,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:d.last_attempted_flush_at??null,last_successful_flush_at:d.last_successful_flush_at??null,last_failed_flush_at:d.last_failed_flush_at??null,last_failed_flush_error:d.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:d.last_otel_attempt_at??null,last_otel_success_at:d.last_otel_success_at??null,last_otel_failure_at:d.last_otel_failure_at??null,last_otel_failure_error:d.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:ZI()}},warnings:_}}async function nA(e){let t;try{t=await vm(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 rA(e){let t="metadata",n=e.items,r=await Gt(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),o=[],s=[];if(i.length>0){n=await zt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Gt(e.pmRoot,n),o=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,k)=>v.localeCompare(k));let w=new Set(o);s=i.filter(v=>!w.has(v))}let{missingStreams:a,unreadableStreams:c,hashMismatches:l,chainMismatches:d,versionSkews:u,driftedItems:m,workspaceStateMismatches:f,workspaceStateMissing:p,workspaceStateUnreadable:_}=r,h=[...a.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...l.map(w=>`history_drift_hash_mismatch:${w}`),...d.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),...f.map(w=>`history_drift_workspace_state_mismatch:${w}`),...p.map(w=>`history_drift_workspace_state_missing:${w}`),..._.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:h.length===0?"ok":"warn",ok:h.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:o,resolved_false_positive_items:s,authoritative_item_source:i.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:l.length,chain_mismatches:d.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:p.length,workspace_state_unreadable:_.length},missing_streams:a,unreadable_streams:c,hash_mismatches:l,chain_mismatches:d,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:p,workspace_state_unreadable:_}},warnings:h}}function iA(e,t){let n=ui(e),r=Zn(n.settings),i=fi(n.settings,t),o=r.active?Ht(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(r.active&&i.active)}}function oA(){return{refreshed:[],skipped:[],warnings:[]}}async function sA(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?oA():zd(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&&_n(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function cA(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 Oh(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:is(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:is(r,e.vector_store?.adapter??null)}}function dA(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function uA(e,t,n){return e.enabled&&n.length>0&&t}async function mA(e,t,n,r,i){let o=iA(t,e),s=await gn(e),a=o.semanticRuntimeAvailable?ls(n,s.entries):[],c=await sA({pmRoot:e,snapshot:o,refreshPolicy:r,staleBefore:a}),l=await gn(e),d=o.semanticRuntimeAvailable?ls(n,l.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,m=aA({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:s,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),f=cA({ledgerBefore:s,ledgerAfter:l,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:d}),p=Ba(a,i),_=Ba(d,i),h=uA(r,o.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:o.semanticRuntimeAvailable,compatibility_mode_auto_defaults:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:o.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:o.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:dA(r),...Oh(t,o),embedding_identity_changed:m,embedding_identity_before:s.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(s.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Eh,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:h,refresh_skipped_reason:lA(r,o.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(l.entries).length,stale_items_after_total:_.total,stale_items_after:_.values,stale_items_after_truncated:_.truncated}},warnings:f}}function fA(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 Dh(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 pA=new Set(["extensions","locks","search"]);function hA(e){let t=new Set(Gc.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(qc));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of pA)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,o)=>i.localeCompare(o)),optionalDirs:[...n].sort((i,o)=>i.localeCompare(o)),optionalDirSet:n}}async function _A(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:o}=hA(t),s=[],a=[],c=[];for(let l of[...r,...i]){let d=ve.join(e,l);c.push(...await He({path:d,scope:"project"})),!await Ka(d)&&(o.has(l)?a.push(l):s.push(l))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:s,missingOptionalDirs:a,missingDirs:n?[...s,...a]:[...s],hookWarnings:c}}function Ph(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 gA(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):zt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Wa(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function yA(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 wA(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 Ya=e=>e.unknown_event_count??0,Xa=e=>e.actionable_unknown_event_count??Ya(e);function bA(e,t,n,r,i,o){let s=Ya(r),a=Xa(r),c=s>0,l=a>0,d=i.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!d?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!d,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...c?{author_attribution:r}:{},...d?{stale_in_progress:i}:{},...o.outcomes.length>0?{provenance_resolver_outcomes:o.outcomes}:{},...o.invalid_values.length>0?{provenance_invalid_values:o.invalid_values}:{},provenance_sample:o.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 Nh(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 SA(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function EA(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 Lh(e){let t=new Map;for(let[i,o]of Object.entries(e.remediationSources))for(let s of o)t.has(s)||t.set(s,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let o=t.get(i)??"integrity",s=Os(i)?.code??Ja(i),a=n.get(o)?.details,c=typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{},l=s==="agent_guidance_outdated"?"pm init --agent-guidance add":s==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":c[s],d=Va(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:s,check:o,severity:d,...typeof l=="string"?{remediation:l}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function xA(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 IA(e){for(let t of e.checks){let n=Ds(e.remediationSources[t.name]);xA({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function AA(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(s=>typeof s=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(s=>Array.isArray(s)?s:[])),i=new Map;for(let s of e.pendingMergeReceipts){if(s.evidence_source!=="clone_local")continue;let a=i.get(s.item_id)??[];a.push(s),i.set(s.item_id,a)}let o=[];for(let s of n){if(r.has(s))continue;let a=i.get(s);if(!(!a||a.length===0))try{await za(s,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),o.push(s)}catch{}}return[...new Set(o)].sort((s,a)=>s.localeCompare(a))}function RA(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 Mh(e,t,n){let r=e.warning_count??e.warnings.length,i={...e,warning_count:r,warning_limit:Qt,warnings_truncated:r>Qt,warnings:e.warnings.slice(0,Qt),findings:(e.findings??[]).filter(s=>e.warnings.slice(0,Qt).includes(s.warning)||e.failed_because.includes(s.warning))},o=n?WI(i):t.brief===!0?HI(i):i;return{...o,warning_count:r,warning_limit:Qt,warnings_truncated:r>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:r,warnings_truncated:r>o.warnings.length}}:{}}}async function jh(e,t={}){let n=N(process.cwd(),e.path);await te(n);let r=Nt(n),{settings:i,warnings:o}=await ld(n),s=[...new Set(o)],a=G(i,H()),c=t.strictDirectories===!0,l=t.strictExit===!0||t.failOnWarn===!0,d=t.requireMergeDrivers===!0||l,u=Dh(t),m=await _A(n,a,c),f=fA(i),p=await tA(i,{checkTelemetry:t.checkTelemetry===!0}),_=await MI(n,i,!!e.noExtensions),h=Ph(t),w=[],v=await gA({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:h,itemReadWarnings:w}),k=v,S=Ci(_e(i.schema),v),A=[...(await fm({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,...Ti(S)],E=h.skipDrift?{warnings:[]}:await yd({pmRoot:n,settings:i,itemIds:v.map(pe=>pe.id),commandLabel:"health"}),b=await xI(n,i.history.compact_policy,await SI(n)),P=await sr(n,20,t.verboseAuthorEvents===!0),U=Xa(P),z=U>0?[`history_unknown_author_events:${U}`]:[],D=Nh(await Wd(n,v,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),Q=await nm(n),Fe=Q.warnings,ye=await nA(n),Ue=h.skipIntegrity&&!d?{...Wa("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await TI(n,a.type_to_folder,i.schema,d,v),ze=h.skipDrift?Wa("history_drift"):await rA({pmRoot:n,items:k,settings:i,typeRegistry:a,itemReadWarnings:w}),tn=[...new Set(w)],W=await AA({gitWorkspaceRoot:Ue.gitWorkspaceRoot,pendingMergeReceipts:Ue.pendingMergeReceipts,historyDriftCheck:ze,global:e});RA(ze,W);let V=h.skipVectors?Wa("vectorization"):await mA(n,i,k,u,t.verboseStaleItems===!0),qn=[yA(r,i,s),wA(m,c),vA(A,S),p.check,_.check,bA(v,i,b,P,D.scan,Q),ye.check,Ue.check,ze.check,V.check],Bn=kA({directoryState:m,normalizedSettingsReadWarnings:s,settingWarnings:A,normalizedItemReadWarnings:tn,telemetryCheck:p,extensionCheck:_,historyPolicyWarnings:E.warnings,historySummary:b,authorAttributionWarnings:z,staleInProgressWarnings:D.warnings,provenanceWarnings:Fe,locksCheck:ye,integrityCheck:Ue,historyDriftCheck:ze,vectorizationCheck:V}),Fc=EA({directoryState:m,normalizedSettingsReadWarnings:s,settingWarnings:A,normalizedItemReadWarnings:tn,telemetryCheck:p,extensionCheck:_,historyPolicyWarnings:E.warnings,historySummary:b,authorAttributionWarnings:z,staleInProgressWarnings:D.warnings,provenanceWarnings:Fe,locksCheck:ye,integrityCheck:Ue,historyDriftCheck:ze,vectorizationCheck:V});IA({checks:qn,remediationSources:Fc,historyDriftedCount:SA(ze),overThresholdCount:b.over_threshold.length});let Lo=Bn.filter(pe=>!Va(pe,d)),Mo=Lh({warnings:Bn,checks:qn,remediationSources:Fc,requireMergeDrivers:d}),Pg=new Set(Mo.filter(pe=>pe.severity==="gate_failing").map(pe=>pe.check)),Ng=new Set(Mo.map(pe=>pe.check));for(let pe of qn)pe.ok=!Pg.has(pe.name),Ng.has(pe.name)&&(pe.status="warn");let Lg={ok:Lo.length===0,verdict:{authority:"ok",...l?{strict_exit:!0}:{},...d?{require_merge_drivers:!0}:{},exit_code:l&&Lo.length>0?g.GENERIC_FAILURE:0},checks:qn,warnings:Bn,findings:Mo,failed_because:Lo,generated_at:C()};return Mh(Lg,t,h.summaryMode)}var pU={buildHierarchyIntegrityWarnings:Ah,buildExtensionHealthTriageSummary:Rh,buildHealthFindings:Lh,buildCapabilityContractMetadata:kr,buildStaleInProgressHealthSummary:Nh,buildVectorizationProviderDetails:Oh,collectUnknownCapabilityGuidance:br,isAdvisoryHealthWarning:Va,isDirectory:Ka,isExpectedUnmanagedExtension:Ga,listItemDocumentPaths:Ih,normalizeEndpointForDisplay:go,normalizeExtensionNameForMatch:Mn,parseTelemetryQueue:Th,probeTelemetryEndpointHealth:$h,projectHealthResult:Mh,resolveActionableUnknownAuthorEventCount:Xa,resolveHealthSkipPolicy:Ph,resolveUnknownAuthorEventCount:Ya,resolveVectorRefreshPolicy:Dh,selectStaleItemDetail:Ba,summarizeHealthCheckDetails:Ch,summarizeExtensionList:ho,summarizeRecordList:ot,summarizeStringList:B,telemetryEnvFlagEnabled:_o,warningCode:Ja};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e1d8d86-3f4e-50eb-ae73-ca7c030f7c0a")}catch{}})();function Fh(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!Xd(e,t).ok)return{reason:"unverified_history"};let r=nd(),i={reason:"no_proven_transition"};for(let[o,s]of e.entries()){let a=n.has(String(r.metadata.status));r=vd(r,s.patch,o+1,s.op),n.has(String(r.metadata.status))?a||(i=["create","close","cancel","update","update_audit"].includes(s.op)&&Et(s.ts)?{timestamp:s.ts,source_index:o+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function Uh(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function zh(e,t,n,r,i){let o=Uh(n),s=t.filter(l=>o.has(l.status)&&!l.closed_at),a=[],c=[];for(let l of r?s:[]){let d;try{let u=await Ft(Lt(e,l.id),l.id),{body:m,...f}=l;d=Fh(u,{metadata:f,body:m},o)}catch{c.push({id:l.id,reason:"unreadable_history"});continue}if("reason"in d){c.push({id:l.id,reason:d.reason});continue}a.push({item_id:l.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:d.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:s.length,missing_closed_at_item_ids:s.slice(0,i).map(l=>l.id),missing_closed_at_item_ids_truncated:s.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:a.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...s.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:a,warnings:s.length>0?[`validate_metadata_missing_closed_at:${s.length}`]:[]}}async function Hh(e,t){let n=N(process.cwd(),t.path),r=await T(n),i=_e(r.schema);await lt({pmRoot:n,settings:r,id:e.item_id,op:"update",author:q(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(o){if(o.metadata.closed_at)return{changedFields:[]};let s=await Ft(Lt(n,o.metadata.id),o.metadata.id),a=Uh(i),c=Fh(s,o,a);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 o.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]="e2cd8850-491a-505c-8709-3dcdb758de75")}catch{}})();function CA(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function Wh(e){return`${e.item_id} ${e.link_kind}`}function Gh(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=CA(i.classification,r.classification),i.owners.set(Wh(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[Wh(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(o=>{let s=t(o.item_id);return{id:o.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:o.link_kind}}).sort((o,s)=>{let a=o.id.localeCompare(s.id);return a!==0?a:o.field.localeCompare(s.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]="ccb0d064-940b-5e14-ae63-2803aced4ee7")}catch{}})();function qh(e,t,n,r,i=40){let o=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,s=new Map(t.map(l=>[l.path,l])),a={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=Gh(e,n).map(l=>{let d=[],u=[];for(let f of l.items){let p=ei(f.status,r)??f.status;r.terminal_statuses.has(p)?(u.push(f),p===r.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):d.push(f)}a.missing_linked_links_count+=l.items.length,a.active_missing_linked_links_count+=d.length,a.legacy_terminal_missing_linked_links_count+=u.length,d.length>0&&(a.active_missing_linked_paths_count+=1);let m=s.get(l.path);return{...l,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:l.items.length,active_link_count:d.length,items:[...d,...u].slice(0,o),items_truncated:l.items.length>o}});return c.sort((l,d)=>+(d.active_link_count>0)-+(l.active_link_count>0)||l.path.localeCompare(d.path)),a.missing_linked_path_rows_count=c.length,a.missing_linked_path_rows=c.slice(0,o),a.missing_linked_path_rows_truncated=c.length>o,a}import jn from"node:fs/promises";import Fn 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]="9bcae2f2-3739-5ef8-b080-daaaf7df2681")}catch{}})();async function TA(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let o;try{o=await jn.readdir(Fn.join(e,i))}catch{return}for(let s of o)for(let a of Jn)if(s.toLowerCase().endsWith(a)){r.push({relativePath:`${i}/${s}`,id:s.slice(0,-a.length)});break}})),r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath))}function $A(e,t){let{id:n,relativePath:r,liveItemIds:i,out:o}=e,s=De(t);if(s){o.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=OA(e,t);a!==null&&(a.op==="delete"&&i.has(n)&&o.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(o.repairReconciliations+=1))}function OA(e,t){let{id:n,relativePath:r,out:i}=e,o=null,s=!1,a=t.split(/\r?\n/).map((c,l)=>({content:c.trim(),number:l+1})).filter(c=>c.content.length>0);for(let c of a){try{let l=JSON.parse(c.content);if(typeof l!="object"||l===null||Array.isArray(l))throw new TypeError("history entry must be an object");o=l}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(o.op==="create"){if(s)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;s=!0}}return o}function Za(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 DA(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await jn.readdir(Fn.join(e,"history"))}catch{return n}for(let i of r.sort((o,s)=>o.localeCompare(s))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await jn.readFile(Fn.join(e,"history",i),"utf8")}catch(s){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Za("history stream",s)});continue}$A({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},o)}return n}function Bh(e){let t=De(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 PA(e){let t=[],n=0,r=null;try{r=await K(Nt(e))}catch(o){n+=1,t.push({path:"settings.json",detail:Za("configuration file",o)})}if(r!==null){n+=1;let o=Bh(r);o!==null&&t.push({path:"settings.json",detail:o})}let i;try{i=await jn.readdir(Fn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of i.sort((s,a)=>s.localeCompare(a))){if(!o.endsWith(".json"))continue;n+=1;let s;try{s=await jn.readFile(Fn.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:Za("configuration file",c)});continue}let a=Bh(s);a!==null&&t.push({path:`schema/${o}`,detail:a})}return{scanned:n,unparseable:t}}async function Vh(e,t,n,r={}){let i=await TA(e,n),o=new Set(i.map(u=>u.id)),s=new Map;for(let u of i){let m=s.get(u.id);m===void 0?s.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...s.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=Fn.join(e,u.relativePath);return xt(await jn.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await DA(e,o),d=await PA(e);return{item_files_on_disk:i.length,item_ids_on_disk:o.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import Ec from"node:fs/promises";import{realpathSync as BR}from"node:fs";import{execFile as VR}from"node:child_process";import be from"node:path";import{promisify as JR}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]="c1b189d7-2939-5891-b936-5f208dc8f5ff")}catch{}})();var NA=["metadata","resolution"],Qa=["metadata","resolution","estimates","timestamps","lifecycle"],LA="completed";function ec(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Jh(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Kh(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Jh(n.close_reason)??LA;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${ec(r)}`,gate:"resolution"})}return t}function Yh(e){let t=[];for(let n of e){let r=Jh(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 ${ec(r)}`,gate:"metadata"})}return t}function Xh(e,t){return e.map(n=>{let r=cd(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 Zh(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 Qh(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 ${ec(n.path)}`})}return t}function e_(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: ${Qa.join(", ")}.`,g.USAGE);return new Set(NA)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Qa.includes(i)){n.add(i);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${Qa.join(", ")}.`,g.USAGE)}return n}function t_(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]="3b09b58f-2ec7-523e-87f3-8d828deb8480")}catch{}})();var MA=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function jA(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=MA.exec(n);if(!r)return null;let i=r[1],o=i.toUpperCase(),s=i.slice(0,i.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(m=>m.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),l=t.evidenceText?.toUpperCase()??"",d=l.includes(`ISSUE CODE: ${o}`)||l.includes(`ISSUE CODE \`${o}\``)||l.includes(`\`${o}\``)||l.includes(`[${o}]`);return s===s.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(s.toUpperCase())||d?o:null}function n_(e){return typeof e=="string"&&e.trim().length>0}function FA(e){let t=new Set(e.map(a=>a.id.toLowerCase())),n=new Map,r=new Map;for(let a of e){let c=a.id.toLowerCase(),l=new Set([...a.parent===null?[]:[a.parent.toLowerCase()],...a.derivations].filter(d=>d!==c&&t.has(d)));n.set(c,l);for(let d of l){let u=r.get(d)??[];u.push(c),r.set(d,u)}}let o=[...[...n].filter(([,a])=>a.size===0).map(([a])=>a)],s=new Set;for(let a=0;a<o.length;a+=1)for(let c of r.get(o[a])??[]){let l=n.get(c);l.delete(o[a]),l.size===0&&(s.add(c),o.push(c))}return e.filter(a=>!s.has(a.id.toLowerCase()))}function r_(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||n_(i.duplicate_of))continue;let o=jA(i.title,{...t,evidenceText:i.body});if(o===null)continue;let s=n.get(o);s||(s=[],n.set(o,s)),s.some(a=>a.id===i.id)||s.push({id:i.id,title:i.title,parent:n_(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(a=>["discovered_from","supersedes","incident_from"].includes(a.kind)).map(a=>a.id.trim().toLowerCase()).filter(a=>a!==i.id.toLowerCase())})}let r=[];for(let[i,o]of n){if(o.length<2)continue;let s=FA(o);if(s.length<2)continue;let a=[...s].sort((c,l)=>c.id.localeCompare(l.id));r.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return r.sort((i,o)=>i.code.localeCompare(o.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]="b51a9fba-7bbe-573b-a708-5ffea6fa040f")}catch{}})();function i_(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,o)=>i.localeCompare(o))){let i=t.get(r),o={};for(let s of[...i.keys()].sort((a,c)=>a.localeCompare(c)))o[s]=i.get(s);n[r]=o}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]="ede22770-cb10-5054-85a7-89bb2758c25f")}catch{}})();var o_=3;function s_(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function a_(e,t,n=o_){let r=Number.isFinite(n)&&n>=1?Math.floor(n):o_,i=new Map;for(let o of t){let s=s_(o);if(s.length===0)continue;let a=i.get(s);a?a.push(o):i.set(s,[o])}return e.map(o=>{if(o.includes(",")||o.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:o,classification:"malformed",candidates:[],candidates_truncated:!1};let s=(i.get(s_(o))??[]).filter(a=>a!==o).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:o,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:o,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function c_(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var UA=/^[a-z][a-z0-9+.-]+:\/\//i;function Cr(e){return UA.test(e.trim())}import zA from"node:fs/promises";import Me from"node:path";import HA from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="02743545-3a44-565d-932c-7fe736d17eb8")}catch{}})();var WA=["path","scope","note"],GA=["pattern","glob","path","scope","note"],qA=["path"],BA=["from","to"],VA=new Set(["note","scope"]);function d_(e){let t=e??"project";if(!jo.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${jo.join(", ")} (default: project).`,g.USAGE);return t}function tc(e){if(e.startsWith("```")||e.includes(`
66
- `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||fd(e)}function JA(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function KA(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!tc(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let o=e.slice(t+2,-1).trim();if(o.length>0&&JA(o))return{path:o,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 YA(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let o=KA(r);if(o!==void 0)return[o]}pd(r,"--add",`${t} path`,tc(r));let i=tc(r)?Yn(n,"--add"):{path:r};if(Xn(i,"--add",WA),!i.path)throw new y(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return[{path:i.path,scope:d_(i.scope),note:i.note?.trim()||void 0}]}):[]}function XA(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",GA);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:d_(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function ZA(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(o=>VA.has(o.toLowerCase()));if(i.length>0)throw new y(`--remove identifies a linked artifact by path only and does not accept ${i.map(o=>`"${o}"`).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",qA),!r.path)throw new y("--remove key/value form requires path=<value>",g.USAGE);return r.path}return n}):[]}function QA(e){return e?e.map(t=>{let n=Yn(t,"--migrate");Xn(n,"--migrate",BA);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 eR(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(o=>Tr(o.path,n))),i=[...new Set(t.map(o=>Tr(o,n)).filter(o=>r.has(o)))].sort((o,s)=>o.localeCompare(s));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 bt(e){return e.split(Me.sep).join("/")}function nc(e,t,n=process.cwd()){let r=e.trim();if(Cr(r))return r;if(Me.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return bt(r.replaceAll("\\",Me.sep));let i=Me.relative(t,n);return i.startsWith(`..${Me.sep}`)||i===".."||Me.isAbsolute(i)?bt(Me.normalize(r)):bt(Me.relative(t,Me.resolve(n,r)))}async function tR(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){let o=Me.isAbsolute(i.pattern),s=await HA(i.pattern,{cwd:n,absolute:o,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>nc(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of a)r.push({path:c,scope:i.scope,note:i.note})}return r}function nR(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 rR(e){return`${e.path}::${e.scope}`}function rc(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function ic(e){return[...new Map(e.map(t=>[rR(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function iR(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],i=[],o=[],s=[];for(let a of n){if(Cr(a)){s.push(a.trim());continue}let c=Me.isAbsolute(a)?a:Me.resolve(t,a);try{(await zA.stat(c)).isFile()?r.push(a):o.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&kt(l)){i.push(a);continue}o.push(a)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:o,remote_references:s}}function oR(e,t,n,r){let i=0;for(let s=0;s<e.length;s+=1){let a=Tr(e[s].path,r);a!==e[s].path&&(e[s]={...e[s],path:a},i+=1)}return{adds:t.map(s=>{let a=Tr(s.path,r);return a!==s.path&&(i+=1),{...s,path:a}}),removes:n.map(s=>Tr(s,r)),count:i}}function sR(e,t,n,r){for(let o of t)e.some(s=>s.path===o.path&&s.scope===o.scope)||e.push(o);if(n.length>0)for(let o=e.length-1;o>=0;o-=1)n.includes(e[o].path)&&e.splice(o,1);let i=ic(e);return r?i:rc(i)}async function l_(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 iR(t,e.workspaceRoot):void 0}}async function yo(e,t,n,r){let{metadataKey:i}=r,o=gd(),s=N(process.cwd(),n.path),a=Ve(s),c=process.cwd();await te(s);let l=await T(s),d=G(l,H()),u=await o.resolveList(t.add,"--add"),m=await o.resolveList(t.addGlob,"--add-glob"),f=await o.resolveList(t.remove,"--remove"),p=await o.resolveList(t.migrate,"--migrate"),_=YA(u,r.bareNoun).map(z=>({...z,path:nc(z.path,a,c)})),h=XA(m),w=await tR(h,a,c),v=nR([..._,...w],t.note,_.length>0||h.length>0),k=ZA(f).map(z=>nc(z,a,c)),S=QA(p);if(eR(v,k,S),!(v.length>0||k.length>0||S.length>0)){let z=await Pe(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!z)throw new y(`Item ${e} not found`,g.NOT_FOUND);let Q=(await Ne(z,{schema:l.schema})).document.metadata[i]??[];return l_({id:z.id,artifacts:Q,changed:!1,options:t,workspaceRoot:a})}let A=q(t.author,l.author_default),E=await lt({pmRoot:s,settings:l,id:e,op:r.op,author:A,message:t.message,force:t.force,skipNoop:!0,mutate(z){let D=z.metadata,Q=D[i]??[],Fe=[...Q],ye=oR(Fe,v,k,S),Ue=sR(Fe,ye.adds,ye.removes,r.supportsAppendStable&&t.appendStable===!0);Ue.length>0?D[i]=Ue:delete D[i];let ze=!sl(Q,Ue);return{changedFields:ze?[i]:[],warnings:ze&&ye.count>0?[`path_migrations_applied:${ye.count}`]:[]}}}),b=E.item[i]??[],P=E.warnings.find(z=>z.startsWith("path_migrations_applied:")),U=P?Number(P.slice(24)):0;return l_({id:E.item.id,artifacts:b,changed:E.changedFields.includes(i),migrationsApplied:U,options:t,workspaceRoot:a})}function wo(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]="aef928ec-4a5b-5614-bb5c-cbf63f891845")}catch{}})();async function u_(e,t,n){let r=await yo(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return wo(r,"docs")}import m_ from"node:fs/promises";import je 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]="573da024-c791-5ff2-b3ee-3529804bab43")}catch{}})();var aR=32768;function oc(e){return bt(je.normalize(e))}async function vo(e){try{return await m_.realpath(e)}catch{return je.resolve(e)}}function Un(e,t){let n=je.isAbsolute(e.path)?je.resolve(e.path):je.resolve(t,e.path);return`${oc(n)}::${e.scope}`}function bo(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)=>bo(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))bo(i,t?`${t}.${r}`:r,n)}function cR(e){let t=[];return bo(e.metadata,"metadata",t),bo(e.body,"body",t),t}function lR(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 dR(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 o=new Set,s=i.value.slice(0,aR);for(let[a,c]of[[n,i.value],[r,s]]){a.lastIndex=0;for(let l of c.matchAll(a)){let d=lR(l[0]);!d||o.has(d)||(o.add(d),t.push({field:i.field,value:d}))}}}return t}async function uR(e,t,n=t){let r=je.isAbsolute(e)?je.resolve(e):je.resolve(n,e),i;try{i=await m_.stat(r)}catch{return}if(!i.isFile())return;let[o,s]=await Promise.all([vo(t),vo(r)]);if(he(o,s)){let a=je.relative(o,s);return!a||a.startsWith("..")||je.isAbsolute(a)?void 0:{path:oc(a),scope:"project"}}return{path:oc(r),scope:"global"}}async function mR(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>Un(c,t))),i=new Map,o=dR(cR(e)),s=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{s.set(c,await uR(c,t,n))}));let a=o.map(c=>({reference:c,resolved:s.get(c.value)}));for(let{reference:c,resolved:l}of a){if(!l)continue;let d=Un(l,t),u=i.get(d)??{path:l.path,scope:l.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(d,u)}return[...i.entries()].map(([c,l])=>({path:l.path,scope:l.scope,status:r.has(c)?"already_linked":"addable",source_count:l.sourceCount,source_fields:[...l.sourceFields].sort((d,u)=>d.localeCompare(u)),original_paths:[...l.originalPaths].sort((d,u)=>d.localeCompare(u))})).sort((c,l)=>{let d=c.status.localeCompare(l.status);if(d!==0)return d;let u=c.path.localeCompare(l.path);return u!==0?u:c.scope.localeCompare(l.scope)})}async function f_(e,t,n){let r=await yo(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return wo(r,"files")}async function fR(e,t){let n=await vo(t),r=await Promise.all(e.map(async o=>{let s=o.trim();if(!s)throw new y("Files lookup paths must not be empty.",g.USAGE);if(!je.isAbsolute(s))return bt(s);let a=await vo(s);return he(n,a)?bt(je.relative(n,a)):bt(a)})),i=[...new Set(r)].sort((o,s)=>o.localeCompare(s));if(i.length===0)throw new y("Files lookup requires at least one path.",g.USAGE);return i}function pR(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 p_(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function h_(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 hR(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(bt(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(h_)}async function _R(e){if(e.explain)return zu({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 gR(e){if([e.strictRead,e.noTruncate,e.explain,Pl()].includes(!0))return null;let t=await mi(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Ad({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function yR(e){let t=[],n=await hn(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=hR({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&i.length>0)throw new y(`Files lookup could not read every item: ${i.join("; ")}`,g.GENERIC_FAILURE);let o=await _R({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(o?[...r].sort((c,l)=>{let d=o.explanations.get(l.item.id).score-o.explanations.get(c.item.id).score;return d!==0?d:h_(c,l)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<r.length,truncated:e.offset+a.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:p_(c.item),files:c.files,...o?{traceability:o.explanations.get(c.item.id)}:{}})),...o?{traceability_receipt:o.receipt}:{}}}async function Rz(e,t){let n=N(process.cwd(),t.path),r=Ve(n);await te(n);let i=await fR(e.paths,r);if(e.lineRange&&i.length!==1)throw new y("Files lookup line attribution requires exactly one source path.",g.USAGE);let o=await T(n),s=G(o,H()),{offset:a,limit:c}=pR(e),l=await gR({pmRoot:n,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return l?{paths:i,total:l.total,count:l.matches.length,offset:a,limit:c,has_more:a+l.matches.length<l.total,truncated:a+l.matches.length<l.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:l.matches.map(d=>({item:p_(d.item),files:d.files}))}:yR({pmRoot:n,settings:o,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function Cz(e,t,n){let r=N(process.cwd(),n.path),i=Ve(r);await te(r);let o=await T(r),s=G(o,H()),a=await Pe(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!a)throw new y(`Item ${e} not found`,g.NOT_FOUND);let c=await Ne(a,{schema:o.schema}),l=await mR(c.document,i,process.cwd()),d=l.filter(b=>b.status==="addable"),u=l.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let b=c.document.metadata.files??[];return{id:a.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let p=q(t.author,o.author_default),_=d.map(b=>({path:b.path,scope:b.scope,note:f})),h=[],w=new Set,v=await lt({pmRoot:r,settings:o,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let P=[...b.metadata.files??[]],U=new Set(P.map(Q=>Un(Q,i)));h=[],w.clear();for(let[Q,Fe]of _.entries()){let ye=Un(Fe,i);U.has(ye)||(P.push(Fe),U.add(ye),h.push(Fe),w.add(Q))}let z=ic(P),D=t.appendStable?z:rc(z);return D.length>0?b.metadata.files=D:delete b.metadata.files,{changedFields:h.length>0?["files"]:[],warnings:h.length!==_.length?[`files_discover_skipped_existing:${_.length-h.length}`]:[]}}}),k=v.item.files??[],S=new Set(h.map(b=>Un(b,i))),x=k.filter(b=>S.has(Un(b,i))),A=d.filter((b,P)=>!w.has(P)),E=[...u,...A];return{id:v.item.id,files:k,changed:x.length>0,apply:!0,count:k.length,candidate_count:l.length,addable_count:d.length,added_count:x.length,skipped_existing_count:E.length,candidates:l,added:x,skipped_existing:E}}import{readFileSync as wR}from"node:fs";import ko 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]="e69d7d9b-9ae8-5337-9ea3-a8e40a62d3af")}catch{}})();var vR=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),sc=new Set(["--pm-path","--path","--author"]),bR={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"])},kR=new Set(["-p","--package"]),SR=new Set(["-c","--call"]),ER=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),xR=new Set(["-C","--prefix","--userconfig","--cache"]),Dz=new Set(["--cwd"]),Pz=new Set(["--cwd"]),IR=new Set(["exec","x"]),Nz=new Set(["run","run-script"]),Lz=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function AR(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function RR(e,t=process.cwd()){let n=CR(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...i]=n;if(__(r)||g_(r,t))return i;if(r==="node"&&i[0]&&g_(i[0],t))return i.slice(1);let o=r==="npx"||r==="bunx"?ac(i):r==="pnpm"?OR(i):r==="npm"?DR(i):null;return o&&(__(o.command)||$R(o.command))?o.args:null}var y_=(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 o=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of AR(o)){let c=RR(a),l=c?PR(c):null,d=l&&vR.has(l.subcommand)?NR(l.remaining,bR[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&s.add(d)}return[...s].sort((a,c)=>a.localeCompare(c))};function CR(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Mz(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(sc.has(n)){t+=2;continue}t+=1;continue}return n}}function __(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function TR(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 $R(e){let t=TR(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function g_(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=ko.resolve(t,e);try{return JSON.parse(wR(ko.join(ko.dirname(ko.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function ac(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 o=i[1];return o?{command:o,args:e.slice(t+1)}:null}if(SR.has(r)){t+=1;break}t+=kR.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function w_(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 OR(e){let t=w_(e,ER);return t?.subcommand!=="dlx"?null:ac(t.args)}function DR(e){let t=w_(e,xR);return!t||!IR.has(t.subcommand)?null:ac(t.args)}function PR(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(sc.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function NR(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("=")&&(sc.has(r)||t.has(r))&&(n+=1)}}import{execFile as LR}from"node:child_process";import{readFile as MR}from"node:fs/promises";import b_ from"node:path";import{promisify as jR}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]="eeb9bc22-b9e1-5449-9ad0-fbb1a14fb09d")}catch{}})();var FR=jR(LR),cc=1,UR="linked-test-trust.json";function lc(e){return b_.join(nl(e),UR)}function v_(){return{version:cc,acknowledged:{}}}async function dc(e){try{let t=JSON.parse(await MR(lc(e),"utf8"));return t.version!==cc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?v_():{version:cc,acknowledged:t.acknowledged}}catch{return v_()}}async function uc(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 FR("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 mc(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function zR(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Ml(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 HR(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 Vz(e,t,n){if(!e||e.length===0)return e;let r=mc();return HR(e,t,n,await uc(r))}function k_(e){return ke(R({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 Jz(e,t,n){let r=await dc(e);return S_(t,n,r)}function S_(e,t,n){let r=k_(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let o=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!zR(e.provenance)?o?{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}:o?{fingerprint:r,trusted:!0,reason:"acknowledged",...$r(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...$r(i,t)}}async function E_(e,t,n){let r=await dc(e);return t.map(i=>S_(i,n,r))}async function Kz(e,t,n){let r=await dc(e),i=t.filter(o=>typeof o.command=="string"&&o.command.length>0).map(k_);for(let o of i)r.acknowledged[o]={acknowledged_at:n};return await Vn(b_.dirname(lc(e))),await ne(lc(e),`${JSON.stringify(r,null,2)}
67
- `),{acknowledged:i.length,fingerprints:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ae38c0a-7f43-5457-b9a5-d23491a371ea")}catch{}})();async function So(e){return e.includeBody?zt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):hn(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]="42402d5d-8074-591f-98b4-75f479509cb4")}catch{}})();var WR=5;async function Eo(e,t,n){let r=await Gt(e,t),o=[["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(([,l])=>l>0).map(([l,d])=>`${l}:${d}`),s=n?Number.POSITIVE_INFINITY:WR,a=r.driftedItems.slice(0,s),c=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:c.length>0?"error":o.length===0?"ok":"warn",ok:c.length===0&&o.length===0,details:{identity_discontinuities:c.slice(0,s),identity_discontinuities_count:c.length,identity_discontinuities_truncated:c.length>s,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.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,s)}},warnings: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]="c357729b-f316-51e7-9768-fc7bb4600e06")}catch{}})();function xo(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],o=new Set([n]),s=a=>{for(let c of(t.get(a)??[]).filter(l=>r.has(l))){if(c===n&&i.length>1)return i.push(n),!0;if(!o.has(c)){if(o.add(c),i.push(c),s(c))return!0;i.pop(),o.delete(c)}}return!1};return s(n)?[...i]:[...e,n]}function GR(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function qR(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let o=r.resolve(i.kind);if(!o?.hierarchy)continue;let s=n.get(i.id.toLowerCase());s&&(o.hierarchyDirection==="source_parent"?t.get(s).push(e.id):t.get(e.id).push(s))}}function fc(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((o,s)=>o.id.localeCompare(s.id))){let o=r.get(i.id),s=GR(i.parent,n);s&&o.push(s),qR(i,r,n,t)}for(let[i,o]of r)r.set(i,[...new Set(o)].sort());return r}function pc(e,t,n=Qn()){let r=pi(e,s=>t?bl(s,t):s==="closed"||s==="canceled",n),i=fc(e,n),o=r.cycles.map(s=>s.item_ids);return{cycle_count:o.length,active_cycle_count:r.cycles.filter(s=>!s.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(s=>s.legacy_terminal).length,cycle_item_ids:[...new Set(o.flat())].sort(),cycle_sample_paths:o.map(s=>xo(s,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(s=>!s.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(s=>s.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(s=>`${s.child_id}:${s.parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(s=>!s.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(s=>s.legacy_terminal).length,parent_divergence_rows:r.divergences.map(s=>`${s.child_id}:scalar=${s.scalar_parent_id}:dependencies=${s.dependency_parent_ids.join(",")}:${s.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]="b32d3476-3270-555f-a684-80318df96527")}catch{}})();function Dt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function hc(e){return Dt(e).replace(/\/+$/,"")}function qe(e){let t=ee(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function _c(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]="1ffaaceb-cc25-5d2f-a840-763ba8c7e81f")}catch{}})();var KR=["src","tests","docs"],YR=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],XR=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),ZR=["resolution","expected_result","actual_result"],QR=["default","tracked-all","tracked-all-strict"],x_=["core","strict","custom"],Ro=["off","warn","error"],wc=["author","acceptance_criteria","estimated_minutes","close_reason"],R_=[...wc,"reviewer","risk","confidence","sprint","release"],vc=Array.from(new Set(R_)),e0={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"},t0={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"},n0={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"},r0={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"},i0={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"},o0=32*1024*1024,s0=1e4,bc=40,Be=5,a0=4096,c0=255,l0=JR(VR);function C_(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?C_(r):r);return t}function d0(e){return{...e,checks:e.checks.map(t=>({...t,details:C_(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 To(e,t){return ei(e,t)??e}function Or(e,t){return t.terminal_statuses.has(To(e,t))}function Pt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Io(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function u0(e){let t=Pt(Bc),n={blocked_reason:Pt(Fr.blocked_reason),resolution:Pt(Fr.resolution),actual_result:Pt(Fr.actual_result)},r=Pt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:Pt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Pt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Pt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Io(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Io(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Io(i.resolution,n.resolution)?"default":"settings",actual_result:Io(i.actual_result,n.actual_result)?"default":"settings"}}}function T_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(x_.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${x_.join(", ")}.`,g.USAGE)}function $_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ro.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Ro.join(", ")}.`,g.USAGE)}function O_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ro.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Ro.join(", ")}.`,g.USAGE)}function m0(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>e0[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function f0(e,t,n){let r=m0(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...wc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...R_],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:[...wc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var p0=new Set(["acceptance_criteria","estimated_minutes"]);function D_(e,t,n,r){return!r&&p0.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"?To(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 P_(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: ${QR.join(", ")}.`,g.USAGE)}function N_(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return be.resolve(t);let n=be.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return be.dirname(be.dirname(n));let i=be.resolve(process.cwd()),o=I_(n),s=I_(i),a=be.relative(o,s);return a.length===0||!a.startsWith("..")&&!be.isAbsolute(a)?n:i}function I_(e){try{return BR.native(e)}catch{return be.resolve(e)}}function h0(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function xc(e,t,n){let r=t.length>0?be.join(e,t):e,i;try{i=await Ec.readdir(r,{withFileTypes:!0})}catch(o){if(j(o))return;throw o}for(let o of i){if(o.name.startsWith("."))continue;let s=t.length>0?be.join(t,o.name):o.name;if(o.isDirectory()){if(XR.has(o.name))continue;await xc(e,s,n);continue}o.isFile()&&n.push(Dt(s))}}async function kc(e){let t=[];for(let n of KR)await xc(e,n,t);for(let n of YR){let r=be.join(e,n);try{(await Ec.stat(r)).isFile()&&t.push(Dt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function L_(e){try{let{stdout:t}=await l0("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:o0,windowsHide:!0,timeout:s0}),n=t.split("\0").map(r=>Dt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function _0(e,t){let n=new Set,r=hc(Wc);r.length>0&&n.add(r);let i=hc(be.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((o,s)=>o.localeCompare(s))}function A_(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function g0(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await L_(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await kc(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await kc(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function oe(e,t=Be){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function en(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=oe(e,bc);return{values:n.values,truncated:n.truncated,total:e.length}}var y0={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},w0={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function v0(e){let t=e.missing_fields.map(n=>`${y0[n]} "${w0[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function M_(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(s=>typeof s=="string"):km(t);if(i.length===0)return;let o=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...o?{fix_hints_truncated:!0}:{}}}function j_(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 b0="validate_metadata_duplicate_issue_codes";function F_(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Be,r=e.slice(0,n);return{rows:r.map(o=>({code:o.code,count:o.count,ids:o.ids,titles:o.titles,remediation_hint:`Items ${o.ids.join(", ")} share issue code "${o.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${b0}:${e.length}`]}}function k0(e,t,n){let r=Object.fromEntries(vc.map(i=>[i,[]]));for(let i of e)for(let o of vc)D_(i,o,t,n)&&r[o].push(i.id);return r}function S0(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let o=t[i];o.length>0&&r.push(`${t0[i]}:${o.length}`)}return r.push(...n),r}function U_(e,t){let n={};for(let r of e.required_fields){let i=t[r],o=i?i.length:0,s=n0[r];n[s]=o}return n}function z_(e,t,n){let r=[];for(let i of e.required_fields){let o=t[i];if(o)for(let s of o){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:i})}}return r}function E0(e,t,n,r){for(let i of t.required_fields){let o=n[i];if(!o||o.length===0)continue;let s=r0[i],a=i0[i];if(!s||!a)continue;let c=oe(o,r?o.length:Be);e[s]=c.values,e[a]=c.truncated}}function H_(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 W_(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 x0(e,t,n,r,i){let o=new Map(e.map(w=>[w.id,w])),s=t.profile==="strict",a=k0(e,n,s),c=r_(e,{configuredPrefixes:i}),l=F_(c,r),d=S0(t,a,l.warnings),u=U_(t,a),m=z_(t,a,o),f=i_(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:[...vc],counts:u,missing_by_type:f,duplicate_issue_codes_count:c.length,duplicate_issue_codes:l.rows,duplicate_issue_codes_truncated:l.truncated};t.configured_custom_fields.length>0&&(p.configured_custom_required_fields=[...t.configured_custom_fields]),E0(p,t,a,r);let _=H_(t,a,o),h=W_(t,a,o);return{check:{name:"metadata",status:d.length===0?"ok":"warn",ok:d.length===0,details:p},warnings:d,closeReasonBackfillRows:_,estimateBackfillRows:h}}function I0(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(To(m.status,t))),o=[],s=[];for(let m of i){let f=ZR.filter(p=>!ee(m[p]));f.length!==0&&(o.push({id:m.id,missing_fields:f}),s.push({id:m.id,missing_fields:f,close_reason:ee(m.close_reason)}))}let a=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:Be,l=oe(o.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=o.map(m=>v0(m)),u=oe(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:i.length,missing_resolution_items:o.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:s}}function G_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function q_(e,t="pm",n=Kc()){let r=new Set(e.map(o=>o.id)),i=[...e].sort((o,s)=>o.id.localeCompare(s.id));return new Map(i.map(o=>{let s=new Set,a=qe(o.blocked_by);a&&r.has(a)&&s.add(a),(o.dependencies??[]).filter(l=>{let d=qe(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>qe(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=qe(o.definition_of_ready);return V_(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[o.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function B_(e,t,n){let r=Vd(e,n?d=>Or(d,n):void 0),i=r.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),o=r.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),s=t?Number.POSITIVE_INFINITY:Be,a=oe(i,s),c=oe(o,s),l=oe(r.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),s);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+o.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:o.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function V_(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${G_(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,o)=>i.localeCompare(o))}function J_(e){let t=0,n=new Map,r=new Map,i=[],o=new Set,s=[],a=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),o.add(d);for(let m of e.get(d)??[])n.has(m)?o.has(m)&&r.set(d,Math.min(r.get(d),n.get(m))):(a(m),r.set(d,Math.min(r.get(d),r.get(m))));if(r.get(d)!==n.get(d))return;let u=[];for(;i.length>0;){let m=i.pop();if(o.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),s.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return s.filter(d=>{if(d.length>1)return!0;let u=d[0];return(e.get(u)??[]).includes(u)}).sort((d,u)=>d[0].localeCompare(u[0])||d.length-u.length||d.join(",").localeCompare(u.join(",")))}function K_(e,t="pm"){let n=q_(e,t),r=J_(n),i=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),o=r.map(s=>xo(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:o}}function Y_(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 Co(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function X_(e,t){let n=Co(e).split("/").filter(Boolean),r=Co(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function A0(e,t){let n=Co(t),r=Co(e),i=t.endsWith("/")?t:`${t}/`,o=e.startsWith(i),s=n.length>0&&n===r,a=X_(e,t);return!o&&!s&&a===0?null:o?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function R0(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function C0(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(o=>(r==="docs"?o.docs??[]:o.files??[]).map(s=>({item:o,link:s}))).forEach(({item:o,link:s})=>{if(s.scope!=="project")return;let a=Dt(s.path);if(a.length===0||a===e)return;let c=A0(e,a);c!==null&&R0(i,o,c.score)&&(i={item:o,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 Z_(e,t){return e.map(n=>{let r=Y_(n),i=r==="docs_unowned"?"docs":"files",o=C0(n,r,t),s=o?.id??"<id>";return{path:n,classification:r,owner_candidate:o,remediation_hint:`pm ${i} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Q_(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function T0(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=qe(e[n]);return i?r.some(o=>i.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function $0(e,t,n,r,i){let o=qe(t.parent),s=o?n.get(r.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!Or(s.status,i)}}function O0(e,t,n,r){let i=qe(e.blocked_by),o=qe(e.blocked_reason),s=o?.toLowerCase(),a=To(e.status,n),c=[];return t.has(a)?(!i&&!o&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(l=>s.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function D0(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!Or(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=T0(c,r);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=qe(c.parent),u=d?i.get(o.get(d.toLowerCase())??d):void 0;if(u&&Or(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push($0(c,u,i,o,n))),t){let m=O0(c,s,n,r);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,p)=>f.localeCompare(p))})}}return a}function P0(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 Ao(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function gc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function N0(e,t,n,r,i){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=Ao("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),a=Ao("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=Ao("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),l=Ao("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),d=gc("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=gc("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=gc("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...o,...s?[s]:[],...a?[a]:[],...c?[c]:[],...l?[l]:[],...d?[d]:[],...u?[u]:[],...m?[m]:[]]}function eg(e){let t=Dt(e);return t.length>a0||t.split(/[\\/]/).some(n=>n.length>c0)}async function L0(e,t){let n=be.isAbsolute(t)?t:be.resolve(e,t);if(eg(n))return!1;try{let r=await Ec.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return h0(r,["ENOENT","ENOTDIR"])}}async function M0(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(o=>({item:i,artifact:o,link_kind:"files"})),...(i.docs??[]).map(o=>({item:i,artifact:o,link_kind:"docs"}))]);for(let{item:i,artifact:o,link_kind:s}of r){if(o.scope!=="project")continue;if(Cr(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let a=Dt(o.path);a.length!==0&&(n.linkedProjectPaths.add(a),await L0(t,o.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:s})))}return n}function j0(e,t,n,r,i,o){let s=r==="tracked-all-strict",a=s&&!i,c=i||s,l=c?[]:_0(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>A_(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!A_(f,l)),m={};if(d.length>0){let f=en(d,o);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function tg(e,t,n,r,i,o,s,a="pm"){let c=D0(e,t,i,o);P0(c);let l=K_(c.activeItems,a),d=pc(e,i),u=Ci(i,e,s?Number.POSITIVE_INFINITY:Be),m=[...N0(c,t,n,r,{dependencyCycles:l.cycle_count,activeHierarchyCycles:d.active_cycle_count,activeHierarchyCardinality:d.active_cardinality_violation_count,activeHierarchyDivergence:d.active_parent_divergence_count,legacyHierarchyCycles:d.legacy_cycle_count,legacyHierarchyCardinality:d.legacy_cardinality_violation_count,legacyHierarchyDivergence:d.legacy_parent_divergence_count}),...Ti(u)],f=s?Number.POSITIVE_INFINITY:Be,p=oe(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),f),_=oe(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),f),h=oe(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),f),w=oe(l.cycle_item_ids,f),v=oe(l.cycle_sample_paths,f),k=oe(d.cycle_item_ids,f),S=oe(d.cycle_sample_paths,f),x=oe(d.cardinality_violation_rows,f),A=oe(d.parent_divergence_rows,f),E=l.cycle_count>0&&n==="error"||(d.active_cycle_count>0||d.active_cardinality_violation_count>0||d.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:E?"error":m.length===0?"ok":"warn",ok:!E&&m.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:p.values,active_closure_like_metadata_rows_truncated:p.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:_.values,active_terminal_parent_rows_truncated:_.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:h.values,stale_blocker_rows_truncated:h.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:w.values,dependency_cycle_item_ids_truncated:w.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,active_parent_cycle_count:d.active_cycle_count,legacy_parent_cycle_count:d.legacy_cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:S.values,parent_cycle_sample_paths_truncated:S.truncated,hierarchy_cardinality_violation_count:d.cardinality_violation_count,active_hierarchy_cardinality_violation_count:d.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:d.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:x.values,hierarchy_cardinality_violation_rows_truncated:x.truncated,hierarchy_parent_divergence_count:d.parent_divergence_count,active_hierarchy_parent_divergence_count:d.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:d.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:A.values,hierarchy_parent_divergence_rows_truncated:A.truncated,stale_blocker_reason_patterns:[...o.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:o.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...o.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:o.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...o.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:o.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...o.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:o.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function ng(e,t,n,r,i,o,s=_e(Vc.schema)){let a=await M0(e,t),c=new Map(e.map(D=>[D.id,D])),l=[...new Set(a.missingLinkedPaths)].sort((D,Q)=>D.localeCompare(Q)),d=await g0(t,r),u=j0(d,n,t,r,i,o),m=u.candidateFiles.filter(D=>!a.linkedProjectPaths.has(D)),f=Z_(m,e),p=a_(l,u.candidateFiles),_=new Map(p.map(D=>[D.path,D.classification])),h=p.filter(D=>D.classification==="moved").length,w=a.staleLinkRows.map(D=>({...D,classification:_.get(D.path)??"deleted"})).sort((D,Q)=>D.item_id.localeCompare(Q.item_id)||D.path.localeCompare(Q.path)||D.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 k=[...a.remoteLinkedPaths].sort((D,Q)=>D.localeCompare(Q)),S=en(k,o),x=en(l,o),A=en(m,o),E=en(f.map(D=>`${D.path}:${D.classification}:owner_candidate=${D.owner_candidate?.id??"unowned"}`),o),b=o?f:en(Q_(f),!1).values,P=en(c_(p),o),z=qh(w,p,D=>c.get(D),s,o?1/0:bc);return z.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${z.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.length===0,details:{workspace_root:t,scan_mode_requested:d.requestedMode,scan_mode_applied:d.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:o?"full":"summary",file_list_summary_limit:bc,candidate_scan_source:d.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:k.length,remote_linked_paths_total:S.total,remote_linked_paths:S.values,remote_linked_paths_truncated:S.truncated,candidate_total_raw:d.candidateTotal,candidate_scanned_raw:d.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:l.length,missing_linked_paths_total:x.total,missing_linked_paths:x.values,missing_linked_paths_truncated:x.truncated,missing_linked_paths_moved_count:h,missing_linked_paths_deleted_count:p.filter(D=>D.classification==="deleted").length,missing_linked_paths_malformed_count:p.filter(D=>D.classification==="malformed").length,missing_linked_path_classifications:P.values,missing_linked_path_classifications_truncated:P.truncated,...z,orphaned_paths_count:m.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.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 F0(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},o)=>{let s=t[o];if(s.trusted)return;let a=_c(i.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function rg(e,t,n,r){let i=new Set(e.map(x=>x.id.toLowerCase())),o=0,s=0,a=new Set,c=[],l=e.flatMap(x=>(x.tests??[]).map(A=>({item:x,linkedTest:A}))),d=await uc(mc()),u=await E_(r,l.map(({linkedTest:x})=>x),d),m=F0(l,u);for(let{item:x,linkedTest:A}of l){if(typeof A.command!="string"||A.command.trim().length===0)continue;o+=1;let E=y_(A.command,t);if(E.length!==0){s+=E.length;for(let b of E)a.add(b),i.has(b.toLowerCase())||c.push(`${x.id}:${b}:${_c(A.command)}`)}}let f=[...new Set(c)].sort((x,A)=>x.localeCompare(A)),p=[...new Set(f.map(x=>x.split(":")[1]??""))].filter(x=>x.length>0).sort((x,A)=>x.localeCompare(A)),_=[];f.length>0&&_.push(`validate_command_references_stale_pm_ids:${f.length}`),m.length>0&&_.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let h=n?Number.POSITIVE_INFINITY:Be,w=oe(f,h),v=oe(p,h),k=oe([...a].sort((x,A)=>x.localeCompare(A)),h),S=oe(m,h);return{check:{name:"command_references",status:_.length===0?"ok":"warn",ok:_.length===0,details:{checked_items:e.length,linked_commands_scanned:o,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:d??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:S.values,untrusted_linked_tests_truncated:S.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:_}}function U0(e,t){let n=Qr(e.map(c=>({ref:c.id,version:Zr(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:Be,o=oe(n.outdated,i),s=oe(n.ahead,i),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:Gl,outdated_items_count:n.outdated.length,outdated_items:o.values,outdated_items_truncated:o.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var Sc="pm validate auto-fix";async function ig(e,t,n){switch(e.kind){case"set_closed_at":await Hh(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Sc};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 yc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function og(e,t,n){let r=[],i=[],o=new Map;for(let s of e.filter(a=>yc(a)===null))try{await ig(s,t,n),r.push(s)}catch(a){i.push({fix:s,error:a})}for(let s of e.filter(a=>yc(a)!==null)){let a=yc(s),c=o.get(a);c?c.push(s):o.set(a,[s])}for(let s of o.values()){let a=s[0];if(!a)continue;let c=s.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await f_(a.item_id,{remove:c,message:Sc},t):await u_(a.item_id,{remove:c,message:Sc},t),r.push(...s)}catch(l){i.push(...s.map(d=>({fix:d,error:l})))}}return{applied:r,failed:i}}var ZH={applyValidateFix:ig,applyValidateFixes:og,attachValidateFixHints:M_,buildCommandReferencesCheck:rg,buildDependencyReferencesCheck:B_,buildCloseReasonBackfillRows:H_,buildFilesCheck:ng,buildLifecycleCheck:tg,buildLifecycleDependencyGraph:q_,buildLifecycleParentGraph:fc,buildEstimateBackfillRows:W_,buildMetadataCounts:U_,buildMissingFieldOccurrences:z_,buildOrphanedPathRows:Z_,classifyOrphanedPath:Y_,collectDefaultProjectFileCandidates:kc,collectTrackedGitFileCandidates:L_,detectLifecycleDependencyCycles:K_,detectLifecycleParentCycles:pc,escapeRegExp:G_,extractItemIds:V_,findLifecycleDependencyCycleComponents:J_,isMetadataFieldMissing:D_,linkedArtifactPathExceedsFilesystemLimits:eg,listFilesRecursive:xc,resolveDependencyCycleSeverity:$_,resolveParentCycleSeverity:O_,resolveFileScanMode:P_,resolveLifecycleDependencyCycleSamplePath:xo,resolveRequestedChecks:j_,resolveValidateMetadataProfile:T_,resolveWorkspaceRoot:N_,sharedDirectoryPrefixLength:X_,summarizeOrphanedPathRows:Q_,summarizeDuplicateIssueCodes:F_,toMeaningfulString:qe};function z0(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function H0(e,t,n,r){let i=await Vh(e,new Set(t.map(h=>h.id)),n,{schema:r.schema,extensionFieldNames:nn(H())}),o=[];i.unreadable_item_files.length>0&&o.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&o.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&o.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&o.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&o.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&o.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let s=o.length,a=await oo(e);a.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await ji(e,An(r));c.status==="drift"&&o.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await tt(e),d=l===null?null:await Rn(l);d!==null&&d.status!=="ok"&&o.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=await yt(l??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:f,lossless:p}=Nn(m);f.length>0&&o.push(`validate_merge_decisions_unreviewed:${f.length}`),z0(o,u.invalid_evidence_count);let _=s>0?"error":o.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:_,ok:_==="ok",details:{...i,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:f.length,pending_merge_decision_items:[...new Set(f.map(h=>h.item_id))].sort((h,w)=>h.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(h=>h.item_id))].sort((h,w)=>h.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:o}}function st(e,t,n){n&&M_(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function W0(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 gu(e.pmRoot,e.items,r?1/0:Be,e.sourceIncomplete);st(t,i,n)}if(e.requestedChecks.has("metadata")){let i=x0(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let o=await zh(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,r?1/0:Be);t.closureTimestampFixes=o.fixes,Object.assign(i.check.details,o.details),i.warnings.push(...o.warnings),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",st(t,i,n)}if(e.requestedChecks.has("resolution")){let i=I0(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,st(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=tg(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,st(t,i,n),st(t,B_(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await ng(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,st(t,i,n)}return e.requestedChecks.has("command_references")&&st(t,await rg(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&st(t,await Eo(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&st(t,U0(e.items,r),n),e.requestedChecks.has("storage_integrity")&&st(t,await H0(e.pmRoot,e.items,G(e.settings,H()).type_to_folder,e.settings),n),t}function G0(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...Yh(t.closeReasonBackfillRows)),r.push(...Kh(t.resolutionBackfillRows)),r.push(...Xh(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Zh(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Qh(t.staleLinkPruneRows)),r}async function q0(e,t,n,r,i,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=G0(e,t,n),{applicable:a,gated:c}=t_(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await og(a,i,o);d.push(...m.applied.map(Rr)),u.push(...m.failed.map(({fix:f,error:p})=>({...Rr(f),error:p instanceof Error?p.message:String(p)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,f)=>m.localeCompare(f)),planned_count:s.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(Rr),applied_fixes:d,gated_fixes:c.map(m=>({...Rr(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function sg(e,t,n={}){Ll(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=e_(e.fixScope),o=N(process.cwd(),t.path);await te(o);let s=await T(o),a=_e(s.schema),c=G(s,H()),l=j_(e),d=[],u=await So({includeBody:["history_drift","metadata","completeness"].some(U=>l.has(U)),pmRoot:o,settings:s,typeToFolder:c.type_to_folder,warnings:d}),m=d.length>0;if(l.has("history_drift")){let U=await sr(o);U.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${U.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=T_(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),_=f0(p,f,s.validation.metadata_required_fields),h=u0(s),w=$_(e.dependencyCycleSeverity),v=O_(e.parentCycleSeverity),k=P_(e.scanMode),S=N_(o),x=await W0({requestedChecks:l,options:e,global:t,pmRoot:o,workspaceRoot:S,settings:s,items:u,statusRegistry:a,metadataPolicy:_,lifecyclePatternPolicy:h,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:k,initialWarnings:[...new Set(d)],sourceIncomplete:m}),A=r?await q0(e,x,s,i,t,n):void 0,E=[...new Set(x.warnings)].sort((U,z)=>U.localeCompare(z)),P={ok:!x.checks.some(U=>U.status==="error"),has_warnings:E.length>0,checks:x.checks,warnings:E,...A!==void 0?{fixes:A}:{},generated_at:C(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?P:{...d0(P),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as B0}from"node:child_process";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]="894154aa-88b8-5a3b-a03c-e3ef8a85f1c0")}catch{}})();var J0=V0(B0),K0=16,Y0=3e4;function X0(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(o=>typeof o=="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 Z0(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 o of Object.entries(i).filter(([,s])=>s.required===!0).map(([s])=>s))if(!Object.hasOwn(r,o))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${o}`);for(let[o,s]of Object.entries(r)){let a=i[o];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${o}`);if(s===null||typeof s!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${o} must be ${a.type}`)}return{...r}}async function Q0(e,t,n,r){let i=Z0(e,t),o=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Dl(n)}));o.catch(()=>{});let s;try{let a=await Promise.race([o,new Promise((c,l)=>{s=setTimeout(()=>l(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??Y0),s.unref?.()})]);return X0(e,t.key,a)}finally{clearTimeout(s)}}function cg(e,t,n,r){let i=e;for(let o 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[o]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(o=>typeof o=="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 ag(e,t,n,r){let i=e.checks.find(s=>s.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:cg(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function eC(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await J0("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(K0,t.length)},async()=>{for(;r<t.length;){let o=r;r+=1;let s=t[o],a=await Ft(Lt(e,s.id),s.id);n[o]=a.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=G(n),i=_e(n.schema),s=(t.strict_read===!0?(await Kd(void 0,{status:"all",full:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await hn(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(f=>({...f,id:f.id,status:f.status,type:f.type})),a={path:e},c=H(),l=Object.fromEntries((c?.assurance_providers??[]).map(f=>[f.definition.id,{cost_class:f.runtime_definition.cost_class,network:f.runtime_definition.network}])),d=new Map,u,m;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await eC(e,t.tree_id),items:s,history:t.include_history===!1?[]:await tC(e,s),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...l,...t.provider_capabilities},external:async f=>{if(f.kind==="graph"){let h=R({operation:f.operation,parameters:f.parameters??{}}),w=d.get(h);w===void 0&&(w=Zd(f.operation,void 0,void 0,{...f.parameters,full:!0},a),d.set(h,w));let v=await w;return{value:cg(v,f.field,f.kind),population_size:s.length,cost:s.length}}if(f.kind==="validate"){u??=sg({counts:!0},a);let h=await u;return ag(h,f.check,f.field,f.kind)}if(f.kind==="health"){m??=jh(a,{checkOnly:!0,full:!0});let h=await m;return ag(h,f.check,f.field,f.kind)}let p=t.providers?.[f.provider];if(p)return p(f);let _=dd(c,f.provider);if(!_)throw new TypeError(`assurance provider ${f.provider} is not registered`);return Q0(_.runtime_definition,f,e,t.trigger??"sdk")}}}import{createHash as nC}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]="538168d9-116c-5e72-81a4-a23e021c48f5")}catch{}})();function lg(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}=Kr({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function rC(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 iC(e,t,n,r,i,o){let s=Object.fromEntries(Yo.map(f=>[f,0])),a=0,c=0,l=0,d=0,u=[],m=nC("sha256").update(i);for(let f of r){let p=e.membership.get(f),_=n.has(f),h=p.family_ids.length>0;h&&_&&(a+=1),h||(c+=1),_||(l+=1);let w=t.get(f)?.escape_class;w!==void 0&&Yo.includes(w)&&(s[w]+=1,d+=1),m.update(R([f,_,t.get(f)??null,p.id,p.family_ids])),(!o||!h||!_)&&u.push(f)}return{classCounts:s,coveredCount:a,uncoveredCount:c,missingCount:l,classifiedCount:d,selected:u,fingerprint:m.digest("hex")}}function dg(e,t,n={}){Hl(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,o=new Map;for(let S of t){if(i.has(S.id))throw new TypeError(`Duplicate recurrence item ${S.id}`);i.add(S.id);let x=Jr(S);x!==void 0&&o.set(S.id,x)}let s=Fl(e.families,o),a=[...s.membership.keys()].sort(),c=R({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:l,coveredCount:d,uncoveredCount:u,missingCount:m,classifiedCount:f,selected:p,fingerprint:_}=iC(s,o,i,a,c,n.uncoveredOnly===!0),h=rC(n.cursor,_);if(h>p.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=p.slice(h,h+r).map(S=>{let x=s.membership.get(S),A=i.has(S);return{item_id:S,lineage_id:x.id,lineage_item_count:x.item_ids.length,family_ids:x.family_ids,present:A,...A?x.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=h+w.length,k=a.length===0?null:l.production_defect/a.length;return{ok:u===0&&m===0,fingerprint:_,items:w,total:p.length,has_more:v<p.length,...v<p.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:_,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:a.length,lineage_count:s.lineages.length,edge_count:s.edge_count,covered_item_count:d,uncovered_item_count:u,missing_item_count:m,classified_item_count:f,unclassified_item_count:a.length-f,class_counts:l,escape_rate:f===a.length?k:null,escape_rate_lower_bound:k},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:s.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as oC}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]="77425e45-ae19-569b-b196-e024f9e2729f")}catch{}})();var Ic,ug=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],Ac=["measurement","assertion","gate"];function sC(e){if(ug.includes(e))return e;throw ci({command_path:"assurance",token:e,allowed:ug,display_name:"assurance action"})}function zn(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 aC(e){if(!e)return zn("kind",`Assurance declaration kind is required. Expected: ${Ac.join(", ")}`,"pm assurance list measurement");if(Ac.includes(e))return e;throw new y(`Assurance declaration kind is required. Expected: ${Ac.join(", ")}`,g.USAGE)}function mg(e){if(!e)return zn("preset",`Assurance preset is required. Expected: ${ar.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(ar.includes(e))return e;throw new y(`Assurance preset is required. Expected: ${ar.join(", ")}`,g.USAGE)}function Rc(e){return e.owner?.trim()?e.owner.trim():zn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function cC(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 lC(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 fg(e,t){return t===!0?{id:e.id}:e}async function dC(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(s=>s.id===n),o=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!o.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=bs(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>wn))throw new y(`assurance verdict limit must be an integer from 1 through ${wn}`,g.USAGE);let r=await hu(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 mC(e,t,n){if(e==="presets"){if(t.preset??t.id)return Ai(mg(t.preset??t.id),Rc(t));let i=ar.map(o=>{let s=Ai(o,"pm-owner");return{id:o,title:s.title,description:s.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return yn(()=>Wu(n,mg(t.preset??t.id),Rc(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await Gu(await Dr(n,{resolve_tree:!1,trigger:"derive"}),Rc(t)),o=t.apply?await yn(()=>qu(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...o?{applied:o}:{}}}if(!t.id)return zn("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 gs(n,"assertion",t.id);return yn(()=>Bu(n,r,t.enforcement,{author:t.author,message:t.message}))}async function fC(e,t,n){if(!e.id)return zn("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(!Wt.includes(e.trigger))throw new y(`Unknown assurance trigger ${e.trigger}. Expected: ${Wt.join(", ")}`,g.USAGE);let i=e.trigger,[o,s]=await Promise.all([lC(t),Dr(t,{...n.workspace,tree_id:e.tree,trigger:i})]),a=await Qd(()=>uu(r,o,s,{trigger:i,dry_run:e.dry_run===!0}));return a.dry_run||await pu(t,a,{author:e.author,message:e.message}),a}function pg(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"?lg(t):Kr(t)}catch(n){return pg(n)}}function hC(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 _C(e,t,n){let r=R(t.policy),i=Ic?.pm_root===e?Ic:void 0,o=new Map(n.map(l=>[l.id,oC("sha256").update(R([jl(l),Jr(l)])).digest("hex")])),s=i?.policy_serialized===r?i:void 0,a=s?hC(s,o):new Set,c=Ul(t.policy,s?n.filter(l=>a.has(l.id)):n,s?{previous_index:s.index,changed_item_ids:[...a]}:{});return Ic={pm_root:e,policy_serialized:r,item_fingerprints:o,index:c},c}async function gC(e,t){let n=pC(e),r=await Dr(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?zl(_C(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):dg(n.policy,r.items,n)}catch(i){return pg(i)}}async function yC(e,t={},n={}){let r=sC(e.action),i=N(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return mC(r,e,i);if(r==="verdicts")return uC(e,i);if(r==="run")return fC(e,i,n);if(["risk","lineages"].includes(r))return gC(e,i);let o=aC(e.kind);if(r==="list")return nr(i,o);if(!e.id)return zn("id",`assurance ${r} requires an id`,`pm assurance ${r} ${o} <id>`);let s=e.id;if(r==="show")return gs(i,o,s);if(r==="remove"){let d=await yn(()=>fu(i,o,s,{author:e.author,message:e.message}));return fg(d,e.idOnly)}let a=cC(o,e.definition);if(a.id!==s)throw new y(`Assurance definition id ${a.id} does not match requested id ${s}`,g.USAGE);let c={author:e.author,message:e.message,...o==="assertion"?{authorized_decision_ids:await dC(i,a)}:{}},l=await yn(()=>vi(i,o,a,c));return fg(l,e.idOnly)}function DW(e,t,n){let r={...e,...t};return yC({action:O(r,"subcommand")??O(r,"assuranceAction")??O(r,"operation")??"",kind:O(r,"kind"),id:O(r,"id"),definition:r.definition,trigger:O(r,"trigger"),tree:O(r,"treeId")??O(r,"tree"),gate:O(r,"gate"),limit:bs(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:O(r,"author"),message:O(r,"message"),preset:O(r,"preset"),owner:O(r,"owner"),apply:r.apply===!0,enforcement:O(r,"enforcement")},n)}import Hn from"node:fs/promises";import Oo from"node:path";import $o from"node:fs/promises";import Cc 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]="fe72275e-b195-5a7e-b963-a9f159f9c67c")}catch{}})();var wC=864e5;function vC(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 bC(e,t){let n;try{n=await $o.readdir(e,{withFileTypes:!0})}catch(i){if(j(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let o=Cc.join(e,i.name),s;try{s=await $o.readdir(o)}catch(a){j(a)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of s)a.endsWith(".json")&&r.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function hg(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*wC,s=Cc.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await bC(s,a.warnings);for(let l of c){let d=Cc.join(s,l),u=`checkpoints/${l}`;a.scanned+=1,r?.onRead&&a.warnings.push(...await r.onRead(d));let m;try{m=await $o.readFile(d,"utf8")}catch(w){if(j(w)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${l}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=vC(m),p=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(p)){a.warnings.push(`checkpoint_unparseable:${l}`),a.retained.push(u),a.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let _=i-p,h={file:u,created_at:f,age_seconds:Math.floor(_/1e3),stale:_>o,reason:_>o?"expired":"active"};if(!h.stale){a.retained.push(u),a.entries.push(h);continue}if(!n){try{await $o.unlink(d)}catch(w){if(!j(w)){a.warnings.push(`checkpoint_remove_failed:${l}`),a.retained.push(u),a.entries.push(h);continue}}r?.onWrite&&a.warnings.push(...await r.onWrite(d))}a.removed.push(u),a.entries.push(h)}return a}import Tc from"node:fs/promises";import _g 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]="9189cea6-950f-5594-9321-b7590171297c")}catch{}})();var kC=1440*60*1e3,SC=new Set(["committed","compensated"]);function EC(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 xC(e,t,n,r,i){let o=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(o))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let s=r-o;return SC.has(t)?s>i?{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"active"},remove:!1}}async function IC(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],o=EC(await Tc.readFile(e,"utf8")),s=xC(t,o.status,o.updatedAt,r.nowMs,r.retentionMs);return s.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),s.remove&&!r.dryRun&&(await Tc.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:s,warnings:i}}async function gg(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*kC,s=_g.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Tc.readdir(s)).filter(l=>l.endsWith(".json")).sort((l,d)=>l.localeCompare(d))}catch(l){if(j(l))return a;throw l}for(let l of c){let d=_g.join(s,l),u=`transactions/sdk/${l}`,m=await IC(d,u,l,{dryRun:n,hooks:r,nowMs:i,retentionMs:o});a.warnings.push(...m.warnings),a.scanned+=1;let{decision:f}=m;if(!f.remove){a.retained.push(u),a.entries.push(f.entry);continue}a.removed.push(u),a.entries.push(f.entry)}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]="8e2e3b62-5eb1-5773-96bf-866b26a59345")}catch{}})();var Pr=["index","embeddings","runtime","locks","checkpoints","transactions"],AC=1440*60*1e3,RC=[{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 CC(e,t,n){let r=t.relativePath,i=Oo.join(e,r),o=await He({path:i,scope:"project"});try{let s=await Hn.stat(i);if(t.kind==="file"&&!s.isFile())return{removed:!1,warnings:[...o,`not_a_file:${r}`]};if(t.kind==="directory"&&!s.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await Hn.unlink(i):await Hn.rm(i,{recursive:!0,force:!0});let a=await X({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...a]}}catch(s){if(j(s))return{removed:!1,warnings:o};throw s}}async function TC(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],o=[],s=Date.now()-AC;for(let a of n){let c=Oo.join(e,a.relativePath);if(!await $(c))continue;let l=(await Hn.readdir(c)).filter(d=>d.startsWith(a.prefix)).sort();for(let d of l){let u=Oo.posix.join(a.relativePath,d),m=Oo.join(c,d);o.push(...await He({path:m,scope:"project"}));let f=await Hn.stat(m).catch(p=>{if(!j(p))throw p});if(f){if(f.mtimeMs>s){i.push(u);continue}r.push(u),!t&&(await Hn.rm(m,{recursive:!0,force:!0}),o.push(...await X({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:o}}function $C(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 OC(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 nG(e,t={}){let n=N(process.cwd(),e.path);await te(n);let r=await T(n),i=t.dryRun===!0,o=$C(t.scope),s=RC.filter(p=>o.includes(p.scope)),a=[],c=[],l=[];for(let p of s){let _=await CC(n,p,i);_.removed?a.push(p.relativePath):c.push(p.relativePath),l.push(..._.warnings)}if(o.includes("runtime")){let p=await TC(n,i);a.push(...p.removed),c.push(...p.retained),l.push(...p.warnings)}let d;if(o.includes("locks")){let p=await bm(n,{dryRun:i,hooks:{onRead:_=>He({path:_,scope:"project"}),onWrite:_=>X({path:_,scope:"project",op:"gc:lock_remove"})}});a.push(...p.removed),c.push(...p.retained),l.push(...p.warnings),d={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(o.includes("transactions")){let p=r.checkpoints.retention_days,_=await gg(n,{dryRun:i,retentionDays:p,hooks:{onRead:h=>He({path:h,scope:"project"}),onWrite:h=>X({path:h,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(..._.removed),c.push(..._.retained),l.push(..._.warnings),u={scanned:_.scanned,removed:_.removed.length,retained:_.retained.length,retention_days:p}}let m;if(o.includes("checkpoints")){let p=r.checkpoints.retention_days,_=await hg(n,{dryRun:i,retentionDays:p,hooks:{onRead:h=>He({path:h,scope:"project"}),onWrite:h=>X({path:h,scope:"project",op:"gc:checkpoint_remove"})}});a.push(..._.removed),c.push(..._.retained),l.push(..._.warnings),m={scanned:_.scanned,removed:_.removed.length,retained:_.retained.length,retention_days:p}}l.push(...await Vr({mode:i?"gc:dry-run":"gc",total_items:s.length}));let f=OC({dryRun:i,scopes:o,removed:a});return{ok:l.length===0,dry_run:i,scope:o,removed:a,retained:c,warnings:l,...d?{locks:d}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:f,generated_at:C()}}import{execFile as DC}from"node:child_process";import PC from"node:path";import{promisify as NC}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]="4bc28901-e70b-5a76-80bb-762ed8227e5f")}catch{}})();var LC=NC(DC),wg="@unbrained/pm-cli",MC="latest",jC={global:["--global"],project:[]};function yg(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 Po(e){return e.trim().toLowerCase()}function vg(e,t){let n=Po(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(i=>typeof i=="string"&&Po(i)===n)}function FC(e,t){let n=N(process.cwd(),t.path),r=rn(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function UC(e,t,n){try{let r=await LC(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??""):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new y(`Command failed: ${e} ${t.join(" ")}
68
- ${o}`,g.GENERIC_FAILURE)}}function No(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():MC}function Do(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():wg}async function zC(e,t){let n=e.commandRunner??UC,r=Do(e),i=No(e),o=`${r}@${i}`,s=["npm","install","-g",o];e.repair===!0&&s.push("--force");let a=Yc(import.meta.url,["../../.."]),c={requested:!0,status:"planned",package:r,target:o,command:s,before_version:a,...r===wg?{migration_guidance:["Calendar scheduling commands are package-owned. If calendar is absent, run pm package install calendar --project; use pm calendar meet, pm calendar event, or pm calendar remind."]}:{},repair:e.repair===!0};if(t)return c;try{await n(s[0],s.slice(1));let l=await n("pm",["--version"]);return{...c,status:"updated",after_version:l.stdout.trim()||void 0}}catch(l){return{...c,status:"failed",error:l instanceof Error?l.message:String(l)}}}function HC(e){return PC.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function WC(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!HC(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 GC(e,t){let n=WC(e,t);return e.kind!=="local"||await $(n)?n:await $(e.location)?e.location:n}function qC(e,t,n,r){let i=["pm","package","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&r&&r.trim().length>0&&i.push("--ref",r.trim()),i}async function bg(e,t){let n=FC(e,t);return(await we(n.selected_root)).state.entries.filter(i=>i.scope===e)}async function BC(e,t,n){let r=await bg(e,t);return r.find(i=>vg(i,n.name))??r.find(i=>Po(i.directory)===Po(n.directory))}async function VC(e,t,n,r,i){let o=No(t),s=await GC(e.source,o),a=qC(e.source,s,r,e.source.ref),c={name:e.name,directory:e.directory,scope:r,source:e.source,status:"planned",command:a,previous_version:e.manifest_version};if(i)return c;try{await ba(s,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let l=await BC(r,n,e);return{...c,status:"updated",installed_version:l?.manifest_version}}catch(l){return{...c,status:"failed",error:l instanceof Error?l.message:String(l)}}}function JC(e,t,n,r){let i=[n?e.status:void 0,...t.map(o=>o.status)].filter(o=>typeof o=="string");return{requested_cli:n,requested_packages:r,planned:i.filter(o=>o==="planned").length,updated:i.filter(o=>o==="updated").length,skipped:i.filter(o=>o==="skipped").length,failed:i.filter(o=>o==="failed").length}}async function dG(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",...jC[yg(t)]];throw new y('Options "--cli-only" and "--packages-only" are mutually exclusive.',g.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:Xe(m),suggested_retry_args:m}})}let i=yg(t),o=t.dryRun===!0;if(t.cliOnly===!0&&r)throw new y('A package target cannot be used with "--cli-only".',g.USAGE);let s=!(t.packagesOnly===!0||r),a=t.cliOnly!==!0,c=s?await zC(t,o):{requested:!1,status:"skipped",package:Do(t),target:`${Do(t)}@${No(t)}`,command:["npm","install","-g",`${Do(t)}@${No(t)}`],repair:t.repair===!0,reason:"not_requested"},l=a?await bg(i,n):[];if(r&&(l=l.filter(m=>vg(m,r)),l.length===0))throw new y(`Managed package "${r}" was not found in ${i} scope.`,g.NOT_FOUND);let d=[];for(let m of l)d.push(await VC(m,t,n,i,o));let u=JC(c,d,s,a);return{ok:u.failed===0,action:"upgrade",dry_run:o,scope:i,target:r,cli:c,packages:d,summary:u}}import{createHash as KC}from"node:crypto";import{isUtf8 as YC}from"node:buffer";import Nr from"node:fs/promises";import $c from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0001f37-7941-5cad-8950-2c6925056d10")}catch{}})();async function kg(e){try{return(await Nr.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(j(t))return[];throw t}}function XC(e,t,n,r){let i=t.at(-1),o;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)){o=t[c];break}let s=t[0]?.context?.history_compaction,a=typeof s=="object"&&s!==null&&"pruned_stream_digest"in s&&typeof s.pruned_stream_digest=="string"?s.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?Ee(i.hash_algorithm):null,rewrite_count:t.reduce((c,l)=>c+(l.reanchor_evidence?.length??0),0),checkpoint_digest:a,last_maintenance:o?{op:o.op,ts:o.ts,record_hash:o.record_hash??null}:null}}function ZC(e,t,n){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!YC(t))return null;let r=[];for(let i of t.toString("utf8").split(/\r?\n/u)){if(!i.trim())continue;let o=JSON.parse(i);if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=o;if(![s.op,s.author,s.ts,s.before_hash,s.after_hash].every(a=>typeof a=="string")||!Array.isArray(s.patch))return null;r.push(s)}return Kn(r).ok?XC(e,r,t.length,n):null}catch{return null}}async function Oc(e,t){if(!(await Nr.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let n=$c.join(e,"history"),r=await kg(n),i=new Map,o=[];for(let s of r){let a=s.slice(0,-6),c={id:a,digest:null,stream:null};o.push(c);let l=$c.join(n,s);try{let d=await Nr.lstat(l);if(i.set(s,R([d.ino,d.size,d.mtimeMs,d.ctimeMs])),!d.isFile())continue;let u=await Nr.readFile(l);c.digest=KC(t).update(u).digest("hex"),c.stream=ZC(a,u,c.digest)}catch{}}if(R(r)!==R(await kg(n)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of i){let c=await Nr.lstat($c.join(n,s));if(a!==R([c.ino,c.size,c.mtimeMs,c.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}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]="0a4b3fc5-70bb-5ec0-82b5-a7cdd03c09ea")}catch{}})();function Dc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pc(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 QC(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 eT(e){return e===null?!0:!Dc(e)||!Pc(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"&&Et(e.ts)&&(e.record_hash===null||Wn(e.record_hash,"sha256")||Wn(e.record_hash,"sha512"))}function tT(e,t){return!Dc(e)||!Pc(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)&&QC(e)&&(e.checkpoint_digest===null||Wn(e.checkpoint_digest,"sha256"))&&eT(e.last_maintenance)}function Sg(e){if(!Dc(e)||!Pc(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==Zo.format||e.version!==1||typeof e.generated_at!="string"||!Et(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 o of e.streams){if(!tT(o,t))throw new TypeError("Invalid history attestation stream");let s=o.id;if(n!==void 0&&s<=n)throw new TypeError("Invalid history attestation stream order");n=s}let{workspace_digest:r,...i}=e;if(Qo(R(i),t)!==r)throw new TypeError("History attestation rollup mismatch");return e}async function Eg(e={}){let t=Ee(e.hashAlgorithm),n=e.generatedAt??C();if(!Et(n))throw new TypeError("Invalid history attestation timestamp");let r=await Oc(N(e.cwd??process.cwd(),e.pmRoot),t),i=r.filter(s=>s.stream===null);if(i.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${i.map(s=>s.id).join(", ")}`);let o={format:Zo.format,version:1,hash_algorithm:t,generated_at:n,streams:r.map(s=>s.stream)};return Sg({...o,workspace_digest:Qo(R(o),t)})}async function xg(e,t={}){let n=Sg(e),r=await Oc(N(t.cwd??process.cwd(),t.pmRoot),n.hash_algorithm),i=new Map(r.map(d=>[d.id,d])),o=new Map(n.streams.map(d=>[d.id,d])),s=n.streams.filter(d=>!i.has(d.id)).map(d=>d.id),a=r.filter(d=>!o.has(d.id)).map(d=>d.id),c=r.filter(d=>d.stream===null).map(d=>d.id),l=[];for(let d of n.streams){let u=i.get(d.id);u&&(u.digest!==d.stream_digest||R(u.stream)!==R(d))&&l.push({id:d.id,before_digest:d.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:s.length+a.length+c.length+l.length===0,workspace_digest:n.workspace_digest,streams_checked:r.length,changed_streams:l.map(d=>d.id),missing_streams:s,added_streams:a,invalid_streams:c,transitions:l}}import Ig 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]="825d7132-a49d-584a-b4ac-0801cfe6ad49")}catch{}})();async function PG(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 Ig.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 xg(r,{pmRoot:t.path})}let n=await Eg({pmRoot:t.path,hashAlgorithm:Ee(e.hashAlgorithm)});if(e.output===void 0)return n;try{await Ig.writeFile(e.output,`${JSON.stringify(n,null,2)}
69
- `,{flag:"wx",mode:384})}catch{throw new y("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",g.USAGE)}return{output:e.output,workspace_digest:n.workspace_digest,streams:n.streams.length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48abeea1-703c-57e9-9d99-787cb2829efb")}catch{}})();function Ag(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 Rg(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?Xe([...r,"merge","report"],n):e==="history_evidence_invalid"?Xe([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?Xe([...r,"merge","reconcile"],n):e==="history_repair_required"?Xe([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?Xe([...r,"merge","install"],n):null}function Cg(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(r=>typeof r=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(r=>typeof r=="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 VG(e){let t=N(process.cwd(),e.path);await te(t);let n=await T(t),r=G(n,H()),i=[],o=await So({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),s=await tt(t),[a,c,l,d]=await Promise.all([ji(t,An(n)),s===null?Promise.resolve(null):Rn(s),yt(s??t,{includeLossless:!0,pmRoot:t}),Eo(t,o,!1)]),{pendingDecisions:u,lossless:m}=Nn(l.receipts),f=[...new Set(u.map(w=>w.item_id))].sort((w,v)=>w.localeCompare(v)),p=d.check.details,_=Cg(p),h=Ag({invalidEvidenceCount:l.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:m.length,historyEvidenceValid:_.evidence_valid,driftedItemCount:_.drifted_item_count,fence:a,drivers:c});return{ok:h==="ready",state:h,merge_fence:{committed:a,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:f.slice(0,25),pending_item_ids_truncated:f.length>25,lossless_count:m.length,invalid_evidence_count:l.invalid_evidence_count},history_drift:_,next_action:{command:Rg(h,t),reason:h},warnings:[...new Set(i)].sort((w,v)=>w.localeCompare(v)),generated_at:C()}}function JG(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
70
- `)}var KG={commandForWorkspacePositionState:Rg,normalizeWorkspaceHistoryDrift:Cg,selectWorkspacePositionState:Ag};import nT 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]="dae5fa09-fdac-58db-9dbe-5c5c12eb6c9b")}catch{}})();var Nc="index/manifest.json",Lc="search/embeddings.jsonl",rT="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function iT(e){return e.progress===!0||process.stderr.isTTY===!0}function le(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
71
- `)}catch{}}function oT(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 sT(e,t,n,r){let i=[];return{candidates:await Rd(e,t,n,i,r),warnings:i}}async function jc(e,t,n,r,i){let o=nn(H()),s=[];for(let a of t)if(!(i&&!i.has(a.metadata.id))){if(typeof a.body=="string"){s.push({metadata:a.metadata,body:a.body});continue}try{let c=await nT.readFile(a.item_path,"utf8"),l=xt(c,{format:a.item_format,schema:n,extensionFieldNames:o,onWarning:d=>r.push(d)});s.push({metadata:a.metadata,body:l.body})}catch{r.push(`item_list_item_read_failed:${Lr.relative(e,a.item_path)}`),s.push({metadata:a.metadata,body:""})}}return s}function aT(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:$d(e,{fields:n})}}var Gn=ee;function cT(e){let t=H(),n=Gn(e.search?.provider);if(!n)return null;let r=ud(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=Gn(i.name)??Gn(r.definition.name);if(!o)return null;let s=i.embedBatch,a=i.embed_batch,c=i.embed,l=typeof s=="function"?s:typeof a=="function"?a:void 0,d=typeof c=="function"?c:void 0;return!l&&!d?null:{name:o,embedBatch:l,embed:d}}function lT(e){let t=H(),n=Gn(e.vector_store?.adapter);if(!n)return null;let r=md(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=Gn(i.name)??Gn(r.definition.name);if(!o)return null;let s=i.upsert,a=i.delete;return{adapterName:o,...typeof s=="function"?{upsert:s}:{},...typeof a=="function"?{delete:a}:{}}}function Mc(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 dT(e,t,n){let r=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let o=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:r}));if(!Array.isArray(o))throw new y(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,g.GENERIC_FAILURE);return o.map((s,a)=>Mc(s,`extension search provider "${e.name}" embedBatch output at index ${a}`))}if(!e.embed)throw new y(`Extension search provider "${e.name}" does not implement embed/embedBatch`,g.GENERIC_FAILURE);let i=[];for(let[o,s]of n.entries()){let a=await Promise.resolve(e.embed({input:s,settings:t,model:r}));i.push(Mc(a,`extension search provider "${e.name}" embed output at index ${o}`))}return i}function Tg(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function $g(e,t,n){let r=n?Ht(n.name,Tg(e)):t?Ht(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 Og(e,t,n,r,i,o,s,a){let c=r?.name??n?.name,l=Od(c,e.search.embedding_corpus_max_characters).maxCharacters,d=os(e),u=i.map(p=>Dd(p,{providerName:c,maxCharacters:l,fields:d})),m=[],f=null;if(r)try{m=await dT(r,e,u),f=Ht(r.name,Tg(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);o.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 Pd(n,e,u,{onProgress:_=>{_.phase==="complete"&&(s.batches_completed=_.batch_index),le(a,`embedding_batch_${_.phase} batch=${_.batch_index}/${_.batch_total} size=${_.batch_size} completed_inputs=${_.completed_inputs}/${_.total_inputs}`)}});o.push(...p.warnings),s.batching=p.receipt,m=p.vectors,f=Ht(n.name,n.model)}if(le(a,`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 mT(e,t,n,r,i,o){let s=Object.keys(n);if(t){if(s.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:s.sort((a,c)=>a.localeCompare(c)),settings:r}))}catch(a){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${a instanceof Error?a.message:String(a)}`,g.GENERIC_FAILURE)}else s.length>0&&i.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${s.length}`);if(!e)return}e&&await Md(e,s,{},o)}async function Dg(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(o){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${o instanceof Error?o.message:String(o)}`,g.GENERIC_FAILURE)}else i.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Ld(e,n)}}function fT(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 hT(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=fi(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 _T(e){let t=G(e.settings,H()),n=await sT(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 gT(e){let t=await gn(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 $g(e.settings,Zn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&_n(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(rT))}async function yT(e){let t=await gn(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=$g(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(l=>l.metadata.id)),i=uT(t.entries,r),o=_n(t.embedding,n);e.forceFullSemantic&&!o&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let s=e.forceFullSemantic||o?e.metadataDocuments:e.metadataDocuments.filter(l=>t.entries[l.metadata.id]!==l.metadata.updated_at),a=new Set(s.map(l=>l.metadata.id)),c=a.size>0?await jc(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,a):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:i,resetRequired:o,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function wT(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await jc(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,le(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await Og(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:ss(r.vectors,"Reindex embeddings")}}async function vT(e){let t=await Og(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=ss(n,"Reindex embeddings");if(!(!e.resetRequired&&(_n(e.ledgerEmbedding,r)||Fd(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let s=await wT(e);return n=s.vectors,r=s.embeddingIdentity,i=s.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:s.staleDocuments,vectorDimension:i,resetRequired:!0}}async function bT(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(le(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new y(`Extension vector adapter "${t}" does not support upserting vectors.`,g.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,le(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof y)throw t;if(!e.activeVectorStore)throw new y(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,g.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),le(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){le(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Nd(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,le(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new y(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,g.USAGE)}function kT(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:Mc(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 ST(e){le(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await vT({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(le(e.progressEnabled,"vector_reset_start"),await mT(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),le(e.progressEnabled,"vector_reset_complete")):await Dg(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=kT(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await bT({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:jd(t.embeddingIdentity,t.vectorDimension)}}async function ET(e){let t=await yT(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(o=>[o.metadata.id,o.metadata.updated_at]));if(le(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return le(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await Dg(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await ST({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let i=new Map(r.staleDocuments.map(o=>[o.metadata.id,o]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(o=>i.get(o.metadata.id)??o),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:r.embeddingMetadata}}async function xT(e){let t=Lr.join(e.pmRoot,Nc),n=Lr.join(e.pmRoot,Lc),r=os(e.settings),i=e.documentsForKeywordArtifacts.map(s=>JSON.stringify(aT(s,e.mode,r))).join(`
72
- `);le(e.progressEnabled,"writing keyword artifacts"),await ne(t,`${JSON.stringify(e.manifest,null,2)}
73
- `),await ne(n,`${i}
74
- `);let o=[];if(e.mode!=="keyword")try{le(e.progressEnabled,"writing vectorization status ledger"),await Ud(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(s){o.push(`search_vectorization_status_ledger_write_failed:${s instanceof Error?s.message:String(s)}`)}return o}async function t2(e,t){let n=oT(e.mode),r=iT(e),i=e.full===!0;le(r,`start mode=${n}`);let o=N(process.cwd(),t.path);await te(o);let s=ui(await T(o)).settings,a=null;try{a=await ce(o,wd,s.locks.ttl_seconds,q(void 0,"pm-reindex"),!1,s.governance.force_required_for_stale_lock,s.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=cT(s),l=lT(s),d=hT({requestedMode:n,pmRoot:o,settings:s,extensionEmbedding:c,extensionVectorAdapter:l}),u=n;le(r,"loading item corpus");let m=await _T({pmRoot:o,settings:s}),f=m.warnings,{documentCandidates:p,metadataDocuments:_}=m;le(r,`loaded_items=${_.length}`);let h=C(),w=pT(u,h,_),v=Lr.join(o,Nc),k=Lr.join(o,Lc),S=u==="keyword"?await jc(o,p,s.schema,f):_,x=[],A={},E=null,b=fT(u);if(u==="keyword"&&await gT({pmRoot:o,settings:s,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let z=await ET({pmRoot:o,settings:s,requestedMode:n,activeEmbeddingProvider:d.activeEmbeddingProvider,activeVectorStore:d.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:p,metadataDocuments:_,documentsForKeywordArtifacts:S,forceFullSemantic:i,reindexWarnings:f,semanticWarnings:x,semanticSummary:b,progressEnabled:r});S=z.documentsForKeywordArtifacts,A=z.vectorizationLedgerEntries,E=z.vectorizationEmbeddingMetadata}let P=await xT({pmRoot:o,mode:u,manifest:w,documentsForKeywordArtifacts:S,settings:s,vectorizationLedgerEntries:A,vectorizationEmbeddingMetadata:E,progressEnabled:r}),U=[...await X({path:v,scope:"project",op:"reindex:manifest"}),...await X({path:k,scope:"project",op:"reindex:embeddings"}),...await Vr({mode:u,total_items:_.length})];return le(r,"done"),{ok:!0,mode:u,total_items:_.length,semantic:b,artifacts:{manifest:Nc,embeddings:Lc},warnings:[...f,...x,...P,...U],generated_at:h}}finally{await a?.()}}export{L as a,Ie as b,Ze as c,yn as d,Qd as e,tu as f,Wt as g,ds as h,Gg as i,fs as j,ps as k,ou as l,vn as m,tr as n,_s as o,ly as p,uu as q,nr as r,gs as s,vi as t,ys as u,fu as v,pu as w,hu as x,Ym as y,xD as z,tv as A,nv as B,tt as C,iP as D,bv as E,my as F,UT as G,yu as H,hy as I,s$ as J,cb as K,cN as L,uN as M,mN as N,fr as O,fN as P,pN as Q,hN as R,_N as S,gN as T,yN as U,wN as V,vN as W,bN as X,kN as Y,SN as Z,pp as _,ba as $,eD as aa,fm as ba,j$ as ca,O as da,se as ea,F$ as fa,bs as ga,U$ as ha,z$ as ia,Cu as ja,H$ as ka,W$ as la,G$ as ma,Oy as na,q$ as oa,B$ as pa,ks as qa,V$ as ra,J$ as sa,vs as ta,K$ as ua,Y$ as va,$u as wa,X$ as xa,Py as ya,Pu as za,aO as Aa,sr as Ba,cO as Ca,zy as Da,Hy as Ea,lO as Fa,Wy as Ga,u_ as Ha,pO as Ia,zu as Ja,f_ as Ka,Rz as La,Cz as Ma,ar as Na,Ai as Oa,Wu as Pa,Gu as Qa,qu as Ra,Bu as Sa,Yu as Ta,Zu as Ua,Qu as Va,nm as Wa,Ot as Xa,zj as Ya,Hj as Za,Wj as _a,Gj as $a,tF as ab,Qp as bb,Ma as cb,bF as db,yt as eb,kF as fb,SF as gb,Yx as hb,eI as ib,fh as jb,lw as kb,im as lb,za as mb,_1 as nb,g1 as ob,Ci as pb,Ti as qb,jh as rb,pU as sb,Fh as tb,zh as ub,Hh as vb,qh as wb,Vh as xb,ER as yb,xR as zb,Dz as Ab,Pz as Bb,Nz as Cb,Lz as Db,AR as Eb,RR as Fb,CR as Gb,Mz as Hb,__ as Ib,$R as Jb,g_ as Kb,ac as Lb,w_ as Mb,OR as Nb,DR as Ob,PR as Pb,uc as Qb,mc as Rb,Vz as Sb,Jz as Tb,Kz as Ub,d0 as Vb,ZH as Wb,sg as Xb,Dr as Yb,lg as Zb,dg as _b,ug as $b,Ac as ac,yC as bc,DW as cc,nG as dc,dG as ec,Sg as fc,Eg as gc,xg as hc,PG as ic,VG as jc,JG as kc,KG as lc,t2 as mc};
75
- //# sourceMappingURL=chunk-6J2YCGSN.js.map