@unbrained/pm-cli 2026.8.19 → 2026.8.21
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.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +41 -0
- package/dist/cli/error-guidance.d.ts +20 -0
- package/dist/cli/error-guidance.js +29 -30
- package/dist/cli/register-list-query.js +12 -10
- package/dist/cli/register-structured-mutation.d.ts +2 -0
- package/dist/cli/register-structured-mutation.js +29 -6
- package/dist/cli-bundle/bundle-manifest.json +156 -148
- package/dist/cli-bundle/chunks/chunk-2MA6ZQVZ.js +197 -0
- package/dist/cli-bundle/chunks/{chunk-4NRRH7AM.js → chunk-3AFAUHUE.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-7VHZS727.js +5 -0
- package/dist/cli-bundle/chunks/chunk-BKYB45NQ.js +2092 -0
- package/dist/cli-bundle/chunks/{chunk-BHYMXLAE.js → chunk-BUNIEJNE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QXSH7BLM.js → chunk-JSLOFXGA.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-LARJJ3RK.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-TOXJM4WA.js → chunk-LOVTQ52Z.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-N3DSV4CH.js +77 -0
- package/dist/cli-bundle/chunks/chunk-OCLPLFAY.js +35 -0
- package/dist/cli-bundle/chunks/chunk-S4IRYKBU.js +13 -0
- package/dist/cli-bundle/chunks/register-list-query-F57EWDEF.js +11 -0
- package/dist/cli-bundle/chunks/{register-mutation-AUWVCW4M.js → register-mutation-7IY2D5KO.js} +20 -20
- package/dist/cli-bundle/chunks/{register-operations-PZQPHXW5.js → register-operations-FALL3YTU.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-I4LUHGVW.js → register-setup-HXU7IZZD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2NIY5NKG.js +18 -0
- package/dist/cli-bundle/focused-chunks/{chunk-US7VEYZG.js → chunk-4ERLO7QD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-7WZRLCYF.js +50 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MCZXYZAF.js → chunk-CKKQSJNN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-EEFKYMDR.js +16 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZBIQQYMI.js → chunk-F2A56DHV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ESISGDAY.js → chunk-F4YEW5I2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ODHQEECS.js → chunk-FH6DYED3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-FJ22HNRP.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-FV5ACOK7.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-JEAVFOWM.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-EXBCLIBU.js → chunk-KDNG7TKQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-NJ63LOP6.js +155 -0
- package/dist/cli-bundle/focused-chunks/chunk-NXRTQ7HI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JDOMQ7VQ.js → chunk-TJ7EMJ46.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-UZE7XUZK.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DKPLYW3L.js → chunk-YKBKIEAJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-VXDSU5MC.js → chunk-ZOSEELYJ.js} +2 -2
- package/dist/cli-bundle/main.js +12 -12
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +41 -41
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +32 -32
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +5 -5
- package/dist/core/output/mutation-projection.js +26 -2
- package/dist/core/shared/constants.d.ts +1 -5
- package/dist/core/shared/constants.js +3 -81
- package/dist/core/shared/errors.d.ts +16 -0
- package/dist/core/shared/errors.js +2 -2
- package/dist/core/shared/item-metadata-contract.d.ts +14 -0
- package/dist/core/shared/item-metadata-contract.js +90 -0
- package/dist/core/store/item-store.d.ts +60 -0
- package/dist/core/store/item-store.js +26 -94
- package/dist/core/store/tracker-preflight.d.ts +7 -0
- package/dist/core/store/tracker-preflight.js +142 -0
- package/dist/sdk/agent/closed-domain-contracts.d.ts +25 -0
- package/dist/sdk/agent/closed-domain-contracts.js +140 -0
- package/dist/sdk/agent/refusal-closure.d.ts +13 -1
- package/dist/sdk/agent/refusal-closure.js +45 -3
- package/dist/sdk/agent/refusal-reachability.d.ts +26 -0
- package/dist/sdk/agent/refusal-reachability.js +26 -2
- package/dist/sdk/agent/tracker-preflight-contracts.d.ts +63 -0
- package/dist/sdk/agent/tracker-preflight-contracts.js +127 -0
- package/dist/sdk/agent-capability-contracts.js +6 -11
- package/dist/sdk/annotations.js +6 -7
- package/dist/sdk/cli-contracts/completeness.js +8 -2
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +4 -2
- package/dist/sdk/cli-contracts/enum-contracts.js +16 -6
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +11 -2
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.d.ts +19 -2
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +105 -5
- package/dist/sdk/cli-contracts/grammar-contracts.d.ts +2 -2
- package/dist/sdk/cli-contracts/grammar-contracts.js +5 -2
- package/dist/sdk/cli-contracts/runtime-contracts.js +7 -3
- package/dist/sdk/cli-contracts/tool-schema.js +7 -2
- package/dist/sdk/cli-contracts.d.ts +2 -2
- package/dist/sdk/cli-contracts.js +4 -4
- package/dist/sdk/config.d.ts +5 -0
- package/dist/sdk/config.js +5 -5
- package/dist/sdk/context-intent-runtime.js +7 -4
- package/dist/sdk/contracts.d.ts +2 -0
- package/dist/sdk/contracts.js +4 -2
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +3 -3
- package/dist/sdk/dependencies.js +5 -7
- package/dist/sdk/dependency-flag-validation.d.ts +1 -1
- package/dist/sdk/dependency-flag-validation.js +10 -4
- package/dist/sdk/environment/tracker-preflight.d.ts +6 -0
- package/dist/sdk/environment/tracker-preflight.js +10 -0
- package/dist/sdk/eval.js +5 -7
- package/dist/sdk/files.js +6 -10
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +110 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +179 -46
- package/dist/sdk/governance/assurance.d.ts +36 -2
- package/dist/sdk/governance/assurance.js +184 -10
- package/dist/sdk/governance/gc.js +5 -6
- package/dist/sdk/governance/health.js +5 -6
- package/dist/sdk/governance/reindex.js +5 -6
- package/dist/sdk/governance/validate.d.ts +1 -2
- package/dist/sdk/governance/validate.js +6 -12
- package/dist/sdk/graph/governance.d.ts +7 -5
- package/dist/sdk/graph/governance.js +32 -16
- package/dist/sdk/graph/run.js +5 -7
- package/dist/sdk/graph/traversal.js +14 -5
- package/dist/sdk/history-compact.js +6 -9
- package/dist/sdk/history-read.js +5 -7
- package/dist/sdk/history-redact.js +5 -6
- package/dist/sdk/history-repair.js +6 -9
- package/dist/sdk/improvement-ledger.js +7 -10
- package/dist/sdk/index.d.ts +7 -3
- package/dist/sdk/index.js +8 -4
- package/dist/sdk/init-agent-guidance.d.ts +5 -3
- package/dist/sdk/init-agent-guidance.js +69 -9
- package/dist/sdk/lifecycle/append.d.ts +0 -5
- package/dist/sdk/lifecycle/append.js +5 -6
- package/dist/sdk/lifecycle/claim.d.ts +0 -5
- package/dist/sdk/lifecycle/claim.js +6 -9
- package/dist/sdk/lifecycle/close-many.d.ts +0 -5
- package/dist/sdk/lifecycle/close-many.js +5 -6
- package/dist/sdk/lifecycle/close.d.ts +0 -5
- package/dist/sdk/lifecycle/close.js +5 -6
- package/dist/sdk/lifecycle/copy.d.ts +0 -5
- package/dist/sdk/lifecycle/copy.js +5 -6
- package/dist/sdk/lifecycle/create.d.ts +0 -5
- package/dist/sdk/lifecycle/create.js +5 -9
- package/dist/sdk/lifecycle/delete.js +5 -6
- package/dist/sdk/lifecycle/focus.d.ts +0 -5
- package/dist/sdk/lifecycle/focus.js +5 -6
- package/dist/sdk/lifecycle/mcp-actions.d.ts +18 -0
- package/dist/sdk/lifecycle/mcp-actions.js +52 -0
- package/dist/sdk/lifecycle/plan.d.ts +0 -5
- package/dist/sdk/lifecycle/plan.js +5 -6
- package/dist/sdk/lifecycle/reopen.d.ts +44 -0
- package/dist/sdk/lifecycle/reopen.js +69 -0
- package/dist/sdk/lifecycle/restore.js +5 -6
- package/dist/sdk/lifecycle/update-many.d.ts +0 -5
- package/dist/sdk/lifecycle/update-many.js +5 -6
- package/dist/sdk/lifecycle/update.d.ts +31 -5
- package/dist/sdk/lifecycle/update.js +140 -19
- package/dist/sdk/linked-artifacts.js +6 -7
- package/dist/sdk/merge/install.js +5 -6
- package/dist/sdk/mutation-events.js +5 -7
- package/dist/sdk/package-import-adapters.js +6 -8
- package/dist/sdk/profile.js +6 -7
- package/dist/sdk/query/activity.js +5 -6
- package/dist/sdk/query/calendar.js +5 -6
- package/dist/sdk/query/get.d.ts +1 -6
- package/dist/sdk/query/get.js +20 -55
- package/dist/sdk/query/history.d.ts +0 -5
- package/dist/sdk/query/history.js +5 -6
- package/dist/sdk/query/list.d.ts +7 -21
- package/dist/sdk/query/list.js +38 -54
- package/dist/sdk/query/projection-contracts.d.ts +33 -0
- package/dist/sdk/query/projection-contracts.js +185 -0
- package/dist/sdk/query/search-contracts.d.ts +2 -1
- package/dist/sdk/query/search-contracts.js +18 -87
- package/dist/sdk/query/search.d.ts +15 -0
- package/dist/sdk/query/search.js +34 -10
- package/dist/sdk/relationship-kinds/contract.d.ts +8 -0
- package/dist/sdk/relationship-kinds/contract.js +13 -13
- package/dist/sdk/relationships.d.ts +1 -1
- package/dist/sdk/relationships.js +20 -2
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +3 -3
- package/dist/sdk/runtime.d.ts +6 -0
- package/dist/sdk/runtime.js +18 -14
- package/dist/sdk/schema-migration.js +6 -7
- package/dist/sdk/schema.js +5 -6
- package/dist/sdk/similarity.d.ts +13 -0
- package/dist/sdk/similarity.js +32 -6
- package/dist/sdk/stats.js +5 -8
- package/dist/sdk/templates.js +5 -6
- package/dist/sdk/test/batch.js +5 -7
- package/dist/sdk/test/execution.js +4 -5
- package/dist/sdk/test/runs.js +5 -7
- package/docs/AGENT_UX_CONTRACTS.md +8 -1
- package/docs/COMMANDS.md +13 -1
- package/docs/DEPENDENCY_KIND_CONTRACT.md +12 -1
- package/docs/README.md +1 -0
- package/docs/RECURRENCE_RECOVERY_CONTRACTS.md +151 -0
- package/docs/RELATIONSHIP_GRAPH.md +92 -10
- package/docs/SDK.md +10 -2
- package/docs/SDK_CONTEXT_INTEGRITY.md +45 -0
- package/docs/SDK_PRIMITIVE_INVENTORY.md +15 -1
- package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -1
- package/docs/performance/sdk-entrypoint-import-costs.md +14 -21
- package/marketplace.json +2 -2
- package/package.json +5 -5
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/sdk/public-surface.json +640 -44
- package/dist/cli-bundle/chunks/chunk-4THEB6PD.js +0 -13
- package/dist/cli-bundle/chunks/chunk-GWMXAQOD.js +0 -197
- package/dist/cli-bundle/chunks/chunk-HVFQTLYM.js +0 -35
- package/dist/cli-bundle/chunks/chunk-OI4XI562.js +0 -5
- package/dist/cli-bundle/chunks/chunk-OIOKV6NO.js +0 -2092
- package/dist/cli-bundle/chunks/chunk-SARFF5H5.js +0 -3
- package/dist/cli-bundle/chunks/chunk-YBMRWW4E.js +0 -77
- package/dist/cli-bundle/chunks/register-list-query-Y56KINDU.js +0 -11
- package/dist/cli-bundle/focused-chunks/chunk-34QBIYZI.js +0 -155
- package/dist/cli-bundle/focused-chunks/chunk-BJRYFVSH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-EF6ZS5GH.js +0 -50
- package/dist/cli-bundle/focused-chunks/chunk-L623ZPNK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PRHY2IMX.js +0 -18
- package/dist/cli-bundle/focused-chunks/chunk-RZU5U6Q7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-YBMGXBFV.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-YLVBJ6GF.js +0 -2
package/dist/cli-bundle/main.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as q,d as No,e as P,f as Fo,g as E,h as Mo,m as Ye,n as Lo,o as Do,q as Uo,r as Y,s as Pt,t as Nt,u as Ft,v as Mt,w as jo,x as Lt,z as qo}from"./chunks/chunk-
|
|
2
|
+
import{c as q,d as No,e as P,f as Fo,g as E,h as Mo,m as Ye,n as Lo,o as Do,q as Uo,r as Y,s as Pt,t as Nt,u as Ft,v as Mt,w as jo,x as Lt,z as qo}from"./chunks/chunk-3AFAUHUE.js";import{A as Eo,eb as Po,f as ko}from"./chunks/chunk-BKYB45NQ.js";import"./chunks/chunk-JSLOFXGA.js";import"./chunks/chunk-7VHZS727.js";import{$b as $o,Bc as Ve,Cb as Io,Ec as Ke}from"./chunks/chunk-OCLPLFAY.js";import{Da as Oo,ma as To}from"./chunks/chunk-N3DSV4CH.js";import{Ab as Ro}from"./chunks/chunk-S4IRYKBU.js";import"./chunks/chunk-WYRZZ5ZE.js";import{$ as Dn,Ac as ne,Af as so,Ah as po,Bc as fe,Bh as oe,C as g,Cf as co,Ch as R,Ci as go,D as yt,Dh as uo,Di as Et,Dm as Ao,E as C,Ec as no,Ei as St,Fc as Le,Fi as At,G as me,Gi as ge,Hi as Tt,Ib as Gn,Ii as ho,Je as io,Ji as he,K as wt,Ka as bt,Lc as vt,Mc as De,Mi as yo,Na as V,Nc as oo,Ni as wo,Oc as ro,Pa as zn,Pb as Wn,Pd as ao,Pl as Co,Qa as Fe,Ql as We,Rb as Bn,Se as qe,Ta as xt,Tf as lo,Ua as Hn,Uf as mo,Uh as ze,Va as k,Vh as fo,Vj as He,Wf as kt,Xd as Ue,Xf as y,Xj as we,Ya as j,Yj as Ge,_ as Ln,_i as ye,aa as _t,bj as _o,c as U,dc as Vn,de as O,dm as Be,ec as pe,ed as Ct,ee as je,ej as bo,em as Rt,fm as It,gc as ue,gm as _e,ha as Un,hc as Kn,hm as I,ia as jn,im as So,jj as Ot,jm as $t,ka as qn,kj as xo,lj as vo,pm as F,qc as Yn,rc as Jn,sc as Xn,tc as Qn,uc as B,vc as Zn,wc as eo,xc as K,yc as to,zc as Me}from"./chunks/chunk-2MA6ZQVZ.js";import{Command as En}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]="8eca3029-0d1f-569a-84ce-5ccd0b92a272")}catch{}})();var ri=new Set(["__proto__","prototype","constructor"]),zo=Symbol("looseOptionOccurrences");function be(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,o)=>o.toUpperCase())}function ai(e,t,n){let o=e[t];if(o===void 0){e[t]=n;return}if(Array.isArray(o)){o.push(n),e[t]=o;return}e[t]=[o,n]}function Dt(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let i=n.indexOf("=");if(i>=0)return{consumed:1,key:n.slice(1,i).trim(),value:n.slice(i+1)};let s=n.slice(1).trim(),c=e[t+1];return typeof c=="string"&&!c.startsWith("-")?{consumed:2,key:s,value:c}:{consumed:1,key:s,value:!0}}let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(2,o).trim(),value:n.slice(o+1)};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let r=n.slice(2).trim(),a=e[t+1];return typeof a=="string"&&!a.startsWith("-")?{consumed:2,key:r,value:a}:{consumed:1,key:r,value:!0}}function Je(e){return ri.has(e)}function Ho(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return Ln(t)}function xe(e){let t=[],n=typeof e.long=="string"?e.long.trim():"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let r=be(n.slice(2));r.length>0&&!Je(r)&&t.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){let r=be(o.slice(1));r.length>0&&!Je(r)&&t.push(r)}return[...new Set(t)]}function Go(e){let t=new Set;for(let n of e)for(let o of xe(n))t.add(o);return t}function ii(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")){let n=be(t.slice(2));if(n.length>0&&!Je(n))return n}return xe(e)[0]??null}function si(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")&&t.length>2)return t;let n=typeof e.short=="string"?e.short.trim():"";return n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function Ut(e,t,n){if(t.length===0)return;let o=new Set,r=new Map,a=[],i=[];for(let s of t){let c=xe(s),l=si(s);l!==null&&i.push(l);for(let d of c)o.add(d),s.enabled===!1&&r.set(d,l);s.required===!0&&s.enabled!==!1&&c.length>0&&a.push({keys:c,label:l})}for(let s of Object.keys(e)){if(!o.has(s)){let l=i.length>0?` Expected one of: ${[...new Set(i)].join(", ")}.`:"";throw new C(`Unknown option '--${s}' for extension command '${n}'.${l}`,g.USAGE)}let c=r.get(s);if(c)throw new C(`Option '${c}' is disabled for extension command '${n}'.`,g.USAGE)}for(let s of a)if(!s.keys.some(c=>Object.hasOwn(e,c)))throw new C(`Missing required option '${s.label}' for extension command '${n}'.`,g.USAGE)}function ci(e){return typeof e=="string"||e==null?e:String(e)}function li(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);return Number.isFinite(t)?t:e}return e}function di(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return e}var mi={string:ci,number:li,boolean:di};function Xe(e,t){return Array.isArray(e)?e.map(n=>Xe(n,t)):mi[t](e)}function Wo(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):Dn(e);return t?o.map(r=>Xe(r,t)):o}function pi(e,t,n,o){return n?Wo(e,t,o):t?Xe(e,t):e}function ui(e,t,n){let o=e[zo];if(!o||o.length===0)return n;let r=new Set(t);return o.filter(a=>r.has(a.key)).map(a=>a.value)}function Bo(e,t,n=e){if(t.length===0)return e;let o=Object.create(null);for(let[r,a]of Object.entries(e))o[r]=a;for(let r of t){let a=ii(r);if(!a)continue;let i=r.list===!0,s=xe(r);for(let d of s)if(!(d===a||!Object.hasOwn(o,d))){if(Object.hasOwn(o,a)){if(!i){delete o[d];continue}let m=o[a],p=o[d];o[a]=[...Array.isArray(m)?m:[m],...Array.isArray(p)?p:[p]].filter(u=>u!=null),delete o[d];continue}o[a]=o[d],delete o[d]}let c=Ho(r),l=r.repeatable===!0;if(!Object.hasOwn(o,a)){r.default!==void 0&&(o[a]=pi(r.default,c,i,l));continue}if(i){o[a]=Wo(ui(n,s,o[a]),c,l);continue}c&&(o[a]=Xe(o[a],c))}return o}function Vo(e){let t=Object.create(null),n=[];Object.defineProperty(t,zo,{value:n});let o=0;for(;o<e.length;){let r=Dt(e,o);if(!r){o+=1;continue}let a=be(r.key);if(a.length===0||Je(a)){o+=r.consumed;continue}ai(t,a,r.value),n.push({...r,key:a}),o+=r.consumed}return t}function Ko(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=Dt(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function jt(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let i of t){let s=Ho(i);for(let c of xe(i))n.add(c),s==="boolean"&&o.add(c)}if(n.size===0)return[...e];let r=[],a=0;for(;a<e.length;){if(e[a]==="--"){r.push(...e.slice(a+1));break}let i=Dt(e,a);if(i){let s=be(i.key);if(n.has(s)){let c=e[a],l=o.has(s)&&!c.includes("=")?1:i.consumed;a+=l;continue}}r.push(e[a]),a+=1}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0186e30-9c25-5539-b778-1ef2ee21764a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cf83881-9464-5c18-b196-ee669057a873")}catch{}})();function Yo(e){return e.length>0?[e[0]]:[]}function fi(e){let t=["","Intent:",` ${e.why}`],n=Yo(e.examples);return n.length>0&&(t.push("","Example:"),t.push(` ${n[0]}`)),t.push("","Need deeper rationale and more examples?"),t.push(" Re-run with --explain."),t.join(`
|
|
3
3
|
`)}function gi(e){let t=["","Why use this command:",` ${e.why}`,"","Examples:",...e.examples.map(n=>` ${n}`)];return e.tips&&e.tips.length>0&&(t.push("","Tips:"),t.push(...e.tips.map(n=>` - ${n}`))),t.join(`
|
|
4
|
-
`)}function Jo(e,t){return t==="detailed"?gi(e):fi(e)}function $(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var hi={cal:"calendar",ctx:"context"};function yi(e,t){return e.commands.find(n=>n.name()===t)??null}function wi(e,t){let n=e;for(let o of t){let r=yi(n,o);if(!r)return null;n=r}return n}function qt(e,t,n,o){let r=wi(e,t.split(" ").filter(a=>a.length>0));r&&r.addHelpText("after",Jo(n,o))}function Ht(e){return e.includes("--explain")?"detailed":"compact"}var Xo={init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm install ./my-package --project","pm install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm extension catalog --project","pm extension catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list-all --limit 50","pm list-all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-in-progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list-blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' in one read: the single highest-priority ready item with rationale, plus the ranked ready and blocked queues (project management = context management).",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "All acceptance criteria met" --message "Close after verification"','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:['pm claim pm-a1b2 --message "Claim for implementation"','pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:['pm release pm-a1b2 --message "Release after closure"']},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}},zt={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]};function _i(e){let t=$(e??"");return t?hi[t]??t:""}function xi(e){let t=_i(e);return t?Xo[t]??zt:zt}function Qo(e,t){let n=xi(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Yo(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Zo(e,t=process.argv.slice(2)){let n=Ht(t);e.addHelpText("after",Jo(zt,n));for(let[i,s]of Object.entries(Xo))qt(e,i,s,n);let o=$(P(t).commandPathTokens.join(" ")),r=we(o);if(r){qt(e,r.parent,{why:r.description,examples:[r.example],tips:[`Action path: pm ${r.command}`,Ge(r.accepted_flags)]},n);return}let a=He.filter(({parent:i})=>i===o);a.length>0&&qt(e,o,{why:`Dispatches one declared positional action: ${a.map(({action:i})=>i).join("|")}.`,examples:a.map(({example:i})=>i),tips:[`Inspect one action directly with pm ${o} <action> --help --json.`]},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]="1944833a-5d9b-514d-99d0-50cdad5db8f4")}catch{}})();async function er(e,t){await bo(e,{ok:t.ok,error:t.error,result:fe(),exit_code:t.exit_code,error_code:t.error_code,error_category:t.error_category,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage})}async function tr(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t=await R(e.pmRoot);await Ro({pmRoot:e.pmRoot,author:Ue(e.author,t.author_default),itemIds:e.itemIds,intent:e.intent})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b6eea75-9da4-5cc1-9e26-dde9fcb863d1")}catch{}})();function M(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function J(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return M(t)}function X(e){let t=new Set,n=[];for(let o of e){let r=J(o);r&&(t.has(r)||n.push(r),t.add(r))}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]="367d9302-9e1e-5813-a913-e4e87f34d8b9")}catch{}})();function et(e){let{required:t,why:n,title:o,...r}=e;return r}var bi=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function ir(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!bi.has(e.code)}function sr(e){return`urn:pm-cli:error:${e}`}function b(e){return{...e,type:sr(e.code)}}var re={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},nr={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},or={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},Qe={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},vi={guide:re,shell:re,completion:re,"completion-statuses":re,"completion-tags":re,"completion-types":re,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:nr,cal:nr,reindex:or,"search-advanced":or,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":Qe,"dedupe-audit":Qe,"dedupe-merge":Qe,normalize:Qe};function Ci(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return vi[t]}function Gt(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function ki(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function Ei(e){if(!Array.isArray(e))return;let t=e.map(n=>({source:typeof n?.source=="string"?n.source.trim():"",command:typeof n?.command=="string"?n.command.trim():"",reason:typeof n?.reason=="string"?n.reason.trim():""})).filter(n=>n.source.length>0&&n.command.length>0&&n.reason.length>0);return t.length>0?t:void 0}function Wt(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function z(e,t,n){if(t==="parsed_positionals"){if(!Array.isArray(n))return;let r=n.map(a=>({role:typeof a?.role=="string"?a.role.trim():"",value:typeof a?.value=="string"?a.value.trim():""})).filter(a=>a.role.length>0&&a.value.length>0);r.length>0&&(e.parsed_positionals=r);return}let o=ki(n);o&&(e[t]=o)}function tt(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Wt(t,"attempted_command",e.attempted_command),z(t,"normalized_args",e.normalized_args),z(t,"parsed_positionals",e.parsed_positionals),z(t,"provided_fields",e.provided_fields),z(t,"missing",e.missing),z(t,"missing_required_fields",e.missing_required_fields),z(t,"suggested_flags",e.suggested_flags),z(t,"allowed_values",e.allowed_values),z(t,"candidate_commands",e.candidate_commands),typeof e.candidate_commands_total=="number"&&Number.isSafeInteger(e.candidate_commands_total)&&e.candidate_commands_total>=0&&(t.candidate_commands_total=e.candidate_commands_total),e.candidate_commands_truncated===!0&&(t.candidate_commands_truncated=!0),(e.option_scope==="declared_on_path"||e.option_scope==="declared_elsewhere"||e.option_scope==="declared_nowhere")&&(t.option_scope=e.option_scope),Wt(t,"suggested_retry",e.suggested_retry),z(t,"suggested_retry_args",e.suggested_retry_args),typeof e.retry_after_ms=="number"&&Number.isSafeInteger(e.retry_after_ms)&&e.retry_after_ms>=0&&(t.retry_after_ms=e.retry_after_ms);let n=Ei(e.fallback_candidates);return n&&(t.fallback_candidates=n),Wt(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Bt(e,t,n){n&&e.push(` ${t}: ${n}`)}function Q(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function Si(e){let t=tt(e);if(!t)return[];let n=["Recovery bundle:"];if(Bt(n,"attempted_command",t.attempted_command),Q(n,"normalized_args",t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){n.push(" parsed_positionals:");for(let o of t.parsed_positionals)n.push(` - ${o.role}: ${o.value}`)}if(Q(n,"provided_fields",t.provided_fields,", "),Q(n,"missing",t.missing,", "),Q(n,"missing_required_fields",t.missing_required_fields,", "),Q(n,"suggested_flags",t.suggested_flags,", "),Q(n,"allowed_values",t.allowed_values,", "),Q(n,"candidate_commands",t.candidate_commands,", "),typeof t.candidate_commands_total=="number"&&n.push(` candidate_commands_total: ${String(t.candidate_commands_total)}`),t.candidate_commands_truncated===!0&&n.push(" candidate_commands_truncated: true"),t.option_scope!==void 0&&n.push(` option_scope: ${t.option_scope}`),Bt(n,"suggested_retry",t.suggested_retry),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),Bt(n,"next_best_command",t.next_best_command),t.fallback_candidates&&t.fallback_candidates.length>0){n.push(" fallback_candidates:");for(let o of t.fallback_candidates)n.push(` - ${o.source}: ${o.command} (${o.reason})`)}return n}function cr(e){let t=[`Error: ${e.title}`,"","What happened:",` ${e.happened}`,"","What is required:",` ${e.required}`];e.why&&(t.push("","Why:"),t.push(` ${e.why}`)),e.examples&&e.examples.length>0&&(t.push(""),t.push(...Gt("Examples:",e.examples))),e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...Gt("Next steps:",e.nextSteps))),e.verificationErrors&&e.verificationErrors.length>0&&(t.push(""),t.push(...Gt("Verification errors:",e.verificationErrors)));let n=Si(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
|
|
5
|
-
`)}function Kt(e,t){let n={type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t};return ir(e)&&(n.why=e.why),e.examples&&e.examples.length>0&&(n.examples=e.examples),e.nextSteps&&e.nextSteps.length>0&&(n.next_steps=e.nextSteps),e.verificationErrors&&e.verificationErrors.length>0&&(n.verification_errors=e.verificationErrors),e.recovery&&(n.recovery=e.recovery),n}function Yt(e){let t={type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required};return ir(e)&&(t.why=e.why),e.examples&&e.examples.length>0&&(t.examples=e.examples),e.nextSteps&&e.nextSteps.length>0&&(t.next_steps=e.nextSteps),e.verificationErrors&&e.verificationErrors.length>0&&(t.verification_errors=e.verificationErrors),e.recovery&&(t.recovery=e.recovery),t}function nt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Ai(e){let t=e.toLowerCase();return t.includes("cannot find module")||t.includes("cannot find package")||t.includes("err_module_not_found")||t.includes("module_not_found")}function Z(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function rr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Ti(e){return Do(e?.normalized_args)}function Oi(e){let t=e.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);return t?t[1].split(/[|,]/).map(n=>n.trim()).filter(n=>/^[A-Za-z0-9_.-]+$/.test(n)):[]}function Ri(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let a of o){let i=n.findIndex(s=>s===a);if(i>=0&&i<n.length-1&&!n[i+1]?.startsWith("-")){let s=[...n];return s[i+1]=r,O(s)}}}function Ii(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function Ze(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function H(e,t,n){if(!n)return e;let o=nt(t),r=Ze(n.code,e.code),a=Ze(n.type,sr(r)),i=Z(n.examples)??e.examples,s=Z(n.nextSteps)??e.nextSteps,c=Z(n.verification_errors)??e.verificationErrors,l=e.code==="command_failed"&&n.code?Ii(o):void 0,d=tt(n.recovery)??e.recovery;return{...e,code:r,type:a,title:l??e.title,happened:o.length>0?o:e.happened,required:Ze(n.required,e.required),why:Ze(n.why,e.why),examples:i,nextSteps:s,verificationErrors:c,recovery:d}}function $i(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. Run pm init first\.$/);if(!o)return null;let r=o[1],a=Hn(process.cwd(),r);return H(b(a?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${a}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${a} <command>`,`PM_PATH=${a} pm <command>`],nextSteps:[`Re-run with "--pm-path ${a}" or export PM_PATH=${a}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function Pi(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],a=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),i=a?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return H(b({code:"item_not_found",title:"Item ID not found",happened:i,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:a?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function Ni(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:H(b({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function Fi(e,t,n){return t.includes("is locked")?H(b({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function Mi(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let a=!!r,i=a?null:t.replace(/^Missing required option\s+/,"").trim(),s=i??"",c=i?`Pass ${i} with a valid value before running the command.`:"Provide the required option for this command invocation.";return H(b({code:"missing_required_option",title:a?"Missing required options":`Missing required option ${s}`,happened:t,required:a?"Provide every required option for this command invocation.":c,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,n)}function Li(e,t,n){return t.startsWith("No update flags provided")?H(b({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function Di(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=tt(n?.recovery),r=Ti(o),a=r?`pm ${r} --help`:"pm <command> --help",i=Oi(t),s=Ri(o,i),c=s?[s,a]:[a,"pm contracts --command <command> --flags-only --json"],l=i.length>0?[`Allowed values: ${i.join("|")}`,`Run "${a}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return H(b({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:c,nextSteps:l}),e,n)}function Jt(e,t){let n=nt(e),o=$i(e,n,t)??Pi(e,n,t)??Ni(e,n,t)??Fi(e,n,t)??Mi(e,n,t)??Li(e,n,t)??Di(e,n,t);return o||H(b({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function Ui(e,t,n){return e==="create"&&t.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${n.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:e==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${e??"<command>"} --help`]}function ji(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function qi(e){if(!(!Array.isArray(e)||e.length===0))return O(e)}function Xt(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function L(e,t={}){let n=Xt(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:qi(o),a=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return tt({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:a,...t})}function Vt(e,t){return!t||e.includes(t)?e:[...e,t]}var zi=new Set(["--add","--add-json","--remove"]),Hi=new Set(["command","cmd","path"]);function Gi(e){if(Array.isArray(e))for(let t of e){if(!t.startsWith("--"))continue;let n=t.indexOf("="),o=n>=0?t.slice(0,n):t;if(zi.has(o))return o}}function Wi(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let r=e[o];if(r!=="--add"&&r!=="--remove")continue;let a=e[o+1];if(typeof a!="string"||!Hi.has(a))return;let i=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;i.push(d)}if(i.length<2)return;let s=`${a}=${i.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+i.length)];return O(c)}}function Bi(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let a=ji(r[1]),i=a.startsWith("--type"),s=o?.suggestedRetryCommand,c=Xt(o?.providedOptionFlags),l=[a],d=Ui(t,a,n),m=s?Vt(d,s):d,p=i?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Vt(p,`Replay with preserved arguments: ${s}`):p,f=c&&c.length>0?Vt(u,`Already provided options: ${c.join(", ")}`):u;return b({code:"missing_required_option",title:`Missing required option ${a}`,happened:`Commander rejected the command because ${a} was not provided.`,required:`Pass ${a} with a valid value before running the command.`,why:i?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:f,recovery:L(o,{missing:l})})}function Vi(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return b({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:L(n,{missing:[r]})})}function Ki(e,t,n){return b({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:L(t,{suggested_flags:n})})}var Yi={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function Ji(e){let t=Z(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function Xi(e,t,n,o,r){let a=o.otherCommands.slice(0,3),i=o.candidateTotal-a.length,s=i>0?` and ${String(i)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,a.length?`${e} is accepted by ${a.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,r?`Replay with suggested correction: ${r}`:void 0].filter(c=>typeof c=="string")}function Qi(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=n??{},a=o[1],i=Xt(r.unknownOptionSuggestions)??[],s=r.suggestedRetryCommand;if(t==="update"&&(a==="--file"||a==="--doc"))return Ki(a,n,i);let c=Ji(r),l=Xi(a,t,i,c,s),d=[s,`pm ${t??"<command>"} --help`].filter(m=>typeof m=="string");return b({code:"unknown_option",title:`Unknown option ${a}`,happened:`Commander does not recognize option ${a} for this command path.`,required:Yi[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",examples:d,nextSteps:l,recovery:L(n,{suggested_flags:i.length>0?i:void 0,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function Zi(e,t,n,o,r){let a=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,i=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return b({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:rr([t.installCommand,...n]),nextSteps:rr([a,...i]),recovery:L(r)})}function es(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=Z(t?.unknownCommandExamples),a=Z(t?.unknownCommandNextSteps),i=Ci(o),s=r??["pm --help"],c=a??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=i?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return i&&(!d||!l.has(d))?Zi(o,i,s,c,t):b({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:c,recovery:L(t)})}function ts(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=Z(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let r=e?.suggestedRetryCommand;return b({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...r?[r]:[],`pm ${t} --help`],nextSteps:r?[`Retry with the declared hyphenated action: ${r}`]:["Choose one value from recovery.allowed_values."],recovery:L(e,{allowed_values:o,suggested_retry:r})})}function ns(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=Gi(o);if(!r)return null;let a=Wi(o);return b({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...a?[a]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...a?[`Replay with the value re-joined into one argument: ${a}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:L(n,a?{suggested_retry:a}:{})})}var os=new Set(["comments","docs","files","learnings","notes","test"]);function rs(e,t,n){if(!/too many arguments/i.test(e)||!os.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>l===t),a=o[r+1],i=o[r+2],s=n?.verifiedCollectionItemId?.trim();if(a?.toLowerCase()!=="add"||!i||i.startsWith("-")||!s||s.toLowerCase()!==i.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return b({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[c,`pm ${t} --help`],recovery:L(n,{parsed_positionals:[{role:"transposed_subcommand",value:a},{role:"item_id",value:s}],suggested_retry:c})})}var as=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]),ar=new Set(["context","ctx"]);function is(e,t,n){if(!/too many arguments/i.test(e)||!ar.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>ar.has(l)),a=r===-1?1:r+1,i=e.match(/got \d+:\s*(\S+)/i),s=i?i[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(a)){if(l){l=!1;continue}let m=d.split("=")[0];if(as.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return b({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${c} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[c,`pm context --parent ${s}`],recovery:L(n,{suggested_retry:c})})}function Qt(e,t,n,o){let r=nt(e),a=Bi(r,t,n,o)??Vi(r,t,o)??Qi(r,t,o)??es(r,o)??ts(o)??rs(r,t,o)??ns(r,t,o)??is(r,t,o);return a||b({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:L(o)})}function lr(e,t){return cr(Jt(e,t))}function dr(e,t){return Yt(Jt(e,t))}function Zt(e,t,n){return Kt(Jt(e,n),t)}function mr(e,t,n,o){return cr(Qt(e,t,n,o))}function en(e,t,n,o){return Yt(Qt(e,t,n,o))}function ot(e,t,n,o,r){return Kt(Qt(e,t,n,r),o)}function pr(e,t){let n=ur(e);return Kt(n,t)}function ur(e){let t=nt(e);return Ai(t)?b({code:"module_import_failed",title:"Module import failed",happened:t,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):b({code:"unknown_error",title:"Unhandled error",happened:t,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function fr(e){return Yt(ur(e))}import{Option as ss}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]="45f3bebb-c075-5573-97bc-b573ae4d2d76")}catch{}})();function _(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function hr(e,t){let n=new Map;for(let o of e){let r=_(o.command);for(let a of t){if(a.layer!==o.layer||a.name!==o.name)continue;let i=_(a.command),s=i.split(" "),c=s.at(-1),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&r===d){n.set(r,i);break}}}return n}function tn(e,t,n,o){if(!t||!n)return;let r,a=0;for(let[s,c]of e.entries()){if(c!==t)continue;let l=e.slice(s);for(let[d,m]of o.entries()){let p=d.split(" ");p.length>a&&p.every((u,f)=>l[f]===u)&&(r=m,a=p.length)}}let i=r?.flags.find(s=>s.long===n||s.short===n);if(i)return rt(i).takesValue}function A(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function G(e){return typeof e=="boolean"?e:void 0}function rt(e){let t=A(e.value_type)??A(e.type),n=A(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||G(e.required)===!0||G(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function cs(e){if(G(e.visible)===!1)return null;let n=A(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=A(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",a=A(e.value_name),i=a?` <${a}>`:"",s=A(e.description)??"Extension-provided option.",c=[];G(e.required)===!0&&c.push("required"),G(e.enabled)===!1&&c.push("disabled");let l=c.length>0?` [${c.join(", ")}]`:"";return`${r}${n}${i} ${s}${l}`}function yr(e){let t=[...new Set(e.map(cs).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
|
|
4
|
+
`)}function Jo(e,t){return t==="detailed"?gi(e):fi(e)}function $(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var hi={cal:"calendar",ctx:"context"};function yi(e,t){return e.commands.find(n=>n.name()===t)??null}function wi(e,t){let n=e;for(let o of t){let r=yi(n,o);if(!r)return null;n=r}return n}function qt(e,t,n,o){let r=wi(e,t.split(" ").filter(a=>a.length>0));r&&r.addHelpText("after",Jo(n,o))}function Ht(e){return e.includes("--explain")?"detailed":"compact"}var Xo={init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm install ./my-package --project","pm install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm extension catalog --project","pm extension catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list-all --limit 50","pm list-all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-in-progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list-blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' in one read: the single highest-priority ready item with rationale, plus the ranked ready and blocked queues (project management = context management).",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "All acceptance criteria met" --message "Close after verification"','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:['pm claim pm-a1b2 --message "Claim for implementation"','pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:['pm release pm-a1b2 --message "Release after closure"']},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}},zt={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]};function _i(e){let t=$(e??"");return t?hi[t]??t:""}function bi(e){let t=_i(e);return t?Xo[t]??zt:zt}function Qo(e,t){let n=bi(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Yo(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Zo(e,t=process.argv.slice(2)){let n=Ht(t);e.addHelpText("after",Jo(zt,n));for(let[i,s]of Object.entries(Xo))qt(e,i,s,n);let o=$(P(t).commandPathTokens.join(" ")),r=we(o);if(r){qt(e,r.parent,{why:r.description,examples:[r.example],tips:[`Action path: pm ${r.command}`,Ge(r.accepted_flags)]},n);return}let a=He.filter(({parent:i})=>i===o);a.length>0&&qt(e,o,{why:`Dispatches one declared positional action: ${a.map(({action:i})=>i).join("|")}.`,examples:a.map(({example:i})=>i),tips:[`Inspect one action directly with pm ${o} <action> --help --json.`]},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]="1944833a-5d9b-514d-99d0-50cdad5db8f4")}catch{}})();async function er(e,t){await xo(e,{ok:t.ok,error:t.error,result:fe(),exit_code:t.exit_code,error_code:t.error_code,error_category:t.error_category,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage})}async function tr(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t=await R(e.pmRoot);await Ro({pmRoot:e.pmRoot,author:Ue(e.author,t.author_default),itemIds:e.itemIds,intent:e.intent})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b6eea75-9da4-5cc1-9e26-dde9fcb863d1")}catch{}})();function M(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function J(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return M(t)}function X(e){let t=new Set,n=[];for(let o of e){let r=J(o);r&&(t.has(r)||n.push(r),t.add(r))}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]="d90c153b-bb1d-57b1-81fd-e0ea7347c520")}catch{}})();function et(e){let{required:t,why:n,title:o,...r}=e;return r}var xi=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function vi(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!xi.has(e.code)}function ir(e){return`urn:pm-cli:error:${e}`}function x(e){return{...e,type:ir(e.code)}}var re={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},nr={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},or={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},Qe={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Ci={guide:re,shell:re,completion:re,"completion-statuses":re,"completion-tags":re,"completion-types":re,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:nr,cal:nr,reindex:or,"search-advanced":or,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":Qe,"dedupe-audit":Qe,"dedupe-merge":Qe,normalize:Qe};function ki(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Ci[t]}function Gt(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Ei(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function Si(e){if(!Array.isArray(e))return;let t=e.map(n=>({source:typeof n?.source=="string"?n.source.trim():"",command:typeof n?.command=="string"?n.command.trim():"",reason:typeof n?.reason=="string"?n.reason.trim():""})).filter(n=>n.source.length>0&&n.command.length>0&&n.reason.length>0);return t.length>0?t:void 0}function Wt(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function z(e,t,n){if(t==="parsed_positionals"){if(!Array.isArray(n))return;let r=n.map(a=>({role:typeof a?.role=="string"?a.role.trim():"",value:typeof a?.value=="string"?a.value.trim():""})).filter(a=>a.role.length>0&&a.value.length>0);r.length>0&&(e.parsed_positionals=r);return}let o=Ei(n);o&&(e[t]=o)}function tt(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Wt(t,"attempted_command",e.attempted_command),z(t,"normalized_args",e.normalized_args),z(t,"parsed_positionals",e.parsed_positionals),z(t,"provided_fields",e.provided_fields),z(t,"missing",e.missing),z(t,"missing_required_fields",e.missing_required_fields),z(t,"suggested_flags",e.suggested_flags),z(t,"allowed_values",e.allowed_values),z(t,"candidate_commands",e.candidate_commands),typeof e.candidate_commands_total=="number"&&Number.isSafeInteger(e.candidate_commands_total)&&e.candidate_commands_total>=0&&(t.candidate_commands_total=e.candidate_commands_total),e.candidate_commands_truncated===!0&&(t.candidate_commands_truncated=!0),(e.option_scope==="declared_on_path"||e.option_scope==="declared_elsewhere"||e.option_scope==="declared_nowhere")&&(t.option_scope=e.option_scope),Wt(t,"suggested_retry",e.suggested_retry),z(t,"suggested_retry_args",e.suggested_retry_args),typeof e.retry_after_ms=="number"&&Number.isSafeInteger(e.retry_after_ms)&&e.retry_after_ms>=0&&(t.retry_after_ms=e.retry_after_ms);let n=Si(e.fallback_candidates);return n&&(t.fallback_candidates=n),Wt(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Bt(e,t,n){n&&e.push(` ${t}: ${n}`)}function Q(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function Ai(e){let t=tt(e);if(!t)return[];let n=["Recovery bundle:"];if(Bt(n,"attempted_command",t.attempted_command),Q(n,"normalized_args",t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){n.push(" parsed_positionals:");for(let o of t.parsed_positionals)n.push(` - ${o.role}: ${o.value}`)}if(Q(n,"provided_fields",t.provided_fields,", "),Q(n,"missing",t.missing,", "),Q(n,"missing_required_fields",t.missing_required_fields,", "),Q(n,"suggested_flags",t.suggested_flags,", "),Q(n,"allowed_values",t.allowed_values,", "),Q(n,"candidate_commands",t.candidate_commands,", "),typeof t.candidate_commands_total=="number"&&n.push(` candidate_commands_total: ${String(t.candidate_commands_total)}`),t.candidate_commands_truncated===!0&&n.push(" candidate_commands_truncated: true"),t.option_scope!==void 0&&n.push(` option_scope: ${t.option_scope}`),Bt(n,"suggested_retry",t.suggested_retry),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),Bt(n,"next_best_command",t.next_best_command),t.fallback_candidates&&t.fallback_candidates.length>0){n.push(" fallback_candidates:");for(let o of t.fallback_candidates)n.push(` - ${o.source}: ${o.command} (${o.reason})`)}return n}function sr(e){let t=[`Error: ${e.title}`,"","What happened:",` ${e.happened}`,"","What is required:",` ${e.required}`];e.why&&(t.push("","Why:"),t.push(` ${e.why}`)),e.examples&&e.examples.length>0&&(t.push(""),t.push(...Gt("Examples:",e.examples))),e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...Gt("Next steps:",e.nextSteps))),e.verificationErrors&&e.verificationErrors.length>0&&(t.push(""),t.push(...Gt("Verification errors:",e.verificationErrors)));let n=Ai(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
|
|
5
|
+
`)}function cr(e,t){return vi(t)&&(e.why=t.why),t.examples&&t.examples.length>0&&(e.examples=t.examples),t.nextSteps&&t.nextSteps.length>0&&(e.next_steps=t.nextSteps),t.verificationErrors&&t.verificationErrors.length>0&&(e.verification_errors=t.verificationErrors),t.flag!==void 0&&(e.flag=t.flag),t.value!==void 0&&(e.value=t.value),t.unmatchedSelectors!==void 0&&(e.unmatched_selectors=t.unmatchedSelectors),t.availableDependencies!==void 0&&(e.available_dependencies=t.availableDependencies),t.recovery&&(e.recovery=t.recovery),e}function Kt(e,t){return cr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t},e)}function Yt(e){return cr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required},e)}function nt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Ti(e){let t=e.toLowerCase();return t.includes("cannot find module")||t.includes("cannot find package")||t.includes("err_module_not_found")||t.includes("module_not_found")}function Z(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function rr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Oi(e){return Do(e?.normalized_args)}function Ri(e){let t=e.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);return t?t[1].split(/[|,]/).map(n=>n.trim()).filter(n=>/^[A-Za-z0-9_.-]+$/.test(n)):[]}function Ii(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let a of o){let i=n.findIndex(s=>s===a);if(i>=0&&i<n.length-1&&!n[i+1]?.startsWith("-")){let s=[...n];return s[i+1]=r,O(s)}}}function $i(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function Ze(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function H(e,t,n){if(!n)return e;let o=nt(t),r=Ze(n.code,e.code),a=Ze(n.type,ir(r)),i=Z(n.examples)??e.examples,s=Z(n.nextSteps)??e.nextSteps,c=Z(n.verification_errors)??e.verificationErrors,l=e.code==="command_failed"&&n.code?$i(o):void 0,d=tt(n.recovery)??e.recovery;return{...e,code:r,type:a,title:l??e.title,happened:o.length>0?o:e.happened,required:Ze(n.required,e.required),why:Ze(n.why,e.why),examples:i,nextSteps:s,verificationErrors:c,flag:n.flag,value:n.value,unmatchedSelectors:n.unmatched_selectors,availableDependencies:n.available_dependencies,recovery:d}}function Pi(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let r=o[1],a=Hn(process.cwd(),r);return H(x(a?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${a}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${a} <command>`,`PM_PATH=${a} pm <command>`],nextSteps:[`Re-run with "--pm-path ${a}" or export PM_PATH=${a}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function Ni(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],a=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),i=a?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return H(x({code:"item_not_found",title:"Item ID not found",happened:i,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:a?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function Fi(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:H(x({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function Mi(e,t,n){return t.includes("is locked")?H(x({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function Li(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let a=!!r,i=a?null:t.replace(/^Missing required option\s+/,"").trim(),s=i??"",c=i?`Pass ${i} with a valid value before running the command.`:"Provide the required option for this command invocation.";return H(x({code:"missing_required_option",title:a?"Missing required options":`Missing required option ${s}`,happened:t,required:a?"Provide every required option for this command invocation.":c,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,n)}function Di(e,t,n){return t.startsWith("No update flags provided")?H(x({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function Ui(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=tt(n?.recovery),r=Oi(o),a=r?`pm ${r} --help`:"pm <command> --help",i=Ri(t),s=Ii(o,i),c=s?[s,a]:[a,"pm contracts --command <command> --flags-only --json"],l=i.length>0?[`Allowed values: ${i.join("|")}`,`Run "${a}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return H(x({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:c,nextSteps:l}),e,n)}function Jt(e,t){let n=nt(e),o=Pi(e,n,t)??Ni(e,n,t)??Fi(e,n,t)??Mi(e,n,t)??Li(e,n,t)??Di(e,n,t)??Ui(e,n,t);return o||H(x({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function ji(e,t,n){return e==="create"&&t.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${n.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:e==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${e??"<command>"} --help`]}function qi(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function zi(e){if(!(!Array.isArray(e)||e.length===0))return O(e)}function Xt(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function L(e,t={}){let n=Xt(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:zi(o),a=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return tt({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:a,...t})}function Vt(e,t){return!t||e.includes(t)?e:[...e,t]}var Hi=new Set(["--add","--add-json","--remove"]),Gi=new Set(["command","cmd","path"]);function Wi(e){if(Array.isArray(e))for(let t of e){if(!t.startsWith("--"))continue;let n=t.indexOf("="),o=n>=0?t.slice(0,n):t;if(Hi.has(o))return o}}function Bi(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let r=e[o];if(r!=="--add"&&r!=="--remove")continue;let a=e[o+1];if(typeof a!="string"||!Gi.has(a))return;let i=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;i.push(d)}if(i.length<2)return;let s=`${a}=${i.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+i.length)];return O(c)}}function Vi(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let a=qi(r[1]),i=a.startsWith("--type"),s=o?.suggestedRetryCommand,c=Xt(o?.providedOptionFlags),l=[a],d=ji(t,a,n),m=s?Vt(d,s):d,p=i?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Vt(p,`Replay with preserved arguments: ${s}`):p,f=c&&c.length>0?Vt(u,`Already provided options: ${c.join(", ")}`):u;return x({code:"missing_required_option",title:`Missing required option ${a}`,happened:`Commander rejected the command because ${a} was not provided.`,required:`Pass ${a} with a valid value before running the command.`,why:i?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:f,recovery:L(o,{missing:l})})}function Ki(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return x({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:L(n,{missing:[r]})})}function Yi(e,t,n){return x({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:L(t,{suggested_flags:n})})}var Ji={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function Xi(e){let t=Z(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function Qi(e,t,n,o,r){let a=o.otherCommands.slice(0,3),i=o.candidateTotal-a.length,s=i>0?` and ${String(i)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,a.length?`${e} is accepted by ${a.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,r?`Replay with suggested correction: ${r}`:void 0].filter(c=>typeof c=="string")}function Zi(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=n??{},a=o[1],i=Xt(r.unknownOptionSuggestions)??[],s=r.suggestedRetryCommand;if(t==="update"&&(a==="--file"||a==="--doc"))return Yi(a,n,i);let c=Xi(r),l=Qi(a,t,i,c,s),d=[s,`pm ${t??"<command>"} --help`].filter(m=>typeof m=="string");return x({code:"unknown_option",title:`Unknown option ${a}`,happened:`Commander does not recognize option ${a} for this command path.`,required:Ji[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",examples:d,nextSteps:l,recovery:L(n,{suggested_flags:i.length>0?i:void 0,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function es(e,t,n,o,r){let a=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,i=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return x({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:rr([t.installCommand,...n]),nextSteps:rr([a,...i]),recovery:L(r)})}function ts(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=Z(t?.unknownCommandExamples),a=Z(t?.unknownCommandNextSteps),i=ki(o),s=r??["pm --help"],c=a??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=i?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return i&&(!d||!l.has(d))?es(o,i,s,c,t):x({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:c,recovery:L(t)})}function ns(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=Z(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let r=e?.suggestedRetryCommand;return x({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...r?[r]:[],`pm ${t} --help`],nextSteps:r?[`Retry with the declared hyphenated action: ${r}`]:["Choose one value from recovery.allowed_values."],recovery:L(e,{allowed_values:o,suggested_retry:r})})}function os(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=Wi(o);if(!r)return null;let a=Bi(o);return x({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...a?[a]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...a?[`Replay with the value re-joined into one argument: ${a}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:L(n,a?{suggested_retry:a}:{})})}var rs=new Set(["comments","docs","files","learnings","notes","test"]);function as(e,t,n){if(!/too many arguments/i.test(e)||!rs.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>l===t),a=o[r+1],i=o[r+2],s=n?.verifiedCollectionItemId?.trim();if(a?.toLowerCase()!=="add"||!i||i.startsWith("-")||!s||s.toLowerCase()!==i.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return x({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[c,`pm ${t} --help`],recovery:L(n,{parsed_positionals:[{role:"transposed_subcommand",value:a},{role:"item_id",value:s}],suggested_retry:c})})}var is=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]),ar=new Set(["context","ctx"]);function ss(e,t,n){if(!/too many arguments/i.test(e)||!ar.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>ar.has(l)),a=r===-1?1:r+1,i=e.match(/got \d+:\s*(\S+)/i),s=i?i[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(a)){if(l){l=!1;continue}let m=d.split("=")[0];if(is.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return x({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${c} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[c,`pm context --parent ${s}`],recovery:L(n,{suggested_retry:c})})}function Qt(e,t,n,o){let r=nt(e),a=Vi(r,t,n,o)??Ki(r,t,o)??Zi(r,t,o)??ts(r,o)??ns(o)??as(r,t,o)??os(r,t,o)??ss(r,t,o);return a||x({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:L(o)})}function lr(e,t){return sr(Jt(e,t))}function dr(e,t){return Yt(Jt(e,t))}function Zt(e,t,n){return Kt(Jt(e,n),t)}function mr(e,t,n,o){return sr(Qt(e,t,n,o))}function en(e,t,n,o){return Yt(Qt(e,t,n,o))}function ot(e,t,n,o,r){return Kt(Qt(e,t,n,r),o)}function pr(e,t){let n=ur(e);return Kt(n,t)}function ur(e){let t=nt(e);return Ti(t)?x({code:"module_import_failed",title:"Module import failed",happened:t,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):x({code:"unknown_error",title:"Unhandled error",happened:t,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function fr(e){return Yt(ur(e))}import{Option as cs}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]="45f3bebb-c075-5573-97bc-b573ae4d2d76")}catch{}})();function _(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function hr(e,t){let n=new Map;for(let o of e){let r=_(o.command);for(let a of t){if(a.layer!==o.layer||a.name!==o.name)continue;let i=_(a.command),s=i.split(" "),c=s.at(-1),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&r===d){n.set(r,i);break}}}return n}function tn(e,t,n,o){if(!t||!n)return;let r,a=0;for(let[s,c]of e.entries()){if(c!==t)continue;let l=e.slice(s);for(let[d,m]of o.entries()){let p=d.split(" ");p.length>a&&p.every((u,f)=>l[f]===u)&&(r=m,a=p.length)}}let i=r?.flags.find(s=>s.long===n||s.short===n);if(i)return rt(i).takesValue}function A(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function G(e){return typeof e=="boolean"?e:void 0}function rt(e){let t=A(e.value_type)??A(e.type),n=A(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||G(e.required)===!0||G(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function ls(e){if(G(e.visible)===!1)return null;let n=A(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=A(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",a=A(e.value_name),i=a?` <${a}>`:"",s=A(e.description)??"Extension-provided option.",c=[];G(e.required)===!0&&c.push("required"),G(e.enabled)===!1&&c.push("disabled");let l=c.length>0?` [${c.join(", ")}]`:"";return`${r}${n}${i} ${s}${l}`}function yr(e){let t=[...new Set(e.map(ls).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
|
|
6
6
|
Extension-provided flags:
|
|
7
7
|
${t.join(`
|
|
8
|
-
`)}`}function wr(e){let t=new Map;for(let r of e){let a=_(r.target_command);if(a.length===0)continue;let i=t.get(a)??[];i.push(...r.flags),t.set(a,i)}let n=[...t.entries()].sort(([r],[a])=>r.localeCompare(a)),o=new Map;for(let[r,a]of n){let i=yr(a);i&&o.set(r,i)}return o}function _r(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function gr(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let r=o.trim();r.length===0||n.has(r)||(n.add(r),t.push(r))}return t}function
|
|
8
|
+
`)}`}function wr(e){let t=new Map;for(let r of e){let a=_(r.target_command);if(a.length===0)continue;let i=t.get(a)??[];i.push(...r.flags),t.set(a,i)}let n=[...t.entries()].sort(([r],[a])=>r.localeCompare(a)),o=new Map;for(let[r,a]of n){let i=yr(a);i&&o.set(r,i)}return o}function _r(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function gr(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let r=o.trim();r.length===0||n.has(r)||(n.add(r),t.push(r))}return t}function ds(e){return Array.isArray(e)?e.map(t=>{let n=typeof t.name=="string"?t.name.trim():"";if(n.length===0)return null;let o={name:n,required:t.required===!0,variadic:t.variadic===!0};return typeof t.description=="string"&&t.description.trim().length>0&&(o.description=t.description.trim()),o}).filter(t=>t!==null):[]}function ms(e){let t=new Map;for(let n of e){let o=_(n.command);if(o.length===0)continue;let r=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,a=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:_r(o,n.action),description:r,intent:a,examples:gr(n.examples),failure_hints:gr(n.failure_hints),arguments:ds(n.arguments),flags:[],source:{layer:n.layer,name:n.name,package:n.source_package}})}return t}function ps(e){let t=new Map;for(let n of e){let o=_(n.target_command);if(o.length===0)continue;let r=t.get(o)??[];r.push(...n.flags),t.set(o,r)}return t}function us(e,t,n){let o=new Set;for(let r of e){let a=_(r);a.length>0&&o.add(a)}for(let r of t.keys())o.add(r);for(let r of n.keys())o.add(r);return o}function fs(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function br(e,t,n,o=new Map){let r=ms(t),a=ps(n),i=us(e,r,a),s=new Map,c=[...i].sort((l,d)=>l.localeCompare(d));for(let l of c){let d=fs(l,r,o)??r.get(l),m=a.get(l)??(d?a.get(d.command):void 0)??[];if(d){s.set(l,{...d,command:l,flags:m});continue}s.set(l,{command:l,action:_r(l,void 0),examples:[],failure_hints:[],arguments:[],flags:m})}return s}function gs(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function xr(e,t){for(let n of t.arguments)e.argument(gs(n),n.description??"Extension argument.")}function vr(e){if(G(e.visible)===!1)return null;let n=A(e.long),o=A(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,a=n&&n.startsWith("--")&&n.length>2?n:null,i=[r,a].filter(s=>s!==null);return i.length>0?i:null}function hs(e){let t=vr(e);if(!t)return null;let{valueName:n}=rt(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function ys(e){let t=vr(e);if(!t)return null;let{valueName:n}=rt(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function Cr(e){let t=A(e.description)??"Extension-provided option.",n=[];G(e.required)===!0&&n.push("required"),G(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function kr(e,t){let n=A(t.long),o=A(t.short);return e.options.some(r=>{let a=r;return n!==null&&a.long===n||o!==null&&a.short===o})}function nn(e,t){for(let n of t){if(kr(e,n))continue;let o=ys(n);if(!o)continue;let r=Cr(n);if(n.list!==!0){e.option(o,r);continue}e.addOption(new cs(o,r).argParser((a,i=[])=>[...Array.isArray(i)?i:[i],a]))}}function on(e,t){return yr(t.filter(n=>!kr(e,n)))}function ws(e){let t=hs(e);if(!t)return null;let n=A(e.long),o=A(e.short),r=n&&n.startsWith("--")&&n.length>2?n:null,a=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,{takesValue:i,valueName:s}=rt(e),c=G(e.required)===!0;return{flags:t,long:r,short:a,description:Cr(e),takes_value:i,value_required:i,value_name:s,variadic:!1,required:c,aliases:[],alias_for:null}}function Er(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let r=ws(o);!r||n.has(r.flags)||(n.add(r.flags),t.push(r))}return t}function Sr(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(r=>r.flags));for(let r of t)o.has(r.flags)||(o.add(r.flags),n.push(r));return n}function Ar(e){let t=[];if(e.intent&&t.push(`Intent: ${e.intent}`),e.action&&t.push(`Action contract: ${e.action}`),e.examples.length>0){t.push("Examples:");for(let n of e.examples)t.push(` - ${n}`)}if(e.failure_hints.length>0){t.push("Common failure hints:");for(let n of e.failure_hints)t.push(` - ${n}`)}return t.length===0?null:`
|
|
9
9
|
Extension command metadata:
|
|
10
10
|
${t.join(`
|
|
11
|
-
`)}`}function rn(e){let t=e;if(typeof t.aliases=="function")return t.aliases().map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);if(typeof t.alias=="function"){let n=t.alias();if(typeof n=="string"&&n.trim().length>0)return[n.trim().toLowerCase()]}return Array.isArray(t._aliases)?t._aliases.map(n=>n.trim().toLowerCase()).filter(n=>n.length>0):[]}function ve(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:rn(o).includes(n))??null}function ae(e,t){let n=e;for(let o of t){let r=ve(n,o);if(!r)return null;n=r}return n}var Tr=new WeakSet;function Or(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let r=t[o],a=ve(n,r);if(a){n=a;continue}let i=n.command(r);Tr.add(i),o<t.length-1?(i.description("Extension-provided command group."),i.action(()=>{i.help()})):i.description("Extension-provided command path."),n=i}return n}function
|
|
11
|
+
`)}`}function rn(e){let t=e;if(typeof t.aliases=="function")return t.aliases().map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);if(typeof t.alias=="function"){let n=t.alias();if(typeof n=="string"&&n.trim().length>0)return[n.trim().toLowerCase()]}return Array.isArray(t._aliases)?t._aliases.map(n=>n.trim().toLowerCase()).filter(n=>n.length>0):[]}function ve(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:rn(o).includes(n))??null}function ae(e,t){let n=e;for(let o of t){let r=ve(n,o);if(!r)return null;n=r}return n}var Tr=new WeakSet;function Or(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let r=t[o],a=ve(n,r);if(a){n=a;continue}let i=n.command(r);Tr.add(i),o<t.length-1?(i.description("Extension-provided command group."),i.action(()=>{i.help()})):i.description("Extension-provided command path."),n=i}return n}function _s(e,t){let n=e,o=[];for(let r of t){let a=ve(n,r);if(!a)return null;if(o.push(r),!Tr.has(a))return{core_path:o.join(" "),extension_path:t.join(" ")};n=a}return null}function bs(e,t,n,o){let r=t.split(" ").filter(s=>s.length>0),a=_s(e,r);if(!a||a.core_path===t&&!n.has(t))return null;let i=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${a.extension_path}:core_owner=pm-cli:${a.core_path}:extension_owner=${i}`}function Rr(e,t,n,o,r){return[...new Set([...t,...n.keys()])].filter(a=>a.trim().length>0).sort((a,i)=>a.localeCompare(i)).filter(a=>{let i=bs(e,a,o,n.get(a));return i?(r(i),!1):!0})}function Ir(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="33842ea7-43c9-52a3-a9ec-75f190a5fd6f")}catch{}})();function xs(e,t){let n=me(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function vs(e){return me(e.status)?.toLowerCase()??"pending"}function Cs(e){return e.mandatory===!0}function ks(e,t){let n=e.layer.localeCompare(t.layer);if(n!==0)return n;let o=e.name.localeCompare(t.name);return o!==0?o:e.id.localeCompare(t.id)}function Nr(e){let t=[];return e.forEach((n,o)=>{if(!Cs(n.definition))return;let r=vs(n.definition);r!=="applied"&&t.push({layer:n.layer,name:n.name,id:xs(n.definition,o),status:r})}),t.sort(ks),t}function $r(e){return Array.isArray(e)&&e.length>0}var Es=new Set(["create","beads import","todos import"]),Ss=new Set(["restore","update","close","delete","append","claim","release"]),As=new Set(["comments","notes","learnings"]),Ts=new Set(["files","docs","test"]),Os=new Set(["activate","add","add-field","add-status","add-type","apply","compact","create","deactivate","delete","disable","edit","enable","import","infer","install","materialize","migrate","redact","remove","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type","repair","run","save","set","unset","update","upgrade"]);function an(e,t){let n=t.force===!0;return Es.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:Ss.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:As.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:Ts.has(e)?{isMutation:$r(t.add)||$r(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function Rs(e,t,n){if(an(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return wo(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(r=>Os.has(r.trim().toLowerCase())):!1}function Pr(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Is(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let r=[];if(me(t[1])||r.push("source"),me(n.to)||r.push("--to"),r.length!==0)throw new C(`Schema migration requires ${r.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:r.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:r,suggested_flags:r.filter(a=>a.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function $s(e,t,n,o,r){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Pr(n.status)!==Pr(r.schema.workflow.in_progress_status))return;let a=t[0];if(!a)return;let i=V(r,K()),s=await ze(o,a,r.id_prefix,r.item_format,i.type_to_folder);if(!s)return;let c=await fo(s,{schema:r.schema}),l=typeof n.assignee=="string"?n.assignee.trim():void 0;(l===void 0?c.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(l.toLowerCase())&&l)||y(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function sn(e,t,n,o,r){if(!Rs(e,t,n)||(Is(e,t,n),!await U(j(r))))return;let a=await oe(r);o.json!==!0&&await $s(e,t,n,r,a.settings);let i=yo({author:Ue(o.author,a.settings.author_default),payload:{command:e,args:t,options:n},settings:a.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of i.warnings)y(`warning:${s}`)}function Fr(e,t,n){if(n.length===0)return;let o=an(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let r=n.map(i=>`extension_migration_blocking:${i.layer}:${i.name}:${i.id}:${i.status}`),a=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new C(`Write command "${e}" blocked by unresolved mandatory extension migrations (${r.join(",")}). ${a}`,g.CONFLICT)}async function cn(e,t,n,o){if(!an(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await U(j(n)))return;let{settings:a,metadata:i,warnings:s}=await oe(n);for(let c of s)y(`warning:${c}`);if(o.enforce_item_format_gate&&!i.has_explicit_item_format&&(po(a),await uo(n,a,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let c=V(a,K());await _o(n,a.item_format,"item_format:pre_mutation_sync",c.type_to_folder,a.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]="adb5b95f-be2d-5bcf-b376-09f6094e0bda")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48877bbb-17bf-5a78-91fa-19a2f2f4c2be")}catch{}})();var Ce=qn.join("|"),Ps={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"},Ns={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}},Mr=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function Fs(e,t){let n=Ns[e];if(!n)return[];let o=M(t);for(let[r,a]of Object.entries(n))if(M(r)===o)return a;return[]}function ln(e,t,n){if(n.length===0)return e;if(t){let i=n.find(s=>s.declared_command_match===!0);return JSON.stringify({...JSON.parse(e),...i?{extension_command_failure:{code:"extension_command_activation_failed",extension:i.name,layer:i.layer,error:i.error,recovery_commands:i.recovery_commands??[]}}:{},failed_extensions:n},null,2)}let o=n.map(i=>`- ${i.layer}:${i.name}: ${i.error}`).join(`
|
|
12
12
|
`),r=n.find(i=>i.declared_command_match===!0);if(!r)return`${e}
|
|
13
13
|
Extension activation failures:
|
|
14
14
|
${o}`;let a=(r.recovery_commands??[]).map(i=>`- ${i}`).join(`
|
|
@@ -19,11 +19,11 @@ ${a}`:""}
|
|
|
19
19
|
|
|
20
20
|
${e}
|
|
21
21
|
Extension activation failures:
|
|
22
|
-
${o}`}function dn(e){return P(e).commandPathTokens[0]??E(e)??"<command>"}function
|
|
23
|
-
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function Ks(e){let t=e.length;for(;t>0;){let n=e[t-1];if(n!==","&&n!==":"&&n!==";")break;t-=1}return e.slice(0,t)}function Ys(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(a=>a.trim().toLowerCase()===n))}function qr(e,t){if(t.length===0)return!0;let n=e,o=!1;for(let r of t){let a=Ys(n,r);if(!a)return o;o=!0,n=a}return o}async function Js(e,t,n,o){try{let r=k(process.cwd(),e.path);if(!await U(j(r)))return{allowedTypes:Ce};let a=await R(r),i=e.noExtensions?void 0:K(),s=V(a,i),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let l=n.findIndex(m=>m===o),d=n[l+2];if(n[l+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{c=(await ze(r,d,a.id_prefix,a.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Ce,pmRoot:r,settings:a,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:Ce}}}function Xs(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?jr([...Ns(t,n[1]),...Ds(n[1],ke(t))]):void 0,r=n?qs(n[1],t):[],a=n!==null&&ke(t).includes(M(n[1]));return{match:n,suggestions:o,otherCommands:r,scope:a?"declared_on_path":r.length>0?"declared_elsewhere":"declared_nowhere"}}function Qs(e,t,n){if(!t||!n||n.length===0)return;let o=zs(e,t[1],n[0]);return o?mn(o):void 0}function Zs(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Ks(Vs(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let r=E(t);if(r)return Uo(t,r,[o])}function ec(e,t){if(!/too many arguments/i.test(e)||E(t)!=="schema")return;let n=Fo(t),o=t[n+1]?.trim().toLowerCase(),r=t[n+2]?.trim().toLowerCase();if(!o||!r)return;let a=`${o}-${r}`;if(!Mr.includes(a))return;let i=[...t.slice(0,n+1),a,...t.slice(n+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${o} ${r}`,unknownSubcommandAllowedValues:[...Mr],suggestedRetryCommand:mn(i)}}async function Ee(e,t,n,o={}){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",i=Ye(process.argv.slice(2)).argv,s=q(i),c=E(i),l=mn(i),d=X(i),m=await Js(s,a,i,c),p=m.allowedTypes,u=pn(a,t,n),f=Xs(a,c),h=ec(a,i),w=h?.suggestedRetryCommand??Qs(i,f.match,f.suggestions)??Zs(a,i);return{message:a,commandName:c,allowedTypes:p,attemptedCommand:l,normalizedInvocationArgs:[...i],providedOptionFlags:d,unknownOptionSuggestions:f.suggestions,unknownOptionOtherCommands:f.otherCommands.length>0?f.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:f.otherCommands.length>0?f.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:f.otherCommands.length>12||void 0,unknownOptionScope:f.scope,suggestedRetryCommand:w,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function un(e,t,n,o={}){let r=await Ee(e,t,n,o),{message:a,commandName:i,allowedTypes:s,unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:w,unknownOptionScope:v,unknownSubcommandPath:D,unknownSubcommandToken:W,unknownSubcommandAllowedValues:te,suggestedRetryCommand:gt,verifiedCollectionItemId:Pe,failedExtensions:Ne}=r,de=mr(a,i,s,{unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:w,unknownOptionScope:v,unknownSubcommandPath:D,unknownSubcommandToken:W,unknownSubcommandAllowedValues:te,suggestedRetryCommand:gt,verifiedCollectionItemId:Pe,failedExtensions:Ne}),ht=await ro("help_format",{message:de,command:i,allowed_types:s});return ht.handled&&typeof ht.result=="string"?ht.result:de}async function fn(e,t,n,o=!1,r={}){let a=await Ee(e,t,n,r),i=ot(a.message,a.commandName,a.allowedTypes,g.USAGE,{unknownCommandExamples:a.unknownCommandExamples,unknownCommandNextSteps:a.unknownCommandNextSteps,attemptedCommand:a.attemptedCommand,normalizedInvocationArgs:a.normalizedInvocationArgs,providedOptionFlags:a.providedOptionFlags,unknownOptionSuggestions:a.unknownOptionSuggestions,unknownOptionOtherCommands:a.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:a.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:a.unknownOptionOtherCommandsTruncated,unknownOptionScope:a.unknownOptionScope,unknownSubcommandPath:a.unknownSubcommandPath,unknownSubcommandToken:a.unknownSubcommandToken,unknownSubcommandAllowedValues:a.unknownSubcommandAllowedValues,suggestedRetryCommand:a.suggestedRetryCommand,verifiedCollectionItemId:a.verifiedCollectionItemId,failedExtensions:a.failedExtensions});return JSON.stringify(o?et(i):i,null,2)}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]="f3543bab-fa67-5e91-a700-0cbee84f2dc8")}catch{}})();async function gn(e,t={},n=[]){let o={readSettings:R,loadExtensions:pe,activateExtensions:ue,resolveImplicitPmRoot:bt,...t};try{let r=await o.readSettings(e),a=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),i=await o.activateExtensions(a);return[...a.failed,...i.failed].map(s=>{let c=(a.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map($).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map($),m=l.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...l.length>0?{declared_commands:l}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function zr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await gn(t,n,o),a={readSettings:R,loadExtensions:pe,activateExtensions:ue,resolveImplicitPmRoot:bt,...n};try{let i=a.resolveImplicitPmRoot(process.cwd());if(ie.resolve(i)===ie.resolve(t))return r;let[s,c]=await Promise.all([a.readSettings(t),a.readSettings(i)]),[l,d]=await Promise.all([a.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),a.loadExtensions({pmRoot:i,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(d.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,f)=>u.localeCompare(f));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${ie.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${ie.resolve(i)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${ie.resolve(i)}, or install the extension into the selected tracker with "pm --pm-path ${ie.resolve(t)} install <package> --project".`})}catch{}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="abdb8d3e-8c1b-511e-b25b-220d5a40ae3f")}catch{}})();function tc(e,t){if(t.length===0)return e;let n=ae(e,t);if(n)return n;let o=t.join(" ");if(!qe.some(r=>r===o)&&!Co(o)&&!we(o))return null;for(let r=t.length-1;r>0;r-=1){let a=ae(e,t.slice(0,r));if(a)return a}return t.length===1?e:null}function nc(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Hr(e){let t=e;if(typeof t.attributeName=="function"){let n=t.attributeName();return typeof n=="string"&&n.trim().length>0?n.trim():null}return typeof t.attributeName=="string"&&t.attributeName.trim().length>0?t.attributeName.trim():null}function oc(e){let t=new Map;for(let n of e){let o=n,r=Hr(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let a=t.get(r)??[];a.push(o.long.trim()),t.set(r,a)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,a)=>r.localeCompare(a)));return t}function rc(e){return O(e)}function ac(e){let t=e.options??[],n=oc(t);return t.map(o=>{let r=o,a=typeof r.flags=="string"?r.flags.trim():"",i=typeof r.description=="string"?r.description.trim():"",s=Hr(o),l=(s?n.get(s)??[]:[]).filter(w=>w!==r.long).map(w=>w.trim()).filter(w=>w.length>0),d=i.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,p=r.mandatory===!0||i.includes("[required]")||i.toLowerCase().includes("required;"),u=a.includes("<"),f=u||a.includes("["),h={flags:a,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:i,takes_value:f,value_required:u,value_name:nc(a),variadic:r.variadic===!0,required:p,aliases:l,alias_for:m};return r.defaultValue!==void 0&&(h.default_value=r.defaultValue),h})}function ic(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let r=o.alias_for,a=t.get(r);if(!a)continue;let i=o.long,s=new Set([...a.aliases??[],i]);a.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function sc(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",a=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0||a?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:a}})}function cc(e){return e.createHelp().visibleCommands(e).filter(t=>t.name()!=="help"||e.parent===null).map(t=>{let n=$(I(t)).split(" ")[0];return{name:t.name().trim(),aliases:rn(t),description:t.description().trim(),tier:Ke(n),family:Ve(n)}}).sort((t,n)=>t.name.localeCompare(n.name))}function lc(e,t,n){if(!n)return t;let o=n.examples??[],r=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?r.length>0?[...r]:[...t.tips]:[],detail_mode:e}}function dc(e,t,n,o){if(!e){let a=sc(t),i=cc(t),s=new Set(i.map(({name:c})=>c));return{arguments:a,options:o,subcommands:[...i,...He.filter(({parent:c,action:l})=>c===n&&!s.has(l)).map(({action:c,description:l})=>({name:c,aliases:[],description:l,tier:Ke(n.split(" ")[0]),family:Ve(n.split(" ")[0])}))].sort((c,l)=>c.name.localeCompare(l.name)),usage:[n,a.reduce((c,l)=>l.required?c.replace(`[${l.name}${l.variadic?"...":""}]`,`<${l.name}${l.variadic?"...":""}>`):c,t.usage())].filter(c=>c.length>0).join(" ")}}let r=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:a,required:i,variadic:s,value_kind:c,polymorphic:l})=>({name:a,required:i,variadic:s,description:l?`Polymorphic ${c} value; inspect the action contract before mutation.`:`${c.replaceAll("_"," ")} value.`})),options:o.filter(({long:a,aliases:i})=>a!==null&&r.has(a)||i.some(s=>r.has(s))),subcommands:[],usage:[e.command,...e.slots.map(({name:a,required:i,variadic:s})=>{let c=s?`${a}...`:a;return i?`<${c}>`:`[${c}]`})].join(" ")}}function mc(e,t,n,o,r){let a=Ht(n),i=$(I(t)),s=$(o.join(" ")),c=s.length>i.length?s:i,l=we(c),d=l?.command??c,m=d.length>0?d:void 0,p=m?.split(" ")[0],u=Qo(m,a),f=m?r.get(m):void 0,h=lc(a,u,f),w=ic(Sr(ac(t),Er(f))),v=dc(l,t,d,w);return{format:"pm_help_v1",detail_mode:a,root_command:e.name(),requested_path:o,resolved_path:d.length>0?d:e.name(),visibility_tier:p===void 0?null:Ke(p),capability_family:p===void 0?null:Ve(p),description:l?.description??t.description(),usage:v.usage,intent:l?.description??h.intent,examples:l?[l.example]:h.examples,tips:l?[Ge(l.accepted_flags)]:h.tips,arguments:v.arguments,options:v.options,subcommands:v.subcommands,has_subcommands:v.subcommands.length>0}}async function Gr(e,t,n){let o=q(t);if(!o.json)return!1;let r=P(t);if(!r.requested)return!1;let a=tc(e,r.commandPathTokens);if(!a){if(!o.quiet){let i=`unknown command '${r.commandPathTokens.join(" ")}'`,s=pn(i,e,n),c=ot(i,"help",Ce,g.USAGE,{...s,attemptedCommand:rc(t),normalizedInvocationArgs:[...t],providedOptionFlags:X(t)});y(JSON.stringify(c,null,2))}return process.exitCode=g.USAGE,!0}if(!o.quiet){let i=mc(e,a,t,r.commandPathTokens,n);mo(`${JSON.stringify(i,null,2)}
|
|
24
|
-
`)}return process.exitCode=g.SUCCESS,!0}function
|
|
25
|
-
`)}function
|
|
26
|
-
`)}let a=n.indexOf("--"),i=a<0?n:n.slice(0,a),s=i.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),c=s<0?void 0:i[s]?.startsWith("--create-mode=")?i[s]?.slice(14):i[s+1],l=e==="create"&&c?.toLowerCase()==="strict",d=
|
|
27
|
-
`)}function Wr(e,t,n){let o=E(n);if(o!=="create"&&o!=="update")return;let r=ve(e,o);r&&r.addHelpText("after",hc(o,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]="fa92f987-990a-5159-8c45-f055d5a15da2")}catch{}})();async function Br(e,t,n,o){if(n)return null;let r=e.some(i=>i==="--for"||i.startsWith("--for=")),a=E(e)==="contracts"&&e.includes("--full");return r||a?await o(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27eeca2d-756c-539b-a0d4-d64516ee4aa6")}catch{}})();var hn="PM_CLI_PACKAGE_ROOT";function yc(){return Un(import.meta.url,["../.."])}(typeof process.env[hn]!="string"||process.env[hn]?.trim().length===0)&&(process.env[hn]=yc());var ce=null,N=null;function wc(e){ce=e}function _c(e){T=e}var xc=new Set(["success","nonexistent_command","invalid_option","missing_required_option","missing_required_argument","invalid_usage","validation_failed","health_findings","validation_findings","conflict","runtime_failed","unknown_failed"]),bc=new Set(["parse","preflight","execute","unknown"]),vc=new Set(["usage","validation","conflict","runtime","unknown"]),Se=null,ee=null,T=new Map,Sn=250,Cc=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),kc=new Set(["1","true","yes","on"]),Ec=ye(()=>import("./chunks/register-setup-I4LUHGVW.js")),Sc=ye(()=>import("./chunks/register-list-query-Y56KINDU.js")),Ac=ye(()=>import("./chunks/register-mutation-AUWVCW4M.js")),Tc=ye(()=>import("./chunks/register-operations-PZQPHXW5.js"));function st(e){return O(e)}function Zr(e){let t=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!t||t.length===0)return;let n=[...new Set(t.map(o=>J(o)??o))];return n.length>0?n:void 0}function Oc(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=X(t),r=new Set(o.map(d=>J(d)??d)),a=Zr(e),i=t.find(d=>x.commands.some(m=>m.name()===d)),s=i?x.commands.find(d=>d.name()===i):void 0,c=new Set([...x.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>J(m)).filter(m=>m!==void 0))),l=a?.filter(d=>{let m=J(d)??d;return r.has(m)?!1:c.has(m)||tn(t,i,m,T)!==void 0});return l&&l.length>0?l:void 0}function Rc(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],a=r?J(r):void 0,i=e.find(p=>x.commands.some(u=>u.name()===p)),s=i?x.commands.find(p=>p.name()===i):void 0,c=a?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(a)):void 0,l=tn(e,i,a,T),d=a?c?.isBoolean()===!0||l===!1?[a]:[a,"<value>"]:[],m=a?st([...e,...d]):t;return m===t?void 0:m}function Ic(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let r=e[o];r!=null&&(n[o]=r)}return n}function $c(e){let t=e.existingRecovery;return{attempted_command:t?.attempted_command??e.attemptedCommand,normalized_args:t?.normalized_args??[...e.invocationArgv],provided_fields:t?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:t?.missing??e.inferredMissing,...Ic(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function ea(e,t,n){let o=je(t),r=o.includes("--explain"),a=e?.recovery,i=a&&o.includes("history-redact")?{...a,...a.attempted_command?{attempted_command:st(o)}:{},...a.normalized_args?{normalized_args:[...o]}:{},...a.suggested_retry?{suggested_retry:st(o)}:{},...a.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:a;if(i?.recovery_mode==="compact"&&!r)return{...e,recovery:i};let s=st(o),c=X(o),l=Oc(n,o,i),d=Rc(o,s,l,i),m=$c({invocationArgv:o,attemptedCommand:s,providedFields:c,inferredMissing:l,suggestedRetry:d,existingRecovery:i});return{...e,recovery:m}}function se(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let r=o.trim();if(r.length>0)return r}}}function ta(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function An(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return Math.max(0,Math.trunc(o))}}function na(e){if(!e)return;let t=e.trim().toLowerCase();if(xc.has(t))return t}function oa(e){if(!e)return;let t=e.trim().toLowerCase();if(bc.has(t))return t}function ra(e){if(!e)return;let t=e.trim().toLowerCase();if(vc.has(t))return t}function aa(e){let t=se(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let i=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof i=="string")return i.trim()}if(ta(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=An(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let a=e?.run_results;if(Array.isArray(a)){let i=a.filter(s=>wt(s)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function ia(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function sa(){let e=wt(fe()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=An(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,r=Io(o),a=se(e,"error_code","errorCode")??ia(r,o),i=ra(se(e,"error_category","errorCategory"))??(r?void 0:yt(a)),s=r?void 0:aa(e)??`command_exit_${o}`,c=na(se(e,"command_resolution","commandResolution"))??Et({ok:r,errorCode:a,errorCategory:i}),l=oa(se(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:a,error_category:i,command_resolution:c,resolution_stage:l}}async function Re(e){let t=N;N=null,await er(t,e);let n=ce;if(ce=null,!n){Le();return}let o=[],r=no();try{await tr({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(a=>a.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Bn(n.hooks,{command:n.commandName,args:n.commandArgs,options:{...n.commandOptions},global:{...n.globalOptions},pm_root:n.pmRoot,ok:e.ok,error:e.error,result:fe(),affected:r}))}catch(a){o=[`afterCommand hooks failed: ${a instanceof Error?a.message:String(a)}`]}finally{Le()}!n.globalOptions.json&&o.length>0&&y(`[pm] warning: afterCommand hook_warnings=${F(o)}`),n.profileEnabled&&o.length>0&&y(`profile:extensions hook_warnings=${F(o)}`)}async function ca(){await go()}function la(e){return kc.has((process.env[e]??"").trim().toLowerCase())}function da(e){return la("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Cc.has(Math.trunc(e))}async function ct(e){return da(e.exit_code)?(await ca(),ho(e),!0):!1}async function ma(e){let t=Y(e.error),n=fr(t);e.bootstrapGlobal.json?y(JSON.stringify(pr(t,g.GENERIC_FAILURE),null,2)):y(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await ca(),Tt(e.error);let a=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=a.errorCategory,r=a.commandResolution,ge(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||y(`Failed to report error: ${Y(a)}`)}try{await Re({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${Y(a)}`)}try{await he()}catch(a){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${Y(a)}`)}}function Vr(e,t,n,o){let r=n.outputInclude;if(r===void 0)return;let a={},{selectors:i,modes:s}=co(t,r,a);if(s.length===0)return;for(let[l,d]of Object.entries(a))o[l]=d,e.setOptionValueWithSource(l,d,"cli");let c=i.length>0?i.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let l=e;l;l=l.parent)l.setOptionValueWithSource("outputInclude",c,"cli");Rt(e,n)}function Ae(e,t,n=[]){let r={...e.optsWithGlobals()};delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession;let a=Vo(t);for(let[i,s]of Object.entries(a))r[i]===void 0&&(r[i]=s);if(n.length>0){let i=Go(n),s=We(I(e)).map(l=>({long:l.flag,short:l.short,aliases:l.aliases})),c={...a};for(let l of i)r[l]!==void 0&&(c[l]=r[l]);return Ut(c,[...s,...n],I(e)),Bo(r,n,a)}return r}function _n(e,t){let n=_(t);return n.length===0?[]:e.flags.filter(o=>_(o.target_command)===n).flatMap(o=>o.flags)}function lt(e,t,n){let o=_n(e,t),r=[t],a=[];for(let i of n){if(i.startsWith("-"))break;r.push(i);let s=_n(e,r.join(" "));s.length>0&&(a=s)}return a.length>0?a:o}function Tn(e){return e.arguments??[]}function Kr(e){let t=Tn(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function pa(e,t){if(!e)return!1;let n=_(t);return e.importers.some(o=>_(`${o.importer} import`)===n)||e.exporters.some(o=>_(`${o.exporter} export`)===n)}function ua(e,t){let n=Tn(e),o=n.filter(c=>c.required).length,a=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,i=e.failure_hints??[],s=i.length>0?` ${i.join(" ")}`:"";if(t.length<o)throw new C(`Missing required argument for extension command '${e.command}'. Usage: ${Kr(e)}${s}`,g.USAGE);if(t.length>a){let c=t.slice(a).join(" ");throw new C(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${Kr(e)}${s}`,g.USAGE)}}function Pc(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Nc(e,t,n){if(n.length>0){Ut(t,n,e.command);return}let o=Object.keys(t).filter(r=>t[r]!==void 0).sort();if(o.length!==0)throw new C(`Unknown option '${o.map(Pc).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function fa(e,t,n,o){e&&(ua(e,t),Nc(e,n,o))}var Fc={create:"create",update:"update","update-many":"update_many",list:"list","list-all":"list","list-draft":"list","list-open":"list","list-in-progress":"list","list-blocked":"list","list-closed":"list","list-canceled":"list",search:"search",calendar:"calendar",context:"context","templates save":"create"},yn=new Map;function xn(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function ga(e,t){return e.options.some(n=>n.long===t)}function ha(e,t){return e.options.some(n=>n.short===t)}function bn(e,t,n,o){let r=t.trim();if(!r)return;let a=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(ha(e,r))return;if(o){e.option(`${r} <value>`,`${a} (repeatable)`,$t);return}e.option(`${r} <value>`,a);return}let i=r.startsWith("--")?r:`--${r}`;if(!ga(e,i)){if(o){e.option(`${i} <value>`,`${a} (repeatable)`,$t);return}e.option(`${i} <value>`,a)}}async function ya(e,t){let n=Fc[e];if(!n)return[];let o=`${t}:${n}`,r=yn.get(o);if(r)return r;if(!await U(j(t)))return yn.set(o,[]),[];let a=await R(t),s=(Ct(a.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:xn(c.type),value_type:xn(c.type)})));return yn.set(o,s),s}async function wa(e,t){let n=q(t),o=k(process.cwd(),n.path);if(!await U(j(o)))return;let r=ee?.key===In(o)?ee.snapshot:null,a=r===null?await R(o):r.settings,i=Ct(a.schema),s=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(let c of s){let l=ae(e,c.path.split(" "));if(l)for(let d of i.command_to_fields.get(c.command)??[]){let m=d.description??"";bn(l,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)bn(l,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function On(e,t,n,o,r){let a=E(n);if(!(a!=="create"&&a!=="update"))try{let i=r??await R(t),s=V(i,o);Wr(e,s,n)}catch{}}function vn(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function _a(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Rn(e){return e.some(t=>t==="--profile")}function In(e){return`pm-root:${e}`}function xa(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=_(n);o.length!==0&&t.push(o)}return t}function Ie(e){let t=_(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(r=>r.length>0);for(let r of xa(e.commandArgs))o.push(...r.split(" ").filter(a=>a.length>0)),n.push(o.join(" "));return[...new Set(n)]}function ba(e,t){let n=_(e);if(n.length===0)return!1;let o=Ie(t);for(let r of o)if(r===n||r.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(r=>n.startsWith(`${r} `)):!1}function $n(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...S(n.commands),...S(n.command_handlers),...S(n.command_overrides),...S(n.flag_commands),...S(n.parser_overrides),...Yr(n.preflight_ownership),...Yr(n.renderer_ownership)]:[]}function S(e){return e??[]}function Yr(e){return S(e).flatMap(t=>t.commands)}function dt(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var va=new Set(["hooks","parser","preflight","renderers"]),Ca=new Set(["commands","schema","services","importers"]),Mc=new Set(["reindex","search","search-advanced"]),Lc=new Set(["--template"]);function Te(e,t){for(let n of t)if(e.has(n))return!0;return!1}function ka(e){let t=_(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return Mc.has(n??t)}function Ea(e,t){for(let n of e.commandArgs??[]){if(!n.startsWith("--"))continue;let[o]=n.split("=",1);if(t.has(o))return!0}return!1}function Pn(e){return _(e.commandPath??"")==="create"&&Ea(e,Lc)}function Sa(e){return e.some(t=>{let n=_(t);return n==="templates"||n.startsWith("templates ")})}function Cn(e,t){return e.some(n=>ba(n,t))||Pn(t)&&Sa(e)}function Aa(e){return[S(e.hooks).length,(e.preflight_overrides??0)-S(e.preflight_ownership).length,S(e.item_types).length,S(e.item_fields).length,S(e.relationship_kinds).length,S(e.service_overrides).length,S(e.assurance_providers).length,S(e.renderer_overrides).length-S(e.renderer_ownership).length].some(n=>n>0)}function Ta(e,t){let n=e.activation?.commands??[];if(n.length>0)return Cn(n,t);let o=$n(e);if(Cn(o,t)||dt(e).has("search")&&ka(t.commandPath))return!0;if(e.contributions)return Aa(e.contributions)}function Nn(e,t){let n=Ta(e,t);if(n!==void 0)return n;let o=dt(e);return!!(Te(o,va)||Te(o,Ca))}function mt(e,t){return e.effective.length===0?!1:_(t.commandPath??"").length>0?e.effective.some(o=>Nn(o,t)):e.effective.some(o=>{let r=dt(o);return $n(o).length>0||Te(r,va)||Te(r,Ca)||r.has("search")})}function Fn(e){let t=Ie(e).filter(r=>r.split(" ").every(a=>!a.startsWith("-"))).sort((r,a)=>a.length-r.length)[0]??_(e.commandPath??"");if(t.length===0)return"all";let n=Pn(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Oa(e){return Fn(e)==="all"?void 0:t=>Nn(t,e)}function $e(e){let t=P(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...a]=t.commandPathTokens;return{commandPath:r,commandArgs:a,allowCommandPrefixMatch:!0}}let n=No(e),o=n.findIndex(r=>r.trim().length>0&&!r.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Ra(e){let t=e.args.map(String);if(_(I(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function kn(e){for(let t of e)t.startsWith("settings_read_")&&y(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Ia(e,t){e.profile&&(y(`profile:extensions loaded=${t.loadedCount} failed=${t.loadFailedCount} warnings=${t.loadWarnings.length} activation_failed=${t.activationFailedCount} hook_counts=before:${t.hooks.beforeCommand.length}|after:${t.hooks.afterCommand.length}|write:${t.hooks.onWrite.length}|read:${t.hooks.onRead.length}|index:${t.hooks.onIndex.length} command_overrides=${t.commands.overrides.length} command_handlers=${t.commands.handlers.length} parser_overrides=${t.parsers.overrides.length} preflight_overrides=${t.preflight.overrides.length} service_overrides=${t.services.overrides.length} renderer_overrides=${t.renderers.overrides.length}`),t.activationWarnings.length>0&&y(`profile:extensions activation_warnings=${F(t.activationWarnings)}`))}function pt(e,t,n){if(!e)return;let o=_(n.commandPath??"")||"<none>";y(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function ut(e,t=oe){let n=In(e);if(ee?.key===n)return ee.snapshot;try{let o=Date.now(),{settings:r,warnings:a}=await t(e),i=await Vn({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:i,discoveryMs:Date.now()-o,settingsReadWarnings:[...a]};return ee={key:n,snapshot:s},s}catch{return ee={key:n,snapshot:null},null}}async function le(e,t,n=R){let o=t?Fn(t):"all",r=_a(e,o);if(Se?.key===r)return Se.snapshot;try{let a=await n(e),i=await pe({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Oa(t):void 0}),s=await ue({...i,loaded:i.loaded}),c=[...new Set(s.commands.handlers.map(u=>_(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),l=wr(s.registrations.flags),d=hr(s.commands.handlers,s.registrations.commands),m=xr(c,s.registrations.commands,s.registrations.flags,d),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:a,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...i.warnings],activationWarnings:[...s.warnings],loadedCount:i.loaded.length,loadFailedCount:i.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:i.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return Se={key:r,snapshot:p},p}catch{return Se={key:r,snapshot:null},null}}async function $a(e){let t=_e(e);if(t.noExtensions){let i=k(process.cwd(),t.path);return await U(j(i))&&kn((await oe(i)).warnings),null}let n=k(process.cwd(),t.path),o=await ut(n);if(!o)return null;kn(o.settingsReadWarnings);let r={commandPath:I(e),commandArgs:Ra(e)};if(!mt(o.discovery,r))return pt(t.profile,o,r),null;let a=await le(n,r);return a?(Ia(t,a),{hooks:a.hooks,commands:a.commands,parsers:a.parsers,preflight:a.preflight,services:a.services,renderers:a.renderers,registrations:a.registrations,pmRoot:n}):null}async function Pa(e){let t=await le(e);return t?new Map(t.commandDescriptors):T}async function Na(e,t){return(await Oo({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function Fa(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return ko(e,Po.forActiveExtensionHost({pmRoot:e,author:n}))}async function Ma(e,t,n,o=[]){let r=I(e),a=jt(e.args.map(String),o),i={...t},s={...n},c=k(process.cwd(),n.path),l=await De({command:r,args:a,options:i,global:s,pm_root:c});n.profile&&l.warnings.length>0&&y(`profile:extensions parser_warnings=${F(l.warnings)}`),a=l.context.args,i=l.context.options,s=l.context.global,fa(T.get(_(r)),a,i,o),ne(void 0),Me({command:r,args:a,options:{...i},global:{...s},pm_root:c});let d=await vt({command:r,args:a,options:i,global:s,pm_root:c,sdk:Fa(c,s)});if(s.profile&&d.warnings.length>0&&y(`profile:extensions command_handler_warnings=${F(d.warnings)}`),!d.handled){if(d.warnings.length>0){let m=d.warnings[0],p=d.errorMessage?.trim(),u=p?` ${p}`:"";throw new C(`Command "${r}" failed in extension handler (${m}).${u}`,g.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new C(`Command "${r}" is provided by extensions and is not currently available.`,g.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),ne(d.result),d.result}var Jr=Symbol("pm.wrappedActionHandler");function Dc(e,t){let n=e[e.length-1];return n instanceof En?n:t}function Xr(e,t,n){e&&n.length>0&&y(`profile:extensions ${t}=${F(n)}`)}function Uc(e){let t=T.get(_(e.commandPath));if(!t||!pa(e.activeRegistrations,e.commandPath))return;let n=Tn(t).length===0?Ko(e.commandArgs):jt(e.commandArgs,e.extensionFlagDefinitions);ua(t,n)}function jc(e,t,n){e.args=[...n],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),t.length>0&&Array.isArray(t[0])&&(t[0]=[...e.processedArgs])}function La(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[Jr]!==!0){let r=o._actionHandler;o._actionHandler=async function(...i){let s=Dc(i,n),c=Date.now();It(s);let l=_e(s),d=I(s),m=k(process.cwd(),l.path),p=s.args.map(String),u=K(),f=u?lt(u,d,p):[],h=await ya(d,m),w=Ae(s,p,[...f,...h]),v=await De({command:d,args:p,options:w,global:l,pm_root:m});Xr(l.profile,"parser_warnings",v.warnings),p=v.context.args,w=v.context.options,l=v.context.global,Uc({activeRegistrations:u,commandPath:d,commandArgs:p,extensionFlagDefinitions:f}),l=await So(l),Rt(s,l),jc(s,i,p),Be(s,w),ne(void 0),Me({command:d,args:p,options:{...w},global:{...l},pm_root:m});let D=await vt({command:d,args:p,options:w,global:l,pm_root:m,sdk:Fa(m,l)});if(Xr(l.profile,"command_handler_warnings",D.warnings),D.handled){ne(D.result),kt(D.result,{...l,command:d,commandArgs:p,commandOptions:w,pmRoot:m}),l.profile&&y(`profile:command=${d} took_ms=${Date.now()-c}`);return}return await r.apply(this,i)},o[Jr]=!0}for(let r of n.commands)t(r)};t(e)}async function it(e){T=new Map,B({overrides:[]}),e&&await On(e.rootProgram,e.pmRoot,e.invocationArgv,Gn(),e.settings)}function qc(e,t,n,o){if(t?.flags&&t.flags.length>0){nn(e,t.flags);let r=on(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}async function Da(e,t){let n=q(t),o=k(process.cwd(),n.path);if(n.noExtensions){await it({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await ut(o),a=$e(t);if(!r){await it();return}if(!mt(r.discovery,a)){await it({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),pt(Rn(t),r,a);return}let i=await le(o,a);if(!i){await it({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}B(i.services),T=new Map(i.commandDescriptors),await On(e,o,t,i.registrations,i.settings);let s=Rr(e,i.commandHandlers,i.commandDescriptors,i.commandAliases,l=>Ir(i.activationWarnings,y,l)),c=l=>{let d=l.split(" ").filter(v=>v.length>0),m=i.commandDescriptors.get(l),p=ae(e,d),u=i.commandFlagHelp.get(l),f=m?Ar(m):null;if(p){qc(p,m,u,f);return}let h=Or(e,d);m?.description&&h.description(m.description);let w=u;m&&(br(h,m),m.flags.length>0&&(nn(h,m.flags),w=on(h,m.flags)??void 0)),w&&h.addHelpText("after",w),f&&h.addHelpText("after",f),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...v)=>{let D=v[v.length-1],W=D instanceof En?D:h,te=_e(W),gt=Date.now(),Pe=lt(i.registrations,l,W.args.map(String)),Ne=Ae(W,W.args.map(String),Pe),de=await Ma(W,Ne,te,Pe);await Ao(te,de),kt(de,{...te,command:l,commandArgs:W.args.map(String),commandOptions:Ne,pmRoot:o}),te.profile&&y(`profile:command=${l} took_ms=${Date.now()-gt}`)})};for(let l of s)c(l)}var Oe=jn(import.meta.url,["../.."])??"0.0.0",x=Lt(Oe);function Ua(e){e.hook("preAction",async(t,n)=>{ce=null,N=null,Le(),It(n);let o=n.optsWithGlobals(),r=_e(n),a=I(n),i=n.args.map(String),s=Ae(n,i),c={...r};so(a,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession,outputCursor:o.outputCursor}),Vr(n,a,c,s),await xo(a,c);let l=k(process.cwd(),r.path),d=await $a(n);if(!d){ce=Kn({commandName:a,commandArgs:i,commandOptions:s,globalOptions:c,pmRoot:l}),N=await Ot({command:a,pm_version:Oe,args:i,options:s,global:c,pm_root:l}),St(a,i,s,{source_context:N?.source_context,source_context_source:N?.source_context_source}),At(a),await cn(a,s,l,vn()),await sn(a,i,s,c,l);return}Yn(d.hooks),Jn(d.commands),Xn(d.parsers),Qn(d.preflight),B(d.services),Zn(d.renderers),eo(d.registrations);let m=lt(d.registrations,a,i);s=Ae(n,i,m),Vr(n,a,c,s);let p=await De({command:a,args:i,options:s,global:c,pm_root:d.pmRoot});c.profile&&p.warnings.length>0&&y(`profile:extensions parser_warnings=${F(p.warnings)}`),i=p.context.args,s=p.context.options,c=p.context.global,Be(n,s);let u=await oo({command:a,args:i,options:s,global:c,pm_root:d.pmRoot,decision:vn()});c.profile&&u.warnings.length>0&&y(`profile:extensions preflight_warnings=${F(u.warnings)}`),i=u.context.args,s=u.context.options,c=u.context.global,Be(n,s);let f=u.decision;await cn(a,s,d.pmRoot,f),await sn(a,i,s,c,d.pmRoot);let h=f.run_extension_migrations?await Na(d.registrations.migrations,d.pmRoot):[];c.profile&&h.length>0&&y(`profile:extensions migration_warnings=${F(h)}`);let w=Nr(d.registrations.migrations);ce={hooks:d.hooks,commandName:a,commandArgs:i,commandOptions:{...s},globalOptions:{...c},pmRoot:d.pmRoot,profileEnabled:!!c.profile,migrationBlockers:w},ne(void 0),Me({command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot}),N=await Ot({command:a,pm_version:Oe,args:i,options:s,global:c,pm_root:d.pmRoot}),St(a,i,s,{source_context:N?.source_context,source_context_source:N?.source_context_source}),At(a);let v=await Wn(d.hooks,{command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot});c.profile&&v.length>0&&y(`profile:extensions hook_warnings=${F(v)}`),f.enforce_mandatory_migration_gate&&Fr(a,s,w)}),e.hook("postAction",async()=>{let t=sa();ge(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await Re(t)})}Ua(x);var zc=new Set(["--version","-V"]),Hc=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),ja=new Set(["activity","aggregate","context","ctx","events","get","graph","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search"]),qa=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),Gc=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Wc=new Set(["claim","close-task","pause-task","release","start-task","test"]),wn={setup:!0,listQuery:!0,mutation:!0,operation:!0},Bc=new Set(["create","update","update-many","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","search","calendar","context","templates"]);function ft(e){return e.some(t=>zc.has(t))}function za(e){if(ft(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||P(e).requested)return wn;let t=E(e);if(!t)return wn;let n=t.trim().toLowerCase();return Hc.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:ja.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:qa.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Gc.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:wn}function Ha(e){return e.length===0||P(e).requested}var Qr=Symbol("pmCliIdempotentTopLevelRegistration");function Ga(e){let t=e;if(t[Qr])return;t[Qr]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let a=o.split(/\s+/u)[0];return e.commands.some(i=>i.name()===a||i.aliases().includes(a))?new En(a):n(o,...r)})}async function Vc(e,t){if(Ga(e),t.setup){let{registerSetupCommands:n}=await Ec();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Sc(),o=typeof t.targetCommandName=="string"&&ja.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Ac();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Tc();n(e)}}function Wa(e,t){return ft(t)?!1:P(t).requested?!0:!!E(t)}function Ba(e){if(ft(e))return!1;let t=E(e);return t?Bc.has(t):!1}function Kc(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),a=r?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${r}${l.slice(d)}`:r:l}):e.argv,i=je(a),s=r&&n>=0?`${o}=[redacted]`:t,c=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:i,normalizedDisplay:c,sourceDisplay:s}}function Va(e){let t=e.commandName;if(!t)return;let n=e.trace.find(l=>l.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(l=>l.length>0),r=o.length>0?o.join(" "):"the canonical flag",a=qa.has(t)||Wc.has(t),i=a?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=a?"mutating option":"option",c=Kc({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new C(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:i,examples:[O(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:O(c.argv)}})}function Yc(e){return async t=>{let n=yt(t.errorCode),o=Et({ok:!1,errorCode:t.errorCode,errorCategory:n});return await vo({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Oe,pm_root:e.bootstrapPmRoot,error_code:t.errorCode,error_message:t.errorMessage,exit_code:t.exitCode,error_category:n,command_resolution:o,resolution_stage:t.resolutionStage}),{errorCategory:n,commandResolution:o}}}async function Ka(e){if(e.bootstrapGlobal.noExtensions)return;let t=$e(e.invocationArgv),n=await ut(e.bootstrapPmRoot);if(n&&mt(n.discovery,t)){let o=await le(e.bootstrapPmRoot,t);Ya(o);return}n&&pt(Rn(e.invocationArgv),n,t),B({overrides:[]})}function Ya(e){if(!e){B({overrides:[]});return}B(e.services)}async function Mn(e){ge(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await Re({ok:!1,error:e.errorMessage,exit_code:e.exitCode,error_code:e.classificationCode,error_category:e.errorCategory,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage})}async function Ja(){ge(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await Re({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function Xa(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof C)&&(Ft(e.error)||!n))return!1;let o=Y(e.error),r=e.error instanceof C?e.error.exitCode:Nt(t),a=e.error instanceof C?e.error.context:void 0,i=ea(a,e.invocationArgv,o),s=dr(o,i),c=e.bootstrapGlobal.lean?et(Zt(o,r,i)):Zt(o,r,i),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?lo(c,u=>`${JSON.stringify(u,null,2)}
|
|
28
|
-
`):c,null,2):lr(o,i);y(l);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await ct({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:r,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:N?.source_context});return await Mn({errorMessage:o,exitCode:r,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(Tt(Mt(e.error,o)),await he(Sn)),process.exitCode=r,!0}async function Qa(e,t){let n=dn(e.invocationArgv),o=`unknown command '${n}'`,r=k(process.cwd(),e.bootstrapGlobal.path),a=await Pa(r),i=$e(e.invocationArgv),s=await gn(r,{},Ie(i)),c=await Ee({message:o},
|
|
22
|
+
${o}`}function dn(e){return P(e).commandPathTokens[0]??E(e)??"<command>"}function Ms(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let r=o.shift();if(!r)continue;let a=$(I(r)),i=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!i&&n.add(a),o.push(...r.commands)}for(let r of t.keys()){let a=$(r),i=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!i&&n.add(a)}return[...n].sort((r,a)=>r.localeCompare(a))}function Lr(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let r=n.split(" ");if(n===o)return 0;if(r.includes(o))return 1;if(r.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let a=o.length>=5?2:1,i=Number.POSITIVE_INFINITY;for(let s of r){let c=_t(s,o,a);c!==null&&(i=Math.min(i,c))}return Number.isFinite(i)?4+i:Number.POSITIVE_INFINITY}function Dr(e){return M(e).slice(2).replace(/-/g,"")}function mn(e){return O(e)}function Ls(e){let t=e.split(" ")[0]?.trim().toLowerCase();if(!t)return null;let n=Ps[t];return n?`If this command comes from an optional package, install it with: pm install ${n}`:null}function Ur(e){let t=To(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function Ds(e,t){let n=Ur(e);if(n.length===0)return[];let o=[];for(let r of t.values()){let a=new Set,i=r.source;if(i)for(let c of[i.name,i.package]){let l=Ur(c??"");l.length>0&&a.add(l)}if(a.size===0)continue;[...a].some(c=>c===n||c.includes(n)||n.includes(c))&&o.push(r.command)}return[...new Set(o)].sort((r,a)=>r.localeCompare(a))}function ke(e,t){let n=new Set,o=t??We(e);for(let r of o){r.flag.startsWith("--")&&n.add(M(r.flag));for(let a of r.aliases??[])a.startsWith("--")&&n.add(M(a))}return[...n].sort((r,a)=>r.localeCompare(a))}function Us(e,t){if(!e.startsWith("--"))return[];let n=Dr(e);if(n.length===0)return[];let o=n.length>=8?2:1,r=[];for(let a of t){let i=Dr(a);if(i===n)continue;if(n.length>=3&&i.startsWith(n)){r.push({flag:a,rank:0,distance:i.length-n.length});continue}let s=_t(n,i,o);s===null||s<=0||r.push({flag:a,rank:1,distance:s})}return r.sort((a,i)=>a.rank!==i.rank?a.rank-i.rank:a.distance!==i.distance?a.distance-i.distance:a.flag.localeCompare(i.flag)).map(a=>a.flag).slice(0,3)}var at,js=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function qs(){if(at)return at;let e=new Map;for(let t of qe)if(!js.has(t))for(let n of ke(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return at=e,at}function zs(e,t){if(!e.startsWith("--"))return[];let n=qs().get(M(e));if(!n)return[];let o=t?.trim().toLowerCase(),r=new Set(ke(o));return n.filter(a=>a!==o).map(a=>({command:a,sharedFlagCount:ke(a).filter(i=>r.has(i)).length})).sort((a,i)=>a.sharedFlagCount!==i.sharedFlagCount?i.sharedFlagCount-a.sharedFlagCount:a.command.localeCompare(i.command)).map(({command:a})=>a)}function Hs(e,t,n){for(let o=0;o<e.length;o+=1){let r=e[o];if(!r.startsWith("--"))continue;let a=r.indexOf("="),i=a>=0?r.slice(0,a):r;if(M(i)!==M(t))continue;let s=[...e];return s[o]=a>=0?`${n}${r.slice(a)}`:n,s}}function Gs(e){let t=new Set(e.commandPaths),n=a=>Math.min(Lr(a,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?Lr(a,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,r=(a,i)=>{if(!Number.isFinite(i)||!t.has(a))return;let s=o.get(a);(s===void 0||i<s)&&o.set(a,i)};for(let a of e.commandPaths)r(a,n(a));for(let[a,i]of Object.entries(io))a!=="read"&&r(i,n(a));return[...o.entries()].sort(([a,i],[s,c])=>i!==c?i-c:a.localeCompare(s)).map(([a])=>a)}function Ws(e){let t=qo(e.commandPaths,e.primaryToken),n=Gs(e),o=Ds(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return jr([...t,...n,...o])}function Bs(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function Vs(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help"])]:[...new Set(["pm --help",...n])]}function pn(e,t,n){let o=e.match(/unknown command '([^']+)'/i);if(!o||typeof o[1]!="string")return;let r=$(o[1]);if(r.length===0)return;let a=Ms(t,n);if(a.length===0)return;let i=r.split(" ")[0],s=Ws({commandPaths:a,normalizedUnknown:r,primaryToken:i,extensionDescriptors:n}),c=Bs(a),l=(s.length>0?s:c).slice(0,3),d=Vs(l,s.length>0),m=Ls(r),p=s.length>0?`Did you mean: ${l.join(", ")}?`:null;return{unknownCommandExamples:d,unknownCommandNextSteps:[...p?[p]:[],'Run "pm --help" to list commands available in this runtime, including active extensions.',"Use one of the suggested command paths above with --help to inspect valid flags and usage.",...m?[m]:[]]}}function jr(e){return Array.from(new Set(e))}function Ks(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
|
|
23
|
+
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function Ys(e){let t=e.length;for(;t>0;){let n=e[t-1];if(n!==","&&n!==":"&&n!==";")break;t-=1}return e.slice(0,t)}function Js(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(a=>a.trim().toLowerCase()===n))}function qr(e,t){if(t.length===0)return!0;let n=e,o=!1;for(let r of t){let a=Js(n,r);if(!a)return o;o=!0,n=a}return o}async function Xs(e,t,n,o){try{let r=k(process.cwd(),e.path);if(!await U(j(r)))return{allowedTypes:Ce};let a=await R(r),i=e.noExtensions?void 0:K(),s=V(a,i),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let l=n.findIndex(m=>m===o),d=n[l+2];if(n[l+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{c=(await ze(r,d,a.id_prefix,a.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Ce,pmRoot:r,settings:a,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:Ce}}}function Qs(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?jr([...Fs(t,n[1]),...Us(n[1],ke(t))]):void 0,r=n?zs(n[1],t):[],a=n!==null&&ke(t).includes(M(n[1]));return{match:n,suggestions:o,otherCommands:r,scope:a?"declared_on_path":r.length>0?"declared_elsewhere":"declared_nowhere"}}function Zs(e,t,n){if(!t||!n||n.length===0)return;let o=Hs(e,t[1],n[0]);return o?mn(o):void 0}function ec(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Ys(Ks(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let r=E(t);if(r)return Uo(t,r,[o])}function tc(e,t){if(!/too many arguments/i.test(e)||E(t)!=="schema")return;let n=Fo(t),o=t[n+1]?.trim().toLowerCase(),r=t[n+2]?.trim().toLowerCase();if(!o||!r)return;let a=`${o}-${r}`;if(!Mr.includes(a))return;let i=[...t.slice(0,n+1),a,...t.slice(n+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${o} ${r}`,unknownSubcommandAllowedValues:[...Mr],suggestedRetryCommand:mn(i)}}async function Ee(e,t,n,o={}){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",i=Ye(process.argv.slice(2)).argv,s=q(i),c=E(i),l=mn(i),d=X(i),m=await Xs(s,a,i,c),p=m.allowedTypes,u=pn(a,t,n),f=Qs(a,c),h=tc(a,i),w=h?.suggestedRetryCommand??Zs(i,f.match,f.suggestions)??ec(a,i);return{message:a,commandName:c,allowedTypes:p,attemptedCommand:l,normalizedInvocationArgs:[...i],providedOptionFlags:d,unknownOptionSuggestions:f.suggestions,unknownOptionOtherCommands:f.otherCommands.length>0?f.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:f.otherCommands.length>0?f.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:f.otherCommands.length>12||void 0,unknownOptionScope:f.scope,suggestedRetryCommand:w,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function un(e,t,n,o={}){let r=await Ee(e,t,n,o),{message:a,commandName:i,allowedTypes:s,unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:w,unknownOptionScope:v,unknownSubcommandPath:D,unknownSubcommandToken:W,unknownSubcommandAllowedValues:te,suggestedRetryCommand:gt,verifiedCollectionItemId:Pe,failedExtensions:Ne}=r,de=mr(a,i,s,{unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:w,unknownOptionScope:v,unknownSubcommandPath:D,unknownSubcommandToken:W,unknownSubcommandAllowedValues:te,suggestedRetryCommand:gt,verifiedCollectionItemId:Pe,failedExtensions:Ne}),ht=await ro("help_format",{message:de,command:i,allowed_types:s});return ht.handled&&typeof ht.result=="string"?ht.result:de}async function fn(e,t,n,o=!1,r={}){let a=await Ee(e,t,n,r),i=ot(a.message,a.commandName,a.allowedTypes,g.USAGE,{unknownCommandExamples:a.unknownCommandExamples,unknownCommandNextSteps:a.unknownCommandNextSteps,attemptedCommand:a.attemptedCommand,normalizedInvocationArgs:a.normalizedInvocationArgs,providedOptionFlags:a.providedOptionFlags,unknownOptionSuggestions:a.unknownOptionSuggestions,unknownOptionOtherCommands:a.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:a.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:a.unknownOptionOtherCommandsTruncated,unknownOptionScope:a.unknownOptionScope,unknownSubcommandPath:a.unknownSubcommandPath,unknownSubcommandToken:a.unknownSubcommandToken,unknownSubcommandAllowedValues:a.unknownSubcommandAllowedValues,suggestedRetryCommand:a.suggestedRetryCommand,verifiedCollectionItemId:a.verifiedCollectionItemId,failedExtensions:a.failedExtensions});return JSON.stringify(o?et(i):i,null,2)}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]="f3543bab-fa67-5e91-a700-0cbee84f2dc8")}catch{}})();async function gn(e,t={},n=[]){let o={readSettings:R,loadExtensions:pe,activateExtensions:ue,resolveImplicitPmRoot:xt,...t};try{let r=await o.readSettings(e),a=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),i=await o.activateExtensions(a);return[...a.failed,...i.failed].map(s=>{let c=(a.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map($).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map($),m=l.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...l.length>0?{declared_commands:l}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function zr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await gn(t,n,o),a={readSettings:R,loadExtensions:pe,activateExtensions:ue,resolveImplicitPmRoot:xt,...n};try{let i=a.resolveImplicitPmRoot(process.cwd());if(ie.resolve(i)===ie.resolve(t))return r;let[s,c]=await Promise.all([a.readSettings(t),a.readSettings(i)]),[l,d]=await Promise.all([a.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),a.loadExtensions({pmRoot:i,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(d.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,f)=>u.localeCompare(f));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${ie.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${ie.resolve(i)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${ie.resolve(i)}, or install the extension into the selected tracker with "pm --pm-path ${ie.resolve(t)} install <package> --project".`})}catch{}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="abdb8d3e-8c1b-511e-b25b-220d5a40ae3f")}catch{}})();function nc(e,t){if(t.length===0)return e;let n=ae(e,t);if(n)return n;let o=t.join(" ");if(!qe.some(r=>r===o)&&!Co(o)&&!we(o))return null;for(let r=t.length-1;r>0;r-=1){let a=ae(e,t.slice(0,r));if(a)return a}return t.length===1?e:null}function oc(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Hr(e){let t=e;if(typeof t.attributeName=="function"){let n=t.attributeName();return typeof n=="string"&&n.trim().length>0?n.trim():null}return typeof t.attributeName=="string"&&t.attributeName.trim().length>0?t.attributeName.trim():null}function rc(e){let t=new Map;for(let n of e){let o=n,r=Hr(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let a=t.get(r)??[];a.push(o.long.trim()),t.set(r,a)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,a)=>r.localeCompare(a)));return t}function ac(e){return O(e)}function ic(e){let t=e.options??[],n=rc(t);return t.map(o=>{let r=o,a=typeof r.flags=="string"?r.flags.trim():"",i=typeof r.description=="string"?r.description.trim():"",s=Hr(o),l=(s?n.get(s)??[]:[]).filter(w=>w!==r.long).map(w=>w.trim()).filter(w=>w.length>0),d=i.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,p=r.mandatory===!0||i.includes("[required]")||i.toLowerCase().includes("required;"),u=a.includes("<"),f=u||a.includes("["),h={flags:a,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:i,takes_value:f,value_required:u,value_name:oc(a),variadic:r.variadic===!0,required:p,aliases:l,alias_for:m};return r.defaultValue!==void 0&&(h.default_value=r.defaultValue),h})}function sc(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let r=o.alias_for,a=t.get(r);if(!a)continue;let i=o.long,s=new Set([...a.aliases??[],i]);a.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function cc(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",a=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0||a?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:a}})}function lc(e){return e.createHelp().visibleCommands(e).filter(t=>t.name()!=="help"||e.parent===null).map(t=>{let n=$(I(t)).split(" ")[0];return{name:t.name().trim(),aliases:rn(t),description:t.description().trim(),tier:Ke(n),family:Ve(n)}}).sort((t,n)=>t.name.localeCompare(n.name))}function dc(e,t,n){if(!n)return t;let o=n.examples??[],r=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?r.length>0?[...r]:[...t.tips]:[],detail_mode:e}}function mc(e,t,n,o){if(!e){let a=cc(t),i=lc(t),s=new Set(i.map(({name:c})=>c));return{arguments:a,options:o,subcommands:[...i,...He.filter(({parent:c,action:l})=>c===n&&!s.has(l)).map(({action:c,description:l})=>({name:c,aliases:[],description:l,tier:Ke(n.split(" ")[0]),family:Ve(n.split(" ")[0])}))].sort((c,l)=>c.name.localeCompare(l.name)),usage:[n,a.reduce((c,l)=>l.required?c.replace(`[${l.name}${l.variadic?"...":""}]`,`<${l.name}${l.variadic?"...":""}>`):c,t.usage())].filter(c=>c.length>0).join(" ")}}let r=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:a,required:i,variadic:s,value_kind:c,polymorphic:l})=>({name:a,required:i,variadic:s,description:l?`Polymorphic ${c} value; inspect the action contract before mutation.`:`${c.replaceAll("_"," ")} value.`})),options:o.filter(({long:a,aliases:i})=>a!==null&&r.has(a)||i.some(s=>r.has(s))),subcommands:[],usage:[e.command,...e.slots.map(({name:a,required:i,variadic:s})=>{let c=s?`${a}...`:a;return i?`<${c}>`:`[${c}]`})].join(" ")}}function pc(e,t,n,o,r){let a=Ht(n),i=$(I(t)),s=$(o.join(" ")),c=s.length>i.length?s:i,l=we(c),d=l?.command??c,m=d.length>0?d:void 0,p=m?.split(" ")[0],u=Qo(m,a),f=m?r.get(m):void 0,h=dc(a,u,f),w=sc(Sr(ic(t),Er(f))),v=mc(l,t,d,w);return{format:"pm_help_v1",detail_mode:a,root_command:e.name(),requested_path:o,resolved_path:d.length>0?d:e.name(),visibility_tier:p===void 0?null:Ke(p),capability_family:p===void 0?null:Ve(p),description:l?.description??t.description(),usage:v.usage,intent:l?.description??h.intent,examples:l?[l.example]:h.examples,tips:l?[Ge(l.accepted_flags)]:h.tips,arguments:v.arguments,options:v.options,subcommands:v.subcommands,has_subcommands:v.subcommands.length>0}}async function Gr(e,t,n){let o=q(t);if(!o.json)return!1;let r=P(t);if(!r.requested)return!1;let a=nc(e,r.commandPathTokens);if(!a){if(!o.quiet){let i=`unknown command '${r.commandPathTokens.join(" ")}'`,s=pn(i,e,n),c=ot(i,"help",Ce,g.USAGE,{...s,attemptedCommand:ac(t),normalizedInvocationArgs:[...t],providedOptionFlags:X(t)});y(JSON.stringify(c,null,2))}return process.exitCode=g.USAGE,!0}if(!o.quiet){let i=pc(e,a,t,r.commandPathTokens,n);mo(`${JSON.stringify(i,null,2)}
|
|
24
|
+
`)}return process.exitCode=g.SUCCESS,!0}function uc(e,t){let n=["","Type-aware option policies:"," pass --type <value> with --help to render required/disabled/hidden option policy details for that type.",` active type values: ${t.types.join("|")}`];return e==="create"&&n.push(" scheduling shortcut: use --schedule-preset lightweight for Reminder/Meeting/Event minimal create flows."),n.join(`
|
|
25
|
+
`)}function fc(e,t){if(t.options.length===0){e.push(" type options: none");return}e.push(" type options:");for(let n of t.options){let o=n.required?" (required)":"",r=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${r.length>0?r.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function gc(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let r of[...t.required_create_fields,...t.required_create_repeatables])o.add(r);return{progressive:n,strict:o}}function hc(e,t,n,o){let r=new Set(n),a=o.filter(c=>!r.has(c)),i=c=>c.length>0?c.map(l=>bt("create",l)).join(", "):"none";e.push(` required in strict mode: ${i(a)}`);let s=a.map($o).filter(c=>c!==void 0);e.push(` explicit empty assertion: ${s.length>0?s.join(", "):"none"}`),["Reminder","Meeting","Event"].includes(t.name)&&(e.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy."),e.push(" strict parity remains available via --create-mode strict."))}function yc(e,t,n){let o=Lo(n);if(!o)return uc(e,t);let r=zn(o,t);if(!r){let h=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${h}`].join(`
|
|
26
|
+
`)}let a=n.indexOf("--"),i=a<0?n:n.slice(0,a),s=i.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),c=s<0?void 0:i[s]?.startsWith("--create-mode=")?i[s]?.slice(14):i[s+1],l=e==="create"&&c?.toLowerCase()==="strict",d=gc(e,r),m=Fe(r,e,d.progressive),p=Fe(r,e,l?d.strict:d.progressive),u=h=>h.length>0?h.map(w=>bt(e,w)).join(", "):"none",f=["",`Type-aware option policies for ${r.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let h=Fe(r,e,d.strict);hc(f,r,m.required,h.required)}return fc(f,r),p.errors.length>0&&f.push(` config errors: ${p.errors.join("; ")}`),f.join(`
|
|
27
|
+
`)}function Wr(e,t,n){let o=E(n);if(o!=="create"&&o!=="update")return;let r=ve(e,o);r&&r.addHelpText("after",yc(o,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]="fa92f987-990a-5159-8c45-f055d5a15da2")}catch{}})();async function Br(e,t,n,o){if(n)return null;let r=e.some(i=>i==="--for"||i.startsWith("--for=")),a=E(e)==="contracts"&&e.includes("--full");return r||a?await o(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27eeca2d-756c-539b-a0d4-d64516ee4aa6")}catch{}})();var hn="PM_CLI_PACKAGE_ROOT";function wc(){return Un(import.meta.url,["../.."])}(typeof process.env[hn]!="string"||process.env[hn]?.trim().length===0)&&(process.env[hn]=wc());var ce=null,N=null;function _c(e){ce=e}function bc(e){T=e}var xc=new Set(["success","nonexistent_command","invalid_option","missing_required_option","missing_required_argument","invalid_usage","validation_failed","health_findings","validation_findings","conflict","runtime_failed","unknown_failed"]),vc=new Set(["parse","preflight","execute","unknown"]),Cc=new Set(["usage","validation","conflict","runtime","unknown"]),Se=null,ee=null,T=new Map,Sn=250,kc=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),Ec=new Set(["1","true","yes","on"]),Sc=ye(()=>import("./chunks/register-setup-HXU7IZZD.js")),Ac=ye(()=>import("./chunks/register-list-query-F57EWDEF.js")),Tc=ye(()=>import("./chunks/register-mutation-7IY2D5KO.js")),Oc=ye(()=>import("./chunks/register-operations-FALL3YTU.js"));function st(e){return O(e)}function Zr(e){let t=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!t||t.length===0)return;let n=[...new Set(t.map(o=>J(o)??o))];return n.length>0?n:void 0}function Rc(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=X(t),r=new Set(o.map(d=>J(d)??d)),a=Zr(e),i=t.find(d=>b.commands.some(m=>m.name()===d)),s=i?b.commands.find(d=>d.name()===i):void 0,c=new Set([...b.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>J(m)).filter(m=>m!==void 0))),l=a?.filter(d=>{let m=J(d)??d;return r.has(m)?!1:c.has(m)||tn(t,i,m,T)!==void 0});return l&&l.length>0?l:void 0}function Ic(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],a=r?J(r):void 0,i=e.find(p=>b.commands.some(u=>u.name()===p)),s=i?b.commands.find(p=>p.name()===i):void 0,c=a?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(a)):void 0,l=tn(e,i,a,T),d=a?c?.isBoolean()===!0||l===!1?[a]:[a,"<value>"]:[],m=a?st([...e,...d]):t;return m===t?void 0:m}function $c(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let r=e[o];r!=null&&(n[o]=r)}return n}function Pc(e){let t=e.existingRecovery;return{attempted_command:t?.attempted_command??e.attemptedCommand,normalized_args:t?.normalized_args??[...e.invocationArgv],provided_fields:t?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:t?.missing??e.inferredMissing,...$c(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function ea(e,t,n){let o=je(t),r=o.includes("--explain"),a=e?.recovery,i=a&&o.includes("history-redact")?{...a,...a.attempted_command?{attempted_command:st(o)}:{},...a.normalized_args?{normalized_args:[...o]}:{},...a.suggested_retry?{suggested_retry:st(o)}:{},...a.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:a;if(i?.recovery_mode==="compact"&&!r)return{...e,recovery:i};let s=st(o),c=X(o),l=Rc(n,o,i),d=Ic(o,s,l,i),m=Pc({invocationArgv:o,attemptedCommand:s,providedFields:c,inferredMissing:l,suggestedRetry:d,existingRecovery:i});return{...e,recovery:m}}function se(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let r=o.trim();if(r.length>0)return r}}}function ta(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function An(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return Math.max(0,Math.trunc(o))}}function na(e){if(!e)return;let t=e.trim().toLowerCase();if(xc.has(t))return t}function oa(e){if(!e)return;let t=e.trim().toLowerCase();if(vc.has(t))return t}function ra(e){if(!e)return;let t=e.trim().toLowerCase();if(Cc.has(t))return t}function aa(e){let t=se(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let i=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof i=="string")return i.trim()}if(ta(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=An(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let a=e?.run_results;if(Array.isArray(a)){let i=a.filter(s=>wt(s)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function ia(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function sa(){let e=wt(fe()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=An(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,r=Io(o),a=se(e,"error_code","errorCode")??ia(r,o),i=ra(se(e,"error_category","errorCategory"))??(r?void 0:yt(a)),s=r?void 0:aa(e)??`command_exit_${o}`,c=na(se(e,"command_resolution","commandResolution"))??Et({ok:r,errorCode:a,errorCategory:i}),l=oa(se(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:a,error_category:i,command_resolution:c,resolution_stage:l}}async function Re(e){let t=N;N=null,await er(t,e);let n=ce;if(ce=null,!n){Le();return}let o=[],r=no();try{await tr({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(a=>a.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Bn(n.hooks,{command:n.commandName,args:n.commandArgs,options:{...n.commandOptions},global:{...n.globalOptions},pm_root:n.pmRoot,ok:e.ok,error:e.error,result:fe(),affected:r}))}catch(a){o=[`afterCommand hooks failed: ${a instanceof Error?a.message:String(a)}`]}finally{Le()}!n.globalOptions.json&&o.length>0&&y(`[pm] warning: afterCommand hook_warnings=${F(o)}`),n.profileEnabled&&o.length>0&&y(`profile:extensions hook_warnings=${F(o)}`)}async function ca(){await go()}function la(e){return Ec.has((process.env[e]??"").trim().toLowerCase())}function da(e){return la("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!kc.has(Math.trunc(e))}async function ct(e){return da(e.exit_code)?(await ca(),ho(e),!0):!1}async function ma(e){let t=Y(e.error),n=fr(t);e.bootstrapGlobal.json?y(JSON.stringify(pr(t,g.GENERIC_FAILURE),null,2)):y(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await ca(),Tt(e.error);let a=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=a.errorCategory,r=a.commandResolution,ge(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||y(`Failed to report error: ${Y(a)}`)}try{await Re({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${Y(a)}`)}try{await he()}catch(a){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${Y(a)}`)}}function Vr(e,t,n,o){let r=n.outputInclude;if(r===void 0)return;let a={},{selectors:i,modes:s}=co(t,r,a);if(s.length===0)return;for(let[l,d]of Object.entries(a))o[l]=d,e.setOptionValueWithSource(l,d,"cli");let c=i.length>0?i.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let l=e;l;l=l.parent)l.setOptionValueWithSource("outputInclude",c,"cli");Rt(e,n)}function Ae(e,t,n=[]){let r={...e.optsWithGlobals()};delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession;let a=Vo(t);for(let[i,s]of Object.entries(a))r[i]===void 0&&(r[i]=s);if(n.length>0){let i=Go(n),s=We(I(e)).map(l=>({long:l.flag,short:l.short,aliases:l.aliases})),c={...a};for(let l of i)r[l]!==void 0&&(c[l]=r[l]);return Ut(c,[...s,...n],I(e)),Bo(r,n,a)}return r}function _n(e,t){let n=_(t);return n.length===0?[]:e.flags.filter(o=>_(o.target_command)===n).flatMap(o=>o.flags)}function lt(e,t,n){let o=_n(e,t),r=[t],a=[];for(let i of n){if(i.startsWith("-"))break;r.push(i);let s=_n(e,r.join(" "));s.length>0&&(a=s)}return a.length>0?a:o}function Tn(e){return e.arguments??[]}function Kr(e){let t=Tn(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function pa(e,t){if(!e)return!1;let n=_(t);return e.importers.some(o=>_(`${o.importer} import`)===n)||e.exporters.some(o=>_(`${o.exporter} export`)===n)}function ua(e,t){let n=Tn(e),o=n.filter(c=>c.required).length,a=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,i=e.failure_hints??[],s=i.length>0?` ${i.join(" ")}`:"";if(t.length<o)throw new C(`Missing required argument for extension command '${e.command}'. Usage: ${Kr(e)}${s}`,g.USAGE);if(t.length>a){let c=t.slice(a).join(" ");throw new C(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${Kr(e)}${s}`,g.USAGE)}}function Nc(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Fc(e,t,n){if(n.length>0){Ut(t,n,e.command);return}let o=Object.keys(t).filter(r=>t[r]!==void 0).sort();if(o.length!==0)throw new C(`Unknown option '${o.map(Nc).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function fa(e,t,n,o){e&&(ua(e,t),Fc(e,n,o))}var Mc={create:"create",update:"update","update-many":"update_many",list:"list","list-all":"list","list-draft":"list","list-open":"list","list-in-progress":"list","list-blocked":"list","list-closed":"list","list-canceled":"list",search:"search",calendar:"calendar",context:"context","templates save":"create"},yn=new Map;function bn(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function ga(e,t){return e.options.some(n=>n.long===t)}function ha(e,t){return e.options.some(n=>n.short===t)}function xn(e,t,n,o){let r=t.trim();if(!r)return;let a=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(ha(e,r))return;if(o){e.option(`${r} <value>`,`${a} (repeatable)`,$t);return}e.option(`${r} <value>`,a);return}let i=r.startsWith("--")?r:`--${r}`;if(!ga(e,i)){if(o){e.option(`${i} <value>`,`${a} (repeatable)`,$t);return}e.option(`${i} <value>`,a)}}async function ya(e,t){let n=Mc[e];if(!n)return[];let o=`${t}:${n}`,r=yn.get(o);if(r)return r;if(!await U(j(t)))return yn.set(o,[]),[];let a=await R(t),s=(Ct(a.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:bn(c.type),value_type:bn(c.type)})));return yn.set(o,s),s}async function wa(e,t){let n=q(t),o=k(process.cwd(),n.path);if(!await U(j(o)))return;let r=ee?.key===In(o)?ee.snapshot:null,a=r===null?await R(o):r.settings,i=Ct(a.schema),s=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(let c of s){let l=ae(e,c.path.split(" "));if(l)for(let d of i.command_to_fields.get(c.command)??[]){let m=d.description??"";xn(l,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)xn(l,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function On(e,t,n,o,r){let a=E(n);if(!(a!=="create"&&a!=="update"))try{let i=r??await R(t),s=V(i,o);Wr(e,s,n)}catch{}}function vn(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function _a(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Rn(e){return e.some(t=>t==="--profile")}function In(e){return`pm-root:${e}`}function ba(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=_(n);o.length!==0&&t.push(o)}return t}function Ie(e){let t=_(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(r=>r.length>0);for(let r of ba(e.commandArgs))o.push(...r.split(" ").filter(a=>a.length>0)),n.push(o.join(" "));return[...new Set(n)]}function xa(e,t){let n=_(e);if(n.length===0)return!1;let o=Ie(t);for(let r of o)if(r===n||r.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(r=>n.startsWith(`${r} `)):!1}function $n(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...S(n.commands),...S(n.command_handlers),...S(n.command_overrides),...S(n.flag_commands),...S(n.parser_overrides),...Yr(n.preflight_ownership),...Yr(n.renderer_ownership)]:[]}function S(e){return e??[]}function Yr(e){return S(e).flatMap(t=>t.commands)}function dt(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var va=new Set(["hooks","parser","preflight","renderers"]),Ca=new Set(["commands","schema","services","importers"]),Lc=new Set(["reindex","search","search-advanced"]),Dc=new Set(["--template"]);function Te(e,t){for(let n of t)if(e.has(n))return!0;return!1}function ka(e){let t=_(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return Lc.has(n??t)}function Ea(e,t){for(let n of e.commandArgs??[]){if(!n.startsWith("--"))continue;let[o]=n.split("=",1);if(t.has(o))return!0}return!1}function Pn(e){return _(e.commandPath??"")==="create"&&Ea(e,Dc)}function Sa(e){return e.some(t=>{let n=_(t);return n==="templates"||n.startsWith("templates ")})}function Cn(e,t){return e.some(n=>xa(n,t))||Pn(t)&&Sa(e)}function Aa(e){return[S(e.hooks).length,(e.preflight_overrides??0)-S(e.preflight_ownership).length,S(e.item_types).length,S(e.item_fields).length,S(e.relationship_kinds).length,S(e.service_overrides).length,S(e.assurance_providers).length,S(e.renderer_overrides).length-S(e.renderer_ownership).length].some(n=>n>0)}function Ta(e,t){let n=e.activation?.commands??[];if(n.length>0)return Cn(n,t);let o=$n(e);if(Cn(o,t)||dt(e).has("search")&&ka(t.commandPath))return!0;if(e.contributions)return Aa(e.contributions)}function Nn(e,t){let n=Ta(e,t);if(n!==void 0)return n;let o=dt(e);return!!(Te(o,va)||Te(o,Ca))}function mt(e,t){return e.effective.length===0?!1:_(t.commandPath??"").length>0?e.effective.some(o=>Nn(o,t)):e.effective.some(o=>{let r=dt(o);return $n(o).length>0||Te(r,va)||Te(r,Ca)||r.has("search")})}function Fn(e){let t=Ie(e).filter(r=>r.split(" ").every(a=>!a.startsWith("-"))).sort((r,a)=>a.length-r.length)[0]??_(e.commandPath??"");if(t.length===0)return"all";let n=Pn(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Oa(e){return Fn(e)==="all"?void 0:t=>Nn(t,e)}function $e(e){let t=P(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...a]=t.commandPathTokens;return{commandPath:r,commandArgs:a,allowCommandPrefixMatch:!0}}let n=No(e),o=n.findIndex(r=>r.trim().length>0&&!r.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Ra(e){let t=e.args.map(String);if(_(I(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function kn(e){for(let t of e)t.startsWith("settings_read_")&&y(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Ia(e,t){e.profile&&(y(`profile:extensions loaded=${t.loadedCount} failed=${t.loadFailedCount} warnings=${t.loadWarnings.length} activation_failed=${t.activationFailedCount} hook_counts=before:${t.hooks.beforeCommand.length}|after:${t.hooks.afterCommand.length}|write:${t.hooks.onWrite.length}|read:${t.hooks.onRead.length}|index:${t.hooks.onIndex.length} command_overrides=${t.commands.overrides.length} command_handlers=${t.commands.handlers.length} parser_overrides=${t.parsers.overrides.length} preflight_overrides=${t.preflight.overrides.length} service_overrides=${t.services.overrides.length} renderer_overrides=${t.renderers.overrides.length}`),t.activationWarnings.length>0&&y(`profile:extensions activation_warnings=${F(t.activationWarnings)}`))}function pt(e,t,n){if(!e)return;let o=_(n.commandPath??"")||"<none>";y(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function ut(e,t=oe){let n=In(e);if(ee?.key===n)return ee.snapshot;try{let o=Date.now(),{settings:r,warnings:a}=await t(e),i=await Vn({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:i,discoveryMs:Date.now()-o,settingsReadWarnings:[...a]};return ee={key:n,snapshot:s},s}catch{return ee={key:n,snapshot:null},null}}async function le(e,t,n=R){let o=t?Fn(t):"all",r=_a(e,o);if(Se?.key===r)return Se.snapshot;try{let a=await n(e),i=await pe({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Oa(t):void 0}),s=await ue({...i,loaded:i.loaded}),c=[...new Set(s.commands.handlers.map(u=>_(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),l=wr(s.registrations.flags),d=hr(s.commands.handlers,s.registrations.commands),m=br(c,s.registrations.commands,s.registrations.flags,d),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:a,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...i.warnings],activationWarnings:[...s.warnings],loadedCount:i.loaded.length,loadFailedCount:i.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:i.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return Se={key:r,snapshot:p},p}catch{return Se={key:r,snapshot:null},null}}async function $a(e){let t=_e(e);if(t.noExtensions){let i=k(process.cwd(),t.path);return await U(j(i))&&kn((await oe(i)).warnings),null}let n=k(process.cwd(),t.path),o=await ut(n);if(!o)return null;kn(o.settingsReadWarnings);let r={commandPath:I(e),commandArgs:Ra(e)};if(!mt(o.discovery,r))return pt(t.profile,o,r),null;let a=await le(n,r);return a?(Ia(t,a),{hooks:a.hooks,commands:a.commands,parsers:a.parsers,preflight:a.preflight,services:a.services,renderers:a.renderers,registrations:a.registrations,pmRoot:n}):null}async function Pa(e){let t=await le(e);return t?new Map(t.commandDescriptors):T}async function Na(e,t){return(await Oo({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function Fa(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return ko(e,Po.forActiveExtensionHost({pmRoot:e,author:n}))}async function Ma(e,t,n,o=[]){let r=I(e),a=jt(e.args.map(String),o),i={...t},s={...n},c=k(process.cwd(),n.path),l=await De({command:r,args:a,options:i,global:s,pm_root:c});n.profile&&l.warnings.length>0&&y(`profile:extensions parser_warnings=${F(l.warnings)}`),a=l.context.args,i=l.context.options,s=l.context.global,fa(T.get(_(r)),a,i,o),ne(void 0),Me({command:r,args:a,options:{...i},global:{...s},pm_root:c});let d=await vt({command:r,args:a,options:i,global:s,pm_root:c,sdk:Fa(c,s)});if(s.profile&&d.warnings.length>0&&y(`profile:extensions command_handler_warnings=${F(d.warnings)}`),!d.handled){if(d.warnings.length>0){let m=d.warnings[0],p=d.errorMessage?.trim(),u=p?` ${p}`:"";throw new C(`Command "${r}" failed in extension handler (${m}).${u}`,g.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new C(`Command "${r}" is provided by extensions and is not currently available.`,g.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),ne(d.result),d.result}var Jr=Symbol("pm.wrappedActionHandler");function Uc(e,t){let n=e[e.length-1];return n instanceof En?n:t}function Xr(e,t,n){e&&n.length>0&&y(`profile:extensions ${t}=${F(n)}`)}function jc(e){let t=T.get(_(e.commandPath));if(!t||!pa(e.activeRegistrations,e.commandPath))return;let n=Tn(t).length===0?Ko(e.commandArgs):jt(e.commandArgs,e.extensionFlagDefinitions);ua(t,n)}function qc(e,t,n){e.args=[...n],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),t.length>0&&Array.isArray(t[0])&&(t[0]=[...e.processedArgs])}function La(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[Jr]!==!0){let r=o._actionHandler;o._actionHandler=async function(...i){let s=Uc(i,n),c=Date.now();It(s);let l=_e(s),d=I(s),m=k(process.cwd(),l.path),p=s.args.map(String),u=K(),f=u?lt(u,d,p):[],h=await ya(d,m),w=Ae(s,p,[...f,...h]),v=await De({command:d,args:p,options:w,global:l,pm_root:m});Xr(l.profile,"parser_warnings",v.warnings),p=v.context.args,w=v.context.options,l=v.context.global,jc({activeRegistrations:u,commandPath:d,commandArgs:p,extensionFlagDefinitions:f}),l=await So(l),Rt(s,l),qc(s,i,p),Be(s,w),ne(void 0),Me({command:d,args:p,options:{...w},global:{...l},pm_root:m});let D=await vt({command:d,args:p,options:w,global:l,pm_root:m,sdk:Fa(m,l)});if(Xr(l.profile,"command_handler_warnings",D.warnings),D.handled){ne(D.result),kt(D.result,{...l,command:d,commandArgs:p,commandOptions:w,pmRoot:m}),l.profile&&y(`profile:command=${d} took_ms=${Date.now()-c}`);return}return await r.apply(this,i)},o[Jr]=!0}for(let r of n.commands)t(r)};t(e)}async function it(e){T=new Map,B({overrides:[]}),e&&await On(e.rootProgram,e.pmRoot,e.invocationArgv,Gn(),e.settings)}function zc(e,t,n,o){if(t?.flags&&t.flags.length>0){nn(e,t.flags);let r=on(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}async function Da(e,t){let n=q(t),o=k(process.cwd(),n.path);if(n.noExtensions){await it({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await ut(o),a=$e(t);if(!r){await it();return}if(!mt(r.discovery,a)){await it({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),pt(Rn(t),r,a);return}let i=await le(o,a);if(!i){await it({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}B(i.services),T=new Map(i.commandDescriptors),await On(e,o,t,i.registrations,i.settings);let s=Rr(e,i.commandHandlers,i.commandDescriptors,i.commandAliases,l=>Ir(i.activationWarnings,y,l)),c=l=>{let d=l.split(" ").filter(v=>v.length>0),m=i.commandDescriptors.get(l),p=ae(e,d),u=i.commandFlagHelp.get(l),f=m?Ar(m):null;if(p){zc(p,m,u,f);return}let h=Or(e,d);m?.description&&h.description(m.description);let w=u;m&&(xr(h,m),m.flags.length>0&&(nn(h,m.flags),w=on(h,m.flags)??void 0)),w&&h.addHelpText("after",w),f&&h.addHelpText("after",f),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...v)=>{let D=v[v.length-1],W=D instanceof En?D:h,te=_e(W),gt=Date.now(),Pe=lt(i.registrations,l,W.args.map(String)),Ne=Ae(W,W.args.map(String),Pe),de=await Ma(W,Ne,te,Pe);await Ao(te,de),kt(de,{...te,command:l,commandArgs:W.args.map(String),commandOptions:Ne,pmRoot:o}),te.profile&&y(`profile:command=${l} took_ms=${Date.now()-gt}`)})};for(let l of s)c(l)}var Oe=jn(import.meta.url,["../.."])??"0.0.0",b=Lt(Oe);function Ua(e){e.hook("preAction",async(t,n)=>{ce=null,N=null,Le(),It(n);let o=n.optsWithGlobals(),r=_e(n),a=I(n),i=n.args.map(String),s=Ae(n,i),c={...r};so(a,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession,outputCursor:o.outputCursor}),Vr(n,a,c,s),await bo(a,c);let l=k(process.cwd(),r.path),d=await $a(n);if(!d){ce=Kn({commandName:a,commandArgs:i,commandOptions:s,globalOptions:c,pmRoot:l}),N=await Ot({command:a,pm_version:Oe,args:i,options:s,global:c,pm_root:l}),St(a,i,s,{source_context:N?.source_context,source_context_source:N?.source_context_source}),At(a),await cn(a,s,l,vn()),await sn(a,i,s,c,l);return}Yn(d.hooks),Jn(d.commands),Xn(d.parsers),Qn(d.preflight),B(d.services),Zn(d.renderers),eo(d.registrations);let m=lt(d.registrations,a,i);s=Ae(n,i,m),Vr(n,a,c,s);let p=await De({command:a,args:i,options:s,global:c,pm_root:d.pmRoot});c.profile&&p.warnings.length>0&&y(`profile:extensions parser_warnings=${F(p.warnings)}`),i=p.context.args,s=p.context.options,c=p.context.global,Be(n,s);let u=await oo({command:a,args:i,options:s,global:c,pm_root:d.pmRoot,decision:vn()});c.profile&&u.warnings.length>0&&y(`profile:extensions preflight_warnings=${F(u.warnings)}`),i=u.context.args,s=u.context.options,c=u.context.global,Be(n,s);let f=u.decision;await cn(a,s,d.pmRoot,f),await sn(a,i,s,c,d.pmRoot);let h=f.run_extension_migrations?await Na(d.registrations.migrations,d.pmRoot):[];c.profile&&h.length>0&&y(`profile:extensions migration_warnings=${F(h)}`);let w=Nr(d.registrations.migrations);ce={hooks:d.hooks,commandName:a,commandArgs:i,commandOptions:{...s},globalOptions:{...c},pmRoot:d.pmRoot,profileEnabled:!!c.profile,migrationBlockers:w},ne(void 0),Me({command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot}),N=await Ot({command:a,pm_version:Oe,args:i,options:s,global:c,pm_root:d.pmRoot}),St(a,i,s,{source_context:N?.source_context,source_context_source:N?.source_context_source}),At(a);let v=await Wn(d.hooks,{command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot});c.profile&&v.length>0&&y(`profile:extensions hook_warnings=${F(v)}`),f.enforce_mandatory_migration_gate&&Fr(a,s,w)}),e.hook("postAction",async()=>{let t=sa();ge(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await Re(t)})}Ua(b);var Hc=new Set(["--version","-V"]),Gc=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),ja=new Set(["activity","aggregate","context","ctx","events","get","graph","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search"]),qa=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),Wc=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Bc=new Set(["claim","close-task","pause-task","release","start-task","test"]),wn={setup:!0,listQuery:!0,mutation:!0,operation:!0},Vc=new Set(["create","update","update-many","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","search","calendar","context","templates"]);function ft(e){return e.some(t=>Hc.has(t))}function za(e){if(ft(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||P(e).requested)return wn;let t=E(e);if(!t)return wn;let n=t.trim().toLowerCase();return Gc.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:ja.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:qa.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Wc.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:wn}function Ha(e){return e.length===0||P(e).requested}var Qr=Symbol("pmCliIdempotentTopLevelRegistration");function Ga(e){let t=e;if(t[Qr])return;t[Qr]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let a=o.split(/\s+/u)[0];return e.commands.some(i=>i.name()===a||i.aliases().includes(a))?new En(a):n(o,...r)})}async function Kc(e,t){if(Ga(e),t.setup){let{registerSetupCommands:n}=await Sc();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Ac(),o=typeof t.targetCommandName=="string"&&ja.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Tc();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Oc();n(e)}}function Wa(e,t){return ft(t)?!1:P(t).requested?!0:!!E(t)}function Ba(e){if(ft(e))return!1;let t=E(e);return t?Vc.has(t):!1}function Yc(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),a=r?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${r}${l.slice(d)}`:r:l}):e.argv,i=je(a),s=r&&n>=0?`${o}=[redacted]`:t,c=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:i,normalizedDisplay:c,sourceDisplay:s}}function Va(e){let t=e.commandName;if(!t)return;let n=e.trace.find(l=>l.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(l=>l.length>0),r=o.length>0?o.join(" "):"the canonical flag",a=qa.has(t)||Bc.has(t),i=a?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=a?"mutating option":"option",c=Yc({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new C(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:i,examples:[O(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:O(c.argv)}})}function Jc(e){return async t=>{let n=yt(t.errorCode),o=Et({ok:!1,errorCode:t.errorCode,errorCategory:n});return await vo({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Oe,pm_root:e.bootstrapPmRoot,error_code:t.errorCode,error_message:t.errorMessage,exit_code:t.exitCode,error_category:n,command_resolution:o,resolution_stage:t.resolutionStage}),{errorCategory:n,commandResolution:o}}}async function Ka(e){if(e.bootstrapGlobal.noExtensions)return;let t=$e(e.invocationArgv),n=await ut(e.bootstrapPmRoot);if(n&&mt(n.discovery,t)){let o=await le(e.bootstrapPmRoot,t);Ya(o);return}n&&pt(Rn(e.invocationArgv),n,t),B({overrides:[]})}function Ya(e){if(!e){B({overrides:[]});return}B(e.services)}async function Mn(e){ge(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await Re({ok:!1,error:e.errorMessage,exit_code:e.exitCode,error_code:e.classificationCode,error_category:e.errorCategory,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage})}async function Ja(){ge(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await Re({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function Xa(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof C)&&(Ft(e.error)||!n))return!1;let o=Y(e.error),r=e.error instanceof C?e.error.exitCode:Nt(t),a=e.error instanceof C?e.error.context:void 0,i=ea(a,e.invocationArgv,o),s=dr(o,i),c=e.bootstrapGlobal.lean?et(Zt(o,r,i)):Zt(o,r,i),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?lo(c,u=>`${JSON.stringify(u,null,2)}
|
|
28
|
+
`):c,null,2):lr(o,i);y(l);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await ct({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:r,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:N?.source_context});return await Mn({errorMessage:o,exitCode:r,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(Tt(Mt(e.error,o)),await he(Sn)),process.exitCode=r,!0}async function Qa(e,t){let n=dn(e.invocationArgv),o=`unknown command '${n}'`,r=k(process.cwd(),e.bootstrapGlobal.path),a=await Pa(r),i=$e(e.invocationArgv),s=await gn(r,{},Ie(i)),c=await Ee({message:o},b,a,{failedExtensions:s}),l=en(c.message,c.commandName,c.allowedTypes,{unknownCommandExamples:c.unknownCommandExamples,unknownCommandNextSteps:c.unknownCommandNextSteps,attemptedCommand:c.attemptedCommand,normalizedInvocationArgs:c.normalizedInvocationArgs,providedOptionFlags:c.providedOptionFlags,unknownOptionSuggestions:c.unknownOptionSuggestions,suggestedRetryCommand:c.suggestedRetryCommand,failedExtensions:s}),{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:n,errorCode:l.code,errorMessage:l.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await ct({command:n,error_code:l.code,error_category:d,exit_code:g.USAGE,error_message:l.detail,command_resolution:m,resolution_stage:"parse",source_context:N?.source_context}),u=e.jsonErrors?await fn({message:o},b,a,e.bootstrapGlobal.lean===!0,{failedExtensions:s}):await un({message:o},b,a,{failedExtensions:s}),f=ln(u,e.jsonErrors,s);await Mn({errorMessage:o,exitCode:g.USAGE,classificationCode:l.code,errorCategory:d,commandResolution:m,resolutionStage:"parse"}),y(f),p&&await he(Sn),process.exitCode=g.USAGE}async function Za(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let r=P(e.invocationArgv);return r.requested&&!qr(b,r.commandPathTokens)?(await Qa(e,t),!0):(await Ja(),!0)}async function ei(e,t){let n=await Ee(e.error,b,T),o=en(n.message,n.commandName,n.allowedTypes,{unknownCommandExamples:n.unknownCommandExamples,unknownCommandNextSteps:n.unknownCommandNextSteps,attemptedCommand:n.attemptedCommand,normalizedInvocationArgs:n.normalizedInvocationArgs,providedOptionFlags:n.providedOptionFlags,unknownOptionSuggestions:n.unknownOptionSuggestions,suggestedRetryCommand:n.suggestedRetryCommand}),{errorCategory:r,commandResolution:a}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),i=await ct({command:e.attemptedCommand,error_code:o.code,error_category:r,exit_code:g.USAGE,error_message:o.detail,command_resolution:a,resolution_stage:"parse",source_context:N?.source_context}),s=e.jsonErrors?await fn(e.error,b,T,e.bootstrapGlobal.lean===!0):await un(e.error,b,T),c=await zr(o.code,e.bootstrapPmRoot,{},Ie($e(e.invocationArgv))),l=ln(s,e.jsonErrors,c);await Mn({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:r,commandResolution:a,resolutionStage:"parse"}),y(l),i&&await he(Sn),process.exitCode=g.USAGE}function ti(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return typeof t=="string"&&(t==="commander.version"||t.startsWith("commander."))?!0:String(e.message??"").includes("(outputHelp)")}async function ni(e){let t=e.error.code,n=String(e.error.message??"");if(!await Za(e,t,n)){if(t==="commander.version"){await Ja();return}await ei(e,t)}}async function oi(e){let t=q(e.invocationArgv),n=k(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:E(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:Jc({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await Ka({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await Xa(o,Pt(e.error))){if(ti(e.error)){await ni(o);return}await ma({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}async function Cd(e=process.argv.slice(2)){b=Lt(Oe),Ua(b),Se=null,ee=null,T=new Map,to();let t=[...e],n,o;try{let r=Ye(e);t=r.argv;let a=[process.argv[0],process.argv[1],...t],i=t.length===0,s=q(t);if(s.authorMissingValue)throw new C("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});n=jo(s.author),Va(r),o=Mo(t);let c=za(t);if(await Kc(b,c),Ha(t)&&Zo(b,t),Wa(b,t)?await Da(b,t):(T=new Map,B({overrides:[]})),Ba(t)&&await wa(b,t),La(b),await Gr(b,t,T))return;if(i){b.outputHelp();return}let m=await R(k(process.cwd(),s.path)),p=await Br(t,k(process.cwd(),s.path),s.noExtensions,le);await Eo({pmRoot:k(process.cwd(),s.path),packages:p?.contextIntentPackages},()=>ao(m.agent_identity.harness_signals,()=>b.parseAsync(a),{probesEnabled:m.agent_identity?.probes_enabled}))}catch(r){await oi({error:r,invocationArgv:t})}finally{o?.(),n?.()}}var kd={activationCommandMatchesProbe:xa,bootstrapProfileEnabled:Rn,buildBootstrapActivationProbe:$e,buildPostActionTelemetryOutcome:sa,buildPmCliRecoveryContext:ea,buildRuntimeExtensionDiscoverySnapshotCacheKey:In,buildRuntimeExtensionActivationScope:Fn,buildRuntimeExtensionSnapshotCacheKey:_a,buildRuntimeExtensionFilterForProbe:Oa,addRuntimeFieldOption:xn,collectActivationCommandCandidates:Ie,collectExtensionFlagDefinitionsForCommand:_n,collectExtensionFlagDefinitionsForInvocation:lt,collectLeadingCommandArgs:ba,collectParsedActivationCommandArgs:Ra,collectRuntimeFieldLooseFlagDefinitionsForCommand:ya,commandHasLongOption:ga,commandHasShortOption:ha,commandPathNeedsSearchExtensions:ka,commandPathNeedsTemplateExtensions:Pn,describeUnknownError:Y,defaultPreflightDecision:vn,discoveryNeedsActivationForProbe:mt,emitExtensionProfile:Ia,emitExtensionSkippedProfile:pt,emitSettingsReadWarnings:kn,ensureIdempotentTopLevelCommandRegistration:Ga,enforceExplicitRetryForFlagTypos:Va,envFlagEnabled:la,executeRegisteredRuntimeMigrations:Na,extractCommandScopedOptions:Ae,extensionActivationCommands:$n,extensionCapabilities:dt,extensionNeedsActivationForProbe:Nn,extensionProvidesTemplatesRuntime:Sa,hasAnyCapability:Te,hasGlobalExtensionContributions:Aa,handleGenericRunPmCliError:ma,handleRunPmCliCommanderError:ni,handleRunPmCliError:oi,handleRunPmCliHelpDisplayError:Za,handleRunPmCliKnownError:Xa,handleRunPmCliCommanderUsageError:ei,handleUnknownHelpCommandError:Qa,inferMissingFieldsFromErrorMessage:Zr,inferPostActionErrorCode:ia,inferPostActionFailureMessage:aa,invocationRequestsVersion:ft,isCommanderError:Ft,loadRuntimeExtensionCommandDescriptorsForRecovery:Pa,loadRuntimeExtensionDiscoverySnapshot:ut,loadRuntimeExtensionSnapshot:le,maybeLoadRuntimeExtensions:$a,maybeAttachCreateUpdatePolicyHelpText:On,maybeLogHandledCliErrorToSentry:ct,matchesStaticExtensionCommand:Cn,normalizeTelemetryCommandResolution:na,normalizeTelemetryErrorCategory:ra,normalizeTelemetryResolutionStage:oa,normalizeThrownExitCode:Nt,probeUsesAnyFlag:Ea,prepareExtensionServicesForRunPmCliError:Ka,readRecordBoolean:ta,readRecordNumber:An,readRecordString:se,registerDynamicExtensionCommandPaths:Da,registerRuntimeSchemaFieldFlags:wa,resolveCoreCommandRegistrationSelection:za,resolveStaticExtensionActivationDecision:Ta,resolveUnknownHelpToken:dn,readThrownExitCode:Pt,runAndClearAfterCommandHooks:Re,runRequiredExtensionCommand:Ma,shouldAttachRichHelpTextForInvocation:Ha,shouldLogHandledErrorToSentry:da,shouldRegisterDynamicExtensionPaths:Wa,shouldRegisterRuntimeSchemaFlags:Ba,shouldHandleRunPmCliCommanderError:ti,setActiveExtensionHookContextForTest:_c,setActiveRuntimeExtensionCommandDescriptorsForTest:bc,setRecoveredExtensionServices:Ya,toLooseFieldDefinitionType:bn,isImporterOrExporterCommandPath:pa,validateDynamicExtensionCommandInvocation:fa,wrapProgramActionsForExtensionHandlers:La,wrapThrownErrorForSentry:Mt};export{kd as _testOnly,Cd as runPmCli};
|
|
29
29
|
//# sourceMappingURL=main.js.map
|