@unbrained/pm-cli 2026.9.15 → 2026.9.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +58 -0
  3. package/dist/cli/error-guidance.d.ts +1 -1
  4. package/dist/cli/error-guidance.js +1 -1
  5. package/dist/cli/register-setup.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +149 -149
  7. package/dist/cli-bundle/chunks/{chunk-3RB6Z7XE.js → chunk-5ZY4WE3F.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-UKLOSZV6.js → chunk-C3MFMGCR.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-WLJJ4MAU.js → chunk-CPFBDM53.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-YMMLKKEP.js → chunk-DN2RIHRN.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-5P5PYCZX.js → chunk-E67MIO3Z.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-3AHONKLL.js → chunk-G2IJF244.js} +48 -48
  13. package/dist/cli-bundle/chunks/{chunk-RM2OGG65.js → chunk-LD2FH2YE.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-RKPUO75B.js → chunk-Q6KPZGMP.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-Y2P3DSSO.js → chunk-T526C5DX.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-BOZ4HVYL.js → chunk-UF75LUAK.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-J4DRE3WN.js → chunk-UJSB6NO6.js} +76 -76
  18. package/dist/cli-bundle/chunks/{chunk-WDF7PP4P.js → chunk-YZXB4XGA.js} +4 -4
  19. package/dist/cli-bundle/chunks/{register-list-query-IWSPNFFD.js → register-list-query-ISM35VIX.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-mutation-3DVF4R64.js → register-mutation-KHMBJJS6.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-operations-LXP3MECQ.js → register-operations-HHDROJD6.js} +2 -2
  22. package/dist/cli-bundle/chunks/{register-setup-KFQSNBDX.js → register-setup-YAURJMY5.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-533DCWPY.js → chunk-267N774W.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-ZHX3433X.js → chunk-5FSGN4MP.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-BMATJLPT.js → chunk-5KYHDFDN.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-SHF57M2H.js → chunk-7S7XWMXC.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-AXDAIBT3.js → chunk-7ZC4CKOX.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-JKJYXCT6.js → chunk-BFUXTNZU.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-PBJC2ZNA.js → chunk-G4TKJZ4A.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-ZOE2NSJB.js → chunk-GKSAMNBG.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-63YRRGKX.js → chunk-IVWUQE7T.js} +51 -51
  32. package/dist/cli-bundle/focused-chunks/{chunk-6C3CUU2G.js → chunk-JZSLDLR4.js} +20 -20
  33. package/dist/cli-bundle/focused-chunks/{chunk-YBQTVE5S.js → chunk-LNM3BS45.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-5SBU4QDC.js → chunk-NOK652OP.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-OGGF2RBL.js → chunk-OCTTDZOU.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-MD7ADLME.js → chunk-OWDDVMAP.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-UACMCSCC.js → chunk-WUMGGQYN.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-4YTDKIPF.js → chunk-Z4PWEIMX.js} +21 -21
  39. package/dist/cli-bundle/main.js +11 -10
  40. package/dist/cli-bundle/sdk-authoring.js +1 -1
  41. package/dist/cli-bundle/sdk-contracts.js +1 -1
  42. package/dist/cli-bundle/sdk-core.js +2 -2
  43. package/dist/cli-bundle/sdk-governance.js +1 -1
  44. package/dist/cli-bundle/sdk-graph.js +1 -1
  45. package/dist/cli-bundle/sdk-merge.js +40 -40
  46. package/dist/cli-bundle/sdk-query.js +1 -1
  47. package/dist/cli-bundle/sdk-runtime.js +1 -1
  48. package/dist/cli-bundle/sdk-testing.js +1 -1
  49. package/dist/cli-bundle/sdk.js +2 -2
  50. package/dist/core/diagnostics/remediation.js +1 -1
  51. package/dist/core/store/tracker-preflight.js +1 -1
  52. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  53. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  54. package/dist/sdk/index.d.ts +1 -1
  55. package/dist/sdk/index.js +1 -1
  56. package/dist/sdk/init.d.ts +22 -1
  57. package/dist/sdk/init.js +1 -1
  58. package/dist/sdk/merge/install.js +2 -2
  59. package/dist/sdk/public-surface.json +1 -1
  60. package/dist/sdk/read-output-budget.d.ts +2 -0
  61. package/dist/sdk/read-output-budget.js +1 -1
  62. package/dist/sdk/read-output-contracts.d.ts +4 -0
  63. package/dist/sdk/read-output-contracts.js +1 -1
  64. package/docs/MERGE_SAFETY.md +13 -2
  65. package/docs/PACKED_FIRST_RUN.md +46 -0
  66. package/docs/QUICKSTART.md +16 -0
  67. package/docs/READ_OUTPUT_CONTRACTS.md +14 -0
  68. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  69. package/marketplace.json +2 -2
  70. package/package.json +1 -1
  71. package/packages/pm-beads/package.json +1 -1
  72. package/packages/pm-calendar/package.json +1 -1
  73. package/packages/pm-command-kit/package.json +1 -1
  74. package/packages/pm-digital-twin/package.json +1 -1
  75. package/packages/pm-governance-audit/package.json +1 -1
  76. package/packages/pm-guide-shell/package.json +1 -1
  77. package/packages/pm-kanban/package.json +1 -1
  78. package/packages/pm-lifecycle-hooks/package.json +1 -1
  79. package/packages/pm-linked-test-adapters/package.json +1 -1
  80. package/packages/pm-search-advanced/package.json +1 -1
  81. package/packages/pm-templates/package.json +1 -1
  82. package/packages/pm-todos/package.json +1 -1
  83. package/packages/pm-vcs/package.json +1 -1
  84. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  85. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
@@ -1,66 +1,66 @@
1
- import{$a as So,$d as $t,$j as Tt,Ac as be,Ba as xt,Ca as dn,Cb as Ue,Da as pn,Dc as Do,E as _o,Fc as Et,Fi as gn,Gc as jo,Hc as Lo,Hi as Ho,I as cn,Ii as Ge,Ij as Zo,Jj as Qo,K as wo,Kj as Se,Lj as ei,Mi as ke,Mj as ti,N as ln,O as h,Pj as ni,Q as f,Rc as B,Sd as I,T as vo,Tb as Ao,Td as X,Ub as To,Ud as Fo,Vd as Y,Vj as oi,Wd as oe,Yd as Mo,Zd as nt,Ze as Uo,_a as xo,_c as K,_j as Ee,ab as G,ac as Oo,ak as Ot,ba as T,bc as Co,bg as At,cf as H,cg as zo,cj as Ko,dc as Ro,df as Q,dg as mn,dj as Ce,dk as Re,eg as fn,ej as ot,fg as hn,fj as Vo,gj as Yo,hg as Jo,hj as re,ib as P,ig as qo,ij as ze,ik as ii,jb as Eo,jj as Xo,jk as yn,k as go,kb as $o,kj as le,kl as ri,lb as Io,lg as Wo,o as S,oa as bo,oo as Ct,p as bt,q as ie,qa as ko,r as W,ra as V,s as fe,sg as Bo,tc as un,tj as ae,u as yo,uc as Po,va as ce,vc as No,wc as St,wf as Go,wj as A,x as kt,xf as It,xj as xe,yc as ve}from"./chunk-J4DRE3WN.js";import{mkdir as Ls,readFile as Fs}from"node:fs/promises";import pi from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d7f490a-03a3-512c-ba3c-b19fcc9a1270")}catch{}})();var _n=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Ms="sdk-workspace-transaction",Us=/^[a-zA-Z0-9._-]+$/,Gs=30,zs=3e3;function ai(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Us.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function si(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function ci(e,t,n){let o=e??t;if(!Number.isInteger(o)||o<=0)throw new TypeError(`${n} must be a positive integer`);return o}function ui(e,t){return pi.join(e,"transactions","sdk",`${t}.json`)}async function $e(e,t){t.updatedAt=T();let n=ui(e,t.transactionId);await Ls(pi.dirname(n),{recursive:!0}),await fe(n,`${JSON.stringify(t,null,2)}
2
- `)}function Js(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Pe(e){return Object.assign(Object.create(null),e)}function qs(e,t){try{let n=JSON.stringify(e,(o,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function wn(e,t){return e===void 0?void 0:qs(e,t)}function vn(e,t,n,o){let i=wn(n,o);i===void 0?delete e[t]:e[t]=i}function li(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function di(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Ws(e,t){if(!di(e.startedStepIds,t)||!di(e.completedStepIds,t)||!li(e.results)||!li(e.compensationData))return!1;let n=e.startedStepIds,o=new Set(n),i=e.completedStepIds,r=new Set(i);return Object.keys(e.compensationData).some(a=>!o.has(a))||Object.keys(e.results).some(a=>!r.has(a))?!1:e.status==="committed"?t.every(a=>r.has(a)):e.status!=="compensated"||r.size===0&&o.size===0}function Bs(e,t,n){let o;try{o=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let i=o,r=i.schemaVersion===1&&i.transactionId===t,a=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((d,p)=>d===n[p]),s=Ws(i,n),c=Js(i),l=["applying","compensating","compensated","committed"].includes(String(i.status));if(!r||!a||!s||!c||!l)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...i,results:Pe(i.results),compensationData:Pe(i.compensationData)}}async function Hs(e,t,n,o,i){let r=i,a=r!==void 0;if(r?.status==="compensating"&&await mi(e,r),r===void 0||r.status==="compensated"){let s=T();r={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(r?.attempt??0)+1,createdAt:r?.createdAt??s,updatedAt:s,stepIds:o,startedStepIds:[],completedStepIds:[],results:Pe(),compensationData:Pe()},await $e(e.pmRoot,r),await he(e,r,"prepared")}return{journal:r,recovered:a}}async function Ks(e,t,n){try{await Ys(t,e.steps),await $e(e.pmRoot,t);let o=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let r of e.steps){if(o.has(r.id))continue;let a=await r.inspect(),s=wn(a.result,`Step ${r.id} result`);if(a.state!=="applied"){let c=await r.prepareCompensation?.();vn(t.compensationData,r.id,c,`Step ${r.id} compensation data`),i.add(r.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>i.has(d)),await $e(e.pmRoot,t);let l=await r.apply();s=wn(l,`Step ${r.id} result`)}await he(e,t,"step_applied",r.id),o.add(r.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>o.has(c)),vn(t.results,r.id,s,`Step ${r.id} result`),await $e(e.pmRoot,t),await he(e,t,"step_recorded",r.id)}return await he(e,t,"committing"),t.status="committed",await $e(e.pmRoot,t),await he(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Pe(t.results)}}catch(o){if(o instanceof _n||t.status==="committed")throw o;try{await mi(e,t)}catch(i){throw new AggregateError([o,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw o}}async function Vs(e,t,n){try{return Bs(await Fs(ui(e,t),"utf8"),t,n)}catch(o){if(o!==null&&typeof o=="object"&&"code"in o&&ie(o))return;throw o}}async function he(e,t,n,o){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...o===void 0?{}:{stepId:o}})}async function Ys(e,t){let n=new Set,o=Pe();for(let i of t){let r=await i.inspect();r.state==="applied"&&(n.add(i.id),vn(o,i.id,r.result,`Step ${i.id} result`))}e.results=o,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function mi(e,t){t.status="compensating",await $e(e.pmRoot,t),await he(e,t,"compensating");let n=new Set(t.completedStepIds),o=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!o.has(i.id)&&!n.has(i.id))continue;let r;try{r=o.has(i.id)&&(await i.inspect()).state==="applied"}catch{r=o.has(i.id)}r&&(await he(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),o.delete(i.id),t.completedStepIds=e.steps.map(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>o.has(a)),delete t.results[i.id],delete t.compensationData[i.id],await $e(e.pmRoot,t),await he(e,t,"step_compensated",i.id)}t.status="compensated",await $e(e.pmRoot,t),await he(e,t,"compensated")}async function fi(e){let t=si(e.pmRoot,"Transaction pmRoot"),n=ai(e.transactionId,"Transaction id"),o=si(e.author,"Transaction author"),i=ci(e.lockTtlSeconds,Gs,"Transaction lock TTL"),r=ci(e.lockWaitMs,zs,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(d=>{let p=ai(d.id,"Transaction step id");if(p!==d.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return p});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:o,steps:a,lockTtlSeconds:i,lockWaitMs:r},l=await Q(t,Ms,i,o,!1,!1,r);try{let d=await Vs(t,n,s),p=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Pe(d.results)};let u=await Hs(c,n,o,s,d);return await Ks(c,u.journal,p||u.recovered)}finally{await l()}}import{readFile as Xs,writeFile as Zs}from"node:fs/promises";import it from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5b131b40-e139-5a7d-a6ef-633fe2cbee64")}catch{}})();var gi="# pm-cli:runtime-cache:start",bn="# pm-cli:runtime-cache:end",yi=".agents/pm",Qs=["runtime/","search/","locks/","transactions/","checkpoints/"],ec=["search/eval-queries.json"];async function hi(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new f("The workspace .gitignore is not writable.",h.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function _i(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function kn(e){let t=e.replaceAll("\\","/");return it.isAbsolute(e)||t===".."||t.startsWith("../")}function tc(e=yi){let t=_i(e);return[gi,...Qs.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...ec.map(n=>`!${t}/${n}`),bn].join(`
3
- `)}async function wi(e,t={}){let n=it.join(e,".gitignore"),o=yi;if(t.pmRoot!==void 0){let d=_i(it.relative(it.resolve(e),it.resolve(t.pmRoot)));if(kn(d))return{path:n,changed:!1};d.length>0&&(o=d)}let i="";try{i=await hi(()=>Xs(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&ie(d)))throw d}let r=i.indexOf(gi),a=i.indexOf(bn),c=(r>=0&&a>=r?`${i.slice(0,r)}${i.slice(a+bn.length)}`:i).trimEnd(),l=`${c.length>0?`${c}
1
+ import{$a as So,$d as At,$j as Ot,Ac as be,Ba as Et,Ca as pn,Cb as Ue,Da as un,Dc as Do,E as _o,Fc as It,Fi as yn,Gc as jo,Hc as Lo,Hi as Ho,I as ln,Ii as Ge,Ij as Zo,Jj as Qo,K as wo,Kj as Se,Lj as ei,Mi as ke,Mj as ti,N as dn,O as h,Pj as ni,Q as f,Rc as B,Sd as I,T as vo,Tb as Ao,Td as X,Ub as To,Ud as Fo,Vd as Y,Vj as oi,Wd as oe,Yd as Mo,Zd as nt,Ze as Uo,_a as xo,_c as K,_j as Ee,ab as G,ac as Oo,ak as Ct,ba as T,bc as Co,bg as Tt,cf as H,cg as zo,cj as Ko,dc as Ro,df as Q,dg as fn,dj as Ce,dk as Re,eg as hn,ej as it,fg as gn,fj as Vo,gj as Yo,hg as Jo,hj as re,ib as N,ig as qo,ij as ze,ik as ii,jb as Eo,jj as Xo,jk as _n,k as go,kb as $o,kj as le,kl as ri,lb as Io,lg as Wo,o as S,oa as bo,oo as Rt,p as xt,q as ie,qa as ko,r as W,ra as V,s as fe,sg as Bo,tc as mn,tj as ae,u as yo,uc as Po,va as ce,vc as No,wc as $t,wf as Go,wj as A,x as St,xf as ot,xj as xe,yc as ve}from"./chunk-UJSB6NO6.js";import{mkdir as Ls,readFile as Fs}from"node:fs/promises";import pi from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d7f490a-03a3-512c-ba3c-b19fcc9a1270")}catch{}})();var wn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Ms="sdk-workspace-transaction",Us=/^[a-zA-Z0-9._-]+$/,Gs=30,zs=3e3;function ai(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Us.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function si(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function ci(e,t,n){let o=e??t;if(!Number.isInteger(o)||o<=0)throw new TypeError(`${n} must be a positive integer`);return o}function ui(e,t){return pi.join(e,"transactions","sdk",`${t}.json`)}async function $e(e,t){t.updatedAt=T();let n=ui(e,t.transactionId);await Ls(pi.dirname(n),{recursive:!0}),await fe(n,`${JSON.stringify(t,null,2)}
2
+ `)}function Js(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Pe(e){return Object.assign(Object.create(null),e)}function qs(e,t){try{let n=JSON.stringify(e,(o,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function vn(e,t){return e===void 0?void 0:qs(e,t)}function bn(e,t,n,o){let i=vn(n,o);i===void 0?delete e[t]:e[t]=i}function li(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function di(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Ws(e,t){if(!di(e.startedStepIds,t)||!di(e.completedStepIds,t)||!li(e.results)||!li(e.compensationData))return!1;let n=e.startedStepIds,o=new Set(n),i=e.completedStepIds,r=new Set(i);return Object.keys(e.compensationData).some(a=>!o.has(a))||Object.keys(e.results).some(a=>!r.has(a))?!1:e.status==="committed"?t.every(a=>r.has(a)):e.status!=="compensated"||r.size===0&&o.size===0}function Bs(e,t,n){let o;try{o=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let i=o,r=i.schemaVersion===1&&i.transactionId===t,a=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((d,p)=>d===n[p]),s=Ws(i,n),c=Js(i),l=["applying","compensating","compensated","committed"].includes(String(i.status));if(!r||!a||!s||!c||!l)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...i,results:Pe(i.results),compensationData:Pe(i.compensationData)}}async function Hs(e,t,n,o,i){let r=i,a=r!==void 0;if(r?.status==="compensating"&&await mi(e,r),r===void 0||r.status==="compensated"){let s=T();r={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(r?.attempt??0)+1,createdAt:r?.createdAt??s,updatedAt:s,stepIds:o,startedStepIds:[],completedStepIds:[],results:Pe(),compensationData:Pe()},await $e(e.pmRoot,r),await he(e,r,"prepared")}return{journal:r,recovered:a}}async function Ks(e,t,n){try{await Ys(t,e.steps),await $e(e.pmRoot,t);let o=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let r of e.steps){if(o.has(r.id))continue;let a=await r.inspect(),s=vn(a.result,`Step ${r.id} result`);if(a.state!=="applied"){let c=await r.prepareCompensation?.();bn(t.compensationData,r.id,c,`Step ${r.id} compensation data`),i.add(r.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>i.has(d)),await $e(e.pmRoot,t);let l=await r.apply();s=vn(l,`Step ${r.id} result`)}await he(e,t,"step_applied",r.id),o.add(r.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>o.has(c)),bn(t.results,r.id,s,`Step ${r.id} result`),await $e(e.pmRoot,t),await he(e,t,"step_recorded",r.id)}return await he(e,t,"committing"),t.status="committed",await $e(e.pmRoot,t),await he(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Pe(t.results)}}catch(o){if(o instanceof wn||t.status==="committed")throw o;try{await mi(e,t)}catch(i){throw new AggregateError([o,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw o}}async function Vs(e,t,n){try{return Bs(await Fs(ui(e,t),"utf8"),t,n)}catch(o){if(o!==null&&typeof o=="object"&&"code"in o&&ie(o))return;throw o}}async function he(e,t,n,o){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...o===void 0?{}:{stepId:o}})}async function Ys(e,t){let n=new Set,o=Pe();for(let i of t){let r=await i.inspect();r.state==="applied"&&(n.add(i.id),bn(o,i.id,r.result,`Step ${i.id} result`))}e.results=o,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function mi(e,t){t.status="compensating",await $e(e.pmRoot,t),await he(e,t,"compensating");let n=new Set(t.completedStepIds),o=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!o.has(i.id)&&!n.has(i.id))continue;let r;try{r=o.has(i.id)&&(await i.inspect()).state==="applied"}catch{r=o.has(i.id)}r&&(await he(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),o.delete(i.id),t.completedStepIds=e.steps.map(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>o.has(a)),delete t.results[i.id],delete t.compensationData[i.id],await $e(e.pmRoot,t),await he(e,t,"step_compensated",i.id)}t.status="compensated",await $e(e.pmRoot,t),await he(e,t,"compensated")}async function fi(e){let t=si(e.pmRoot,"Transaction pmRoot"),n=ai(e.transactionId,"Transaction id"),o=si(e.author,"Transaction author"),i=ci(e.lockTtlSeconds,Gs,"Transaction lock TTL"),r=ci(e.lockWaitMs,zs,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(d=>{let p=ai(d.id,"Transaction step id");if(p!==d.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return p});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:o,steps:a,lockTtlSeconds:i,lockWaitMs:r},l=await Q(t,Ms,i,o,!1,!1,r);try{let d=await Vs(t,n,s),p=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Pe(d.results)};let u=await Hs(c,n,o,s,d);return await Ks(c,u.journal,p||u.recovered)}finally{await l()}}import{readFile as Xs,writeFile as Zs}from"node:fs/promises";import rt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5b131b40-e139-5a7d-a6ef-633fe2cbee64")}catch{}})();var gi="# pm-cli:runtime-cache:start",kn="# pm-cli:runtime-cache:end",yi=".agents/pm",Qs=["runtime/","search/","locks/","transactions/","checkpoints/"],ec=["search/eval-queries.json"];async function hi(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new f("The workspace .gitignore is not writable.",h.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function _i(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function xn(e){let t=e.replaceAll("\\","/");return rt.isAbsolute(e)||t===".."||t.startsWith("../")}function tc(e=yi){let t=_i(e);return[gi,...Qs.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...ec.map(n=>`!${t}/${n}`),kn].join(`
3
+ `)}async function wi(e,t={}){let n=rt.join(e,".gitignore"),o=yi;if(t.pmRoot!==void 0){let d=_i(rt.relative(rt.resolve(e),rt.resolve(t.pmRoot)));if(xn(d))return{path:n,changed:!1};d.length>0&&(o=d)}let i="";try{i=await hi(()=>Xs(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&ie(d)))throw d}let r=i.indexOf(gi),a=i.indexOf(kn),c=(r>=0&&a>=r?`${i.slice(0,r)}${i.slice(a+kn.length)}`:i).trimEnd(),l=`${c.length>0?`${c}
4
4
 
5
5
  `:""}${tc(o)}
6
- `;return l===i?{path:n,changed:!1}:(await hi(()=>Zs(n,l,"utf8")),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7999053-cf48-5588-b8c8-570789086dac")}catch{}})();var nc=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Je(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Et(t.extensionName));for(let m of t.extensionNames??[])n.add(Et(m));let o=m=>n.size===0||n.has(Et(m)),i=(m,_)=>vi(m.filter(v=>o(v.name)).map(_)),r=(m,_)=>vi(m.filter(v=>o(v.name)).flatMap(_)),{registrations:a,commands:s,parsers:c,preflight:l,services:d,renderers:p,hooks:u}=e,g=r(a.relationship_kinds??[],m=>m.definitions.map(_=>_.kind)),y=p.overrides.filter(m=>o(m.name)&&((m.commands?.length??0)>0||m.resultDiscriminator!==void 0)).map(m=>({format:m.format,commands:[...m.commands??[]],result_discriminator:m.resultDiscriminator!==void 0})).sort((m,_)=>m.format.localeCompare(_.format)),w=i(a.assurance_providers??[],m=>m.definition.id);return{capabilities:jo(e,t),commands:i(a.commands,m=>m.command),command_overrides:i(s.overrides,m=>m.command),command_handlers:i(s.handlers,m=>m.command),hooks:nc.filter(([m])=>u[m].some(_=>o(_.name))).map(([,m])=>m),flag_commands:i(a.flags,m=>m.target_command),item_types:r(a.item_types,m=>m.types.map(_=>_.name)),item_fields:r(a.item_fields,m=>m.fields.map(_=>_.name)),...g.length>0?{relationship_kinds:g}:{},migrations:r(a.migrations,m=>typeof m.definition.id=="string"?[m.definition.id]:[]),profiles:i(a.profiles,m=>m.profile.name),importers:i(a.importers,m=>m.importer),exporters:i(a.exporters,m=>m.exporter),search_providers:i(a.search_providers,m=>m.definition.name),vector_store_adapters:i(a.vector_store_adapters,m=>m.definition.name),...w.length>0?{assurance_providers:w}:{},parser_overrides:i(c.overrides,m=>m.command),service_overrides:i(d.overrides,m=>m.service),renderer_overrides:i(p.overrides,m=>m.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:l.overrides.filter(m=>o(m.name)).length,preflight_ownership:l.overrides.filter(m=>o(m.name)).map(m=>({commands:[...m.commands??[]]}))}}function vi(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d1a6b35-70e8-5a61-8ce6-3bea9ed8170b")}catch{}})();var oc="PM_SOURCE_CONTEXT_ACCESS",ic="PM_ALLOW_SOURCE_CONTEXT_WRITES";function bi(e){let t=e[oc],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",o=n==="read_only"&&e[ic]?.trim()==="1";return{access:n,write_override_applied:o,source_writes_allowed:n==="write"||o}}import{readFile as Pt,realpath as xn,writeFile as rc}from"node:fs/promises";import{execFile as ac}from"node:child_process";import F from"node:path";import{promisify as sc}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0200a3f7-93f5-5aaf-a6e8-2239e5b2ec3a")}catch{}})();var En=sc(ac),Rt="# pm-cli:merge-drivers:start",Ei="# pm-cli:merge-drivers:end",qe="# pm-cli:merge-drivers:v2:start",Sn="# pm-cli:merge-drivers:v2:end",cc="merge-fence";function ki(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function $i(){let e=ce(import.meta.url,["../../.."]);return`${ki(process.execPath)} ${ki(F.join(e,"dist","cli.js"))}`}var Ii=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function lc(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),o=e.environment.PM_SOURCE_PM_PATH?.trim(),i=bi(e.environment),r=!!(n&&o),a=t===void 0&&r&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let s=P(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:r,source_context_selected:!1,source_policy:i}}return a?{pm_root:F.resolve(o),workspace_start:F.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:r?P(e.cwd,".agents/pm"):P(e.cwd),workspace_start:e.cwd,source_coordinates_available:r,source_context_selected:!1,source_policy:i}}async function $n(e){try{let{stdout:t}=await En("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await xn(t.trim())}catch{return null}}async function Ai(e){let t=await $n(e);if(t===null)throw new f("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function In(e,t){return F.relative(e,t).replaceAll("\\","/")}function de(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function xi(e,t){if(e[t]!=="'")return null;let n="";for(let o=t+1;o<e.length;o+=1){if(e.startsWith(`'"'"'`,o)){n+="'",o+=4;continue}if(e[o]==="'")return{value:n,nextOffset:o+1};n+=e[o]}return null}async function dc(e,t){let n=xi(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let o=xi(e,n.nextOffset+1);if(o===null||e.slice(o.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(F.basename(n.value))||F.basename(o.value)!=="cli.js"||F.basename(F.dirname(o.value))!=="dist"||!await S(n.value)||!await S(o.value))return!1;try{let i=F.dirname(F.dirname(o.value)),r=JSON.parse(await Pt(F.join(i,"package.json"),"utf8")),a=typeof r.bin=="object"&&r.bin!==null&&"pm"in r.bin?r.bin.pm:void 0;return r.name==="@unbrained/pm-cli"&&(r.bin==="dist/cli.js"||a==="dist/cli.js")}catch{return!1}}function An(e,t){let n=e.length>0?`${e}/`:"",o=[`${de(`${n}**/*.toon`)} merge=pm-item-toon`,`${de(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)o.push(`${de(`${n}${i}/*.toon`)} merge=pm-item-toon`),o.push(`${de(`${n}${i}/*.md`)} merge=pm-item-markdown`);return o.push(`${de(`${n}**/*.jsonl`)} merge=pm-relationship`),o.push(`${de(`${n}history/*.jsonl`)} merge=pm-history`),o.push(`${de(`${n}settings.json`)} merge=pm-json`),o.push(`${de(`${n}**/*.json`)} merge=pm-json`),o.push(`${de(`${n}extensions/**`)} -merge`),o.push(`${de(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),o}function Si(e,t,n){let o=e.indexOf(t),i=e.indexOf(n);return o>=0&&i>o?`${e.slice(0,o)}${e.slice(i+n.length)}`:e.replace(t,"").replace(n,"")}async function Ti(e,t,n){let o=F.join(e,".gitattributes"),i="";try{i=await Pt(o,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&ie(l)))throw l}let r=[qe,...t,Sn].join(`
7
- `),s=Si(Si(i,qe,Sn),Rt,Ei).trimEnd(),c=`${s.length>0?`${s}
6
+ `;return l===i?{path:n,changed:!1}:(await hi(()=>Zs(n,l,"utf8")),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7999053-cf48-5588-b8c8-570789086dac")}catch{}})();var nc=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Je(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(It(t.extensionName));for(let m of t.extensionNames??[])n.add(It(m));let o=m=>n.size===0||n.has(It(m)),i=(m,_)=>vi(m.filter(v=>o(v.name)).map(_)),r=(m,_)=>vi(m.filter(v=>o(v.name)).flatMap(_)),{registrations:a,commands:s,parsers:c,preflight:l,services:d,renderers:p,hooks:u}=e,g=r(a.relationship_kinds??[],m=>m.definitions.map(_=>_.kind)),y=p.overrides.filter(m=>o(m.name)&&((m.commands?.length??0)>0||m.resultDiscriminator!==void 0)).map(m=>({format:m.format,commands:[...m.commands??[]],result_discriminator:m.resultDiscriminator!==void 0})).sort((m,_)=>m.format.localeCompare(_.format)),w=i(a.assurance_providers??[],m=>m.definition.id);return{capabilities:jo(e,t),commands:i(a.commands,m=>m.command),command_overrides:i(s.overrides,m=>m.command),command_handlers:i(s.handlers,m=>m.command),hooks:nc.filter(([m])=>u[m].some(_=>o(_.name))).map(([,m])=>m),flag_commands:i(a.flags,m=>m.target_command),item_types:r(a.item_types,m=>m.types.map(_=>_.name)),item_fields:r(a.item_fields,m=>m.fields.map(_=>_.name)),...g.length>0?{relationship_kinds:g}:{},migrations:r(a.migrations,m=>typeof m.definition.id=="string"?[m.definition.id]:[]),profiles:i(a.profiles,m=>m.profile.name),importers:i(a.importers,m=>m.importer),exporters:i(a.exporters,m=>m.exporter),search_providers:i(a.search_providers,m=>m.definition.name),vector_store_adapters:i(a.vector_store_adapters,m=>m.definition.name),...w.length>0?{assurance_providers:w}:{},parser_overrides:i(c.overrides,m=>m.command),service_overrides:i(d.overrides,m=>m.service),renderer_overrides:i(p.overrides,m=>m.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:l.overrides.filter(m=>o(m.name)).length,preflight_ownership:l.overrides.filter(m=>o(m.name)).map(m=>({commands:[...m.commands??[]]}))}}function vi(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d1a6b35-70e8-5a61-8ce6-3bea9ed8170b")}catch{}})();var oc="PM_SOURCE_CONTEXT_ACCESS",ic="PM_ALLOW_SOURCE_CONTEXT_WRITES";function bi(e){let t=e[oc],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",o=n==="read_only"&&e[ic]?.trim()==="1";return{access:n,write_override_applied:o,source_writes_allowed:n==="write"||o}}import{access as rc,readFile as Nt,realpath as at,writeFile as ac}from"node:fs/promises";import{constants as sc}from"node:fs";import{execFile as cc}from"node:child_process";import P from"node:path";import{promisify as lc}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b9c865a-c932-5394-b068-6fcf0dce5d3a")}catch{}})();var En=lc(cc),Pt="# pm-cli:merge-drivers:start",Ei="# pm-cli:merge-drivers:end",qe="# pm-cli:merge-drivers:v2:start",Sn="# pm-cli:merge-drivers:v2:end",dc="merge-fence";function ki(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function $i(){let e=ce(import.meta.url,["../../.."]),t=process.execPath,n=await at(process.execPath);for(let o of(process.env.PATH??"").split(P.delimiter)){if(!P.isAbsolute(o))continue;let i=P.join(o,P.basename(process.execPath));try{if(await rc(i,sc.X_OK),i!==n&&await at(i)===n){t=i;break}}catch{}}return`${ki(t)} ${ki(P.join(e,"dist","cli.js"))}`}var Ii=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function pc(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),o=e.environment.PM_SOURCE_PM_PATH?.trim(),i=bi(e.environment),r=!!(n&&o),a=t===void 0&&r&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let s=N(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:r,source_context_selected:!1,source_policy:i}}return a?{pm_root:P.resolve(o),workspace_start:P.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:r?N(e.cwd,".agents/pm"):N(e.cwd),workspace_start:e.cwd,source_coordinates_available:r,source_context_selected:!1,source_policy:i}}async function $n(e){try{let{stdout:t}=await En("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await at(t.trim())}catch{return null}}async function Ai(e){let t=await $n(e);if(t===null)throw new f("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function In(e,t){return P.relative(e,t).replaceAll("\\","/")}function de(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function xi(e,t){if(e[t]!=="'")return null;let n="";for(let o=t+1;o<e.length;o+=1){if(e.startsWith(`'"'"'`,o)){n+="'",o+=4;continue}if(e[o]==="'")return{value:n,nextOffset:o+1};n+=e[o]}return null}async function uc(e,t){let n=xi(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let o=xi(e,n.nextOffset+1);if(o===null||e.slice(o.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(P.basename(n.value))||P.basename(o.value)!=="cli.js"||P.basename(P.dirname(o.value))!=="dist"||!await S(n.value)||!await S(o.value))return!1;try{let i=P.dirname(P.dirname(o.value)),r=JSON.parse(await Nt(P.join(i,"package.json"),"utf8")),a=typeof r.bin=="object"&&r.bin!==null&&"pm"in r.bin?r.bin.pm:void 0;return r.name==="@unbrained/pm-cli"&&(r.bin==="dist/cli.js"||a==="dist/cli.js")}catch{return!1}}function An(e,t){let n=e.length>0?`${e}/`:"",o=[`${de(`${n}**/*.toon`)} merge=pm-item-toon`,`${de(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)o.push(`${de(`${n}${i}/*.toon`)} merge=pm-item-toon`),o.push(`${de(`${n}${i}/*.md`)} merge=pm-item-markdown`);return o.push(`${de(`${n}**/*.jsonl`)} merge=pm-relationship`),o.push(`${de(`${n}history/*.jsonl`)} merge=pm-history`),o.push(`${de(`${n}settings.json`)} merge=pm-json`),o.push(`${de(`${n}**/*.json`)} merge=pm-json`),o.push(`${de(`${n}extensions/**`)} -merge`),o.push(`${de(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),o}function Si(e,t,n){let o=e.indexOf(t),i=e.indexOf(n);return o>=0&&i>o?`${e.slice(0,o)}${e.slice(i+n.length)}`:e.replace(t,"").replace(n,"")}async function Ti(e,t,n){let o=P.join(e,".gitattributes"),i="";try{i=await Nt(o,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&ie(l)))throw l}let r=[qe,...t,Sn].join(`
7
+ `),s=Si(Si(i,qe,Sn),Pt,Ei).trimEnd(),c=`${s.length>0?`${s}
8
8
 
9
9
  `:""}${r}
10
- `;return c===i?{path:o,changed:!1}:(n||await rc(o,c,"utf8"),{path:o,changed:!0})}function Oi(e){let t=G(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,o)=>n.localeCompare(o))}async function wf(e,t){let n=F.resolve(e),o=null,i="",r=n;for(let v=0;v<8;v+=1){let k=F.join(r,".gitattributes");try{let C=await Pt(k,"utf8");if(C.includes(qe)||C.includes(Rt)){o=r,i=C;break}}catch{}let x=F.dirname(r);if(x===r)break;r=x}if(o===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let a=F.join(o,".gitattributes"),s=i.includes(qe),c=s?qe:Rt,l=s?Sn:Ei,d=i.indexOf(c),p=i.indexOf(l),u=p>d?i.slice(d+c.length,p).split(`
11
- `).map(v=>v.trim()).filter(v=>v.length>0):[],g=An(In(o,n),t),y=new Set(u),w=new Set(g),m=g.filter(v=>!y.has(v)),_=u.filter(v=>!w.has(v));return{status:m.length>0||_.length>0?"drift":"ok",path:a,missing_patterns:m,stale_patterns:_,schema_scope:"project"}}async function vf(e){let t=$i(),n=[],o=[];for(let i of Ii){let r=`merge.${i.key}.driver`,a=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`,s=`${t}${a}`;try{let{stdout:c}=await En("git",["config","--local","--get",r],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==s&&!await dc(l,a)&&o.push(r)}catch{n.push(r)}}return{status:n.length>0?"missing":o.length>0?"drift":"ok",missing_keys:n,drifted_keys:o}}async function Ci(e){let t;try{t=await Ai(F.resolve(e))}catch{return{status:"no_git"}}let n=In(t,F.resolve(e)),o=await A(e),i=H(void 0,o.author_default),r=await Q(e,cc,o.locks.ttl_seconds,i,!1,ae(o).force_required_for_stale_lock,o.locks.wait_ms);try{let a=F.join(t,".gitattributes"),s;try{s=await Pt(a,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&ie(p))return{status:"not_installed",path:a};throw p}if(!s.includes(qe)&&!s.includes(Rt))return{status:"not_installed",path:a};let c=await A(e),l=Oi(c),d=await Ti(t,An(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await r()}}async function bf(e,t){let n=lc({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),o=n.pm_root;await Ee(o);let i=await Ai(n.workspace_start);return Tn({pmRoot:o,workspaceRoot:i,dryRun:e.dryRun===!0})}async function Tn(e){let t=F.resolve(e.pmRoot),n=F.resolve(e.workspaceRoot),o=e.dryRun===!0,i,r;try{[i,r]=await Promise.all([xn(t),xn(n)])}catch(g){throw new f(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(g)}`,h.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let a=In(r,i);if(kn(a))throw new f(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,h.USAGE);let s=await A(i),c=Oi(s),l=An(a,c),d=[],p=$i();for(let g of Ii)d.push({key:`merge.${g.key}.name`,value:g.name}),d.push({key:`merge.${g.key}.driver`,value:`${p} merge driver ${g.artifact} "%O" "%A" "%B"${g.itemPath===void 0?"":` --item-path ${g.itemPath}`}`});if(!o)try{for(let g of d)await En("git",["config","--local",g.key,g.value],{cwd:r,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new f(`Cannot install repository-local merge drivers in ${r}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,h.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let u=await Ti(r,l,o);return{ok:!0,dry_run:o,workspace_root:r,pm_root:i,gitattributes:{path:u.path,changed:u.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0daf7c89-abc5-5c35-ba3f-9772a50408c0")}catch{}})();var rt={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Nt={type:"array",minItems:1,maxItems:mn,items:rt},Ri={...Nt,items:{...rt,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},pc={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Nt])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:rt,id:rt}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Ri}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Nt}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Ri,authors:Nt}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:mn,items:{type:"array",minItems:2,maxItems:2,items:rt}}}}]}}},Sf={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:zo,items:pc}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42dee0a5-d003-5e44-8b2d-d74a23d3f2ce")}catch{}})();async function Af(e,t,n,o){let i=await Se(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Pi(i,t,n,o)}function uc(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Pi(e,t,n=5,o=!1){let i=[],r=new Map,a=e.policies.filter(m=>m.rule.kind==="require_fields"),s=a.filter(m=>m.subject?.operations===void 0),c=new Set,l=0,d=0,p=0,u=0,g=0,y=Wo(e);for(let m of t){let _=y({operation:"",author:"",before:m,after:m,completeness_only:!0});l+=+(_.decisions.length>0),d+=_.decisions.length,_.decisions.forEach(x=>c.add(x.policy_id));let v=_.decisions.filter(x=>!x.satisfied);if(v.length===0)continue;u+=1;let k=r.get(m.type)??{items:0,violations:0,missing_fields:0};k.items+=1;for(let x of v)p+=1,k.violations+=1,k.missing_fields+=x.missing_fields.length,x.effect==="refuse"&&(g+=1),i.length<n&&i.push({id:m.id,type:m.type,status:m.status,decision:x});r.set(m.type,k)}let w=o||g>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:w,ok:w==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:a.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:d,governed_items:l,ungoverned_items:t.length-l,contract_status:uc(a.length,t.length,l),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:u,violation_count:p,refused_violations:g,missing_by_type:Object.fromEntries(r),violations:i,violations_truncated:i.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...o?["validate_completeness_source_incomplete"]:[]]}}import mc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f54fe358-8f4c-5bf4-ae2a-9c92cd08c953")}catch{}})();function fc(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([t,n])=>({id:`completeness-${t.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${t} work reaches completion.`,subject:{types:[t],statuses:["closed"]},rule:{kind:"require_fields",fields:[...n]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function ji(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new f("Policy definition must be valid JSON.",h.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new f("Policy definition must be an object.",h.USAGE);return t}async function hc(e,t){let n=P(process.cwd(),e.path);await Ee(n);let o=await A(n);return{pmRoot:n,settings:o,author:H(t,o.author_default)}}function Ni(e,t,n,o){if(e==="policy-mode")return hn({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let r=fn(o.definition),a=hn({...n,policies:[...i,r].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(a,null,2)}
12
- `)>Zo)throw new f("Policy registry exceeds its byte ceiling.",h.USAGE);return a}async function Di(e,t,n,o){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:Ni(e,t,await Se(o.pmRoot),n)};let i=await Ho({pmRoot:o.pmRoot,filePath:mc.join(o.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:o.author,message:n.message,lockTtlSeconds:o.settings.locks.ttl_seconds,lockWaitMs:o.settings.locks.wait_ms,mutate(r){let a=Ni(e,t,Qo(r),n);return{raw:`${JSON.stringify(a,null,2)}
13
- `,result:a}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function gc(e,t,n){let o,i=await ii({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:o}),async mutate(r){let s=(await Se(n.pmRoot)).policies.find(c=>c.id===t.policy);if(!s||s.rule.kind!=="approval")throw new f("--policy must name an approval rule.",h.USAGE);if(!s.rule.authors.includes(n.author))throw new f("This actor is not a declared approver.",h.CONFLICT);return await ei(n.pmRoot,r.metadata.id),o={policy_id:s.id,policy_fingerprint:Jo(s),content_fingerprint:qo(s,{...r.metadata,body:r.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...o,warnings:i.warnings}}}function yc(e,t){let n=ji(t),o=fn({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==o.id)throw new f("Policy id operand does not match definition.id.",h.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return o}async function Wf(e,t,n={},o={}){if(!At.includes(e))throw new f("Unknown workflow policy action.",h.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:fc()};let i=await hc(o,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Se(i.pmRoot)};if(e==="policy-put"){let d=yc(t,n.definition);return Di(e,d.id,{...n,definition:d},i)}if(!t?.trim())throw new f(`schema ${e} requires an operand.`,h.USAGE);if(["policy-remove","policy-mode"].includes(e))return Di(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new f("Use policy-check to preview; policy-approve records an approval.",h.USAGE);return gc(t,n,i)}let r=G(i.settings,B()),a=await Tt(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,r.type_to_folder);if(!a)throw new f(`Item ${t} not found.`,h.NOT_FOUND);let{document:s}=await Ot(a,{schema:i.settings.schema}),c={...s.metadata,body:s.body},l=n.definition===void 0?c:{...c,...ji(n.definition)};if(l.id!==c.id)throw new f("Policy preview cannot change the item id.",h.USAGE);return{policy_result:!0,action:e,changed:!1,result:await ti(i.pmRoot,await Se(i.pmRoot),{operation:"update",author:i.author,before:c,after:l,completeness_only:n.definition===void 0})}}import{createHash as Yi}from"node:crypto";import De from"node:fs/promises";import Ye from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f9535c02-9214-5d5e-bac0-2dabbe5d395e")}catch{}})();var _c=new Set(dn),wc=new Set(pn),Li=new Set([..._o.filter(e=>e!=="severity"),"id","title","type","status","priority","tags","assignee","parent","description","body","created_at","updated_at","closed_at","completed_at","author","deadline","estimate","sprint","release","risk","confidence","reviewer","resolution","expected","actual"]),vc=["create","update"];function Gi(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function Fi(e){return e.replaceAll("_","-")}function bc(e,t){let n=new Set;for(let o of e){let i=Gi(o);i.length>0&&i!==t&&n.add(i)}return[...n].sort((o,i)=>o.localeCompare(i))}function kc(e){let t=new Set;for(let n of e??[]){let o=n.trim();o.length>0&&t.add(o)}return[...t].sort((n,o)=>n.localeCompare(o))}function xc(e){let t=new Set,n=[];for(let o of e??[]){let i=o.trim().toLowerCase();if(i.length!==0){if(!wc.has(i))throw new Error(`Invalid field command "${o}". Allowed: ${pn.join(", ")}.`);t.has(i)||(t.add(i),n.push(i))}}return e===void 0||n.length===0?[...vc]:n}function zi(e){let t=I(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(Li.has(t))throw new Error(`Cannot define custom field "${t}": custom schema field "${t}" collides with built-in item metadata "${t}". Rename the custom field with a project-specific prefix. Reserved fields: ${[...Li].sort((d,p)=>d.localeCompare(p)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!_c.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${dn.join(", ")}.`);let o=n,i=xc(e.commands),r=Gi(e.cliFlag),a=r.length>0&&r!==Fi(t)?r:void 0,s=a??Fi(t),c=bc(e.aliases??[],s),l=e.description?.trim();return{key:t,type:o,commands:i,description:l&&l.length>0?l:void 0,cliFlag:a,cliAliases:c,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:kc(e.requiredTypes)}}function Sc(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function Ec(e){let t=Sc(e);if(!t)return[];let n=[];for(let o of t){if(typeof o!="object"||o===null||Array.isArray(o))continue;let i=o;typeof i.key!="string"||i.key.trim().length===0||n.push(i)}return n}function We(e){if(e==null||e.trim().length===0)return{fields:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/fields.json contains invalid JSON.")}return{fields:Ec(t)}}function Be(e){return`${JSON.stringify({fields:e.fields},null,2)}
14
- `}function Ji(e,t){let n=e.fields.find(a=>I(a.key)===t.key),o=n!==void 0,i=e.fields.filter(a=>I(a.key)!==t.key),r={...n,key:t.key,type:t.type,commands:[...t.commands]};return Mi(r,"description",t.description),Mi(r,"cli_flag",t.cliFlag),t.cliAliases.length>0?r.cli_aliases=[...t.cliAliases]:delete r.cli_aliases,Ui(r,"required",t.required),Ui(r,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?r.allow_unset=!1:delete r.allow_unset,t.requiredTypes.length>0?r.required_types=[...t.requiredTypes]:delete r.required_types,i.push(r),i.sort((a,s)=>I(a.key).localeCompare(I(s.key))),{file:{fields:i},definition:r,replaced:o}}function qi(e,t){let n=I(t);if(n.length===0)throw new Error("Field key must not be empty.");let o=[],i=e.fields.filter(r=>I(r.key)===n?(o.push(r),!1):!0);return o.length===0?{file:{fields:i},removed:!1}:{file:{fields:i},removed:!0,definition:o[0]}}function Mi(e,t,n){let o=e;n!==void 0&&n.length>0?o[t]=n:delete o[t]}function Ui(e,t,n){let o=e;n?o[t]=!0:delete o[t]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e3a1e65b-55d7-5206-b3e7-cac3ac29745c")}catch{}})();var $c=new Set(xt),Ne=new Set(Fo.map(e=>I(e.id)).filter(e=>e.length>0));function Ic(e){let t=new Set;for(let n of e){let o=I(n);o.length>0&&t.add(o)}return[...t].sort((n,o)=>n.localeCompare(o))}function Wi(e){let t=I(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(Ne.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...Ne].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let a=new Set;for(let s of e.roles){let c=typeof s=="string"?s.trim().toLowerCase():"";if(c.length!==0){if(!$c.has(c))throw new Error(`Invalid status role "${s}". Allowed roles: ${xt.join(", ")}.`);a.has(c)||(a.add(c),n.push(c))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${xt.join(", ")}.`)}let o=e.aliases===void 0?void 0:Ic(e.aliases).filter(a=>a!==t),i=e.description?.trim(),r=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:o,description:i&&i.length>0?i:void 0,order:r}}function Ac(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function Tc(e){let t=Ac(e);if(!t)return[];let n=[];for(let o of t){if(typeof o!="object"||o===null||Array.isArray(o))continue;let i=o;typeof i.id!="string"||i.id.trim().length===0||n.push(i)}return n}function He(e){if(e==null||e.trim().length===0)return{statuses:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/statuses.json contains invalid JSON.")}return{statuses:Tc(t)}}function Ke(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
15
- `}function Bi(e,t,n){let o=e.statuses.slice(),i=o.findIndex(s=>I(s.id)===t.id),r=i>=0?o[i]:n,a={...r,id:t.id};return t.roles!==void 0&&(t.roles.length>0?a.roles=[...t.roles]:a.roles!==void 0&&delete a.roles),t.aliases!==void 0&&(t.aliases.length>0?a.aliases=[...t.aliases]:a.aliases!==void 0&&delete a.aliases),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),i>=0?o[i]=a:o.push(a),{file:{statuses:o},definition:a,replaced:r!==void 0}}function Hi(e,t){let n=I(t);if(n.length===0)throw new Error("Status id must not be empty.");if(Ne.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...Ne].join(", ")}.`);let o=e.statuses.slice(),i=o.findIndex(a=>I(a.id)===n);if(i<0)return{file:{statuses:o},removed:!1};let[r]=o.splice(i,1);return{file:{statuses:o},removed:!0,definition:r}}function On(e,t){let n=[e.id,...e.aliases??[]];for(let o of n){let i=I(o);if(i.length===0)continue;let r=t.get(i);if(r!==void 0&&r!==e.id)throw new Error(`Status token "${i}" already belongs to status "${r}". Choose a different id/alias to avoid shadowing it.`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9052af10-ff8c-55db-8a35-b45e1e23a901")}catch{}})();function ge(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Xi(e){let t=ge(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Zi(e,t){let n=Rn(e),o=ge(t,"migrationScope");return`auto-${Yi("sha256").update(JSON.stringify({scope:o,request:n})).digest("hex").slice(0,20)}`}function Rn(e){let t=e.kind==="rename-type"?{kind:e.kind,from:ge(e.from,"source"),to:ge(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:I(ge(e.from,"source")),to:I(ge(e.to,"target")),...e.type===void 0?{}:{type:ge(e.type,"type")}}:{kind:e.kind,from:I(ge(e.from,"source")),to:I(ge(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Oc(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Cc(e,t,n){let o=Y(t.schema),i=Oc(n);return oe(e,o.files[i],X[i])}function Qi(e,t){return Ye.join(e,"transactions","schema",`${t}-plan.json`)}function Dt(e){return e.length===0?null:JSON.parse(e)}async function Ve(e){let t=await W(e);return{exists:t!==null,raw:t??""}}async function er(e,t){t.exists?await fe(e,t.raw):await De.rm(e,{force:!0})}function Rc(e,t,n){let o=re(e),i=o.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),r=o.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(r>=0)return le(o);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);o.definitions.push({...o.definitions[i],name:t.to})}else i>=0&&o.definitions.splice(i,1);return le(o)}function Pc(e,t,n){let o=We(e),i=o.fields.findIndex(a=>a.key===t.from),r=o.fields.findIndex(a=>a.key===t.to);if(n==="stage"){if(r>=0)return Be(o);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let a=o.fields[i];o.fields.push({...a,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&o.fields.splice(i,1);return Be(o)}function Nc(e,t,n){let o=He(e),i=o.statuses.findIndex(a=>a.id===t.from),r=o.statuses.findIndex(a=>a.id===t.to);if(n==="stage"){if(r>=0)return Ke(o);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);o.statuses.push({...o.statuses[i],id:t.to})}else i>=0&&o.statuses.splice(i,1);return Ke(o)}function Dc(e,t,n){return t.kind==="rename-type"?Rc(e,t,n):t.kind==="rename-field"?Pc(e,t,n):Nc(e,t,n)}function Ie(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Xe(e){return Array.isArray(e)?e.map(t=>Pn(t)).filter(t=>t!==void 0):[]}function jc(e,t){for(let n of Xe(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(o=>Ie(o,t)));for(let n of Xe(e.type_workflows))n.type=Ie(n.type,t)}function Lc(e,t){for(let o of Xe(e.definitions))o.default_status=Ie(o.default_status,t);let n=Pn(e.workflow);if(n)for(let[o,i]of Object.entries(n))n[o]=Ie(i,t);for(let o of Xe(e.type_workflows))Array.isArray(o.allowed_transitions)&&(o.allowed_transitions=o.allowed_transitions.map(i=>Array.isArray(i)?i.map(r=>Ie(r,t)):i))}function Fc(e,t){for(let n of Xe(e.definitions)){for(let o of["required_create_fields","required_create_repeatables"])Array.isArray(n[o])&&(n[o]=n[o].map(i=>Ie(i,t)));for(let o of["options","command_option_policies"])for(let i of Xe(n[o])){let r=o==="options"?"key":"option";i[r]=Ie(i[r],t)}}}function Mc(e,t){let n=Pn(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let o=t.kind==="rename-type"?"type":"status";n[o]=Ie(n[o],t)}function Cn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let o=n;return t.kind==="rename-type"?jc(o,t):t.kind==="rename-field"?Fc(o,t):Lc(o,t),Mc(o,t),`${JSON.stringify(o,null,2)}
16
- `}function tr(e,t){if(t.kind==="rename-type"){let o=re(e).definitions;return{source:o.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:o.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let o=We(e).fields;return{source:o.some(i=>i.key===t.from),target:o.some(i=>i.key===t.to)}}let n=He(e).statuses;return{source:n.some(o=>o.id===t.from),target:n.some(o=>o.id===t.to)}}function Uc(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function Gc(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function nr(e,t){let n=Rn(t.request),o=t.migrationId===void 0?Zi(n,t.migrationScope??"plan"):Xi(t.migrationId),i=e.map(c=>Gc(c,n)).filter(c=>c!==null).sort((c,l)=>c.id.localeCompare(l.id)),r=Yi("sha256").update(JSON.stringify({migrationId:o,request:n,items:i})).digest("hex"),a=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!a.has(c.id));return Object.freeze({migration_id:o,request:n,fingerprint:r,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function zc(e){let t=G(e.settings,B()),n=[...new Set(Object.values(t.type_to_folder))],o=await oi(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},r=o?await ni({pmRoot:e.pmRoot,expectedSourceCursor:o.source_cursor,query:i}):null;return r?{items:r.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Re(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Jc(e,t){let n=await W(Qi(e,t));if(n===null)return null;try{let o=JSON.parse(n);if(o.schema_version!==1||o.plan.migration_id!==t||!Array.isArray(o.plan.items))throw new TypeError("invalid plan envelope");return o.plan}catch(o){throw new f(`Stored schema migration plan "${t}" is invalid: ${vo(o)}`,h.GENERIC_FAILURE)}}async function qc(e,t){let n=Qi(e,t.migration_id);await De.mkdir(Ye.dirname(n),{recursive:!0});let o={schema_version:1,plan:t,created_at:new Date().toISOString()};await fe(n,`${JSON.stringify(o,null,2)}
17
- `)}function Wc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Bc(e){let t=await Tt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new f(`Schema migration item "${e.id}" no longer exists.`,h.NOT_FOUND);return(await Ot(t,{schema:e.settings.schema})).document.metadata}function Ki(e,t,n){let o=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==o.toLowerCase())throw new TypeError(`Schema migration expected type "${o}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==o.toLowerCase())throw new TypeError(`Schema migration expected status "${o}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let r=e.metadata;if(Object.prototype.hasOwnProperty.call(r,i)&&!Object.prototype.hasOwnProperty.call(r,o))return[];if(!Object.prototype.hasOwnProperty.call(r,o)||Object.prototype.hasOwnProperty.call(r,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return r[i]=r[o],delete r[o],[o,i]}function Vi(e){return{id:e.id,inspect:async()=>{let t=await Ve(e.filePath),n=tr(t.raw,e.request),o=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:o?"applied":"pending",...o?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Ve(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ve(e.filePath);return await fe(e.filePath,Dc(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await er(e.filePath,{exists:t.exists,raw:t.raw})}}}function Hc(e){return{id:e.stepId,inspect:async()=>{let t=await Ve(e.filePath);return{state:Cn(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Ve(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ve(e.filePath);return await fe(e.filePath,Cn(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await er(e.filePath,{exists:t.exists,raw:t.raw})}}}function Kc(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await A(e.pmRoot),n=G(t,B()).type_to_folder,o=await Bc({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=Uc(o,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await A(e.pmRoot),n=G(t,B()).type_to_folder,o=await yn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:Ki(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:o.changedFields}},compensate:async()=>{let t=await A(e.pmRoot),n=G(t,B()).type_to_folder;await yn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(o){return{changedFields:Ki(o,e.request,"reverse")}}})}}}async function Vc(e){let t=await Jc(e.pmRoot,e.migrationId);if(t){if(!Wc(t.request,e.request))throw new f(`Schema migration id "${e.migrationId}" already belongs to a different request.`,h.CONFLICT);return{plan:t,stored:!0}}let n=await zc({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...nr(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Yc(e){let t=tr(await W(e.schemaPath)??"",e.request);if(!t.source)throw new f(`Schema migration source "${e.request.from}" is not a custom definition.`,h.NOT_FOUND);if(t.target)throw new f(`Schema migration target "${e.request.to}" already exists.`,h.CONFLICT);await qc(e.pmRoot,e.plan)}async function Xc(e){let t=Y(e.settings.schema),n=[...new Set([["types",X.types],["fields",X.fields],["workflows",X.workflows]].map(([i,r])=>oe(e.pmRoot,t.files[i],r)).filter(i=>i!==e.schemaPath))];try{let i=Ye.join(e.pmRoot,"templates"),r=await De.readdir(i,{withFileTypes:!0});n.push(...r.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>Ye.join(i,a.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!ie(i))throw i}n.sort((i,r)=>i.localeCompare(r));let o=[];for(let i of n){let r=await W(i);r!==null&&Cn(r,e.request)!==r&&o.push({filePath:i,beforeRaw:r})}return{paths:n,snapshots:o}}async function Zc(e){for(let t of e.snapshots){let n=await De.readFile(t.filePath,"utf8"),o=Ye.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await gn({pmRoot:e.pmRoot,author:e.author,documentPath:o,before:Dt(t.beforeRaw),after:Dt(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${o}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function Qc(e,t,n){let o=Rn(e),i=P(process.cwd(),n.path);await Ee(i);let r=t.migrationId===void 0?Zi(o,await De.realpath(i)):Xi(t.migrationId),a=await A(i),s=H(t.author,a.author_default),c=await Vc({pmRoot:i,settings:a,migrationId:r,request:o}),l=c.plan;if(t.dryRun===!0)return{...l,action:o.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=Cc(i,a,o),p=await De.readFile(d,"utf8");c.stored||await Yc({pmRoot:i,schemaPath:d,request:o,plan:l});let u=await Xc({pmRoot:i,schemaPath:d,settings:a,request:o}),g=[Vi({id:"stage-schema",filePath:d,request:o,phase:"stage"}),...u.paths.map((_,v)=>Hc({filePath:_,request:o,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...l.items.map(_=>Kc({pmRoot:i,id:_.id,request:o,author:s,force:t.force===!0})),Vi({id:"retire-source",filePath:d,request:o,phase:"retire"})],y=await fi({pmRoot:i,transactionId:`schema-${r}`,author:s,steps:g,lockTtlSeconds:Math.max(a.locks.ttl_seconds,300),lockWaitMs:a.locks.wait_ms}),w=await De.readFile(d,"utf8"),{historyPath:m}=await gn({pmRoot:i,author:s,documentPath:Ye.relative(i,d).replaceAll("\\","/"),before:Dt(p),after:Dt(w),op:"schema_migration",idempotencyKey:`${l.migration_id}:${l.fingerprint}`,message:`${o.kind}: ${o.from} -> ${o.to}; affected=${l.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await Zc({pmRoot:i,author:s,settings:a,request:o,plan:l,snapshots:u.snapshots}),{...l,action:o.kind,applied:!0,recovered:y.recovered,migrated_item_count:l.affected_item_count,workspace_history_path:m}}function el(e){let t=e.applied?"applied":"dry-run",n=e.recovered?" (recovered)":"";return[`${e.action}: ${e.request.from} -> ${e.request.to} [${t}${n}]`,`migration_id: ${e.migration_id}`,`affected: ${e.affected_item_count}`,`pending: ${e.pending_item_count}`,`fingerprint: ${e.fingerprint}`].join(`
18
- `)}import rl from"node:path";import{mkdir as al}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebcb45a2-996a-5194-8086-efe882dbcacc")}catch{}})();var at=["agile","ops","research"],tl={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function jt(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${at.join(", ")}.`)}function st(e){return tl[e].map(t=>ot(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96cec314-edb6-5c51-abc4-d028bdc4f10c")}catch{}})();var nl=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function ol(e){let t=nl.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function il(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function or(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,o=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=ol(s);if(c===void 0)continue;let l=i.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<o&&l.examples.push(s),i.set(c,l)}let r=[];for(let[a,s]of i.entries()){if(s.count<n)continue;let c=il(a);r.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:Ko(c)!==void 0})}return r.sort((a,s)=>s.count-a.count||a.name.localeCompare(s.name)),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]="3b47d4d5-a224-5e46-8f91-9988c353c26b")}catch{}})();var og=[...At,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Lt="schema-types",ir="schema-statuses",rr="schema-fields";function Ae(e){return Ge({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function rg(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let i;try{i=ot({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(g){throw new f(g instanceof Error?g.message:String(g),h.USAGE)}let r=await A(o),a=Y(r.schema),s=oe(o,a.files.types,X.types),c=[],l=H(t.author,r.author_default),d=ae(r),p=await Q(o,Lt,r.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let g=await W(s),y;try{y=re(g)}catch(w){throw new f(w instanceof Error?w.message:String(w),h.GENERIC_FAILURE)}try{Vo(i,y);let w=new Map,m=G(r,B());for(let[_,v]of Object.entries(m.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!w.has(k)&&w.set(k,_)}Yo(i,y,w)}catch(w){throw new f(w instanceof Error?w.message:String(w),h.USAGE)}u=ze(y,i),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await Ae({pmRoot:o,filePath:s,raw:le(u.file),op:"schema:add-type",author:l,settings:r}),await ct(o,[u.definition],c,"schema:add-type-folder"),c.push(...await K({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await ar(o,c),{action:"add-type",registered:!0,replaced:u.replaced,type:u.definition,file:{path:s,definitions:u.file.definitions.length},warnings:Te(c),generated_at:T()}}async function ye(e){await Ee(e)}async function ar(e,t){try{let n=await Ci(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Te(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function sl(e,t,n,o){let i=G(t,B()),r=o.trim().toLowerCase();return(await Re(e,t.item_format,i.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===r).length}async function cl(e,t,n,o){let i=G(t,B()),r=nt(n),a=I(o);return(await Re(e,t.item_format,i.type_to_folder,[],n)).filter(c=>{let l=typeof c.status=="string"?c.status:"";return(r.alias_to_id.get(I(l))??I(l))===a}).length}async function ll(e,t,n,o,i){if(i.length===0||Ne.has(i))return;let r=await cl(t,n,o,i);r>0&&e.push(`items_using_status:${r}`);let a=sr(o.workflow,i);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function sr(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,o])=>o!==void 0&&I(o)===t).map(([o])=>o)}async function ag(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let i=await A(o),r=Y(i.schema),a=oe(o,r.files.types,X.types),s=[],c=H(t.author,i.author_default),l=ae(i),d=await Q(o,Lt,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await W(a),g;try{g=re(u)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=Xo(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=(p.definition?.name??e??"").trim();if(y.length>0){let w=await sl(o,i,r,y);w>0&&s.push(`items_using_type:${w}`)}await Ae({pmRoot:o,filePath:a,raw:le(p.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await K({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return p.removed&&await ar(o,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:a,definitions:p.file.definitions.length},warnings:Te(s),generated_at:T()}}function Nn(e,t){return oe(e,t.files.statuses,X.statuses)}function Ft(e,t){return oe(e,t.files.fields,X.fields)}function cr(e,t){return oe(e,t.files.types,X.types)}async function ct(e,t,n,o){for(let i of t){let r=So(i.folder??xo(i.name)),a=rl.join(e,r);await S(a)||(await al(a,{recursive:!0}),n.push(...await K({path:a,scope:"project",op:o})))}}function Dn(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function dl(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function pl(e){let t=new Map;for(let n of e){let o=I(n.id);if(o.length!==0){t.set(o,o);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let r=I(i);r.length>0&&!t.has(r)&&t.set(r,o)}}}return t}async function sg(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let i;try{i=Wi({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(m){throw new f(m instanceof Error?m.message:String(m),h.USAGE)}let r=await A(o),a=Y(r.schema),s=Nn(o,a),c=nt(a);try{On(i,c.alias_to_id)}catch(m){throw new f(m instanceof Error?m.message:String(m),h.USAGE)}let l=dl(c.by_id.get(i.id));if((i.roles??l?.roles??[]).length===0)throw new f(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,h.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Ce(i.id)}" --role active`,`pm schema add-status "${Ce(i.id)}" --role blocked`]});let p=[],u=H(t.author,r.author_default),g=ae(r),y=await Q(o,ir,r.locks.ttl_seconds,u,!!t.force,g.force_required_for_stale_lock,r.locks.wait_ms),w;try{let m=await W(s),_;try{_=He(m)}catch(k){throw new f(k instanceof Error?k.message:String(k),h.GENERIC_FAILURE)}let v=pl(_.statuses);try{On(i,v)}catch(k){throw new f(k instanceof Error?k.message:String(k),h.USAGE)}w=Bi(_,i,l),await Ae({pmRoot:o,filePath:s,raw:Ke(w.file),op:"schema:add-status",author:u,settings:r}),p.push(...await K({path:s,scope:"project",op:"schema:add-status"}))}finally{await y()}return{action:"add-status",registered:!0,replaced:w.replaced,status:w.definition,file:{path:s,statuses:w.file.statuses.length},warnings:Te(p),generated_at:T()}}async function cg(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let i=await A(o),r=Y(i.schema),a=Nn(o,r),s=[],c=H(t.author,i.author_default),l=ae(i),d=await Q(o,ir,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await W(a),g;try{g=He(u)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=Hi(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=I(p.definition?.id??e);await ll(s,o,i,r,y),await Ae({pmRoot:o,filePath:a,raw:Ke(p.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await K({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:a,statuses:p.file.statuses.length},warnings:Te(s),generated_at:T()}}function lr(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function ul(e,t,n){return{...lr(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function dr(e){return{id:e.id,source:Ne.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function pr(e,t,n){let o=e.toLowerCase();return n.has(o)?"extension":t.has(o)?"custom":"builtin"}function ml(){let e=new Map,t=B();for(let n of t?.item_types??[]){let o=n.types;if(Array.isArray(o))for(let i of o){if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i.name;typeof r=="string"&&r.trim().length>0&&e.set(r.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function fl(e){let t=nt(e),n=[],o=[];for(let i of t.definitions){let r=dr(i);r.source==="builtin"?n.push(r):o.push(r)}return{builtin:n,custom:o}}async function lt(e){let t=P(process.cwd(),e.path);await ye(t);let n=await A(t),o=Y(n.schema),i=oe(t,o.files.types,X.types),r=Nn(t,o),a=G(n,B()),s=ml(),c=new Set((n.item_types?.definitions??[]).map(l=>l.name.trim().toLowerCase()).filter(l=>l.length>0&&!s.has(l)));return{pmRoot:t,typesPath:i,statusesPath:r,byType:a.by_type,customNames:c,extensionProvenance:s,schema:o}}async function lg(e){let t=await lt(e),n=[],o=[],i=[];for(let s of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=pr(s.name,t.customNames,new Set(t.extensionProvenance.keys())),l=lr(s);c==="extension"?i.push(l):c==="custom"?o.push(l):n.push(l)}let r=fl(t.schema),a=$t(t.schema).definitions.map(Dn);return{action:"list",builtin:n,custom:o,extension:i,counts:{builtin:n.length,custom:o.length,extension:i.length,total:n.length+o.length+i.length},statuses:{builtin:r.builtin,custom:r.custom,counts:{builtin:r.builtin.length,custom:r.custom.length,total:r.builtin.length+r.custom.length}},fields:{custom:a,counts:{total:a.length}},file:{path:t.typesPath},generated_at:T()}}async function dg(e,t){let n=(e??"").trim();if(n.length===0)throw new f("Type name must not be empty.",h.USAGE);let o=await lt(t),i=Object.values(o.byType).find(r=>r.name.toLowerCase()===n.toLowerCase()||r.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!i)throw new f(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Ce(n)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:ul(i,pr(i.name,o.customNames,new Set(o.extensionProvenance.keys())),o.extensionProvenance.get(i.name.toLowerCase())),file:{path:o.typesPath},generated_at:T()}}async function pg(e,t){let n=I(e);if(n.length===0)throw new f("Status id must not be empty.",h.USAGE);let o=await lt(t),i=nt(o.schema),r=i.alias_to_id.get(n)??n,a=i.by_id.get(r);if(!a)throw new f(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Ce(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:dr(a),file:{path:o.statusesPath},generated_at:T()}}async function ug(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let i;try{i=zi({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}let r=await A(o),a=Y(r.schema),s=Ft(o,a),c=[],l=Ct(i.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let d=H(t.author,r.author_default),p=ae(r),u=await Q(o,rr,r.locks.ttl_seconds,d,!!t.force,p.force_required_for_stale_lock,r.locks.wait_ms),g;try{let y=await W(s),w;try{w=We(y)}catch(m){throw new f(m instanceof Error?m.message:String(m),h.GENERIC_FAILURE)}g=Ji(w,i),await Ae({pmRoot:o,filePath:s,raw:Be(g.file),op:"schema:add-field",author:d,settings:r}),c.push(...await K({path:s,scope:"project",op:"schema:add-field"}))}finally{await u()}return{action:"add-field",registered:!0,replaced:g.replaced,field:g.definition,file:{path:s,fields:g.file.fields.length},warnings:Te(c),generated_at:T()}}async function hl(e,t,n,o){let i=G(t,B());return(await Re(e,t.item_format,i.type_to_folder,[],n)).filter(a=>{let s=a[o];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function mg(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let i=await A(o),r=Y(i.schema),a=Ft(o,r),s=[],c=H(t.author,i.author_default),l=ae(i),d=await Q(o,rr,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await W(a),g;try{g=We(u)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=qi(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=I(p.definition?.key??e),w=I(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(w.length>0){let m=await hl(o,i,r,w);m>0&&s.push(`items_using_field:${m}`)}await Ae({pmRoot:o,filePath:a,raw:Be(p.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await K({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:a,fields:p.file.fields.length},warnings:Te(s),generated_at:T()}}async function fg(e){let t=await lt(e),n=$t(t.schema).definitions.map(Dn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Ft(t.pmRoot,t.schema)},generated_at:T()}}async function hg(e,t){let n=I(e);if(n.length===0)throw new f("Field key must not be empty.",h.USAGE);let o=await lt(t),i=$t(o.schema).by_key.get(n);if(!i)throw new f(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Ce(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Dn(i),file:{path:Ft(o.pmRoot,o.schema)},generated_at:T()}}async function gg(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let i;try{let w=jt(e);if(w===void 0)throw new Error(`Type preset name is required. Allowed: ${at.join(", ")}.`);i=w}catch(w){throw new f(w instanceof Error?w.message:String(w),h.USAGE)}let r=await A(o),a=Y(r.schema),s=cr(o,a),c=[],l=H(t.author,r.author_default),d=ae(r),p=[],u=[],g,y=await Q(o,Lt,r.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms);try{let w=await W(s),m;try{m=re(w)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let _=m;for(let v of st(i)){let k=ze(_,v);_=k.file,(k.replaced?u:p).push(k.definition.name)}g=_.definitions.length,await Ae({pmRoot:o,filePath:s,raw:le(_),op:"schema:apply-preset",author:l,settings:r}),await ct(o,st(i),c,"schema:apply-preset-folder"),c.push(...await K({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:i,registered:p,replaced:u,file:{path:s,definitions:g},warnings:Te(c),generated_at:T()}}function gl(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new f("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function yg(e,t){let n=P(process.cwd(),t.path);await ye(n);let o=await A(n),i=Y(o.schema),r=cr(n,i),a=gl(e.minCount),s=G(o,B()),l=(await Re(n,o.item_format,s.type_to_folder,[],i)).map(k=>typeof k.title=="string"?k.title:""),d=or(l,{minCount:a}),p=[],u=[],g=[],y=[],w;if(!e.apply){let k;try{k=re(await W(r))}catch(x){throw new f(x instanceof Error?x.message:String(x),h.GENERIC_FAILURE)}return w=k.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:d,registered:u,replaced:g,skipped:y,file:{path:r,definitions:w},warnings:p,generated_at:T()}}let m=H(e.author,o.author_default),_=ae(o),v=await Q(n,Lt,o.locks.ttl_seconds,m,!!e.force,_.force_required_for_stale_lock,o.locks.wait_ms);try{let k=await W(r),x;try{x=re(k)}catch(U){throw new f(U instanceof Error?U.message:String(U),h.GENERIC_FAILURE)}let C=x;for(let U of d){if(U.shadows_builtin){y.push({name:U.name,reason:"shadows_builtin"});continue}let L;try{L=ot({name:U.name})}catch{y.push({name:U.name,reason:"invalid_type_token"});continue}let E=ze(C,L);C=E.file,(E.replaced?g:u).push(E.definition.name)}w=C.definitions.length,await Ae({pmRoot:n,filePath:r,raw:le(C),op:"schema:infer-types",author:m,settings:o}),await ct(n,C.definitions.filter(U=>u.includes(U.name)||g.includes(U.name)),p,"schema:infer-types-folder"),p.push(...await K({path:r,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:d,registered:u,replaced:g,skipped:y,file:{path:r,definitions:w},warnings:Te(p),generated_at:T()}}function _g(e){let t=e.replaced?"Updated":"Registered",n=e.type.aliases&&e.type.aliases.length>0?` (aliases: ${e.type.aliases.join(", ")})`:"";return`${t} custom item type "${e.type.name}"${n} in ${e.file.path}. Run: pm create "${Ce(e.type.name)}" "<title>"`}function wg(e){return e.removed?`Removed custom item type "${e.type?.name??"(unknown)"}" from ${e.file.path}.`:`No custom item type matched; nothing removed from ${e.file.path}.`}function vg(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",o=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${o} in ${e.file.path}.`}function bg(e){return e.removed?`Removed custom status "${e.status?.id??"(unknown)"}" from ${e.file.path}.`:`No custom status matched; nothing removed from ${e.file.path}.`}function kg(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,o]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])o.length!==0&&t.push(`${n}: ${o.map(i=>i.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,o]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])o.length!==0&&t.push(`${n}: ${o.map(i=>i.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(n=>`${n.key} (${n.type}, ${n.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
19
- `)}function xg(e){let t=[`type: ${e.type.name}`,`source: ${e.type.source}`,`folder: ${e.type.folder}`];return e.type.default_status&&t.push(`default_status: ${e.type.default_status}`),e.type.aliases.length>0&&t.push(`aliases: ${e.type.aliases.join(", ")}`),e.type.description&&t.push(`description: ${e.type.description}`),e.type.options.length>0&&t.push(`options: ${e.type.options.map(n=>n.key).join(", ")}`),t.join(`
20
- `)}function Sg(e){let t=[`status: ${e.status.id}`,`source: ${e.status.source}`];return e.status.roles.length>0&&t.push(`roles: ${e.status.roles.join(", ")}`),e.status.aliases.length>0&&t.push(`aliases: ${e.status.aliases.join(", ")}`),e.status.description&&t.push(`description: ${e.status.description}`),typeof e.status.order=="number"&&t.push(`order: ${e.status.order}`),t.join(`
21
- `)}function yl(e){let t=[];e.required&&t.push("required"),e.required_on_create&&t.push("required_on_create"),e.allow_unset||t.push("no_unset");let n=t.length>0?` [${t.join(", ")}]`:"";return`${e.key} (${e.type}) ${e.cli_flag} commands=${e.commands.join("/")}${n}`}function Eg(e){return`${e.replaced?"Updated":"Registered"} custom field "${e.field.key}" in ${e.file.path}. Use it: pm create "<title>" --${(e.field.cli_flag??e.field.key).replaceAll("_","-")} <value>`}function $g(e){return e.removed?`Removed custom field "${e.field?.key??"(unknown)"}" from ${e.file.path}.`:`No custom field matched; nothing removed from ${e.file.path}.`}function Ig(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${yl(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
22
- `)}function Ag(e){let t=e.field,n=[`field: ${t.key}`,`type: ${t.type}`,`cli_flag: ${t.cli_flag}`,`commands: ${t.commands.join(", ")}`];return t.cli_aliases.length>0&&n.push(`cli_aliases: ${t.cli_aliases.join(", ")}`),t.description&&n.push(`description: ${t.description}`),t.required&&n.push("required: true"),t.required_on_create&&n.push("required_on_create: true"),t.allow_unset||n.push("allow_unset: false"),t.required_types.length>0&&n.push(`required_types: ${t.required_types.join(", ")}`),n.join(`
23
- `)}function Tg(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",o=[t,n].filter(i=>i.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${o.length>0?` (${o})`:""}.`}function Og(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;let t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(let n of e.candidates){let o=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${o}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
24
- `)}var Cg={workflowSlotsReferencing:sr};import fr from"node:fs/promises";import je from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8269d712-f438-5f18-8137-ed9a0358e23b")}catch{}})();var Mt=["extensions","docs","examples","assets","prompts"],_l=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});function wl(e){return Mt.includes(e)}function vl(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],o=[];for(let i of n){if(typeof i!="string"||i.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);o.push(i.trim())}return[...new Set(o)].sort((i,r)=>i.localeCompare(r))}function bl(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new f("Package manifest field pm must be an object.",h.USAGE);let t={},n=e;for(let[o,i]of Object.entries(n)){if(!wl(o))continue;let r=vl(o,i);r.length>0&&(t[o]=r)}return t}function pe(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function jn(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,o)=>n.localeCompare(o)):void 0}function ur(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=e.url;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}}function kl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:pe(t,"docs"),npm:pe(t,"npm"),repository:pe(t,"repository"),report:pe(t,"report")};return Object.values(n).some(o=>typeof o=="string")?n:void 0}function xl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:pe(t,"image"),video:pe(t,"video")};return Object.values(n).some(o=>typeof o=="string")?n:void 0}function Sl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:pe(t,"display_name")??pe(t,"displayName"),category:pe(t,"category"),summary:pe(t,"summary"),links:kl(t.links),media:xl(t.media),tags:jn(t.tags)};return Object.values(n).some(o=>o!==void 0)?n:void 0}async function dt(e){let t=je.join(e,"package.json");if(!await S(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await fr.readFile(t,"utf8"))}catch(s){throw new f(`Failed to parse package manifest at "${t}": ${String(s)}`,h.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new f(`Package manifest at "${t}" must be a JSON object.`,h.USAGE);let o=n,i=o.pm,r=i!=null,a=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};return{source:r?"pm":"convention",package_json_path:t,package_name:typeof o.name=="string"?o.name:void 0,package_version:typeof o.version=="string"?o.version:void 0,package_private:o.private===!0,package_description:typeof o.description=="string"?o.description:void 0,package_keywords:jn(o.keywords),package_homepage:typeof o.homepage=="string"?o.homepage:void 0,package_repository_url:ur(o.repository),package_bugs_url:ur(o.bugs),aliases:jn(a.aliases),resources:bl(i),catalog:Sl(a.catalog)}}async function mr(e){if(!await S(e))return[];let t=await fr.readdir(e,{withFileTypes:!0}),n=[];for(let o of t){if(!o.isDirectory())continue;let i=je.join(e,o.name);await S(je.join(i,"manifest.json"))&&n.push(i)}return n.sort((o,i)=>o.localeCompare(i))}async function Ut(e){if(await S(je.join(e,"manifest.json")))return[e];let n=(await dt(e)).resources.extensions??[],o=new Set;for(let i of n){if(i.includes("*")||i.startsWith("!"))throw new f(`Package extension entry "${i}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let r=je.resolve(e,i);if(!V(e,r))throw new f(`Package extension entry "${i}" resolves outside package root.`,h.USAGE);if(await S(je.join(r,"manifest.json"))){o.add(r);continue}for(let a of await mr(r))o.add(a)}if(n.length===0)for(let i of _l.extensions)for(let r of await mr(je.join(e,i)))o.add(r);return[...o].sort((i,r)=>i.localeCompare(r))}import{execFile as Wl}from"node:child_process";import R from"node:fs/promises";import Wn from"node:os";import $ from"node:path";import{fileURLToPath as Bl}from"node:url";import{promisify as Hl}from"node:util";import Kl from"npm-package-arg";import{extract as Vl,list as Yl}from"tar";import Dl from"node:fs/promises";import se from"node:path";import hr from"node:fs/promises";import Ln 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]="209566d6-107e-5c01-995a-96a6dc0e40ed")}catch{}})();function ee(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function b(e){return e.trim().toLowerCase()}function Gt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let o=t.length;for(;o>n&&t[o-1]==="-";)o-=1;let i=t.slice(n,o);if(i.length===0)throw new f("Extension manifest name must resolve to a non-empty directory name.",h.USAGE);if(i==="."||i==="..")throw new f('Extension manifest name must not resolve to "." or "..".',h.USAGE);return i}function Fn(e){return Po(e)}async function El(e){try{let t=JSON.parse(await hr.readFile(Ln.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(o=>typeof t.scripts?.[o]=="string")}}catch{return{has_build_script:!1}}}async function $l(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new f(`Extension entry file is missing at "${t}".`,h.USAGE);let o=await El(n.source_root),i=o.package_name?`pm install npm:${o.package_name}`:void 0,r=n.source_input??n.source_root;return new f(`Extension entry "${e.entry}" is absent from GitHub source "${r}". pm install copies GitHub repositories without running package scripts${o.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,h.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${r}`,normalized_args:["install",r],...i?{next_best_command:i}:{}}})}async function Ze(e,t={}){let n=Ln.join(e,"manifest.json");if(!await S(n))throw new f(`Extension manifest is missing at "${n}".`,h.USAGE);let o;try{o=JSON.parse(await hr.readFile(n,"utf8"))}catch(a){throw new f(`Failed to parse extension manifest at "${n}": ${Il(a)}`,h.USAGE)}let i=Fn(o);if(!i)throw new f(`Extension manifest at "${n}" is invalid.`,h.USAGE);let r=Ln.resolve(e,i.entry);if(!V(e,r))throw new f(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,h.USAGE);if(!await S(r))throw await $l(i,r,t);if(!await No(e,r))throw new f(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,h.USAGE);return{directory:e,manifest_path:n,entry_path:r,manifest:i}}function Il(e){return e instanceof Error?e.message:String(e)}import Mn from"node:fs/promises";import Al from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="33b7f318-cc64-55d6-8b57-19a618efe6c0")}catch{}})();var Tl=".managed-extensions.json",zt=1;function pt(e){return Al.join(e,Tl)}function Ol(){return{version:zt,updated_at:T(),entries:[]}}function ut(e){return[...e].sort((t,n)=>{let o=t.scope.localeCompare(n.scope);if(o!==0)return o;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function gr(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function te(e){return typeof e=="string"?e:void 0}function Cl(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function Rl(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:te(t.name),package:te(t.package),version:te(t.version),repository:te(t.repository),owner:te(t.owner),repo:te(t.repo),ref:te(t.ref),subpath:te(t.subpath),commit:te(t.commit)}}function Pl(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Cl(t))return null;let n=Rl(t.source);if(!n)return null;let o=Oo(t.contributions);return o===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:ee(t.capabilities),contributions:o,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:te(t.last_update_check_at),last_update_remote_commit:te(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:te(t.update_error)}}function Nl(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==zt||!Array.isArray(t.entries))return null;let n=[];for(let o of t.entries){let i=Pl(o);i&&n.push(i)}return{version:zt,updated_at:te(t.updated_at)??T(),entries:ut(n)}}async function _e(e){let t=pt(e),n=Ol();try{let o=await Mn.readFile(t,"utf8"),i=JSON.parse(o),r=Nl(i);if(!r)throw new f(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:r,warnings:[]}}catch(o){if(o instanceof f)throw o;if(typeof o=="object"&&o!==null&&"code"in o&&ie(o))return{path:t,state:n,warnings:[]};throw new f(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}async function Le(e,t){let n=pt(e),o={version:zt,updated_at:T(),entries:ut(t.entries)};await Mn.mkdir(e,{recursive:!0}),await Mn.writeFile(n,`${JSON.stringify(o,null,2)}
25
- `,"utf8")}function mt(e,t){let n=e.entries.filter(o=>b(o.name)!==b(t.name)&&b(o.directory)!==b(t.directory));return n.push(t),{...e,updated_at:T(),entries:ut(n)}}async function yr(e,t,n,o){let i=t.entries.find(a=>b(a.name)===b(n));if(!i)return t;let r=mt(t,{...i,contributions:o});return await Le(e,r),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]="96c5708d-1f4d-5f94-9945-7f8baa337106")}catch{}})();var jl="PM_CLI_PACKAGE_ROOT",_r={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Ll=new Set(["*","all"]);function Un(){let e=[],t=process.env[jl];return typeof t=="string"&&t.trim().length>0&&e.push(se.resolve(t.trim())),e.push(ce(import.meta.url,["../../.."])),[...new Set(e)]}async function ft(e){let t=e.trim().toLowerCase(),n=await vr(t);if(n)return n;let o=_r[t];if(!o)return null;for(let i of Un()){let r=se.join(i,".agents","pm","extensions",o.legacy_extension_directory);if(await S(se.join(r,"manifest.json")))return r}return null}function wr(e){return Ll.has(e.trim().toLowerCase())}function Fl(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Ml(e,t){let n=await Dl.readdir(e,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!o.name.startsWith("pm-"))continue;let i=se.join(e,o.name);if(!await S(se.join(i,"package.json")))continue;let r=await dt(i),a=r.aliases&&r.aliases.length>0?r.aliases:[Fl(o.name)];for(let s of a){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:o.name,package_root:i,package_name:r.package_name??null})}}}async function Gn(){let e=new Map;for(let t of Un()){let n=se.join(t,"packages");await S(n)&&await Ml(n,e)}for(let[t,n]of Object.entries(_r))if(!e.has(t))for(let o of Un()){let i=se.join(o,"packages",n.package_directory);if(await S(se.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Jt(){return(await Gn()).map(e=>e.alias)}async function vr(e){let t=e.trim().toLowerCase();return(await Gn()).find(o=>o.alias===t||o.package_directory.toLowerCase()===t||o.package_name?.toLowerCase()===t)?.package_root??null}async function br(e){let t=await vr(e);return t?(await dt(t)).package_name??null:null}async function kr(e){let t=await ft(e);if(!t)return null;try{let n=await Ut(t);return n.length!==1?null:(await Ze(n[0])).manifest.name}catch{return null}}function Ul(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function Gl(e,t,n,o,i,r){let a=o==="global"?"--global":"--project",s=Object.fromEntries(Mt.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||r.has(se.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${a}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:Ul(e),media:e.catalog?.media}}}async function xr(e,t,n={}){let o=St(P(process.cwd(),t.path),process.cwd()),i=e==="global"?o.global:o.project,r=await _e(i),a=new Set(r.state.entries.filter(u=>u.scope===e).filter(u=>u.source.kind!=="builtin").map(u=>se.resolve(u.source.location))),s=new Set(r.state.entries.filter(u=>u.scope===e&&u.source.kind==="builtin").flatMap(u=>[u.source.name,u.source.input,u.source.location]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toLowerCase())),c=[],l=new Map;for(let u of await Gn()){let g=se.resolve(u.package_root),y=l.get(g)??[];y.push(u),l.set(g,y)}for(let u of l.values()){let g=u[0],y=u.map(m=>m.alias).sort((m,_)=>m.localeCompare(_)),w=await dt(g.package_root);c.push(Gl(w,g,y,e,s,a))}let d=Jl(n.fields),p=d?c.map(u=>ql(u,d)):c;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Mt.filter(u=>u!=="extensions"),packages:p}}var zl=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function Jl(e){if(e===void 0)return;let t=ri(e);if(t.length===0)throw new f("Package catalog --fields requires a comma-separated list of field names",h.USAGE);let n=t.filter(o=>!zl.has(o));if(n.length>0)throw new f(`Unknown package catalog --fields value(s): ${n.join(", ")}`,h.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function ql(e,t){let n={};for(let o of t)o==="category"?n[o]=e.catalog?.category??null:o==="display_name"?n[o]=e.catalog?.display_name??null:n[o]=e[o]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="68a37ea1-3571-59ab-b72c-0195efa84e3c")}catch{}})();var Er=Hl(Wl),Wt="@unbrained/pm-cli",Xl={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},zn;async function $r(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let o=$.resolve(t);for(;;){let i=$.join(o,"node_modules",...n.split("/")),r=$.join(i,"package.json");if(await S(r))try{let s=JSON.parse(await R.readFile(r,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let a=$.dirname(o);if(a===o)return null;o=a}}function Jn(e,t,n){let o=e.split("/").map(l=>l.trim()).filter(l=>l.length>0);if(o.length<2)return null;let i=o[0],r=o[1].replace(/\.git$/i,"");if(i.length===0||r.length===0)return null;let a=o.slice(2),s,c;return a[0]==="tree"&&a.length>=2?(s=a[1],c=a.slice(2).join("/")):a.length>0&&(c=a.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:r,repository:`https://github.com/${i}/${r}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function Zl(e,t,n){let o=e.slice(4).trim();if(o.length===0)throw new f('npm package source must include a package spec after "npm:".',h.USAGE);if(t)throw new f('Options "--gh/--github" cannot be combined with npm: package sources.',h.USAGE);if(n)throw new f('Option "--ref" cannot be combined with npm: package sources.',h.USAGE);return{kind:"npm",input:e,spec:o}}function Bt(e,t={}){let n=e.trim();if(n.length===0)throw new f("Extension source is required for --install.",h.USAGE);let o=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Zl(n,t.forceGithub===!0,o);let i=(()=>{try{let a=new URL(n);if(a.hostname!=="github.com")return null;let s=a.pathname.replace(/^\/+/,"");return Jn(s,n,o)}catch{return null}})();if(i)return i;let r=n.startsWith("github.com/")?n.slice(11):null;if(r){let a=Jn(r,n,o);if(!a)throw new f(`Invalid GitHub source "${n}".`,h.USAGE);return a}if(t.forceGithub){let a=Jn(n,n,o);if(!a)throw new f(`Invalid GitHub shorthand "${n}".`,h.USAGE);return a}if(/^https?:\/\//i.test(n))throw new f(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,h.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function qt(e,t=Er,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(o){let i=typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr):"",r=i.trim().length>0?i.trim():o instanceof Error?o.message:String(o);throw new f(`Git command failed: git ${e.join(" ")}
26
- ${r}`,h.GENERIC_FAILURE)}}function Ql(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function ed(e=process.platform){return e==="win32"}async function Ir(e,t,n=Er,o=process.platform,i=process.env){let r=Ql(o),a=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(r,e,{cwd:t,encoding:"utf8",env:a,shell:ed(o)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",l=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new f(`npm command failed: ${r} ${e.join(" ")}
27
- ${l}`,h.GENERIC_FAILURE)}}function Ar(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function Tr(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function td(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("npm err! code e404")||n.includes("404 not found")||n.includes("is not in this registry")}function nd(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return td(e)||n.includes("not found")}function od(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function id(e){let t=Ar(e),n=od(t),o=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${o}`:void 0,r=i?`pm install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:r?[r,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:r?[`Try ${r} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&r?{fallback_candidates:[{source:i,command:r,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:r}:{}}}}}function rd(e,t){if(!nd(t))return null;let n=id(e);return new f(n.message,h.NOT_FOUND,n.context)}async function Or(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await S(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=Bl(t);return await S(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await S(t))return t}return null}async function ad(e){let t=await Or(e);if(t)return t;let n=sd(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function sd(e,t=process.cwd()){let n="@file:",o=e.lastIndexOf(n);if(!Tr(e))return e;let i=e.slice(0,o),r=e.slice(o+n.length);if(r.startsWith("//")&&!r.startsWith("///"))return e;if(!r.startsWith("/"))return`${i}@${$.resolve(t,r)}`;let a;try{a=decodeURIComponent(new URL(`file:${r}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(a)?a.slice(1):a;return`${i}@${s}`}function Sr(e,t){let n=$.resolve(e,t),o=$.relative(e,n);if(o.length===0||o===".."||o.startsWith(`..${$.sep}`)||$.isAbsolute(o))throw new f("npm pack reported a package archive outside its isolated destination.",h.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function cd(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function ld(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,o])=>({key:n,value:o})):[]).flatMap(({key:n,value:o})=>{let i=cd(o,n);return i?[i]:[]})}function dd(e,t){let n=t?.trim().toLowerCase(),o=n?e.filter(a=>{let s=a.name?.trim().toLowerCase();return s!==void 0?s===n:a.key?.trim().toLowerCase()===n}):[];if(o.length===1)return o[0];if(e.length!==1)return;let i=e[0],r=i.name??i.key;return n&&r!==void 0&&r.trim().toLowerCase()!==n?void 0:i}function pd(e,t,n){let o;try{o=JSON.parse(e)}catch{let a=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!a)throw new f("npm pack did not report a tarball filename.",h.GENERIC_FAILURE);return{tarball:Sr(t,a)}}let i=ld(o),r=dd(i,n);if(!r)throw new f("npm pack --json returned an unsupported or ambiguous package receipt.",h.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Sr(t,r.filename),package:r.name??r.key,version:r.version}}async function ud(e){return md(e,Ir)}async function md(e,t){let n=await Or(e.spec);if(n){if((await R.stat(n)).isFile()&&Cr(n))return qn(n);let a=$.join(n,"package.json"),s=await S(a)?JSON.parse(await R.readFile(a,"utf8")):{};return{directory:await Ht(n,e.input),package:typeof s.name=="string"?s.name:void 0,version:typeof s.version=="string"?s.version:void 0,cleanup:async()=>{}}}let o=await R.mkdtemp($.join(Wn.tmpdir(),"pm-npm-package-source-")),i=$.join(o,"pack");await R.mkdir(i,{recursive:!0});try{let r=await ad(e.spec),a=await t(["pack",r,"--json","--pack-destination",i]),s=pd(a,i,Tr(e.spec)?void 0:Ar(e.spec));if(!await S(s.tarball))throw new f("npm pack did not create its reported package archive.",h.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await qn(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await R.rm(o,{recursive:!0,force:!0})}}}}catch(r){await R.rm(o,{recursive:!0,force:!0});let a=rd(e.spec,r);throw a||r}}function Cr(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function we(e){throw new f(e,h.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function fd(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&we(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let o=e.path,i=o.split("/");(o.includes("\\")||o.startsWith("/")||/^[A-Za-z]:/u.test(o)||i.some(r=>r===".."))&&we(`Local package archive contains an escaping path: "${o}".`),i[0]!=="package"&&we(`Local package archive entry "${o}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&we(`Local package archive link "${o}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&we(`Local package archive entry "${o}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&we(`Local package archive entry "${o}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&we(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),o==="package/package.json"&&(n.packageJsonEntries+=1)}async function qn(e,t=Xl){(await R.stat(e)).size>t.maxArchiveBytes&&we(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let o=await R.mkdtemp($.join(Wn.tmpdir(),"pm-local-package-archive-")),i=$.join(o,"extract");await R.mkdir(i,{recursive:!0});let r={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await Yl({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(a===void 0)try{fd(d,t,r)}catch(p){a=p}}}),a!==void 0)throw a;r.packageJsonEntries!==1&&we(`Local package archive must contain exactly one package/package.json entry; found ${r.packageJsonEntries}.`),await Vl({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=$.join(i,"package"),c=$.join(s,"package.json"),l=JSON.parse(await R.readFile(c,"utf8"));return await hd(s),{directory:await Ht(s,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.version:void 0,cleanup:async()=>{await R.rm(o,{recursive:!0,force:!0})}}}catch(s){throw await R.rm(o,{recursive:!0,force:!0}),s}}async function hd(e,t=Ir){let n=$.join(e,"package.json");if(!await S(n))return;let o;try{o=JSON.parse(await R.readFile(n,"utf8"))}catch{return}if(typeof o!="object"||o===null)return;let i=o,r=bd(i),a=gd(i);if(r.length===0&&!a)return;let s={...o};delete s.devDependencies;let c={...s};yd(c),await R.writeFile(n,`${JSON.stringify(c,null,2)}
28
- `,"utf8");try{await Promise.all([R.rm($.join(e,"package-lock.json"),{force:!0}),R.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),r.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),a&&await _d(e)}finally{await R.writeFile(n,`${JSON.stringify(s,null,2)}
29
- `,"utf8")}}function gd(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Wt in t)return!0;return!1}function yd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let o={...n};delete o[Wt],Object.keys(o).length===0?delete e[t]:e[t]=o}}async function _d(e){let t=ce(import.meta.url,["../../.."]),[n,o]=Wt.split("/"),i=$.join(e,"node_modules",n),r=$.join(i,o);await R.mkdir(i,{recursive:!0}),await R.rm(r,{recursive:!0,force:!0}),await R.symlink(t,r,wd(process.platform))}function wd(e){return e==="win32"?"junction":"dir"}function vd(e,t){if(e.startsWith("-"))throw new f(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,h.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(o=>{let i=o.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(o)}))throw new f(`Extension runtime dependency "${e}" has an unsafe version specifier.`,h.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Kl.resolve(e,t)}catch{throw new f(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,h.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function bd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[o,i]of Object.entries(n)){if(o===Wt||typeof i!="string"||i.trim().length===0||t.has(o))continue;let r=i.trim();t.set(o,vd(o,r))}return[...t.values()]}async function Ht(e,t){let n=await Ut(e);if(n.length===1)return n[0];if(n.length>1){let o=n.map(i=>$.relative(e,i).replaceAll($.sep,"/")).sort((i,r)=>i.localeCompare(r));throw new f(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${o.join(", ")}`,h.USAGE)}throw new f(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,h.USAGE)}async function kd(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push($.posix.join(".agents/pm/extensions",t.subpath)),n.push($.posix.join(".custom/pm-extensions",t.subpath)),n.push($.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let r=$.resolve(e,i);if(V(e,r)&&await S($.join(r,"manifest.json")))return{directory:r,resolved_subpath:i}}if(await S($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let o=await Ht(e,t.input);return{directory:o,resolved_subpath:$.relative(e,o).replaceAll($.sep,"/")}}function xd(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function Sd(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!xd(n))return new f(t,h.NOT_FOUND);let o=[];try{let r=process.env.PM_CLI_PACKAGE_ROOT,a=typeof r=="string"&&r.trim().length>0?$.resolve(r.trim()):"";zn?.key!==a&&(zn={key:a,aliases:await Jt()}),o=zn.aliases}catch{}let i=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${o.join(", ")}`];return new f(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,h.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Rr(e){if(e.kind==="local"){let o;try{o=await R.stat(e.absolute_path)}catch{throw await Sd(e)}if(o.isFile()&&Cr(e.absolute_path)){let r=await qn(e.absolute_path);return{source:e,directory:r.directory,source_root:$.dirname(r.directory),resolved_subpath:$.relative($.dirname(r.directory),r.directory).replaceAll($.sep,"/"),npm_package:r.package,npm_version:r.version,cleanup:r.cleanup}}if(!o.isDirectory())throw new f(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let i=await Ht(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let o=await ud(e);return{source:e,directory:o.directory,source_root:$.dirname(o.directory),cleanup:o.cleanup,resolved_subpath:$.relative($.dirname(o.directory),o.directory).replaceAll($.sep,"/"),npm_package:o.package,npm_version:o.version}}let t=await R.mkdtemp($.join(Wn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await qt(n);let o=await qt(["-C",t,"rev-parse","HEAD"]),i=await kd(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:o,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(o){throw await R.rm(t,{recursive:!0,force:!0}),o}}async function Kt(e,t){if(!await S(e)||!await S(t))return!1;let[n,o]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===o}import ht from"node:fs/promises";import gt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60ab864f-43c5-512c-b33f-456de96f8090")}catch{}})();var Bn=1,Fe="2026.6.24",Ed=">=22.18.0",$d={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Pr=new Set([...Bo.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(go).map(e=>e.toLowerCase()),"scaffold"]),Id="^6.0.0",Ad="^22.0.0",jr=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],ue=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Nr(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Lr(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function Fr(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var Td={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Dr=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Mr={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},Od={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},Cd={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},Rd={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},Ur="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Pd={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},Nd={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},Dd={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},jd={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function Gr(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function zr(e,t){return e==="schema"?Dd[t]:e==="profile"?jd[t]:Nd[t]}function Ld(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),o=0;for(;t[o]?.toLowerCase()==="starter";)o+=1;let i=t[o]?.toLowerCase(),r=o>0&&(o===t.length||i!==void 0&&Pr.has(i));return`${(Pr.has(n)||r?["starter",...t]:t).join(" ")} ping`}function Jr(e){let t=e,n=`${e}s`,o=e.replace(/-/g,""),i=o===t?[]:[o],r=`${e.replace(/-/g,"_")}_owner`,a="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(a)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(r)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(a)}],`,` [${JSON.stringify(a)}, "in_progress"],`,` [${JSON.stringify(a)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function Fd(e,t,n){let o=`${e}-search`,i=`${e}-vector`,r=`${e.replace(/-/g," ")} items`,a=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return a;if(n==="search")return[...a,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,l=e.replace(/-/g,""),d=l===s?[]:[l],p=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`;return[...a,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(u)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...a,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...Jr(e).map(s=>` ${s}`)," });"]:n==="importers"?[...a,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(r)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(r)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...a,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...a,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...a,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...a,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function Md(e,t,n){let o=n==="hooks",i=n==="search",r=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",p=n==="services",u=Od[n],g=e,y=`${e}s`,w=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`,_=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=o?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],k=i?Hn(e,t,"search",u):[],x=r?Hn(e,t,"importers",u):[],C=a?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...Nr(Lr({extensionName:e,itemTypeName:g,itemTypeFolder:y,fieldName:w,migrationId:m,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],U=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...Nr(Fr(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],L=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],E=l?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],q=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],tt=p?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",..._,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...jr,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...l?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...v,...k,...x,...C,...U,...L,...E,...q,...tt,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
30
- `)}function Ud(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let o=`${e.replace(/-/g," ")} items`;return[t,`${o} import`,`${o} export`]}return[t]}var Gd={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},zd={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function Jd(e,t,n){let o=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...o?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...o?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function qd(e,t,n){let o=[],i=[...Jd(e,t,n)],r=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,l=e,d=`${e}s`,p=e.replace(/-/g,""),u=p===l?[]:[p],g=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":o.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),r.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":o.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(a)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),r.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":o.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),r.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":o.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(g)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(l)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(u)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(y)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),r.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":o.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...Jr(e),"});"),r.push(" profiles: [starterProfile],");break;case"renderers":o.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),r.push(" renderers: { toon: toonRenderer },");break;case"parser":o.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),r.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":o.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),r.push(" preflights: [preflightOverride],");break;case"services":o.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),r.push(" services: { output_format: outputService },");break}return{builderImports:o,definitions:i,blueprintFields:r}}function Wd(e,t,n){let o=qd(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...o.builderImports].sort((r,a)=>r.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...o.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...o.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
31
- `)}function Hn(e,t,n,o){if(n==="commands")return[];let i=`${e}-search`,r=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,l=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${o},`," });"],u=g=>[...p," let deactivated = false;"," try {",...g.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...u([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...u([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(r)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(r)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...u([` ext.assertImporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(a)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...u(Lr({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:l,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(Fr(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...u([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...u([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...u([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...u([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function Bd(e,t,n){let o=n==="parser",i=JSON.stringify([...Mr[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...jr,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(Fe)},`," },",` target: { pmVersion: ${JSON.stringify(Fe)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...o?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...Hn(e,t,n,i)].join(`
32
- `)}function Hd(e,t,n){let o=Gr(n,"package"),i=zr(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",o,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${Gd[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",Ur,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${zd[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Bn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Fe}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
33
- `)}function Kd(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function Vd(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function Yd(e,t,n,o){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(o.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(o.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(o.itemTypeName)},`,` folder: ${JSON.stringify(o.itemTypeFolder)},`,` aliases: ${JSON.stringify(o.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(o.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(o.itemTypeName)}, folder: ${JSON.stringify(o.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function Xd(e,t,n){let o=[];return t==="renderers"&&o.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&o.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&o.push(" api.registerPreflight(preflightOverride);"),t==="services"&&o.push(' api.registerService("output_format", outputService);'),t==="hooks"&&o.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&o.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&o.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&o.push(" api.registerProfile(starterProfile);"),t==="importers"&&o.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),o}function Zd(e,t,n,o="commands",i=!1){let r=`pm-${e}`,a=Mr[o],s=Ud(e,t,o),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Bn,pm_min_version:Fe,trusted:!0,sandbox_profile:"strict",permissions:{...$d},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
34
- `,l=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Fd(e,t,o),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
35
- `),d=`${JSON.stringify(Td,null,2)}
36
- `,p=Cd[o],u=Gr(o,"package"),g=`${JSON.stringify({name:r,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Ed},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Fe}`},devDependencies:{"@types/node":Ad,typescript:Id},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
37
- `,y=Md(e,t,o),w=Rd[o],m=["node_modules/","*.log","*.tsbuildinfo",""].join(`
38
- `),_=Kd(e),k=["```ts",`import { ${Vd(o)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Yd(e,t,o,_),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Xd(t,o,_),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],x=[`# ${r}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",u,p,w,Ur,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...k,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Pd[o],...zr(o,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Fe}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Bn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Fe}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
39
- `);return{"package.json":g,"manifest.json":c,"index.ts":i?Wd(e,t,o):l,"index.test.ts":i?Bd(e,t,o):y,"tsconfig.json":d,".gitignore":m,"README.md":i?Hd(r,t,o):x}}async function qr(e,t="extension",n="commands",o=!1){let i=n.trim().toLowerCase();if(!Dr.includes(i))throw new f(`Unknown scaffold capability "${n}". Supported capabilities: ${Dr.join(", ")}.`,h.USAGE);let r=i;if(o&&t!=="package")throw new f("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",h.USAGE);let a=o?"declarative":"imperative",s=e.trim(),c=gt.resolve(process.cwd(),s),l=Gt(gt.basename(c)).replace(/^(?:pm-)+/u,""),d=Ld(l),p=Zd(l,d,t,r,o),u=!1;if(await S(c)){if(!(await ht.stat(c)).isDirectory())throw new f(`Scaffold target "${c}" exists and is not a directory.`,h.CONFLICT)}else await ht.mkdir(c,{recursive:!0}),u=!0;for(let[y,w]of Object.entries(p)){let m=gt.join(c,y);if(!await S(m))continue;if(await ht.readFile(m,"utf8")!==w)throw new f(`Scaffold file "${y}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,h.CONFLICT)}let g=[];for(let[y,w]of Object.entries(p)){let m=gt.join(c,y);if(await S(m)){g.push({path:y,status:"unchanged"});continue}await ht.mkdir(gt.dirname(m),{recursive:!0}),await ht.writeFile(m,w,"utf8"),g.push({path:y,status:"created"})}return{extension_name:l,package_name:`pm-${l}`,command_name:d,invocation_command:`pm ${d}`,capability:r,style:a,target_path:c,created_directory:u,files:g}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bc00b8e-0d9f-5af8-9667-d46136ff52b0")}catch{}})();var Wr=1,Kn=6,Br=[["commands","Commands"],["command_overrides","Command overrides"],["flag_commands","Flag commands"],["item_types","Item types"],["item_fields","Item fields"],["migrations","Migrations"],["profiles","Profiles"],["importers","Importers"],["exporters","Exporters"],["search_providers","Search providers"],["vector_store_adapters","Vector store adapters"],["assurance_providers","Assurance measurement providers"],["hooks","Lifecycle hooks"],["parser_overrides","Parser overrides"],["service_overrides","Service overrides"],["renderer_overrides","Renderer overrides"]];function Vn(e){return"#".repeat(e)}function Hr(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let r of e)n=r==="`"?n+1:0,t=Math.max(t,n);let o="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${o}${i}${e}${i}${o}`}function Qd(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(Hr).join(", ")}`}function ep(e,t,n){let o=[`${Vn(t)} ${e}`,""];return n.length===0?(o.push("_None._",""),o):(o.push(...n.map(i=>`- ${Hr(i)}`),""),o)}function tp(e,t,n){return e===0&&!n?[]:[`${Vn(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function Yn(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<Wr||n>Kn)throw new RangeError(`headingLevel must be an integer in [${Wr}, ${Kn}], received ${String(t.headingLevel)}`);let o=Math.min(n+1,Kn),i=t.includeEmpty===!0,r=t.title??"Extension surfaces",a=[`${Vn(n)} ${r}`,""];(i||e.capabilities.length>0)&&a.push(Qd(e.capabilities),"");for(let[c,l]of Br){let d=e[c]??[];d.length===0&&!i||a.push(...ep(l,o,d))}return a.push(...tp(e.preflight_overrides,o,i)),!(e.preflight_overrides>0||Br.some(([c])=>(e[c]?.length??0)>0))&&!i&&a.push("_This extension registers no surfaces._",""),`${a.join(`
10
+ `;return c===i?{path:o,changed:!1}:(n||await ac(o,c,"utf8"),{path:o,changed:!0})}function Oi(e){let t=G(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,o)=>n.localeCompare(o))}async function kf(e,t){let n=P.resolve(e),o=null,i="",r=n;for(let v=0;v<8;v+=1){let k=P.join(r,".gitattributes");try{let C=await Nt(k,"utf8");if(C.includes(qe)||C.includes(Pt)){o=r,i=C;break}}catch{}let x=P.dirname(r);if(x===r)break;r=x}if(o===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let a=P.join(o,".gitattributes"),s=i.includes(qe),c=s?qe:Pt,l=s?Sn:Ei,d=i.indexOf(c),p=i.indexOf(l),u=p>d?i.slice(d+c.length,p).split(`
11
+ `).map(v=>v.trim()).filter(v=>v.length>0):[],g=An(In(o,n),t),y=new Set(u),w=new Set(g),m=g.filter(v=>!y.has(v)),_=u.filter(v=>!w.has(v));return{status:m.length>0||_.length>0?"drift":"ok",path:a,missing_patterns:m,stale_patterns:_,schema_scope:"project"}}async function xf(e){let t=await $i(),n=[],o=[];for(let i of Ii){let r=`merge.${i.key}.driver`,a=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`,s=`${t}${a}`;try{let{stdout:c}=await En("git",["config","--local","--get",r],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==s&&!await uc(l,a)&&o.push(r)}catch{n.push(r)}}return{status:n.length>0?"missing":o.length>0?"drift":"ok",missing_keys:n,drifted_keys:o}}async function Ci(e){let t;try{t=await Ai(P.resolve(e))}catch{return{status:"no_git"}}let n=In(t,P.resolve(e)),o=await A(e),i=H(void 0,o.author_default),r=await Q(e,dc,o.locks.ttl_seconds,i,!1,ae(o).force_required_for_stale_lock,o.locks.wait_ms);try{let a=P.join(t,".gitattributes"),s;try{s=await Nt(a,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&ie(p))return{status:"not_installed",path:a};throw p}if(!s.includes(qe)&&!s.includes(Pt))return{status:"not_installed",path:a};let c=await A(e),l=Oi(c),d=await Ti(t,An(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await r()}}async function Sf(e,t){let n=pc({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),o=n.pm_root;await Ee(o);let i=await Ai(n.workspace_start);return Tn({pmRoot:o,workspaceRoot:i,dryRun:e.dryRun===!0})}async function Tn(e){let t=P.resolve(e.pmRoot),n=P.resolve(e.workspaceRoot),o=e.dryRun===!0,i,r;try{[i,r]=await Promise.all([at(t),at(n)])}catch(g){throw new f(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(g)}`,h.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let a=In(r,i);if(xn(a))throw new f(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,h.USAGE);let s=await A(i),c=Oi(s),l=An(a,c),d=[],p=await $i();for(let g of Ii)d.push({key:`merge.${g.key}.name`,value:g.name}),d.push({key:`merge.${g.key}.driver`,value:`${p} merge driver ${g.artifact} "%O" "%A" "%B"${g.itemPath===void 0?"":` --item-path ${g.itemPath}`}`});if(!o)try{for(let g of d)await En("git",["config","--local",g.key,g.value],{cwd:r,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new f(`Cannot install repository-local merge drivers in ${r}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,h.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let u=await Ti(r,l,o);return{ok:!0,dry_run:o,workspace_root:r,pm_root:i,gitattributes:{path:u.path,changed:u.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0daf7c89-abc5-5c35-ba3f-9772a50408c0")}catch{}})();var st={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Dt={type:"array",minItems:1,maxItems:fn,items:st},Ri={...Dt,items:{...st,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},mc={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Dt])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:st,id:st}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Ri}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Dt}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Ri,authors:Dt}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:fn,items:{type:"array",minItems:2,maxItems:2,items:st}}}}]}}},If={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:zo,items:mc}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42dee0a5-d003-5e44-8b2d-d74a23d3f2ce")}catch{}})();async function Cf(e,t,n,o){let i=await Se(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Pi(i,t,n,o)}function fc(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Pi(e,t,n=5,o=!1){let i=[],r=new Map,a=e.policies.filter(m=>m.rule.kind==="require_fields"),s=a.filter(m=>m.subject?.operations===void 0),c=new Set,l=0,d=0,p=0,u=0,g=0,y=Wo(e);for(let m of t){let _=y({operation:"",author:"",before:m,after:m,completeness_only:!0});l+=+(_.decisions.length>0),d+=_.decisions.length,_.decisions.forEach(x=>c.add(x.policy_id));let v=_.decisions.filter(x=>!x.satisfied);if(v.length===0)continue;u+=1;let k=r.get(m.type)??{items:0,violations:0,missing_fields:0};k.items+=1;for(let x of v)p+=1,k.violations+=1,k.missing_fields+=x.missing_fields.length,x.effect==="refuse"&&(g+=1),i.length<n&&i.push({id:m.id,type:m.type,status:m.status,decision:x});r.set(m.type,k)}let w=o||g>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:w,ok:w==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:a.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:d,governed_items:l,ungoverned_items:t.length-l,contract_status:fc(a.length,t.length,l),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:u,violation_count:p,refused_violations:g,missing_by_type:Object.fromEntries(r),violations:i,violations_truncated:i.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...o?["validate_completeness_source_incomplete"]:[]]}}import hc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f54fe358-8f4c-5bf4-ae2a-9c92cd08c953")}catch{}})();function gc(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([t,n])=>({id:`completeness-${t.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${t} work reaches completion.`,subject:{types:[t],statuses:["closed"]},rule:{kind:"require_fields",fields:[...n]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function ji(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new f("Policy definition must be valid JSON.",h.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new f("Policy definition must be an object.",h.USAGE);return t}async function yc(e,t){let n=N(process.cwd(),e.path);await Ee(n);let o=await A(n);return{pmRoot:n,settings:o,author:H(t,o.author_default)}}function Ni(e,t,n,o){if(e==="policy-mode")return gn({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let r=hn(o.definition),a=gn({...n,policies:[...i,r].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(a,null,2)}
12
+ `)>Zo)throw new f("Policy registry exceeds its byte ceiling.",h.USAGE);return a}async function Di(e,t,n,o){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:Ni(e,t,await Se(o.pmRoot),n)};let i=await Ho({pmRoot:o.pmRoot,filePath:hc.join(o.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:o.author,message:n.message,lockTtlSeconds:o.settings.locks.ttl_seconds,lockWaitMs:o.settings.locks.wait_ms,mutate(r){let a=Ni(e,t,Qo(r),n);return{raw:`${JSON.stringify(a,null,2)}
13
+ `,result:a}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function _c(e,t,n){let o,i=await ii({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:o}),async mutate(r){let s=(await Se(n.pmRoot)).policies.find(c=>c.id===t.policy);if(!s||s.rule.kind!=="approval")throw new f("--policy must name an approval rule.",h.USAGE);if(!s.rule.authors.includes(n.author))throw new f("This actor is not a declared approver.",h.CONFLICT);return await ei(n.pmRoot,r.metadata.id),o={policy_id:s.id,policy_fingerprint:Jo(s),content_fingerprint:qo(s,{...r.metadata,body:r.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...o,warnings:i.warnings}}}function wc(e,t){let n=ji(t),o=hn({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==o.id)throw new f("Policy id operand does not match definition.id.",h.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return o}async function Kf(e,t,n={},o={}){if(!Tt.includes(e))throw new f("Unknown workflow policy action.",h.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:gc()};let i=await yc(o,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Se(i.pmRoot)};if(e==="policy-put"){let d=wc(t,n.definition);return Di(e,d.id,{...n,definition:d},i)}if(!t?.trim())throw new f(`schema ${e} requires an operand.`,h.USAGE);if(["policy-remove","policy-mode"].includes(e))return Di(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new f("Use policy-check to preview; policy-approve records an approval.",h.USAGE);return _c(t,n,i)}let r=G(i.settings,B()),a=await Ot(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,r.type_to_folder);if(!a)throw new f(`Item ${t} not found.`,h.NOT_FOUND);let{document:s}=await Ct(a,{schema:i.settings.schema}),c={...s.metadata,body:s.body},l=n.definition===void 0?c:{...c,...ji(n.definition)};if(l.id!==c.id)throw new f("Policy preview cannot change the item id.",h.USAGE);return{policy_result:!0,action:e,changed:!1,result:await ti(i.pmRoot,await Se(i.pmRoot),{operation:"update",author:i.author,before:c,after:l,completeness_only:n.definition===void 0})}}import{createHash as Yi}from"node:crypto";import De from"node:fs/promises";import Ye from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f9535c02-9214-5d5e-bac0-2dabbe5d395e")}catch{}})();var vc=new Set(pn),bc=new Set(un),Li=new Set([..._o.filter(e=>e!=="severity"),"id","title","type","status","priority","tags","assignee","parent","description","body","created_at","updated_at","closed_at","completed_at","author","deadline","estimate","sprint","release","risk","confidence","reviewer","resolution","expected","actual"]),kc=["create","update"];function Gi(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function Fi(e){return e.replaceAll("_","-")}function xc(e,t){let n=new Set;for(let o of e){let i=Gi(o);i.length>0&&i!==t&&n.add(i)}return[...n].sort((o,i)=>o.localeCompare(i))}function Sc(e){let t=new Set;for(let n of e??[]){let o=n.trim();o.length>0&&t.add(o)}return[...t].sort((n,o)=>n.localeCompare(o))}function Ec(e){let t=new Set,n=[];for(let o of e??[]){let i=o.trim().toLowerCase();if(i.length!==0){if(!bc.has(i))throw new Error(`Invalid field command "${o}". Allowed: ${un.join(", ")}.`);t.has(i)||(t.add(i),n.push(i))}}return e===void 0||n.length===0?[...kc]:n}function zi(e){let t=I(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(Li.has(t))throw new Error(`Cannot define custom field "${t}": custom schema field "${t}" collides with built-in item metadata "${t}". Rename the custom field with a project-specific prefix. Reserved fields: ${[...Li].sort((d,p)=>d.localeCompare(p)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!vc.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${pn.join(", ")}.`);let o=n,i=Ec(e.commands),r=Gi(e.cliFlag),a=r.length>0&&r!==Fi(t)?r:void 0,s=a??Fi(t),c=xc(e.aliases??[],s),l=e.description?.trim();return{key:t,type:o,commands:i,description:l&&l.length>0?l:void 0,cliFlag:a,cliAliases:c,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:Sc(e.requiredTypes)}}function $c(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function Ic(e){let t=$c(e);if(!t)return[];let n=[];for(let o of t){if(typeof o!="object"||o===null||Array.isArray(o))continue;let i=o;typeof i.key!="string"||i.key.trim().length===0||n.push(i)}return n}function We(e){if(e==null||e.trim().length===0)return{fields:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/fields.json contains invalid JSON.")}return{fields:Ic(t)}}function Be(e){return`${JSON.stringify({fields:e.fields},null,2)}
14
+ `}function Ji(e,t){let n=e.fields.find(a=>I(a.key)===t.key),o=n!==void 0,i=e.fields.filter(a=>I(a.key)!==t.key),r={...n,key:t.key,type:t.type,commands:[...t.commands]};return Mi(r,"description",t.description),Mi(r,"cli_flag",t.cliFlag),t.cliAliases.length>0?r.cli_aliases=[...t.cliAliases]:delete r.cli_aliases,Ui(r,"required",t.required),Ui(r,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?r.allow_unset=!1:delete r.allow_unset,t.requiredTypes.length>0?r.required_types=[...t.requiredTypes]:delete r.required_types,i.push(r),i.sort((a,s)=>I(a.key).localeCompare(I(s.key))),{file:{fields:i},definition:r,replaced:o}}function qi(e,t){let n=I(t);if(n.length===0)throw new Error("Field key must not be empty.");let o=[],i=e.fields.filter(r=>I(r.key)===n?(o.push(r),!1):!0);return o.length===0?{file:{fields:i},removed:!1}:{file:{fields:i},removed:!0,definition:o[0]}}function Mi(e,t,n){let o=e;n!==void 0&&n.length>0?o[t]=n:delete o[t]}function Ui(e,t,n){let o=e;n?o[t]=!0:delete o[t]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e3a1e65b-55d7-5206-b3e7-cac3ac29745c")}catch{}})();var Ac=new Set(Et),Ne=new Set(Fo.map(e=>I(e.id)).filter(e=>e.length>0));function Tc(e){let t=new Set;for(let n of e){let o=I(n);o.length>0&&t.add(o)}return[...t].sort((n,o)=>n.localeCompare(o))}function Wi(e){let t=I(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(Ne.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...Ne].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let a=new Set;for(let s of e.roles){let c=typeof s=="string"?s.trim().toLowerCase():"";if(c.length!==0){if(!Ac.has(c))throw new Error(`Invalid status role "${s}". Allowed roles: ${Et.join(", ")}.`);a.has(c)||(a.add(c),n.push(c))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${Et.join(", ")}.`)}let o=e.aliases===void 0?void 0:Tc(e.aliases).filter(a=>a!==t),i=e.description?.trim(),r=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:o,description:i&&i.length>0?i:void 0,order:r}}function Oc(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function Cc(e){let t=Oc(e);if(!t)return[];let n=[];for(let o of t){if(typeof o!="object"||o===null||Array.isArray(o))continue;let i=o;typeof i.id!="string"||i.id.trim().length===0||n.push(i)}return n}function He(e){if(e==null||e.trim().length===0)return{statuses:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/statuses.json contains invalid JSON.")}return{statuses:Cc(t)}}function Ke(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
15
+ `}function Bi(e,t,n){let o=e.statuses.slice(),i=o.findIndex(s=>I(s.id)===t.id),r=i>=0?o[i]:n,a={...r,id:t.id};return t.roles!==void 0&&(t.roles.length>0?a.roles=[...t.roles]:a.roles!==void 0&&delete a.roles),t.aliases!==void 0&&(t.aliases.length>0?a.aliases=[...t.aliases]:a.aliases!==void 0&&delete a.aliases),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),i>=0?o[i]=a:o.push(a),{file:{statuses:o},definition:a,replaced:r!==void 0}}function Hi(e,t){let n=I(t);if(n.length===0)throw new Error("Status id must not be empty.");if(Ne.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...Ne].join(", ")}.`);let o=e.statuses.slice(),i=o.findIndex(a=>I(a.id)===n);if(i<0)return{file:{statuses:o},removed:!1};let[r]=o.splice(i,1);return{file:{statuses:o},removed:!0,definition:r}}function On(e,t){let n=[e.id,...e.aliases??[]];for(let o of n){let i=I(o);if(i.length===0)continue;let r=t.get(i);if(r!==void 0&&r!==e.id)throw new Error(`Status token "${i}" already belongs to status "${r}". Choose a different id/alias to avoid shadowing it.`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9052af10-ff8c-55db-8a35-b45e1e23a901")}catch{}})();function ge(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Xi(e){let t=ge(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Zi(e,t){let n=Rn(e),o=ge(t,"migrationScope");return`auto-${Yi("sha256").update(JSON.stringify({scope:o,request:n})).digest("hex").slice(0,20)}`}function Rn(e){let t=e.kind==="rename-type"?{kind:e.kind,from:ge(e.from,"source"),to:ge(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:I(ge(e.from,"source")),to:I(ge(e.to,"target")),...e.type===void 0?{}:{type:ge(e.type,"type")}}:{kind:e.kind,from:I(ge(e.from,"source")),to:I(ge(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Rc(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Pc(e,t,n){let o=Y(t.schema),i=Rc(n);return oe(e,o.files[i],X[i])}function Qi(e,t){return Ye.join(e,"transactions","schema",`${t}-plan.json`)}function jt(e){return e.length===0?null:JSON.parse(e)}async function Ve(e){let t=await W(e);return{exists:t!==null,raw:t??""}}async function er(e,t){t.exists?await fe(e,t.raw):await De.rm(e,{force:!0})}function Nc(e,t,n){let o=re(e),i=o.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),r=o.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(r>=0)return le(o);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);o.definitions.push({...o.definitions[i],name:t.to})}else i>=0&&o.definitions.splice(i,1);return le(o)}function Dc(e,t,n){let o=We(e),i=o.fields.findIndex(a=>a.key===t.from),r=o.fields.findIndex(a=>a.key===t.to);if(n==="stage"){if(r>=0)return Be(o);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let a=o.fields[i];o.fields.push({...a,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&o.fields.splice(i,1);return Be(o)}function jc(e,t,n){let o=He(e),i=o.statuses.findIndex(a=>a.id===t.from),r=o.statuses.findIndex(a=>a.id===t.to);if(n==="stage"){if(r>=0)return Ke(o);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);o.statuses.push({...o.statuses[i],id:t.to})}else i>=0&&o.statuses.splice(i,1);return Ke(o)}function Lc(e,t,n){return t.kind==="rename-type"?Nc(e,t,n):t.kind==="rename-field"?Dc(e,t,n):jc(e,t,n)}function Ie(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Xe(e){return Array.isArray(e)?e.map(t=>Pn(t)).filter(t=>t!==void 0):[]}function Fc(e,t){for(let n of Xe(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(o=>Ie(o,t)));for(let n of Xe(e.type_workflows))n.type=Ie(n.type,t)}function Mc(e,t){for(let o of Xe(e.definitions))o.default_status=Ie(o.default_status,t);let n=Pn(e.workflow);if(n)for(let[o,i]of Object.entries(n))n[o]=Ie(i,t);for(let o of Xe(e.type_workflows))Array.isArray(o.allowed_transitions)&&(o.allowed_transitions=o.allowed_transitions.map(i=>Array.isArray(i)?i.map(r=>Ie(r,t)):i))}function Uc(e,t){for(let n of Xe(e.definitions)){for(let o of["required_create_fields","required_create_repeatables"])Array.isArray(n[o])&&(n[o]=n[o].map(i=>Ie(i,t)));for(let o of["options","command_option_policies"])for(let i of Xe(n[o])){let r=o==="options"?"key":"option";i[r]=Ie(i[r],t)}}}function Gc(e,t){let n=Pn(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let o=t.kind==="rename-type"?"type":"status";n[o]=Ie(n[o],t)}function Cn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let o=n;return t.kind==="rename-type"?Fc(o,t):t.kind==="rename-field"?Uc(o,t):Mc(o,t),Gc(o,t),`${JSON.stringify(o,null,2)}
16
+ `}function tr(e,t){if(t.kind==="rename-type"){let o=re(e).definitions;return{source:o.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:o.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let o=We(e).fields;return{source:o.some(i=>i.key===t.from),target:o.some(i=>i.key===t.to)}}let n=He(e).statuses;return{source:n.some(o=>o.id===t.from),target:n.some(o=>o.id===t.to)}}function zc(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function Jc(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function nr(e,t){let n=Rn(t.request),o=t.migrationId===void 0?Zi(n,t.migrationScope??"plan"):Xi(t.migrationId),i=e.map(c=>Jc(c,n)).filter(c=>c!==null).sort((c,l)=>c.id.localeCompare(l.id)),r=Yi("sha256").update(JSON.stringify({migrationId:o,request:n,items:i})).digest("hex"),a=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!a.has(c.id));return Object.freeze({migration_id:o,request:n,fingerprint:r,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function qc(e){let t=G(e.settings,B()),n=[...new Set(Object.values(t.type_to_folder))],o=await oi(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},r=o?await ni({pmRoot:e.pmRoot,expectedSourceCursor:o.source_cursor,query:i}):null;return r?{items:r.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Re(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Wc(e,t){let n=await W(Qi(e,t));if(n===null)return null;try{let o=JSON.parse(n);if(o.schema_version!==1||o.plan.migration_id!==t||!Array.isArray(o.plan.items))throw new TypeError("invalid plan envelope");return o.plan}catch(o){throw new f(`Stored schema migration plan "${t}" is invalid: ${vo(o)}`,h.GENERIC_FAILURE)}}async function Bc(e,t){let n=Qi(e,t.migration_id);await De.mkdir(Ye.dirname(n),{recursive:!0});let o={schema_version:1,plan:t,created_at:new Date().toISOString()};await fe(n,`${JSON.stringify(o,null,2)}
17
+ `)}function Hc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Kc(e){let t=await Ot(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new f(`Schema migration item "${e.id}" no longer exists.`,h.NOT_FOUND);return(await Ct(t,{schema:e.settings.schema})).document.metadata}function Ki(e,t,n){let o=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==o.toLowerCase())throw new TypeError(`Schema migration expected type "${o}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==o.toLowerCase())throw new TypeError(`Schema migration expected status "${o}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let r=e.metadata;if(Object.prototype.hasOwnProperty.call(r,i)&&!Object.prototype.hasOwnProperty.call(r,o))return[];if(!Object.prototype.hasOwnProperty.call(r,o)||Object.prototype.hasOwnProperty.call(r,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return r[i]=r[o],delete r[o],[o,i]}function Vi(e){return{id:e.id,inspect:async()=>{let t=await Ve(e.filePath),n=tr(t.raw,e.request),o=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:o?"applied":"pending",...o?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Ve(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ve(e.filePath);return await fe(e.filePath,Lc(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await er(e.filePath,{exists:t.exists,raw:t.raw})}}}function Vc(e){return{id:e.stepId,inspect:async()=>{let t=await Ve(e.filePath);return{state:Cn(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Ve(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ve(e.filePath);return await fe(e.filePath,Cn(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await er(e.filePath,{exists:t.exists,raw:t.raw})}}}function Yc(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await A(e.pmRoot),n=G(t,B()).type_to_folder,o=await Kc({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=zc(o,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await A(e.pmRoot),n=G(t,B()).type_to_folder,o=await _n({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:Ki(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:o.changedFields}},compensate:async()=>{let t=await A(e.pmRoot),n=G(t,B()).type_to_folder;await _n({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(o){return{changedFields:Ki(o,e.request,"reverse")}}})}}}async function Xc(e){let t=await Wc(e.pmRoot,e.migrationId);if(t){if(!Hc(t.request,e.request))throw new f(`Schema migration id "${e.migrationId}" already belongs to a different request.`,h.CONFLICT);return{plan:t,stored:!0}}let n=await qc({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...nr(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Zc(e){let t=tr(await W(e.schemaPath)??"",e.request);if(!t.source)throw new f(`Schema migration source "${e.request.from}" is not a custom definition.`,h.NOT_FOUND);if(t.target)throw new f(`Schema migration target "${e.request.to}" already exists.`,h.CONFLICT);await Bc(e.pmRoot,e.plan)}async function Qc(e){let t=Y(e.settings.schema),n=[...new Set([["types",X.types],["fields",X.fields],["workflows",X.workflows]].map(([i,r])=>oe(e.pmRoot,t.files[i],r)).filter(i=>i!==e.schemaPath))];try{let i=Ye.join(e.pmRoot,"templates"),r=await De.readdir(i,{withFileTypes:!0});n.push(...r.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>Ye.join(i,a.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!ie(i))throw i}n.sort((i,r)=>i.localeCompare(r));let o=[];for(let i of n){let r=await W(i);r!==null&&Cn(r,e.request)!==r&&o.push({filePath:i,beforeRaw:r})}return{paths:n,snapshots:o}}async function el(e){for(let t of e.snapshots){let n=await De.readFile(t.filePath,"utf8"),o=Ye.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await yn({pmRoot:e.pmRoot,author:e.author,documentPath:o,before:jt(t.beforeRaw),after:jt(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${o}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function tl(e,t,n){let o=Rn(e),i=N(process.cwd(),n.path);await Ee(i);let r=t.migrationId===void 0?Zi(o,await De.realpath(i)):Xi(t.migrationId),a=await A(i),s=H(t.author,a.author_default),c=await Xc({pmRoot:i,settings:a,migrationId:r,request:o}),l=c.plan;if(t.dryRun===!0)return{...l,action:o.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=Pc(i,a,o),p=await De.readFile(d,"utf8");c.stored||await Zc({pmRoot:i,schemaPath:d,request:o,plan:l});let u=await Qc({pmRoot:i,schemaPath:d,settings:a,request:o}),g=[Vi({id:"stage-schema",filePath:d,request:o,phase:"stage"}),...u.paths.map((_,v)=>Vc({filePath:_,request:o,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...l.items.map(_=>Yc({pmRoot:i,id:_.id,request:o,author:s,force:t.force===!0})),Vi({id:"retire-source",filePath:d,request:o,phase:"retire"})],y=await fi({pmRoot:i,transactionId:`schema-${r}`,author:s,steps:g,lockTtlSeconds:Math.max(a.locks.ttl_seconds,300),lockWaitMs:a.locks.wait_ms}),w=await De.readFile(d,"utf8"),{historyPath:m}=await yn({pmRoot:i,author:s,documentPath:Ye.relative(i,d).replaceAll("\\","/"),before:jt(p),after:jt(w),op:"schema_migration",idempotencyKey:`${l.migration_id}:${l.fingerprint}`,message:`${o.kind}: ${o.from} -> ${o.to}; affected=${l.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await el({pmRoot:i,author:s,settings:a,request:o,plan:l,snapshots:u.snapshots}),{...l,action:o.kind,applied:!0,recovered:y.recovered,migrated_item_count:l.affected_item_count,workspace_history_path:m}}function nl(e){let t=e.applied?"applied":"dry-run",n=e.recovered?" (recovered)":"";return[`${e.action}: ${e.request.from} -> ${e.request.to} [${t}${n}]`,`migration_id: ${e.migration_id}`,`affected: ${e.affected_item_count}`,`pending: ${e.pending_item_count}`,`fingerprint: ${e.fingerprint}`].join(`
18
+ `)}import sl from"node:path";import{mkdir as cl}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebcb45a2-996a-5194-8086-efe882dbcacc")}catch{}})();var ct=["agile","ops","research"],ol={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function Lt(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${ct.join(", ")}.`)}function lt(e){return ol[e].map(t=>it(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96cec314-edb6-5c51-abc4-d028bdc4f10c")}catch{}})();var il=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function rl(e){let t=il.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function al(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function or(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,o=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=rl(s);if(c===void 0)continue;let l=i.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<o&&l.examples.push(s),i.set(c,l)}let r=[];for(let[a,s]of i.entries()){if(s.count<n)continue;let c=al(a);r.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:Ko(c)!==void 0})}return r.sort((a,s)=>s.count-a.count||a.name.localeCompare(s.name)),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]="3b47d4d5-a224-5e46-8f91-9988c353c26b")}catch{}})();var ag=[...Tt,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Ft="schema-types",ir="schema-statuses",rr="schema-fields";function Ae(e){return Ge({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function cg(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let i;try{i=it({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(g){throw new f(g instanceof Error?g.message:String(g),h.USAGE)}let r=await A(o),a=Y(r.schema),s=oe(o,a.files.types,X.types),c=[],l=H(t.author,r.author_default),d=ae(r),p=await Q(o,Ft,r.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let g=await W(s),y;try{y=re(g)}catch(w){throw new f(w instanceof Error?w.message:String(w),h.GENERIC_FAILURE)}try{Vo(i,y);let w=new Map,m=G(r,B());for(let[_,v]of Object.entries(m.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!w.has(k)&&w.set(k,_)}Yo(i,y,w)}catch(w){throw new f(w instanceof Error?w.message:String(w),h.USAGE)}u=ze(y,i),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await Ae({pmRoot:o,filePath:s,raw:le(u.file),op:"schema:add-type",author:l,settings:r}),await dt(o,[u.definition],c,"schema:add-type-folder"),c.push(...await K({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await ar(o,c),{action:"add-type",registered:!0,replaced:u.replaced,type:u.definition,file:{path:s,definitions:u.file.definitions.length},warnings:Te(c),generated_at:T()}}async function ye(e){await Ee(e)}async function ar(e,t){try{let n=await Ci(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Te(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function ll(e,t,n,o){let i=G(t,B()),r=o.trim().toLowerCase();return(await Re(e,t.item_format,i.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===r).length}async function dl(e,t,n,o){let i=G(t,B()),r=nt(n),a=I(o);return(await Re(e,t.item_format,i.type_to_folder,[],n)).filter(c=>{let l=typeof c.status=="string"?c.status:"";return(r.alias_to_id.get(I(l))??I(l))===a}).length}async function pl(e,t,n,o,i){if(i.length===0||Ne.has(i))return;let r=await dl(t,n,o,i);r>0&&e.push(`items_using_status:${r}`);let a=sr(o.workflow,i);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function sr(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,o])=>o!==void 0&&I(o)===t).map(([o])=>o)}async function lg(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let i=await A(o),r=Y(i.schema),a=oe(o,r.files.types,X.types),s=[],c=H(t.author,i.author_default),l=ae(i),d=await Q(o,Ft,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await W(a),g;try{g=re(u)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=Xo(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=(p.definition?.name??e??"").trim();if(y.length>0){let w=await ll(o,i,r,y);w>0&&s.push(`items_using_type:${w}`)}await Ae({pmRoot:o,filePath:a,raw:le(p.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await K({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return p.removed&&await ar(o,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:a,definitions:p.file.definitions.length},warnings:Te(s),generated_at:T()}}function Nn(e,t){return oe(e,t.files.statuses,X.statuses)}function Mt(e,t){return oe(e,t.files.fields,X.fields)}function cr(e,t){return oe(e,t.files.types,X.types)}async function dt(e,t,n,o){for(let i of t){let r=So(i.folder??xo(i.name)),a=sl.join(e,r);await S(a)||(await cl(a,{recursive:!0}),n.push(...await K({path:a,scope:"project",op:o})))}}function Dn(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function ul(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function ml(e){let t=new Map;for(let n of e){let o=I(n.id);if(o.length!==0){t.set(o,o);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let r=I(i);r.length>0&&!t.has(r)&&t.set(r,o)}}}return t}async function dg(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let i;try{i=Wi({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(m){throw new f(m instanceof Error?m.message:String(m),h.USAGE)}let r=await A(o),a=Y(r.schema),s=Nn(o,a),c=nt(a);try{On(i,c.alias_to_id)}catch(m){throw new f(m instanceof Error?m.message:String(m),h.USAGE)}let l=ul(c.by_id.get(i.id));if((i.roles??l?.roles??[]).length===0)throw new f(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,h.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Ce(i.id)}" --role active`,`pm schema add-status "${Ce(i.id)}" --role blocked`]});let p=[],u=H(t.author,r.author_default),g=ae(r),y=await Q(o,ir,r.locks.ttl_seconds,u,!!t.force,g.force_required_for_stale_lock,r.locks.wait_ms),w;try{let m=await W(s),_;try{_=He(m)}catch(k){throw new f(k instanceof Error?k.message:String(k),h.GENERIC_FAILURE)}let v=ml(_.statuses);try{On(i,v)}catch(k){throw new f(k instanceof Error?k.message:String(k),h.USAGE)}w=Bi(_,i,l),await Ae({pmRoot:o,filePath:s,raw:Ke(w.file),op:"schema:add-status",author:u,settings:r}),p.push(...await K({path:s,scope:"project",op:"schema:add-status"}))}finally{await y()}return{action:"add-status",registered:!0,replaced:w.replaced,status:w.definition,file:{path:s,statuses:w.file.statuses.length},warnings:Te(p),generated_at:T()}}async function pg(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let i=await A(o),r=Y(i.schema),a=Nn(o,r),s=[],c=H(t.author,i.author_default),l=ae(i),d=await Q(o,ir,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await W(a),g;try{g=He(u)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=Hi(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=I(p.definition?.id??e);await pl(s,o,i,r,y),await Ae({pmRoot:o,filePath:a,raw:Ke(p.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await K({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:a,statuses:p.file.statuses.length},warnings:Te(s),generated_at:T()}}function lr(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function fl(e,t,n){return{...lr(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function dr(e){return{id:e.id,source:Ne.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function pr(e,t,n){let o=e.toLowerCase();return n.has(o)?"extension":t.has(o)?"custom":"builtin"}function hl(){let e=new Map,t=B();for(let n of t?.item_types??[]){let o=n.types;if(Array.isArray(o))for(let i of o){if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i.name;typeof r=="string"&&r.trim().length>0&&e.set(r.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function gl(e){let t=nt(e),n=[],o=[];for(let i of t.definitions){let r=dr(i);r.source==="builtin"?n.push(r):o.push(r)}return{builtin:n,custom:o}}async function pt(e){let t=N(process.cwd(),e.path);await ye(t);let n=await A(t),o=Y(n.schema),i=oe(t,o.files.types,X.types),r=Nn(t,o),a=G(n,B()),s=hl(),c=new Set((n.item_types?.definitions??[]).map(l=>l.name.trim().toLowerCase()).filter(l=>l.length>0&&!s.has(l)));return{pmRoot:t,typesPath:i,statusesPath:r,byType:a.by_type,customNames:c,extensionProvenance:s,schema:o}}async function ug(e){let t=await pt(e),n=[],o=[],i=[];for(let s of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=pr(s.name,t.customNames,new Set(t.extensionProvenance.keys())),l=lr(s);c==="extension"?i.push(l):c==="custom"?o.push(l):n.push(l)}let r=gl(t.schema),a=At(t.schema).definitions.map(Dn);return{action:"list",builtin:n,custom:o,extension:i,counts:{builtin:n.length,custom:o.length,extension:i.length,total:n.length+o.length+i.length},statuses:{builtin:r.builtin,custom:r.custom,counts:{builtin:r.builtin.length,custom:r.custom.length,total:r.builtin.length+r.custom.length}},fields:{custom:a,counts:{total:a.length}},file:{path:t.typesPath},generated_at:T()}}async function mg(e,t){let n=(e??"").trim();if(n.length===0)throw new f("Type name must not be empty.",h.USAGE);let o=await pt(t),i=Object.values(o.byType).find(r=>r.name.toLowerCase()===n.toLowerCase()||r.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!i)throw new f(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Ce(n)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:fl(i,pr(i.name,o.customNames,new Set(o.extensionProvenance.keys())),o.extensionProvenance.get(i.name.toLowerCase())),file:{path:o.typesPath},generated_at:T()}}async function fg(e,t){let n=I(e);if(n.length===0)throw new f("Status id must not be empty.",h.USAGE);let o=await pt(t),i=nt(o.schema),r=i.alias_to_id.get(n)??n,a=i.by_id.get(r);if(!a)throw new f(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Ce(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:dr(a),file:{path:o.statusesPath},generated_at:T()}}async function hg(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let i;try{i=zi({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}let r=await A(o),a=Y(r.schema),s=Mt(o,a),c=[],l=Rt(i.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let d=H(t.author,r.author_default),p=ae(r),u=await Q(o,rr,r.locks.ttl_seconds,d,!!t.force,p.force_required_for_stale_lock,r.locks.wait_ms),g;try{let y=await W(s),w;try{w=We(y)}catch(m){throw new f(m instanceof Error?m.message:String(m),h.GENERIC_FAILURE)}g=Ji(w,i),await Ae({pmRoot:o,filePath:s,raw:Be(g.file),op:"schema:add-field",author:d,settings:r}),c.push(...await K({path:s,scope:"project",op:"schema:add-field"}))}finally{await u()}return{action:"add-field",registered:!0,replaced:g.replaced,field:g.definition,file:{path:s,fields:g.file.fields.length},warnings:Te(c),generated_at:T()}}async function yl(e,t,n,o){let i=G(t,B());return(await Re(e,t.item_format,i.type_to_folder,[],n)).filter(a=>{let s=a[o];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function gg(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let i=await A(o),r=Y(i.schema),a=Mt(o,r),s=[],c=H(t.author,i.author_default),l=ae(i),d=await Q(o,rr,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await W(a),g;try{g=We(u)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=qi(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=I(p.definition?.key??e),w=I(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(w.length>0){let m=await yl(o,i,r,w);m>0&&s.push(`items_using_field:${m}`)}await Ae({pmRoot:o,filePath:a,raw:Be(p.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await K({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:a,fields:p.file.fields.length},warnings:Te(s),generated_at:T()}}async function yg(e){let t=await pt(e),n=At(t.schema).definitions.map(Dn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Mt(t.pmRoot,t.schema)},generated_at:T()}}async function _g(e,t){let n=I(e);if(n.length===0)throw new f("Field key must not be empty.",h.USAGE);let o=await pt(t),i=At(o.schema).by_key.get(n);if(!i)throw new f(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Ce(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Dn(i),file:{path:Mt(o.pmRoot,o.schema)},generated_at:T()}}async function wg(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let i;try{let w=Lt(e);if(w===void 0)throw new Error(`Type preset name is required. Allowed: ${ct.join(", ")}.`);i=w}catch(w){throw new f(w instanceof Error?w.message:String(w),h.USAGE)}let r=await A(o),a=Y(r.schema),s=cr(o,a),c=[],l=H(t.author,r.author_default),d=ae(r),p=[],u=[],g,y=await Q(o,Ft,r.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms);try{let w=await W(s),m;try{m=re(w)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let _=m;for(let v of lt(i)){let k=ze(_,v);_=k.file,(k.replaced?u:p).push(k.definition.name)}g=_.definitions.length,await Ae({pmRoot:o,filePath:s,raw:le(_),op:"schema:apply-preset",author:l,settings:r}),await dt(o,lt(i),c,"schema:apply-preset-folder"),c.push(...await K({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:i,registered:p,replaced:u,file:{path:s,definitions:g},warnings:Te(c),generated_at:T()}}function _l(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new f("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function vg(e,t){let n=N(process.cwd(),t.path);await ye(n);let o=await A(n),i=Y(o.schema),r=cr(n,i),a=_l(e.minCount),s=G(o,B()),l=(await Re(n,o.item_format,s.type_to_folder,[],i)).map(k=>typeof k.title=="string"?k.title:""),d=or(l,{minCount:a}),p=[],u=[],g=[],y=[],w;if(!e.apply){let k;try{k=re(await W(r))}catch(x){throw new f(x instanceof Error?x.message:String(x),h.GENERIC_FAILURE)}return w=k.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:d,registered:u,replaced:g,skipped:y,file:{path:r,definitions:w},warnings:p,generated_at:T()}}let m=H(e.author,o.author_default),_=ae(o),v=await Q(n,Ft,o.locks.ttl_seconds,m,!!e.force,_.force_required_for_stale_lock,o.locks.wait_ms);try{let k=await W(r),x;try{x=re(k)}catch(U){throw new f(U instanceof Error?U.message:String(U),h.GENERIC_FAILURE)}let C=x;for(let U of d){if(U.shadows_builtin){y.push({name:U.name,reason:"shadows_builtin"});continue}let F;try{F=it({name:U.name})}catch{y.push({name:U.name,reason:"invalid_type_token"});continue}let E=ze(C,F);C=E.file,(E.replaced?g:u).push(E.definition.name)}w=C.definitions.length,await Ae({pmRoot:n,filePath:r,raw:le(C),op:"schema:infer-types",author:m,settings:o}),await dt(n,C.definitions.filter(U=>u.includes(U.name)||g.includes(U.name)),p,"schema:infer-types-folder"),p.push(...await K({path:r,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:d,registered:u,replaced:g,skipped:y,file:{path:r,definitions:w},warnings:Te(p),generated_at:T()}}function bg(e){let t=e.replaced?"Updated":"Registered",n=e.type.aliases&&e.type.aliases.length>0?` (aliases: ${e.type.aliases.join(", ")})`:"";return`${t} custom item type "${e.type.name}"${n} in ${e.file.path}. Run: pm create "${Ce(e.type.name)}" "<title>"`}function kg(e){return e.removed?`Removed custom item type "${e.type?.name??"(unknown)"}" from ${e.file.path}.`:`No custom item type matched; nothing removed from ${e.file.path}.`}function xg(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",o=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${o} in ${e.file.path}.`}function Sg(e){return e.removed?`Removed custom status "${e.status?.id??"(unknown)"}" from ${e.file.path}.`:`No custom status matched; nothing removed from ${e.file.path}.`}function Eg(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,o]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])o.length!==0&&t.push(`${n}: ${o.map(i=>i.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,o]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])o.length!==0&&t.push(`${n}: ${o.map(i=>i.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(n=>`${n.key} (${n.type}, ${n.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
19
+ `)}function $g(e){let t=[`type: ${e.type.name}`,`source: ${e.type.source}`,`folder: ${e.type.folder}`];return e.type.default_status&&t.push(`default_status: ${e.type.default_status}`),e.type.aliases.length>0&&t.push(`aliases: ${e.type.aliases.join(", ")}`),e.type.description&&t.push(`description: ${e.type.description}`),e.type.options.length>0&&t.push(`options: ${e.type.options.map(n=>n.key).join(", ")}`),t.join(`
20
+ `)}function Ig(e){let t=[`status: ${e.status.id}`,`source: ${e.status.source}`];return e.status.roles.length>0&&t.push(`roles: ${e.status.roles.join(", ")}`),e.status.aliases.length>0&&t.push(`aliases: ${e.status.aliases.join(", ")}`),e.status.description&&t.push(`description: ${e.status.description}`),typeof e.status.order=="number"&&t.push(`order: ${e.status.order}`),t.join(`
21
+ `)}function wl(e){let t=[];e.required&&t.push("required"),e.required_on_create&&t.push("required_on_create"),e.allow_unset||t.push("no_unset");let n=t.length>0?` [${t.join(", ")}]`:"";return`${e.key} (${e.type}) ${e.cli_flag} commands=${e.commands.join("/")}${n}`}function Ag(e){return`${e.replaced?"Updated":"Registered"} custom field "${e.field.key}" in ${e.file.path}. Use it: pm create "<title>" --${(e.field.cli_flag??e.field.key).replaceAll("_","-")} <value>`}function Tg(e){return e.removed?`Removed custom field "${e.field?.key??"(unknown)"}" from ${e.file.path}.`:`No custom field matched; nothing removed from ${e.file.path}.`}function Og(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${wl(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
22
+ `)}function Cg(e){let t=e.field,n=[`field: ${t.key}`,`type: ${t.type}`,`cli_flag: ${t.cli_flag}`,`commands: ${t.commands.join(", ")}`];return t.cli_aliases.length>0&&n.push(`cli_aliases: ${t.cli_aliases.join(", ")}`),t.description&&n.push(`description: ${t.description}`),t.required&&n.push("required: true"),t.required_on_create&&n.push("required_on_create: true"),t.allow_unset||n.push("allow_unset: false"),t.required_types.length>0&&n.push(`required_types: ${t.required_types.join(", ")}`),n.join(`
23
+ `)}function Rg(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",o=[t,n].filter(i=>i.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${o.length>0?` (${o})`:""}.`}function Pg(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;let t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(let n of e.candidates){let o=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${o}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
24
+ `)}var Ng={workflowSlotsReferencing:sr};import fr from"node:fs/promises";import je from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8269d712-f438-5f18-8137-ed9a0358e23b")}catch{}})();var Ut=["extensions","docs","examples","assets","prompts"],vl=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});function bl(e){return Ut.includes(e)}function kl(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],o=[];for(let i of n){if(typeof i!="string"||i.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);o.push(i.trim())}return[...new Set(o)].sort((i,r)=>i.localeCompare(r))}function xl(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new f("Package manifest field pm must be an object.",h.USAGE);let t={},n=e;for(let[o,i]of Object.entries(n)){if(!bl(o))continue;let r=kl(o,i);r.length>0&&(t[o]=r)}return t}function pe(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function jn(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,o)=>n.localeCompare(o)):void 0}function ur(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=e.url;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}}function Sl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:pe(t,"docs"),npm:pe(t,"npm"),repository:pe(t,"repository"),report:pe(t,"report")};return Object.values(n).some(o=>typeof o=="string")?n:void 0}function El(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:pe(t,"image"),video:pe(t,"video")};return Object.values(n).some(o=>typeof o=="string")?n:void 0}function $l(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:pe(t,"display_name")??pe(t,"displayName"),category:pe(t,"category"),summary:pe(t,"summary"),links:Sl(t.links),media:El(t.media),tags:jn(t.tags)};return Object.values(n).some(o=>o!==void 0)?n:void 0}async function ut(e){let t=je.join(e,"package.json");if(!await S(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await fr.readFile(t,"utf8"))}catch(s){throw new f(`Failed to parse package manifest at "${t}": ${String(s)}`,h.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new f(`Package manifest at "${t}" must be a JSON object.`,h.USAGE);let o=n,i=o.pm,r=i!=null,a=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};return{source:r?"pm":"convention",package_json_path:t,package_name:typeof o.name=="string"?o.name:void 0,package_version:typeof o.version=="string"?o.version:void 0,package_private:o.private===!0,package_description:typeof o.description=="string"?o.description:void 0,package_keywords:jn(o.keywords),package_homepage:typeof o.homepage=="string"?o.homepage:void 0,package_repository_url:ur(o.repository),package_bugs_url:ur(o.bugs),aliases:jn(a.aliases),resources:xl(i),catalog:$l(a.catalog)}}async function mr(e){if(!await S(e))return[];let t=await fr.readdir(e,{withFileTypes:!0}),n=[];for(let o of t){if(!o.isDirectory())continue;let i=je.join(e,o.name);await S(je.join(i,"manifest.json"))&&n.push(i)}return n.sort((o,i)=>o.localeCompare(i))}async function Gt(e){if(await S(je.join(e,"manifest.json")))return[e];let n=(await ut(e)).resources.extensions??[],o=new Set;for(let i of n){if(i.includes("*")||i.startsWith("!"))throw new f(`Package extension entry "${i}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let r=je.resolve(e,i);if(!V(e,r))throw new f(`Package extension entry "${i}" resolves outside package root.`,h.USAGE);if(await S(je.join(r,"manifest.json"))){o.add(r);continue}for(let a of await mr(r))o.add(a)}if(n.length===0)for(let i of vl.extensions)for(let r of await mr(je.join(e,i)))o.add(r);return[...o].sort((i,r)=>i.localeCompare(r))}import{execFile as Hl}from"node:child_process";import R from"node:fs/promises";import Wn from"node:os";import $ from"node:path";import{fileURLToPath as Kl}from"node:url";import{promisify as Vl}from"node:util";import Yl from"npm-package-arg";import{extract as Xl,list as Zl}from"tar";import Ll from"node:fs/promises";import se from"node:path";import hr from"node:fs/promises";import Ln 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]="209566d6-107e-5c01-995a-96a6dc0e40ed")}catch{}})();function ee(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function b(e){return e.trim().toLowerCase()}function zt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let o=t.length;for(;o>n&&t[o-1]==="-";)o-=1;let i=t.slice(n,o);if(i.length===0)throw new f("Extension manifest name must resolve to a non-empty directory name.",h.USAGE);if(i==="."||i==="..")throw new f('Extension manifest name must not resolve to "." or "..".',h.USAGE);return i}function Fn(e){return Po(e)}async function Il(e){try{let t=JSON.parse(await hr.readFile(Ln.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(o=>typeof t.scripts?.[o]=="string")}}catch{return{has_build_script:!1}}}async function Al(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new f(`Extension entry file is missing at "${t}".`,h.USAGE);let o=await Il(n.source_root),i=o.package_name?`pm install npm:${o.package_name}`:void 0,r=n.source_input??n.source_root;return new f(`Extension entry "${e.entry}" is absent from GitHub source "${r}". pm install copies GitHub repositories without running package scripts${o.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,h.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${r}`,normalized_args:["install",r],...i?{next_best_command:i}:{}}})}async function Ze(e,t={}){let n=Ln.join(e,"manifest.json");if(!await S(n))throw new f(`Extension manifest is missing at "${n}".`,h.USAGE);let o;try{o=JSON.parse(await hr.readFile(n,"utf8"))}catch(a){throw new f(`Failed to parse extension manifest at "${n}": ${Tl(a)}`,h.USAGE)}let i=Fn(o);if(!i)throw new f(`Extension manifest at "${n}" is invalid.`,h.USAGE);let r=Ln.resolve(e,i.entry);if(!V(e,r))throw new f(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,h.USAGE);if(!await S(r))throw await Al(i,r,t);if(!await No(e,r))throw new f(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,h.USAGE);return{directory:e,manifest_path:n,entry_path:r,manifest:i}}function Tl(e){return e instanceof Error?e.message:String(e)}import Mn from"node:fs/promises";import Ol from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="33b7f318-cc64-55d6-8b57-19a618efe6c0")}catch{}})();var Cl=".managed-extensions.json",Jt=1;function mt(e){return Ol.join(e,Cl)}function Rl(){return{version:Jt,updated_at:T(),entries:[]}}function ft(e){return[...e].sort((t,n)=>{let o=t.scope.localeCompare(n.scope);if(o!==0)return o;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function gr(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function te(e){return typeof e=="string"?e:void 0}function Pl(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function Nl(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:te(t.name),package:te(t.package),version:te(t.version),repository:te(t.repository),owner:te(t.owner),repo:te(t.repo),ref:te(t.ref),subpath:te(t.subpath),commit:te(t.commit)}}function Dl(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Pl(t))return null;let n=Nl(t.source);if(!n)return null;let o=Oo(t.contributions);return o===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:ee(t.capabilities),contributions:o,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:te(t.last_update_check_at),last_update_remote_commit:te(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:te(t.update_error)}}function jl(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Jt||!Array.isArray(t.entries))return null;let n=[];for(let o of t.entries){let i=Dl(o);i&&n.push(i)}return{version:Jt,updated_at:te(t.updated_at)??T(),entries:ft(n)}}async function _e(e){let t=mt(e),n=Rl();try{let o=await Mn.readFile(t,"utf8"),i=JSON.parse(o),r=jl(i);if(!r)throw new f(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:r,warnings:[]}}catch(o){if(o instanceof f)throw o;if(typeof o=="object"&&o!==null&&"code"in o&&ie(o))return{path:t,state:n,warnings:[]};throw new f(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}async function Le(e,t){let n=mt(e),o={version:Jt,updated_at:T(),entries:ft(t.entries)};await Mn.mkdir(e,{recursive:!0}),await Mn.writeFile(n,`${JSON.stringify(o,null,2)}
25
+ `,"utf8")}function ht(e,t){let n=e.entries.filter(o=>b(o.name)!==b(t.name)&&b(o.directory)!==b(t.directory));return n.push(t),{...e,updated_at:T(),entries:ft(n)}}async function yr(e,t,n,o){let i=t.entries.find(a=>b(a.name)===b(n));if(!i)return t;let r=ht(t,{...i,contributions:o});return await Le(e,r),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]="96c5708d-1f4d-5f94-9945-7f8baa337106")}catch{}})();var Fl="PM_CLI_PACKAGE_ROOT",_r={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Ml=new Set(["*","all"]);function Un(){let e=[],t=process.env[Fl];return typeof t=="string"&&t.trim().length>0&&e.push(se.resolve(t.trim())),e.push(ce(import.meta.url,["../../.."])),[...new Set(e)]}async function gt(e){let t=e.trim().toLowerCase(),n=await vr(t);if(n)return n;let o=_r[t];if(!o)return null;for(let i of Un()){let r=se.join(i,".agents","pm","extensions",o.legacy_extension_directory);if(await S(se.join(r,"manifest.json")))return r}return null}function wr(e){return Ml.has(e.trim().toLowerCase())}function Ul(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Gl(e,t){let n=await Ll.readdir(e,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!o.name.startsWith("pm-"))continue;let i=se.join(e,o.name);if(!await S(se.join(i,"package.json")))continue;let r=await ut(i),a=r.aliases&&r.aliases.length>0?r.aliases:[Ul(o.name)];for(let s of a){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:o.name,package_root:i,package_name:r.package_name??null})}}}async function Gn(){let e=new Map;for(let t of Un()){let n=se.join(t,"packages");await S(n)&&await Gl(n,e)}for(let[t,n]of Object.entries(_r))if(!e.has(t))for(let o of Un()){let i=se.join(o,"packages",n.package_directory);if(await S(se.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function qt(){return(await Gn()).map(e=>e.alias)}async function vr(e){let t=e.trim().toLowerCase();return(await Gn()).find(o=>o.alias===t||o.package_directory.toLowerCase()===t||o.package_name?.toLowerCase()===t)?.package_root??null}async function br(e){let t=await vr(e);return t?(await ut(t)).package_name??null:null}async function kr(e){let t=await gt(e);if(!t)return null;try{let n=await Gt(t);return n.length!==1?null:(await Ze(n[0])).manifest.name}catch{return null}}function zl(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function Jl(e,t,n,o,i,r){let a=o==="global"?"--global":"--project",s=Object.fromEntries(Ut.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||r.has(se.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${a}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:zl(e),media:e.catalog?.media}}}async function xr(e,t,n={}){let o=$t(N(process.cwd(),t.path),process.cwd()),i=e==="global"?o.global:o.project,r=await _e(i),a=new Set(r.state.entries.filter(u=>u.scope===e).filter(u=>u.source.kind!=="builtin").map(u=>se.resolve(u.source.location))),s=new Set(r.state.entries.filter(u=>u.scope===e&&u.source.kind==="builtin").flatMap(u=>[u.source.name,u.source.input,u.source.location]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toLowerCase())),c=[],l=new Map;for(let u of await Gn()){let g=se.resolve(u.package_root),y=l.get(g)??[];y.push(u),l.set(g,y)}for(let u of l.values()){let g=u[0],y=u.map(m=>m.alias).sort((m,_)=>m.localeCompare(_)),w=await ut(g.package_root);c.push(Jl(w,g,y,e,s,a))}let d=Wl(n.fields),p=d?c.map(u=>Bl(u,d)):c;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Ut.filter(u=>u!=="extensions"),packages:p}}var ql=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function Wl(e){if(e===void 0)return;let t=ri(e);if(t.length===0)throw new f("Package catalog --fields requires a comma-separated list of field names",h.USAGE);let n=t.filter(o=>!ql.has(o));if(n.length>0)throw new f(`Unknown package catalog --fields value(s): ${n.join(", ")}`,h.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function Bl(e,t){let n={};for(let o of t)o==="category"?n[o]=e.catalog?.category??null:o==="display_name"?n[o]=e.catalog?.display_name??null:n[o]=e[o]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="68a37ea1-3571-59ab-b72c-0195efa84e3c")}catch{}})();var Er=Vl(Hl),Bt="@unbrained/pm-cli",Ql={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},zn;async function $r(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let o=$.resolve(t);for(;;){let i=$.join(o,"node_modules",...n.split("/")),r=$.join(i,"package.json");if(await S(r))try{let s=JSON.parse(await R.readFile(r,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let a=$.dirname(o);if(a===o)return null;o=a}}function Jn(e,t,n){let o=e.split("/").map(l=>l.trim()).filter(l=>l.length>0);if(o.length<2)return null;let i=o[0],r=o[1].replace(/\.git$/i,"");if(i.length===0||r.length===0)return null;let a=o.slice(2),s,c;return a[0]==="tree"&&a.length>=2?(s=a[1],c=a.slice(2).join("/")):a.length>0&&(c=a.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:r,repository:`https://github.com/${i}/${r}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function ed(e,t,n){let o=e.slice(4).trim();if(o.length===0)throw new f('npm package source must include a package spec after "npm:".',h.USAGE);if(t)throw new f('Options "--gh/--github" cannot be combined with npm: package sources.',h.USAGE);if(n)throw new f('Option "--ref" cannot be combined with npm: package sources.',h.USAGE);return{kind:"npm",input:e,spec:o}}function Ht(e,t={}){let n=e.trim();if(n.length===0)throw new f("Extension source is required for --install.",h.USAGE);let o=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return ed(n,t.forceGithub===!0,o);let i=(()=>{try{let a=new URL(n);if(a.hostname!=="github.com")return null;let s=a.pathname.replace(/^\/+/,"");return Jn(s,n,o)}catch{return null}})();if(i)return i;let r=n.startsWith("github.com/")?n.slice(11):null;if(r){let a=Jn(r,n,o);if(!a)throw new f(`Invalid GitHub source "${n}".`,h.USAGE);return a}if(t.forceGithub){let a=Jn(n,n,o);if(!a)throw new f(`Invalid GitHub shorthand "${n}".`,h.USAGE);return a}if(/^https?:\/\//i.test(n))throw new f(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,h.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function Wt(e,t=Er,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(o){let i=typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr):"",r=i.trim().length>0?i.trim():o instanceof Error?o.message:String(o);throw new f(`Git command failed: git ${e.join(" ")}
26
+ ${r}`,h.GENERIC_FAILURE)}}function td(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function nd(e=process.platform){return e==="win32"}async function Ir(e,t,n=Er,o=process.platform,i=process.env){let r=td(o),a=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(r,e,{cwd:t,encoding:"utf8",env:a,shell:nd(o)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",l=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new f(`npm command failed: ${r} ${e.join(" ")}
27
+ ${l}`,h.GENERIC_FAILURE)}}function Ar(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function Tr(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function od(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("npm err! code e404")||n.includes("404 not found")||n.includes("is not in this registry")}function id(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return od(e)||n.includes("not found")}function rd(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function ad(e){let t=Ar(e),n=rd(t),o=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${o}`:void 0,r=i?`pm install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:r?[r,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:r?[`Try ${r} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&r?{fallback_candidates:[{source:i,command:r,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:r}:{}}}}}function sd(e,t){if(!id(t))return null;let n=ad(e);return new f(n.message,h.NOT_FOUND,n.context)}async function Or(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await S(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=Kl(t);return await S(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await S(t))return t}return null}async function cd(e){let t=await Or(e);if(t)return t;let n=ld(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function ld(e,t=process.cwd()){let n="@file:",o=e.lastIndexOf(n);if(!Tr(e))return e;let i=e.slice(0,o),r=e.slice(o+n.length);if(r.startsWith("//")&&!r.startsWith("///"))return e;if(!r.startsWith("/"))return`${i}@${$.resolve(t,r)}`;let a;try{a=decodeURIComponent(new URL(`file:${r}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(a)?a.slice(1):a;return`${i}@${s}`}function Sr(e,t){let n=$.resolve(e,t),o=$.relative(e,n);if(o.length===0||o===".."||o.startsWith(`..${$.sep}`)||$.isAbsolute(o))throw new f("npm pack reported a package archive outside its isolated destination.",h.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function dd(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function pd(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,o])=>({key:n,value:o})):[]).flatMap(({key:n,value:o})=>{let i=dd(o,n);return i?[i]:[]})}function ud(e,t){let n=t?.trim().toLowerCase(),o=n?e.filter(a=>{let s=a.name?.trim().toLowerCase();return s!==void 0?s===n:a.key?.trim().toLowerCase()===n}):[];if(o.length===1)return o[0];if(e.length!==1)return;let i=e[0],r=i.name??i.key;return n&&r!==void 0&&r.trim().toLowerCase()!==n?void 0:i}function md(e,t,n){let o;try{o=JSON.parse(e)}catch{let a=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!a)throw new f("npm pack did not report a tarball filename.",h.GENERIC_FAILURE);return{tarball:Sr(t,a)}}let i=pd(o),r=ud(i,n);if(!r)throw new f("npm pack --json returned an unsupported or ambiguous package receipt.",h.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Sr(t,r.filename),package:r.name??r.key,version:r.version}}async function fd(e){return hd(e,Ir)}async function hd(e,t){let n=await Or(e.spec);if(n){if((await R.stat(n)).isFile()&&Cr(n))return qn(n);let a=$.join(n,"package.json"),s=await S(a)?JSON.parse(await R.readFile(a,"utf8")):{};return{directory:await Kt(n,e.input),package:typeof s.name=="string"?s.name:void 0,version:typeof s.version=="string"?s.version:void 0,cleanup:async()=>{}}}let o=await R.mkdtemp($.join(Wn.tmpdir(),"pm-npm-package-source-")),i=$.join(o,"pack");await R.mkdir(i,{recursive:!0});try{let r=await cd(e.spec),a=await t(["pack",r,"--json","--pack-destination",i]),s=md(a,i,Tr(e.spec)?void 0:Ar(e.spec));if(!await S(s.tarball))throw new f("npm pack did not create its reported package archive.",h.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await qn(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await R.rm(o,{recursive:!0,force:!0})}}}}catch(r){await R.rm(o,{recursive:!0,force:!0});let a=sd(e.spec,r);throw a||r}}function Cr(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function we(e){throw new f(e,h.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function gd(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&we(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let o=e.path,i=o.split("/");(o.includes("\\")||o.startsWith("/")||/^[A-Za-z]:/u.test(o)||i.some(r=>r===".."))&&we(`Local package archive contains an escaping path: "${o}".`),i[0]!=="package"&&we(`Local package archive entry "${o}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&we(`Local package archive link "${o}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&we(`Local package archive entry "${o}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&we(`Local package archive entry "${o}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&we(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),o==="package/package.json"&&(n.packageJsonEntries+=1)}async function qn(e,t=Ql){(await R.stat(e)).size>t.maxArchiveBytes&&we(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let o=await R.mkdtemp($.join(Wn.tmpdir(),"pm-local-package-archive-")),i=$.join(o,"extract");await R.mkdir(i,{recursive:!0});let r={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await Zl({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(a===void 0)try{gd(d,t,r)}catch(p){a=p}}}),a!==void 0)throw a;r.packageJsonEntries!==1&&we(`Local package archive must contain exactly one package/package.json entry; found ${r.packageJsonEntries}.`),await Xl({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=$.join(i,"package"),c=$.join(s,"package.json"),l=JSON.parse(await R.readFile(c,"utf8"));return await yd(s),{directory:await Kt(s,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.version:void 0,cleanup:async()=>{await R.rm(o,{recursive:!0,force:!0})}}}catch(s){throw await R.rm(o,{recursive:!0,force:!0}),s}}async function yd(e,t=Ir){let n=$.join(e,"package.json");if(!await S(n))return;let o;try{o=JSON.parse(await R.readFile(n,"utf8"))}catch{return}if(typeof o!="object"||o===null)return;let i=o,r=xd(i),a=_d(i);if(r.length===0&&!a)return;let s={...o};delete s.devDependencies;let c={...s};wd(c),await R.writeFile(n,`${JSON.stringify(c,null,2)}
28
+ `,"utf8");try{await Promise.all([R.rm($.join(e,"package-lock.json"),{force:!0}),R.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),r.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),a&&await vd(e)}finally{await R.writeFile(n,`${JSON.stringify(s,null,2)}
29
+ `,"utf8")}}function _d(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Bt in t)return!0;return!1}function wd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let o={...n};delete o[Bt],Object.keys(o).length===0?delete e[t]:e[t]=o}}async function vd(e){let t=ce(import.meta.url,["../../.."]),[n,o]=Bt.split("/"),i=$.join(e,"node_modules",n),r=$.join(i,o);await R.mkdir(i,{recursive:!0}),await R.rm(r,{recursive:!0,force:!0}),await R.symlink(t,r,bd(process.platform))}function bd(e){return e==="win32"?"junction":"dir"}function kd(e,t){if(e.startsWith("-"))throw new f(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,h.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(o=>{let i=o.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(o)}))throw new f(`Extension runtime dependency "${e}" has an unsafe version specifier.`,h.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Yl.resolve(e,t)}catch{throw new f(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,h.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function xd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[o,i]of Object.entries(n)){if(o===Bt||typeof i!="string"||i.trim().length===0||t.has(o))continue;let r=i.trim();t.set(o,kd(o,r))}return[...t.values()]}async function Kt(e,t){let n=await Gt(e);if(n.length===1)return n[0];if(n.length>1){let o=n.map(i=>$.relative(e,i).replaceAll($.sep,"/")).sort((i,r)=>i.localeCompare(r));throw new f(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${o.join(", ")}`,h.USAGE)}throw new f(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,h.USAGE)}async function Sd(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push($.posix.join(".agents/pm/extensions",t.subpath)),n.push($.posix.join(".custom/pm-extensions",t.subpath)),n.push($.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let r=$.resolve(e,i);if(V(e,r)&&await S($.join(r,"manifest.json")))return{directory:r,resolved_subpath:i}}if(await S($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let o=await Kt(e,t.input);return{directory:o,resolved_subpath:$.relative(e,o).replaceAll($.sep,"/")}}function Ed(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function $d(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Ed(n))return new f(t,h.NOT_FOUND);let o=[];try{let r=process.env.PM_CLI_PACKAGE_ROOT,a=typeof r=="string"&&r.trim().length>0?$.resolve(r.trim()):"";zn?.key!==a&&(zn={key:a,aliases:await qt()}),o=zn.aliases}catch{}let i=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${o.join(", ")}`];return new f(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,h.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Rr(e){if(e.kind==="local"){let o;try{o=await R.stat(e.absolute_path)}catch{throw await $d(e)}if(o.isFile()&&Cr(e.absolute_path)){let r=await qn(e.absolute_path);return{source:e,directory:r.directory,source_root:$.dirname(r.directory),resolved_subpath:$.relative($.dirname(r.directory),r.directory).replaceAll($.sep,"/"),npm_package:r.package,npm_version:r.version,cleanup:r.cleanup}}if(!o.isDirectory())throw new f(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let i=await Kt(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let o=await fd(e);return{source:e,directory:o.directory,source_root:$.dirname(o.directory),cleanup:o.cleanup,resolved_subpath:$.relative($.dirname(o.directory),o.directory).replaceAll($.sep,"/"),npm_package:o.package,npm_version:o.version}}let t=await R.mkdtemp($.join(Wn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Wt(n);let o=await Wt(["-C",t,"rev-parse","HEAD"]),i=await Sd(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:o,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(o){throw await R.rm(t,{recursive:!0,force:!0}),o}}async function Vt(e,t){if(!await S(e)||!await S(t))return!1;let[n,o]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===o}import yt from"node:fs/promises";import _t from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60ab864f-43c5-512c-b33f-456de96f8090")}catch{}})();var Bn=1,Fe="2026.6.24",Id=">=22.18.0",Ad={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Pr=new Set([...Bo.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(go).map(e=>e.toLowerCase()),"scaffold"]),Td="^6.0.0",Od="^22.0.0",jr=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],ue=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Nr(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Lr(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function Fr(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var Cd={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Dr=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Mr={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},Rd={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},Pd={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},Nd={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},Ur="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Dd={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},jd={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},Ld={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},Fd={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function Gr(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function zr(e,t){return e==="schema"?Ld[t]:e==="profile"?Fd[t]:jd[t]}function Md(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),o=0;for(;t[o]?.toLowerCase()==="starter";)o+=1;let i=t[o]?.toLowerCase(),r=o>0&&(o===t.length||i!==void 0&&Pr.has(i));return`${(Pr.has(n)||r?["starter",...t]:t).join(" ")} ping`}function Jr(e){let t=e,n=`${e}s`,o=e.replace(/-/g,""),i=o===t?[]:[o],r=`${e.replace(/-/g,"_")}_owner`,a="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(a)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(r)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(a)}],`,` [${JSON.stringify(a)}, "in_progress"],`,` [${JSON.stringify(a)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function Ud(e,t,n){let o=`${e}-search`,i=`${e}-vector`,r=`${e.replace(/-/g," ")} items`,a=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return a;if(n==="search")return[...a,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,l=e.replace(/-/g,""),d=l===s?[]:[l],p=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`;return[...a,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(u)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...a,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...Jr(e).map(s=>` ${s}`)," });"]:n==="importers"?[...a,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(r)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(r)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...a,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...a,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...a,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...a,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function Gd(e,t,n){let o=n==="hooks",i=n==="search",r=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",p=n==="services",u=Rd[n],g=e,y=`${e}s`,w=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`,_=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=o?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],k=i?Hn(e,t,"search",u):[],x=r?Hn(e,t,"importers",u):[],C=a?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...Nr(Lr({extensionName:e,itemTypeName:g,itemTypeFolder:y,fieldName:w,migrationId:m,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],U=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...Nr(Fr(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],F=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],E=l?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],q=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],tt=p?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",..._,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...jr,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...l?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...v,...k,...x,...C,...U,...F,...E,...q,...tt,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
30
+ `)}function zd(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let o=`${e.replace(/-/g," ")} items`;return[t,`${o} import`,`${o} export`]}return[t]}var Jd={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},qd={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function Wd(e,t,n){let o=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...o?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...o?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function Bd(e,t,n){let o=[],i=[...Wd(e,t,n)],r=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,l=e,d=`${e}s`,p=e.replace(/-/g,""),u=p===l?[]:[p],g=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":o.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),r.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":o.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(a)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),r.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":o.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),r.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":o.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(g)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(l)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(u)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(y)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),r.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":o.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...Jr(e),"});"),r.push(" profiles: [starterProfile],");break;case"renderers":o.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),r.push(" renderers: { toon: toonRenderer },");break;case"parser":o.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),r.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":o.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),r.push(" preflights: [preflightOverride],");break;case"services":o.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),r.push(" services: { output_format: outputService },");break}return{builderImports:o,definitions:i,blueprintFields:r}}function Hd(e,t,n){let o=Bd(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...o.builderImports].sort((r,a)=>r.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...o.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...o.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
31
+ `)}function Hn(e,t,n,o){if(n==="commands")return[];let i=`${e}-search`,r=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,l=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${o},`," });"],u=g=>[...p," let deactivated = false;"," try {",...g.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...u([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...u([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(r)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(r)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...u([` ext.assertImporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(a)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...u(Lr({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:l,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(Fr(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...u([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...u([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...u([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...u([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function Kd(e,t,n){let o=n==="parser",i=JSON.stringify([...Mr[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...jr,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(Fe)},`," },",` target: { pmVersion: ${JSON.stringify(Fe)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...o?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...Hn(e,t,n,i)].join(`
32
+ `)}function Vd(e,t,n){let o=Gr(n,"package"),i=zr(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",o,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${Jd[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",Ur,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${qd[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Bn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Fe}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
33
+ `)}function Yd(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function Xd(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function Zd(e,t,n,o){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(o.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(o.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(o.itemTypeName)},`,` folder: ${JSON.stringify(o.itemTypeFolder)},`,` aliases: ${JSON.stringify(o.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(o.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(o.itemTypeName)}, folder: ${JSON.stringify(o.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function Qd(e,t,n){let o=[];return t==="renderers"&&o.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&o.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&o.push(" api.registerPreflight(preflightOverride);"),t==="services"&&o.push(' api.registerService("output_format", outputService);'),t==="hooks"&&o.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&o.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&o.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&o.push(" api.registerProfile(starterProfile);"),t==="importers"&&o.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),o}function ep(e,t,n,o="commands",i=!1){let r=`pm-${e}`,a=Mr[o],s=zd(e,t,o),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Bn,pm_min_version:Fe,trusted:!0,sandbox_profile:"strict",permissions:{...Ad},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
34
+ `,l=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Ud(e,t,o),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
35
+ `),d=`${JSON.stringify(Cd,null,2)}
36
+ `,p=Pd[o],u=Gr(o,"package"),g=`${JSON.stringify({name:r,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Id},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Fe}`},devDependencies:{"@types/node":Od,typescript:Td},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
37
+ `,y=Gd(e,t,o),w=Nd[o],m=["node_modules/","*.log","*.tsbuildinfo",""].join(`
38
+ `),_=Yd(e),k=["```ts",`import { ${Xd(o)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Zd(e,t,o,_),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Qd(t,o,_),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],x=[`# ${r}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",u,p,w,Ur,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...k,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Dd[o],...zr(o,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Fe}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Bn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Fe}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
39
+ `);return{"package.json":g,"manifest.json":c,"index.ts":i?Hd(e,t,o):l,"index.test.ts":i?Kd(e,t,o):y,"tsconfig.json":d,".gitignore":m,"README.md":i?Vd(r,t,o):x}}async function qr(e,t="extension",n="commands",o=!1){let i=n.trim().toLowerCase();if(!Dr.includes(i))throw new f(`Unknown scaffold capability "${n}". Supported capabilities: ${Dr.join(", ")}.`,h.USAGE);let r=i;if(o&&t!=="package")throw new f("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",h.USAGE);let a=o?"declarative":"imperative",s=e.trim(),c=_t.resolve(process.cwd(),s),l=zt(_t.basename(c)).replace(/^(?:pm-)+/u,""),d=Md(l),p=ep(l,d,t,r,o),u=!1;if(await S(c)){if(!(await yt.stat(c)).isDirectory())throw new f(`Scaffold target "${c}" exists and is not a directory.`,h.CONFLICT)}else await yt.mkdir(c,{recursive:!0}),u=!0;for(let[y,w]of Object.entries(p)){let m=_t.join(c,y);if(!await S(m))continue;if(await yt.readFile(m,"utf8")!==w)throw new f(`Scaffold file "${y}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,h.CONFLICT)}let g=[];for(let[y,w]of Object.entries(p)){let m=_t.join(c,y);if(await S(m)){g.push({path:y,status:"unchanged"});continue}await yt.mkdir(_t.dirname(m),{recursive:!0}),await yt.writeFile(m,w,"utf8"),g.push({path:y,status:"created"})}return{extension_name:l,package_name:`pm-${l}`,command_name:d,invocation_command:`pm ${d}`,capability:r,style:a,target_path:c,created_directory:u,files:g}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bc00b8e-0d9f-5af8-9667-d46136ff52b0")}catch{}})();var Wr=1,Kn=6,Br=[["commands","Commands"],["command_overrides","Command overrides"],["flag_commands","Flag commands"],["item_types","Item types"],["item_fields","Item fields"],["migrations","Migrations"],["profiles","Profiles"],["importers","Importers"],["exporters","Exporters"],["search_providers","Search providers"],["vector_store_adapters","Vector store adapters"],["assurance_providers","Assurance measurement providers"],["hooks","Lifecycle hooks"],["parser_overrides","Parser overrides"],["service_overrides","Service overrides"],["renderer_overrides","Renderer overrides"]];function Vn(e){return"#".repeat(e)}function Hr(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let r of e)n=r==="`"?n+1:0,t=Math.max(t,n);let o="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${o}${i}${e}${i}${o}`}function tp(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(Hr).join(", ")}`}function np(e,t,n){let o=[`${Vn(t)} ${e}`,""];return n.length===0?(o.push("_None._",""),o):(o.push(...n.map(i=>`- ${Hr(i)}`),""),o)}function op(e,t,n){return e===0&&!n?[]:[`${Vn(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function Yn(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<Wr||n>Kn)throw new RangeError(`headingLevel must be an integer in [${Wr}, ${Kn}], received ${String(t.headingLevel)}`);let o=Math.min(n+1,Kn),i=t.includeEmpty===!0,r=t.title??"Extension surfaces",a=[`${Vn(n)} ${r}`,""];(i||e.capabilities.length>0)&&a.push(tp(e.capabilities),"");for(let[c,l]of Br){let d=e[c]??[];d.length===0&&!i||a.push(...np(l,o,d))}return a.push(...op(e.preflight_overrides,o,i)),!(e.preflight_overrides>0||Br.some(([c])=>(e[c]?.length??0)>0))&&!i&&a.push("_This extension registers no surfaces._",""),`${a.join(`
40
40
  `).trimEnd()}
41
- `}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6c9e36f8-0f95-5768-8893-bf33bbb4d848")}catch{}})();function Kr(e,t){return`${e}:${b(t)}`}function np(e,t){let n=[];for(let[o,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let r=new Map;for(let a of i){let s=r.get(a.command)??[];r.set(a.command,[...s,a])}for(let[a,s]of r){if(t!==null&&!s.some(l=>t.has(b(l.name))))continue;let c=s.at(-1);n.push({command:a,surface:o,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(l=>({name:l.name,layer:l.layer,winner:l===c}))})}}return n.sort((o,i)=>o.command.localeCompare(i.command)||o.surface.localeCompare(i.surface))}function Vr(e,t,n){let o=new Set(n.failed.map(l=>Kr(l.layer,l.name))),i=[...t.loaded.map(l=>({name:l.name,layer:l.layer,version:l.version,activation_status:o.has(Kr(l.layer,l.name))?"failed":"ok",surfaces:Je(n,{extensionName:l.name})})),...t.failed.map(l=>({name:l.name,layer:l.layer,version:"unknown",activation_status:"not_loaded",surfaces:Je(n,{extensionName:l.name})}))].sort((l,d)=>l.name.localeCompare(d.name)||l.layer.localeCompare(d.layer)),r=typeof e=="string"?b(e):null,a=r===null?null:new Set(t.loaded.filter(l=>b(l.name)===r||typeof l.source_package=="string"&&b(l.source_package)===r||(l.source_aliases??[]).some(d=>b(d)===r)).map(l=>b(l.name)).concat(r)),s=a===null?i:i.filter(l=>a.has(b(l.name))),c=a===null?{}:{extensionNames:[...a]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Je(n,c),command_ownership:np(n,a)}}var op={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function By(e,t){let o=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(o.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),o.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){o.push("## Command ownership","");for(let i of e.command_ownership){let r=i.claimants.find(s=>s.winner),a=i.claimants.map(s=>`${s.layer}:${s.name}`).join(", ");o.push(`- \`${i.command}\` (${i.surface}): ${r.layer}:${r.name}; policy=${i.policy}; collision=${String(i.collision)}; claimants=${a}`)}o.push("")}if(e.extensions.length===0)return o.push(`_No ${t}s are loaded._`,""),`${o.join(`
41
+ `}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6c9e36f8-0f95-5768-8893-bf33bbb4d848")}catch{}})();function Kr(e,t){return`${e}:${b(t)}`}function ip(e,t){let n=[];for(let[o,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let r=new Map;for(let a of i){let s=r.get(a.command)??[];r.set(a.command,[...s,a])}for(let[a,s]of r){if(t!==null&&!s.some(l=>t.has(b(l.name))))continue;let c=s.at(-1);n.push({command:a,surface:o,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(l=>({name:l.name,layer:l.layer,winner:l===c}))})}}return n.sort((o,i)=>o.command.localeCompare(i.command)||o.surface.localeCompare(i.surface))}function Vr(e,t,n){let o=new Set(n.failed.map(l=>Kr(l.layer,l.name))),i=[...t.loaded.map(l=>({name:l.name,layer:l.layer,version:l.version,activation_status:o.has(Kr(l.layer,l.name))?"failed":"ok",surfaces:Je(n,{extensionName:l.name})})),...t.failed.map(l=>({name:l.name,layer:l.layer,version:"unknown",activation_status:"not_loaded",surfaces:Je(n,{extensionName:l.name})}))].sort((l,d)=>l.name.localeCompare(d.name)||l.layer.localeCompare(d.layer)),r=typeof e=="string"?b(e):null,a=r===null?null:new Set(t.loaded.filter(l=>b(l.name)===r||typeof l.source_package=="string"&&b(l.source_package)===r||(l.source_aliases??[]).some(d=>b(d)===r)).map(l=>b(l.name)).concat(r)),s=a===null?i:i.filter(l=>a.has(b(l.name))),c=a===null?{}:{extensionNames:[...a]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Je(n,c),command_ownership:ip(n,a)}}var rp={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function Vy(e,t){let o=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(o.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),o.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){o.push("## Command ownership","");for(let i of e.command_ownership){let r=i.claimants.find(s=>s.winner),a=i.claimants.map(s=>`${s.layer}:${s.name}`).join(", ");o.push(`- \`${i.command}\` (${i.surface}): ${r.layer}:${r.name}; policy=${i.policy}; collision=${String(i.collision)}; claimants=${a}`)}o.push("")}if(e.extensions.length===0)return o.push(`_No ${t}s are loaded._`,""),`${o.join(`
42
42
  `).trimEnd()}
43
- `;for(let i of e.extensions){let r=`${i.name} (${i.layer} v${i.version}, ${op[i.activation_status]})`;o.push(Yn(i.surfaces,{title:r,headingLevel:2}))}return e.extensions.length>1&&o.push(Yn(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${o.join(`
43
+ `;for(let i of e.extensions){let r=`${i.name} (${i.layer} v${i.version}, ${rp[i.activation_status]})`;o.push(Yn(i.surfaces,{title:r,headingLevel:2}))}return e.extensions.length>1&&o.push(Yn(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${o.join(`
44
44
  `).trimEnd()}
45
- `}import ip from"node:fs/promises";import rp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4dc16d1-672a-5b1c-b681-97a7b3febd69")}catch{}})();function Xn(e){return rp.join(e,"extension-migrations.json")}function Yr(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Xr(e,t){return`${e.layer}:${e.name}:${t}`}async function ap(e){let t=Xn(e);if(!await S(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await ip.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(o=>typeof o?.key=="string"&&(o.status==="applied"||o.status==="failed")):[]}}async function sp(e,t){let n=await ap(e),o=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,r)=>{let a=Yr(i,r),s=o.get(Xr(i,a));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function cp(e){let t=await sp(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),o=[],i=!1,r=e.migrations.map((d,p)=>({migration:d,index:p})).filter(({migration:d})=>e.scope===void 0||d.layer===e.scope);for(let{migration:d,index:p}of r){let u=Yr(d,p),g=Xr(d,u),y=n.get(g),w=String(d.definition.status??"pending").toLowerCase(),m=y?.status??(w==="applied"||w==="failed"?w:"pending");if(m==="applied"){o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"skipped"});continue}if(e.dryRun===!0){o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"pending"});continue}let _=d.runtime_definition?.run??d.definition.run;if(typeof _!="function"){o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(_({id:u,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:m}));let k={key:g,layer:d.layer,extension:d.name,id:u,status:"applied",attempted_at:v};n.set(g,k),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"applied"}),i=!0}catch(k){let x=k instanceof Error?k.message:String(k),C={key:g,layer:d.layer,extension:d.name,id:u,status:"failed",attempted_at:v,error:x};n.set(g,C),d.definition.status="failed",d.definition.reason=x,o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"failed",error:x}),i=!0}}if(i){let d=await A(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((u,g)=>u.key.localeCompare(g.key))};await Ge({pmRoot:e.pmRoot,filePath:Xn(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
46
- `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let a=o.filter(d=>d.outcome==="pending").length,s=o.filter(d=>d.outcome==="applied").length,c=o.filter(d=>d.outcome==="skipped").length,l=o.filter(d=>d.outcome==="failed").length;return{ok:l===0,dry_run:e.dryRun===!0,state_path:Xn(e.pmRoot),total:o.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:l,migrations:o}}async function Zr(e){let t=await A(e.resolvedRoots.settings_root),n=await ve({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),o=await be(n);e.warnings.push(...n.warnings,...o.warnings);let i=await cp({pmRoot:e.resolvedRoots.pm_root,migrations:o.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:o.failed.length},i.ok)}import Zt from"node:fs/promises";import Xt from"node:path";import Qr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a77d8d8d-f429-5154-ab3a-2caddc44472e")}catch{}})();function Vt(e,t,n){let o=Qr.relative(e,n);return o!==""&&!V(e,n)||n===t||V(t,n)?!1:!o.split(Qr.sep).some(r=>r===".agents"||r==="node_modules"||r.startsWith(".pm-extension-install-backup-"))}import{randomUUID as lp}from"node:crypto";import M from"node:fs/promises";import dp from"node:os";import D 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]="67e85146-6994-5c3b-bcaa-d7001b9b1703")}catch{}})();var ea=3,pp=120,ta=250,up=12e4,mp=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),na=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,oa=e=>mp.has(String(na(e))),Yt=(e,t)=>na(e)===t,ia=e=>new Promise(t=>{setTimeout(t,e)}),ra=async e=>{let t=D.join(e,"package.json");await S(t)||await M.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
47
- `,"utf8")},aa=async e=>{let t=ce(import.meta.url,["../../.."]),n=D.join(e,"node_modules","@unbrained"),o=D.join(n,"pm-cli");await M.mkdir(n,{recursive:!0}),await M.rm(o,{recursive:!0,force:!0}),await M.symlink(t,o,process.platform==="win32"?"junction":"dir")},yt=async e=>{let t=D.resolve(e),n=D.dirname(t),o=D.parse(n).root,i=await M.realpath(o).catch(()=>o),r=D.relative(o,n),a=r===""?[]:r.split(D.sep);for(let[s,c]of a.entries()){let l=D.join(i,c);try{i=await M.realpath(l)}catch{i=D.join(i,...a.slice(s));break}}return D.join(i,D.basename(t))},sa=async(e,t,n,o=dp.tmpdir())=>Ue("extension_install_copy",async()=>{let i=D.resolve(e),r=await M.realpath(i).catch(()=>i),a=await yt(t);if(r===a)return;if(!V(r,a)){await n(r,t,{recursive:!0,force:!0});return}let s=await M.realpath(D.resolve(o)).catch(()=>yt(o)),c=V(r,s)?D.dirname(r):s;if(V(r,c))throw new f(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,h.USAGE,{code:"extension_install_source_contains_destination"});let l=await M.mkdtemp(D.join(c,"pm-extension-copy-")),d=D.join(l,"extension");try{await n(r,d,{recursive:!0,force:!0,filter:p=>Vt(r,a,D.resolve(p))}),await n(d,t,{recursive:!0,force:!0})}finally{await M.rm(l,{recursive:!0,force:!0})}}),ca=async(e,t,n=M.cp)=>{for(let o=1;o<=ea;o+=1)try{await Ue("extension_install_copy",async()=>{await M.rm(t,{recursive:!0,force:!0}),await sa(e,t,n)});return}catch(i){if(!oa(i)||o===ea)throw i;await ia(ta)}},Zn=async e=>{let t;try{t=await M.readFile(D.join(e,"owner.json"),"utf8")}catch(i){if(!bt(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let o=n.token;return typeof o=="string"&&o.length>0?o:null},la=async(e,t)=>await Zn(e)!==t?!1:(await M.rm(e,{recursive:!0,force:!0}),!0),fp=async(e,t)=>{let n;try{n=await M.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let o=await Zn(e);return o===null?(await M.rm(e,{recursive:!0,force:!0}),!0):la(e,o)},hp=(e,t,n)=>{let o=Promise.resolve(),i=setInterval(()=>{o=o.then(async()=>{if(await Zn(e)!==t)return;let r=new Date;await M.utimes(e,r,r)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await o}},gp=async(e,t)=>{await M.mkdir(e);try{await M.writeFile(D.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
48
- `,"utf8")}catch(n){throw await M.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},yp=async(e,t,n,o,i)=>{for(let r=1;r<=n;r+=1)try{return await gp(e,t),!0}catch(a){if(!Yt(a,"EEXIST"))throw a;await fp(e,i)?r-=1:await ia(o)}return!1},Qn=async(e,t,n,o)=>{let i=D.join(e,"runtime","extension-install-locks"),r=D.join(i,"scope.lock");await M.mkdir(i,{recursive:!0});let{attempts:a=pp,delay_ms:s=ta,stale_ms:c=up,heartbeat_ms:l}=o??{};if(![a,s,c,l].filter(_=>_!==void 0).every(Number.isFinite))throw new f("Extension install lock timings must be finite numbers.",h.USAGE);let d=Math.max(1,Math.floor(a)),p=Math.max(0,Math.floor(s)),u=Math.floor(c),g=Math.floor(l??u/3);if(u<=0||g<=0||g>=u)throw new f("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",h.USAGE);let y={pid:process.pid,token:lp(),created_at:T(),destination:t};if(!await yp(r,y,d,p,u))throw new f(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let m=hp(r,y.token,g);try{return await n()}finally{await m(),await la(r,y.token).catch(()=>!1)}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4b9502f-f742-5f11-b341-56763bbed7c2")}catch{}})();var _p=new Set(["node_modules",".git","dist","build","coverage"]);async function da(e,t,n,o){let i=e.source.kind==="local"?await Zt.stat(e.source.absolute_path):void 0,r=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,a=await wp(e.directory,t,o),s={source_mode:r,...r==="archive"?{archive_bytes:i.size}:{},copy:a},c=e.source_root??e.directory;return r==="directory"&&(!a.complete||a.development_entries>0||a.bytes>=16*1024*1024)&&await S(Xt.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),s}async function wp(e,t,n={}){let{maxEntries:o=1e4,maxDepth:i=64,signal:r}=n;if(![o,i].every(p=>Number.isSafeInteger(p)&&p>0))throw new f("maxEntries and maxDepth must be positive safe integers.",h.USAGE);r?.throwIfAborted();let a=await Zt.realpath(e),s=await yt(t),c=await Kt(a,s);r?.throwIfAborted();let l=c?"in_place":V(a,s)?"nested_filtered_snapshot":"directory_snapshot",d={copy_scope:l,source_directory:a,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:o,max_depth:i};return l==="in_place"||await pa(a,0,d,r),d}async function pa(e,t,n,o){o?.throwIfAborted();let i=await Zt.opendir(e);for await(let r of i){if(o?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let a=Xt.join(e,r.name);if(n.copy_scope==="nested_filtered_snapshot"&&!Vt(n.source_directory,n.destination_directory,a)){n.excluded_entries+=1;continue}if(Xt.relative(n.source_directory,a).split(Xt.sep).some(s=>_p.has(s))&&(n.development_entries+=1),await vp(a,t,n,o),!n.complete)return}}async function vp(e,t,n,o){let i=await Zt.lstat(e);if(o?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await pa(e,t+1,n,o)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcdfdabd-8862-502f-8cd1-298c08825985")}catch{}})();async function ua(e,t,n){let o=typeof t=="string"?null:await ft(e),i=o===null?null:e.trim().toLowerCase(),r=i===null?null:await br(i),a=Bt(o??e,{forceGithub:typeof t=="string",ref:n}),s=i===null?null:await $r(e);return{bundledAliasName:i,bundledPackageName:r,installSource:a,sourceResolution:{requested:e,selected:{kind:i===null?a.kind:"builtin",input:i??a.input,...r===null?{}:{package:r}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...r===null?{}:{package:r},command:`pm install ${i}`}],...s===null?[]:[{kind:"npm",input:`npm:${s.package}`,package:s.package,...s.version===void 0?{}:{version:s.version},directory:s.directory,command:`pm install npm:${s.package}`}]]}}}import Oe from"node:fs/promises";import ne 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]="df60255d-fdd6-594a-9e17-547d53f7b3bb")}catch{}})();function eo(e){return e.map(({layer:t,name:n,error:o})=>({layer:t,name:n,error:o}))}function Qt(e,t,n){let o=b(t),i=n.trim();if(o.length===0||i.length===0)return;let r=e.get(o)??new Set;r.add(i),e.set(o,r)}function bp(e){let t=new Map,n=new Map;for(let o of e.registrations.commands)Qt(t,o.name,o.command),Qt(n,o.name,o.action);for(let o of e.commands.handlers)Qt(t,o.name,o.command);for(let o of e.commands.overrides)Qt(t,o.name,o.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function ma(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function kp(e){let{enabled:t,normalizedName:n,loadedNames:o,loadFailedNames:i,activationFailedNames:r}=e;return t?i.has(n)||r.has(n)?{runtime_active:!1,activation_status:"failed"}:o.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function en(e,t,n){let o=new Set(t.loaded.map(c=>b(c.name))),i=new Set(t.failed.map(c=>b(c.name))),r=new Set(n.failed.map(c=>b(c.name))),{commandPathsByExtension:a,actionPathsByExtension:s}=bp(n);return e.map(c=>{let l=b(c.name),d=ma(a.get(l)),p=ma(s.get(l)),u={...d?{command_paths:d}:{},...p?{action_paths:p}:{}},g=kp({enabled:c.enabled,normalizedName:l,loadedNames:o,loadFailedNames:i,activationFailedNames:r});return{...c,...g,...u}})}function xp(e){let t=0,n=0,o=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(o+=1)}return{warning_count:t,violation_count:n,blocked_count:o}}function z(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var ga=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function Sp(e){return ga.has(ka(e))}function fa(e){return e==="project"||e==="global"}function ya(e){let t=e.split(":"),n=t[0];if(!n||!ga.has(n))return null;let o=t.at(-4),i=t.at(-3)?.trim(),r=t.at(-2),a=t.at(-1)?.trim();return!fa(o)||!fa(r)||!i||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:o,name:i},displaced:{layer:r,name:a}}}function Ep(e){let t=new Set;for(let n of e){let o=ya(n);o&&(t.add(o.winner.name),t.add(o.displaced.name))}return[...t].sort((n,o)=>n.localeCompare(o))}function $p(e,t){let n=e.filter(Sp);if(n.length===0)return null;let o=Ep(n);return`Extension registration collisions or handler/override overlaps detected.${o.length>0?` Conflicting extensions: ${o.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function Ip(e,t,n,o){let i=t.map(p=>ya(p)).filter(p=>p!==null).sort((p,u)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`));if(i.length===0)return;let r=e==="global"?"--global":"--project",a=z(o,"deactivate"),s=`${z(o,"doctor")} ${r} --detail deep --trace`,c=new Map(n.map(p=>[b(p.name),p])),l=new Map;for(let p of i)for(let u of[p.winner.name,p.displaced.name]){let g=b(u);l.set(g,(l.get(g)??0)+1)}let d=[...l.entries()].map(([p,u])=>{let g=c.get(p),y=g?.name??p,w=g?.command_paths??[],m=g?.action_paths??[];return{action:"deactivate",extension:y,command:`${a} ${y} ${r}`,affected_collisions:u,feature_loss:{command_paths:[...w].sort((_,v)=>_.localeCompare(v)),action_paths:[...m].sort((_,v)=>_.localeCompare(v))}}}).sort((p,u)=>{let g=u.affected_collisions-p.affected_collisions;if(g!==0)return g;let y=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,w=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length;return y!==w?y-w:p.extension.localeCompare(u.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:l.size,next_best_command:s,collisions:i,remediation_candidates:d}}function _a(e){let t=[];for(let n of e){let o=n.error.toLowerCase();(o.includes("cannot find package '@unbrained/pm-cli'")||o.includes('cannot find module "@unbrained/pm-cli"')||o.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(o.includes("cannot use import statement outside a module")||o.includes("to load an es module")||o.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,o)=>n.localeCompare(o))}function wa(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let o of t){if(!o||typeof o.name!="string")continue;let i=o.trace?.missing_capability??o.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${o.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function va(e,t){let n=[];for(let o of Lo(e.loaded,t))for(let i of o.unused)n.push(`extension_capability_unused:${o.layer}:${o.name}:${i}`);return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}var Ap=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${z(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${yo.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${z(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${z(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${z(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function Tp(e){let{normalizedWarnings:t,options:n,scope:o,scopeFlag:i,updateCheckFailedTotal:r,policyWarningCount:a,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,p=[],u={options:n,scope:o,scopeFlag:i,updateCheckFailedTotal:r,policyWarningCount:a};if(t.length>0){let g=$p(t,{deactivate:`${z(n,"deactivate")} <name> ${i}`,doctor:`${z(n,"doctor")} ${i} --detail deep --trace`});g&&p.push(g);for(let y of Ap)y.matches(t,u)&&p.push(y.build(u))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${z(n,"manage")} ${i} --fix-managed-state (or ${z(n,"adopt-all")} ${i}, ${z(n,"adopt")} <name> ${i}, or reinstall via ${z(n,"install")} ${i} <source>).`),l>0&&p.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${z(n,"manage")} ${i} to request update checks.`),d>0&&p.push(`Update available managed extensions via ${z(n,"install")} ${i} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${z(n,"manage")} ${i} after extension changes.`),p}function tn(e,t,n,o={}){let i=[...new Set(t)].sort((E,q)=>E.localeCompare(q)),r=n.filter(E=>E.managed).length,a=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,c=n.filter(E=>E.update_check_status==="checked"&&E.update_available===!0).length,l=n.filter(E=>E.managed===!1),d=l.filter(E=>ha(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),p=l.filter(E=>!ha(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)u[E.update_check_status]+=1;let g=u.failed,y=n.filter(E=>E.update_check_status==="skipped_non_github"&&E.source?.kind!=="builtin").length,w=Object.entries({skipped_unmanaged:p.length,skipped_non_github:y,failed:g,not_checked:u.not_checked}).filter(([,E])=>E>0).map(([E,q])=>`extension_update_health_partial_coverage:${E}:${q}`),m=w.length>0,_=m?"partial":"full",v=[...new Set([...i,...w])].sort((E,q)=>E.localeCompare(q)),k=[...new Set(v.map(E=>ka(E)))].sort((E,q)=>E.localeCompare(q)),x=xp(v),C=e==="global"?"--global":"--project",U=Ip(e,i,n,o),L=Tp({normalizedWarnings:v,options:o,scope:e,scopeFlag:C,updateCheckFailedTotal:g,policyWarningCount:x.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:u.not_checked,skippedNonGithubTotal:y,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:k,warnings:v,policy_warning_count:x.warning_count,policy_violation_count:x.violation_count,policy_blocked_count:x.blocked_count,total_extensions:n.length,managed_total:r,enabled_total:a,active_total:s,update_available_total:c,update_health_coverage:_,update_health_partial:m,unmanaged_loaded_extension_count:l.length,unmanaged_loaded_extensions:l.map(E=>E.name).sort((E,q)=>E.localeCompare(q)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:u,update_check_failed_total:g,top_warnings:v.slice(0,8),remediation:L,...U?{collision_plan:U}:{}}}function ba(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new f(`Invalid --detail value "${e}". Expected summary or deep.`,h.USAGE)}function ka(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function xa(e){let t=new Set,n=[];for(let o of e){let i=(()=>{let r=Ao(o);return r?[r]:To(o)})();for(let r of i){let a=`${r.layer}:${r.name}:${r.capability}`;t.has(a)||(t.add(a),n.push(r))}}return n}function Sa(){return{version:kt.version,capabilities:[...kt.capabilities],legacy_aliases:{...kt.legacy_aliases}}}function ha(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Ea(e,t,n,o,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let r=[...new Set(t.filter(d=>d.active).map(d=>b(d.name)))].sort((d,p)=>d.localeCompare(p)),a=[...new Set(n.filter(d=>d.layer==="project").map(d=>b(d.name)))].sort((d,p)=>d.localeCompare(p)),s=new Set(o.map(d=>b(d.name))),c=r.filter(d=>!a.includes(d)&&!s.has(d)).sort((d,p)=>d.localeCompare(p));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:r.length,loaded_project_count:a.length,active_project_names:r,loaded_project_names:a,missing_active_project_names:c}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96a05fa4-b833-56ca-b501-40a427d03201")}catch{}})();var $a=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let o=new Array(e.length),i=0,r=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let a=i;i+=1,o[a]=await n(e[a])}});return await Promise.all(r),o};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="37f2dced-3b93-5c64-85ae-56e62c95e8eb")}catch{}})();function Ia(e,t){let n=b(e),o=t.find(i=>b(i.name)===n);return{command_paths:[...o?.command_paths??[]].sort((i,r)=>i.localeCompare(r)),action_paths:[...o?.action_paths??[]].sort((i,r)=>i.localeCompare(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]="fcc97434-1ef5-5c47-b491-f00e9d19b2c6")}catch{}})();function Aa(e,t){let n=new Set((t?.loaded??[]).flatMap(r=>(r.activation?.commands?.length??0)>0?[`${r.layer}:${b(r.name)}`]:[])),o=e.services.overrides.filter(r=>r.service==="output_format").filter(r=>r.passThrough!==!0).filter(r=>!n.has(`${r.layer}:${b(r.name)}`)).map(r=>`extension_output_service_override_global:${r.service}:${r.layer}:${r.name}`),i=e.renderers.overrides.filter(r=>(r.commands?.length??0)===0&&r.resultDiscriminator===void 0).map(r=>`extension_output_renderer_override_global:${r.format}:${r.layer}:${r.name}`);return[...new Set([...o,...i])].sort((r,a)=>r.localeCompare(a))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var Ta=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Ct(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,o)=>o.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8507f364-e079-5743-a54b-bb3a68ab66d0")}catch{}})();var Op=1e4,Cp=(e,t,n)=>{let o=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),i=o.find(a=>a.ref.endsWith("^{}"))??o[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let r=t?.trim();return r?{checked_at:n,remote_commit:i.commit,available:i.commit!==r}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},Oa=async(e,t=qt)=>{let n=T();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let o=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,o,`${o}^{}`],void 0,Op);return Cp(i,e.commit,n)}catch(o){return{checked_at:n,available:null,error:o instanceof Error?o.message:String(o)}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ee1bfa77-6687-578c-9cd6-639fc702c48c")}catch{}})();function Ca(e,t){let n=e.filter(o=>o.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:o,result:i})=>{let r=i.details;return{alias:o,ok:i.ok,extension:r.extension,source:r.source,source_resolution:r.source_resolution,install_plan:r.install_plan,dry_run:r.dry_run,destination_path:r.destination_path,activated:r.activated,settings_changed:r.settings_changed,command_paths:r.command_paths,action_paths:r.action_paths,command_discovery:r.command_discovery,verification:r.verification,runtime_activation_status:r.runtime_activation_status,activation_diagnostics:r.activation_diagnostics,warnings:i.warnings}})}}import Rp from"node:fs/promises";import Pp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1bf79a0-1f04-590f-b613-45ca1b534d5d")}catch{}})();function Np(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Dp(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function jp(e){let t=Pp.join(e,"manifest.json"),n;try{n=await Rp.readFile(t,"utf8")}catch(s){if(bt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let o;try{o=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof o!="object"||o===null||Array.isArray(o))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=o,r=Ro(i),a=Np(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:r.findings,warnings:r.findings.map(s=>Dp(a,s)),remediation:r.findings.map(s=>s.message)}}function Ra(e){return jp(Eo(e))}import Me from"node:fs/promises";import Lp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7afb9a1-be35-5dfd-a52e-2525598b68d8")}catch{}})();var to=async e=>Me.readFile(e).catch(t=>{if(Yt(t,"ENOENT"))return null;throw t}),Pa=async(e,t,n,o,i)=>Ue("extension_install_backup",async()=>{let r=pt(e),a=Io(t),[s,c]=await Promise.all([to(r),to(a)]);return o&&await Me.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:o,managedStatePath:r,managedStateContents:s,settingsPath:a,settingsContents:c}}),Na=async e=>Ue("extension_install_rollback",async()=>{await Me.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Me.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await Me.rm(t,{force:!0}):(await Me.mkdir(Lp.dirname(t),{recursive:!0}),await Me.writeFile(t,n))});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f8fc1a7-748d-559d-9de8-835d0428c6a7")}catch{}})();var Fp=4,Fa=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],Mp=Fa.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Up={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},Gp="__pm_native_output",zp=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Ma=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Jp=["disabled","require_trusted","require_provenance"],Ua={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},qp=e=>{let t=e??Ua,n={};for(let o of zp)n[o]=ee(t[o]??[]);return n},Wp=(e,t)=>{for(let n of Ma)t[n].length>0&&(e[n]=t[n]);return e},Bp=(e,t)=>{for(let n of Jp)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Hp=e=>{let t={};for(let n of Ma)t[n]=ee(e[n]??[]);return t},Kp=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Wp(Bp({name:t},e),Hp(e))},Vp=e=>(e??[]).map(t=>Kp(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Yp=e=>{let t=Object.assign({},Ua,e??{}),n=qp(e),o=Vp(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:o}},Ga=async(e,t)=>{let n=[t],o=await kr(t);o&&n.push(o);let i=[...new Set(n.map(r=>b(r)).filter(r=>r.length>0))];for(let r of i){let a=e.find(c=>b(c.name)===r);if(a)return a;let s=e.find(c=>b(c.directory)===r);if(s)return s}},za=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled));return new Set(ee(e.extensions.disabled)).has(n)?!1:o.size===0?!0:o.has(n)},Ja=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),i=new Set(ee(e.extensions.disabled)),r=[...o],a=[...i];return i.delete(n),o.size>0&&o.add(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Xp=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),i=new Set(ee(e.extensions.disabled)),r=[...o],a=[...i];return o.delete(n),i.add(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Zp=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),i=new Set(ee(e.extensions.disabled)),r=[...o],a=[...i];return o.delete(n),i.delete(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Qp=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),o=Fa.map(([i,r,a])=>({action:r,flag:a,distance:bo(t,i,n)})).filter(i=>i.distance!==null).sort((i,r)=>i.distance-r.distance)[0];return o?{action:o.action,flag:o.flag}:null},eu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=Qp(e);if(!o)return new f(`One action flag is required. Use one of: ${Mp}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let i=`pm ${n} ${o.flag}`;return ko({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(qa),retry_command:i,message_suffix:`. Did you mean "${o.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},tu=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],qa={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},nu=e=>qa[e]??null,ou=(e,t)=>{let n=[...new Set(tu.filter(([o])=>t[o]===!0).map(([,o])=>o))];if(n.length===0){if(e===void 0)return"explore";let o=nu(e.trim().toLowerCase());if(o)return o;throw eu(e,t)}if(n.length>1)throw new f("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},iu=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new f('Options "--project/--local" and "--global" are mutually exclusive.',h.USAGE);return n?"global":"project"},ru=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&e.source.kind!=="github"?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],Wa=e=>{for(let t of ru){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Ba=(e,t,n,o)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,update_error:i.update_error,update_check_status:o.status,update_check_reason:o.reason}},au=(e,t,n,o)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},o),r=o?za(n,o.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Ba({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:r},t,o,Wa(o))}},su=async(e,t,n,o,i,r)=>{let a=ne.join(e,t),s=ne.join(a,"manifest.json"),c=r.get(b(t));if(!await S(s))return au(t,n,o,c);let l=Symbol("invalid-extension-manifest-json"),d=await Oe.readFile(s,"utf8").then(g=>JSON.parse(g)).catch(()=>l);if(d===l)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Fn(d);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=i.get(b(p.name))??r.get(b(t));return{summary:Ba({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:za(o,p.name)},n,u,Wa(u))}},me=async(e,t,n,o)=>{if(!await S(e))return{extensions:[],warnings:[]};let r=(await Oe.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,p)=>d.localeCompare(p)),a=new Map(o.entries.map(d=>[b(d.name),d])),s=new Map(o.entries.map(d=>[b(d.directory),d])),c=[],l=[];for(let d of r){let p=await su(e,d,t,n,a,s);p.warning&&c.push(p.warning),p.summary&&l.push(p.summary)}return{extensions:l.sort((d,p)=>d.name.localeCompare(p.name)),warnings:c.sort((d,p)=>d.localeCompare(p))}},cu=Do(),lu=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,du=(e,t,n,o)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),r=o?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return r&&a.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:lu(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:a,...r?{sdk_dependency_status:"missing"}:{}}},pu=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,o])=>o!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},Ha=e=>e.map(t=>pu(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),Ka=(e,t,n)=>{let o=b(e);return t.find(i=>(n===void 0||i.layer===n)&&b(i.name)===o)},uu=(e,t,n,o)=>n.find(r=>r.scope===t&&b(r.name)===b(e))?.activation_status??(o?"failed":"unknown"),Va=(e,t,n,o,i)=>cu.enqueue(async()=>{let r=process.env.PM_CLI_PACKAGE_ROOT,a=await Oe.mkdtemp(ne.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=ce(import.meta.url,["../.."]);try{let s=await ve({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:un(),cache_bust:!0,module_graph_snapshot_root:a}),c=await be({...s}),l=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...Ha(c.failed)],d=Object.fromEntries(s.loaded.map(p=>[b(p.name),Co(Je(c,{extensionName:p.name}))]));return{installed:en(o,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:l,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:d}}finally{await Oe.rm(a,{recursive:!0,force:!0}),r===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=r}}),oo=async(e,t,n,o)=>{let i=n.filter(c=>!c.managed),r=[...i].sort((c,l)=>{let d=c.name.localeCompare(l.name);return d!==0?d:c.directory.localeCompare(l.directory)}),a=o,s=[];for(let c of r){let l=ne.join(e,c.directory),d=await Ze(l),p=T(),u={kind:"local",input:c.name,location:l};a=mt(a,{name:d.manifest.name,directory:c.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:p,updated_at:p,source:u}),s.push({name:d.manifest.name,directory:c.directory,version:d.manifest.version,entry:d.manifest.entry,source:u})}return s.length>0&&await Le(e,a),{state:a,adopted_entries:s,unmanaged_candidates:r,already_managed_count:n.length-i.length}},mu=(e,t)=>{let n=P(process.cwd(),t.path),o=St(n,process.cwd()),i=e==="global"?$o(process.cwd()):n,r=e==="global"?o.global:o.project;return{pm_root:n,scope:e,settings_root:i,selected_root:r,roots:o}},nn=e=>{let t=[e.gh,e.github].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new f('Options "--gh" and "--github" must match when both are provided.',h.USAGE);return n[0]},fu=e=>Up[e],hu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=e==="install"?"source":"name",i=`${n} ${o}`,r=fu(e),a=`<${o}>`,s=`pm ${n} ${r} ${a}`;throw new f(`Action "${e}" requires ${i} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${o} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${o} target`}]}})},on=(e,t,n={})=>{let o=e?.trim();if(o)return o;if(t==="init")throw new f('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',h.USAGE);return hu(t,n)},gu=(e,t)=>{let n=new Set([...t.registrations.item_types.map(o=>({entry:o,count:o.types.length})),...t.registrations.item_fields.map(o=>({entry:o,count:o.fields.length}))].filter(({count:o})=>o>0).map(({entry:o})=>`${o.layer}:${b(o.name)}`));return e.loaded.filter(o=>(o.activation?.commands??[]).length>0).filter(o=>n.has(`${o.layer}:${b(o.name)}`)).map(o=>`extension_schema_narrow_activation:${o.layer}:${o.name}`).filter((o,i,r)=>r.indexOf(o)===i).sort((o,i)=>o.localeCompare(i))},yu=(e,t)=>{let o=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(i=>i.triggered&&!i.allowed);if(o)throw new f(o.message,h.USAGE)},_u=(e,t,n)=>{let o=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(o)?void 0:e},wu=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},vu=(e,t,n)=>{let o={ok:n,action:e.action,scope:e.scope,roots:wu(e),warnings:[...new Set(e.warnings)].sort((i,r)=>i.localeCompare(r)),details:t};return e.action==="doctor"&&Object.defineProperty(o,Gp,{value:!0,enumerable:!1,configurable:!1}),o},io=async(e,t,n)=>{let o=ou(e,t);yu(o,t);let i=_u(e,o,t),r=iu(t),a=mu(r,n),c={action:o,normalizedTarget:i,scope:r,resolvedRoots:a,warnings:[],options:t,global:n},d={...c,withResult:(p,u=!0)=>vu(c,p,u)};return await Qu(d)},bu=(e,t)=>{let n=t.vocabulary??"extension",o=e.target_path.replace(/\\/g,"/"),i=Go(o),r={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},a={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[r[n],...s,`Install the scaffold: ${It(n==="package"?["install","--project",o]:["extension","--install","--project",o])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},ku=async e=>{let{action:t,normalizedTarget:n,options:o,withResult:i}=e;if([nn(o),o.ref].filter(l=>typeof l=="string").map(l=>l.trim()).filter(Boolean).length>0)throw new f('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let s=on(n,t,o),c=await qr(s,o.vocabulary??"extension",o.capability,o.declarative===!0);return i({scaffolded:c.created_directory||c.files.some(l=>l.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:bu(c,o)})},xu=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:o,options:i,global:r,withResult:a}=e;if(t!==void 0)throw new f('Action "reload" does not accept a target argument.',h.USAGE);let s=await A(n.settings_root),c=un(),l=await ve({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:r.noExtensions,reload_token:c,cache_bust:!0});o.push(...l.warnings);let d=await be(l);o.push(...d.warnings);let p={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:l.loaded.length,failed_count:l.failed.length,activated_count:Math.max(0,l.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:l.loaded.map(u=>({name:u.name,layer:u.layer,version:u.version})),failed_extensions:l.failed.map(u=>({name:u.name,layer:u.layer,error:u.error})),activation_failures:d.failed.map(u=>({name:u.name,layer:u.layer,error:u.error}))};return i.watch===!0&&o.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},Su=async e=>{let{normalizedTarget:t,scope:n,options:o,global:i,withResult:r}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new f('Action "catalog" does not accept a package target.',h.USAGE);return r(await xr(n,i,o))},Eu=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),$u=e=>({kind:"local",input:e.input,location:e.absolute_path}),Iu=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),Au=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),Tu=(e,t,n,o)=>e?Eu(e,t):n.kind==="local"?$u(n):n.kind==="npm"?Iu(n,o):Au(n,o),Ou=(e,t,n,o)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:o}:gr(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:o}:{installed_at:o,updated_at:o},Cu=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:i}=e,{validated:r,destinationDirectoryName:a}=t,s=await A(o.settings_root),c=await _e(o.selected_root);i.push(...c.warnings);let l=ne.join(o.selected_root,a),d=await S(l),p=await Kt(r.directory,l);await Oe.mkdir(o.selected_root,{recursive:!0});let u=await Oe.mkdtemp(ne.join(o.selected_root,".pm-extension-install-backup-")),g=ne.join(u,"destination");try{let y=await Pa(o.selected_root,o.settings_root,l,d,g),w=Tu(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),m=c.state.entries.find(x=>b(x.name)===b(r.manifest.name)),_=Ou(m,r.manifest.version,w,T()),v=mt(c.state,{name:r.manifest.name,directory:a,scope:n,manifest_version:r.manifest.version,manifest_entry:r.manifest.entry,capabilities:[...r.manifest.capabilities],contributions:r.manifest.contributions,..._,source:w}),k=Ja(s,r.manifest.name);try{p||await ca(r.directory,l),await ra(l),await aa(l),await Le(o.selected_root,v),k&&await xe(o.settings_root,s,"settings:write")}catch(x){try{await Na(y)}catch(C){throw new AggregateError([x,C],`Extension install failed: ${String(x)}; rollback failed: ${String(C)}`,{cause:C})}throw x}return{settings:s,managedState:v,sourceRecord:w,destinationDirectory:l,destinationExists:d,installInPlace:p,activationChanged:k}}finally{await Oe.rm(u,{recursive:!0,force:!0}).catch(()=>{})}},Ru=async(e,t,n)=>{let o=n.filter(i=>b(i.name)===b(t)).flatMap(i=>i.types.map(r=>({name:r.name,folder:r.folder})));return e.scope==="project"&&o.length>0&&await ct(e.resolvedRoots.pm_root,o,e.warnings,"install:type-folder"),o},Pu=(e,t,n,o,i)=>{let r=Ka(t,n.activation_failures,e.scope),a=uu(t,e.scope,n.installed,r),s=[!n.extensions_disabled,a==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${a}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:a,failure:r,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:a,activated:s,registered_commands:o.command_paths,registered_actions:o.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},Nu=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:i,global:r,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,l=await Cu(e,t),d=await me(o.selected_root,n,l.settings,l.managedState);i.push(...d.warnings);let p=await Va(o.pm_root,ne.dirname(o.selected_root),l.settings,d.extensions,r);i.push(...p.warnings);let u=await Ru(e,s.manifest.name,p.item_type_registrations),g=Ia(s.manifest.name,p.installed),y=Pu(e,s.manifest.name,p,g,u),w=p.contribution_inventories[b(s.manifest.name)];return w&&(l.managedState=await yr(o.selected_root,l.managedState,s.manifest.name,w)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:l.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:l.destinationDirectory,overwritten:[l.destinationExists,!l.installInPlace].every(Boolean),installed_in_place:l.installInPlace,activated:y.activated,settings_changed:l.activationChanged,runtime_activation_status:y.status,command_paths:g.command_paths,action_paths:g.action_paths,contributions:w,command_discovery:du(s.manifest.name,l.sourceRecord,g,y.failure),verification:y.verification,activation_diagnostics:{failed_count:p.activation_failures.length,failed:p.activation_failures,installed_extension_failed:y.failure??null}},y.activated)},Du=async e=>{let{options:t,global:n,warnings:o,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new f('Action "install all" does not accept --ref.',h.USAGE);let r=[],a=new Map;for(let s of await Jt()){let c=await ft(s),l=ne.resolve(c),d=a.get(l);d===void 0&&(d=await io(s,{...t,install:!0},n),a.set(l,d)),r.push({alias:s,result:d})}return o.push(...r.flatMap(s=>s.result.warnings)),i(Ca(r,t.dryRun===!0),r.every(s=>s.result.ok))},ju=async(e,t,n)=>{let{resolvedRoots:o}=e,{bundledAliasName:i,bundledPackageName:r,installSource:a,sourceResolution:s}=await ua(t,n,e.options.ref);if(s.ambiguous){let l=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${l.package}`)}let c=await Rr(a);try{let l=await Ze(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),d=Gt(l.manifest.name),p=e.options.dryRun===!0||a.kind==="local"&&i===null?await da(c,ne.join(o.selected_root,d),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:l.manifest.name,version:l.manifest.version},source_resolution:s,install_plan:p}):await Qn(o.settings_root,d,()=>Nu(e,{validated:l,destinationDirectoryName:d,bundledAliasName:i,bundledPackageName:r,sourceResolution:s,installSource:a,resolvedSource:c,installPlan:p}))}finally{c.cleanup&&await c.cleanup()}},Lu=async e=>{let t=nn(e.options),n=t??on(e.normalizedTarget,e.action,e.options);return[t===void 0,wr(n)].every(Boolean)?Du(e):ju(e,n,t)},Fu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:i,options:r,withResult:a}=e;if(t!==void 0)throw new f('Action "adopt-all" does not accept a target argument.',h.USAGE);if(nn(r)!==void 0||typeof r.ref=="string"&&r.ref.trim().length>0)throw new f('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let c=await A(o.settings_root),l=await _e(o.selected_root);i.push(...l.warnings);let d=await me(o.selected_root,n,c,l.state);i.push(...d.warnings);let p=await oo(o.selected_root,n,d.extensions,l.state),u=await me(o.selected_root,n,c,p.state);i.push(...u.warnings);let g=tn(n,i,u.extensions,r);i.push(...g.warnings);let y=new Map(u.extensions.map(_=>[`${b(_.name)}:${b(_.directory)}`,_])),w=new Map(u.extensions.map(_=>[b(_.directory),_])),m=p.adopted_entries.map(_=>{let v=b(_.directory),k=y.get(`${b(_.name)}:${v}`)??w.get(v);return{..._,...Ya(k)}});return a({adopted_all:m.length>0,adopted_count:m.length,already_managed_count:p.already_managed_count,extensions:m,triage:g,warning_codes:g.warning_codes,update_health_partial:g.update_health_partial,update_health_coverage:g.update_health_coverage})},Ya=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Mu=(e,t,n,o)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=Bt(e,{forceGithub:!0,ref:o});if(i.kind!=="github")throw new f(`Invalid GitHub shorthand "${e}".`,h.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},Uu=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:i,warnings:r,options:a,withResult:s}=e,c=on(n,t,a),l=nn(a),d=await A(i.settings_root),p=await _e(i.selected_root);r.push(...p.warnings);let u=await me(i.selected_root,o,d,p.state);r.push(...u.warnings);let g=await Ga(u.extensions,c);if(!g)throw new f(`Installed extension "${c}" was not found in ${o} scope.`,h.NOT_FOUND);if(g.managed)return s({adopted:!1,already_managed:!0,extension:{name:g.name,directory:g.directory}});let y=ne.join(i.selected_root,g.directory),w=await Ze(y),m=T(),_=Mu(l,c,y,a.ref),v=mt(p.state,{name:w.manifest.name,directory:g.directory,scope:o,manifest_version:w.manifest.version,manifest_entry:w.manifest.entry,capabilities:[...w.manifest.capabilities],contributions:w.manifest.contributions,installed_at:m,updated_at:m,source:_});await Le(i.selected_root,v);let k=await me(i.selected_root,o,d,v);r.push(...k.warnings);let x=k.extensions.find(C=>b(C.name)===b(w.manifest.name))??k.extensions.find(C=>b(C.directory)===b(g.directory));return s({adopted:!0,extension:{name:w.manifest.name,directory:g.directory,version:w.manifest.version,entry:w.manifest.entry},source:_,...Ya(x)})},Xa=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:i,warnings:r,options:a}=e,s=on(n,t,a),c=await A(i.settings_root),l=await _e(i.selected_root);r.push(...l.warnings);let d=await me(i.selected_root,o,c,l.state);r.push(...d.warnings);let p=await Ga(d.extensions,s);if(!p)throw new f(`Installed extension "${s}" was not found in ${o} scope.`,h.NOT_FOUND);return{settings:c,managedStateRead:l,candidate:p}},Gu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:o,managedStateRead:i,candidate:r}=await Xa(e),a=ne.join(t.selected_root,r.directory);await Oe.rm(a,{recursive:!0,force:!0});let s={...i.state,updated_at:T(),entries:i.state.entries.filter(l=>b(l.name)!==b(r.name)&&b(l.directory)!==b(r.directory))};await Le(t.selected_root,s);let c=Zp(o,r.name);return c&&await xe(t.settings_root,o,"settings:write"),n({removed:!0,extension:{name:r.name,directory:r.directory},destination_path:a,settings_changed:c})},Da=async e=>{let{action:t,resolvedRoots:n,warnings:o,global:i,withResult:r}=e,{settings:a,candidate:s}=await Xa(e),c=t==="activate"?Ja(a,s.name):Xp(a,s.name);c&&await xe(n.settings_root,a,"settings:write");let l=t==="activate"?await Va(n.pm_root,ne.dirname(n.selected_root),a,[s],i).then(d=>(o.push(...d.warnings),Ka(s.name,d.activation_failures,e.scope))):void 0;return l&&o.push(`extension_activate_failed:${e.scope}:${s.name}`),r({extension:{name:s.name,directory:s.directory},active:t==="activate"&&l===void 0,runtime_active:t==="activate"&&l===void 0,activation_failure:l??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},l===void 0)},zu=(e,t,n,o,i,r)=>{let a=o==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=i?.adopted_entries.length??0,l=[[r!==null,r??""],[t>0,`Run pm ${a} explore --project and pm ${a} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${a} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...l.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},no=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Ju=(e,t,n,o)=>{if(e!=="project"||t||!no(o))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},qu=(e,t,n)=>{if(String(e??"").trim().length>0)throw new f('Action "doctor" does not accept a target argument.',h.USAGE);let o=[n.isolated,n.ignoreGlobal].includes(!0);if([o,t==="global"].every(Boolean))throw new f("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let i=ba(n.detail),r=n.trace===!0;if([r,i!=="deep"].every(Boolean))throw new f("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:o,detailMode:i,includeTrace:r}},Wu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let o=await oo(e.resolvedRoots.selected_root,e.scope,t,n);return{state:o.state,fix:o}},Bu=(e,t,n,o)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:no(o),rerun_command:null,pm_global_path_recipe:null};let r=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:no(o),rerun_command:t?null:r,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},Hu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:i,options:r,global:a,withResult:s}=e,{isolated:c,detailMode:l,includeTrace:d}=qu(t,n,r),p=await A(o.settings_root),u=await _e(o.selected_root);i.push(...u.warnings);let g=await me(o.selected_root,n,p,u.state);i.push(...g.warnings);let{state:y,fix:w}=await Wu(e,g.extensions,u.state),m=await me(o.selected_root,n,p,y);i.push(...m.warnings);let _=await ve({pmRoot:o.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await be({..._,loaded:_.loaded}),k=await Ra(o.pm_root);i.push(...k.warnings,..._.warnings),i.push(..._a(_.failed)),i.push(...v.warnings),i.push(...wa(v.failed)),i.push(...va(_,v)),i.push(...Aa(v,_)),i.push(...gu(_,v)),i.push(...Ta(v));let x=en(m.extensions,_,v),C=Ea(n,x,_.loaded.map(O=>({layer:O.layer,name:O.name})),_.failed.map(O=>({name:O.name})),_.disabled_by_flag);i.push(...C.warnings);let U=x.filter(O=>O.update_check_status==="failed").map(O=>`extension_update_check_failed:${O.name}`);i.push(...U);let L=tn(n,i,x,r);i.push(...L.warnings);let E=[...L.warnings],q={mode:_.policy.mode,trust_mode:_.policy.trust_mode,require_provenance:_.policy.require_provenance,default_sandbox_profile:_.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:_.policy.trusted_extensions.length,allowed_extensions_count:_.policy.allowed_extensions.length,blocked_extensions_count:_.policy.blocked_extensions.length,allowed_capabilities_count:_.policy.allowed_capabilities.length,blocked_capabilities_count:_.policy.blocked_capabilities.length,allowed_surfaces_count:_.policy.allowed_surfaces.length,blocked_surfaces_count:_.policy.blocked_surfaces.length,allowed_commands_count:_.policy.allowed_commands.length,blocked_commands_count:_.policy.blocked_commands.length,allowed_actions_count:_.policy.allowed_actions.length,blocked_actions_count:_.policy.blocked_actions.length,allowed_services_count:_.policy.allowed_services.length,blocked_services_count:_.policy.blocked_services.length,extension_override_count:_.policy.extension_overrides.length},tt=xa(E),an=Sa(),fo=L.warning_codes,Rs=Ju(n,c,r.vocabulary,_),Ps=zu(L.remediation,_.failed.length,v.failed.length,r.vocabulary,w,Rs),ho=Bu(n,c,r.vocabulary,_),Ns={status:L.status,scope:n,warning_count:L.warning_count,warning_codes:fo,total_extensions:x.length,managed_total:x.filter(O=>O.managed).length,enabled_total:x.filter(O=>O.enabled).length,active_total:x.filter(O=>O.active).length,unmanaged_loaded_extension_count:L.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:L.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:L.unmanaged_expected_extension_count,runtime_active_total:x.filter(O=>O.runtime_active===!0).length,activation_status_totals:{ok:x.filter(O=>O.activation_status==="ok").length,failed:x.filter(O=>O.activation_status==="failed").length,not_loaded:x.filter(O=>O.activation_status==="not_loaded").length,unknown:x.filter(O=>O.activation_status==="unknown").length},unknown_capability_count:tt.length,capability_contract_version:an.version,update_available_total:L.update_available_total,update_check_status_totals:L.update_check_status_totals,update_health_coverage:L.update_health_coverage,update_health_partial:L.update_health_partial,update_check_failed_total:x.filter(O=>O.update_check_status==="failed").length,load_failure_count:_.failed.length,activation_failure_count:v.failed.length,load_failures:eo(_.failed),activation_failures:eo(v.failed),blocking_failure_count:_.failed.length+v.failed.length,has_blocking_failures:_.failed.length+v.failed.length>0,consistency_warning_count:C.warnings.length,trace_enabled:d,isolation:ho,policy:q,remediation:Ps},Ds=w?{requested:!0,applied:w.adopted_entries.length>0,adopted_count:w.adopted_entries.length,already_managed_count:w.already_managed_count,adopted_extensions:w.adopted_entries.map(O=>O.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:m.extensions.filter(O=>O.managed).length,adopted_extensions:[]},sn={mode:l,summary:Ns,triage:L,trace_enabled:d,capability_contract:an,capability_guidance:tt,managed_state_fix:Ds,author_manifest:k,isolation:ho,policy:_.policy};if(l==="deep"){let O=d?v.failed:v.failed.map(N=>{let{trace:Fm,...js}=N;return js});sn.deep={warnings:E,warning_codes:fo,capability_contract:an,capability_guidance:tt,trace_enabled:d,managed_state:{path:u.path,count:y.entries.length,entries:y.entries},installed_extensions:x,load:{roots:_.roots,policy:_.policy,warnings:_.warnings,failed:_.failed,loaded:_.loaded.map(N=>({layer:N.layer,directory:N.directory,name:N.name,version:N.version,entry:N.entry,priority:N.priority}))},activation:{failed:O,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:C.summary},d&&(sn.deep.trace={activation_failures:v.failed.filter(N=>N.trace!==void 0).map(N=>({layer:N.layer,name:N.name,entry_path:N.entry_path,error:N.error,method:N.trace.method,command:N.trace.command,capability:N.trace.capability,missing_capability:N.trace.missing_capability,registration_index:N.trace.registration_index,expected_schema:N.trace.expected_schema,hint:N.trace.hint,received:N.trace.received}))})}return s(sn)},Ku=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:i,options:r,global:a,withResult:s}=e,c=await A(o.settings_root),l=await ve({pmRoot:o.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),d=await be(l);i.push(...l.warnings),i.push(...d.warnings);let p=Vr(t,l,d);if(t!==void 0&&p.extensions.length===0){let u=r.vocabulary==="package"?"package":"extension",g=[...new Set(l.loaded.map(w=>r.vocabulary==="package"&&typeof w.source_package=="string"&&w.source_package.trim().length>0?w.source_package.trim():w.name))].sort((w,m)=>w.localeCompare(m)),y=g.length>0?` Loaded ${u} names: ${g.join(", ")}.`:"";throw new f(`No loaded ${u} named "${t}" was found in ${n} scope.${y} Run pm ${u} explore to list discovered ${u}s.`,h.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},Vu=async(e,t,n)=>{let o=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await oo(e.resolvedRoots.selected_root,e.scope,t,n),o=i.state),e.action==="manage"){let r=await $a(o.entries,Fp,async a=>{if(a.source.kind!=="github")return a;let s=await Oa(a.source);return{...a,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});o={...o,updated_at:T(),entries:ut(r)},await Le(e.resolvedRoots.selected_root,o)}return{state:o,fix:i}},Yu=async(e,t,n)=>{let o=await ve({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await be({...o,loaded:o.loaded});return e.warnings.push(...o.warnings,...i.warnings),{installed:en(n,o,i),failures:Ha(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:o.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...o.warnings,...i.warnings])].length,policy:o.policy}}},Xu=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},ja=async e=>{let{action:t,scope:n,resolvedRoots:o,warnings:i,options:r,withResult:a}=e,s=await A(o.settings_root),c=Yp(s.extensions.policy),l=await _e(o.selected_root);i.push(...l.warnings);let d=await me(o.selected_root,n,s,l.state);i.push(...d.warnings);let{state:p,fix:u}=await Vu(e,d.extensions,l.state),g=await me(o.selected_root,n,s,p);if(i.push(...g.warnings),t==="manage"){let v=g.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);i.push(...v)}let y=await Yu(e,s,g.extensions),w=y.installed,m=tn(n,i,w,r);i.push(...m.warnings);let _={total:w.length,managed_total:w.filter(v=>v.managed).length,enabled_total:w.filter(v=>v.enabled).length,active_total:w.filter(v=>v.active).length,extensions:w,triage:m,policy:c};return y.failures!==void 0&&(_.activation_diagnostics={failed_count:y.failures.length,failed:y.failures}),t==="explore"&&(_.runtime_probe=y.summary),t==="manage"&&(_.runtime_probe=y.summary,_.managed_state_fix=Xu(u,w)),a(_)},La={init:ku,install:Lu,uninstall:Gu,explore:ja,manage:ja,describe:Ku,reload:xu,doctor:Hu,catalog:Su,adopt:Uu,"adopt-all":Fu,activate:Da,deactivate:Da,migrate:Zr},Zu=e=>[e.action==="uninstall",e.action==="manage",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[e.action==="doctor",e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Qu=e=>Zu(e)?Qn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>La[e.action](e)):La[e.action](e);import so from"node:fs/promises";import J from"node:path";import Za from"node:readline/promises";import{stdin as Qa,stdout as _t}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5ae3e66-4a45-5c62-9144-46f8f5bff7cf")}catch{}})();var es=["ask","add","skip","status"],em=["AGENTS.md","CLAUDE.md"],tm=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],nm=8,co=1,om="<!-- pm-cli:agent-guidance:start:",im=`<!-- pm-cli:agent-guidance:start:v${co} -->`,ro="<!-- pm-cli:agent-guidance:end -->",vt="Add workflow guidance later: pm init --agent-guidance add",Vw={toPortableRelativePath:Qe,ensureTrailingNewline:ao,detectLineEnding:ns,findGuidanceBlockRange:lo,buildAgentGuidanceBlock:os,upsertAgentGuidanceBlock:is,resolveProjectRoot:rs,resolveTargetGuidancePath:as,parsePromptChoice:ss,pushUnique:et,promptForGuidanceWrite:cs,normalizeAgentGuidanceState:po,applyAgentGuidanceState:ds,writeGuidanceFile:ps,setAgentGuidanceReadlineFactoryForTests:rm},ts=()=>Za.createInterface({input:Qa,output:_t});function rm(e){ts=e??(()=>Za.createInterface({input:Qa,output:_t}))}function Qe(e,t){let n=J.relative(e,t);return n.length===0?J.basename(t):n.split(J.sep).join("/")}function ao(e){return e.endsWith(`
45
+ `}import ap from"node:fs/promises";import sp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4dc16d1-672a-5b1c-b681-97a7b3febd69")}catch{}})();function Xn(e){return sp.join(e,"extension-migrations.json")}function Yr(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Xr(e,t){return`${e.layer}:${e.name}:${t}`}async function cp(e){let t=Xn(e);if(!await S(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await ap.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(o=>typeof o?.key=="string"&&(o.status==="applied"||o.status==="failed")):[]}}async function lp(e,t){let n=await cp(e),o=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,r)=>{let a=Yr(i,r),s=o.get(Xr(i,a));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function dp(e){let t=await lp(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),o=[],i=!1,r=e.migrations.map((d,p)=>({migration:d,index:p})).filter(({migration:d})=>e.scope===void 0||d.layer===e.scope);for(let{migration:d,index:p}of r){let u=Yr(d,p),g=Xr(d,u),y=n.get(g),w=String(d.definition.status??"pending").toLowerCase(),m=y?.status??(w==="applied"||w==="failed"?w:"pending");if(m==="applied"){o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"skipped"});continue}if(e.dryRun===!0){o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"pending"});continue}let _=d.runtime_definition?.run??d.definition.run;if(typeof _!="function"){o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(_({id:u,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:m}));let k={key:g,layer:d.layer,extension:d.name,id:u,status:"applied",attempted_at:v};n.set(g,k),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"applied"}),i=!0}catch(k){let x=k instanceof Error?k.message:String(k),C={key:g,layer:d.layer,extension:d.name,id:u,status:"failed",attempted_at:v,error:x};n.set(g,C),d.definition.status="failed",d.definition.reason=x,o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"failed",error:x}),i=!0}}if(i){let d=await A(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((u,g)=>u.key.localeCompare(g.key))};await Ge({pmRoot:e.pmRoot,filePath:Xn(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
46
+ `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let a=o.filter(d=>d.outcome==="pending").length,s=o.filter(d=>d.outcome==="applied").length,c=o.filter(d=>d.outcome==="skipped").length,l=o.filter(d=>d.outcome==="failed").length;return{ok:l===0,dry_run:e.dryRun===!0,state_path:Xn(e.pmRoot),total:o.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:l,migrations:o}}async function Zr(e){let t=await A(e.resolvedRoots.settings_root),n=await ve({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),o=await be(n);e.warnings.push(...n.warnings,...o.warnings);let i=await dp({pmRoot:e.resolvedRoots.pm_root,migrations:o.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:o.failed.length},i.ok)}import Qt from"node:fs/promises";import Zt from"node:path";import Qr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a77d8d8d-f429-5154-ab3a-2caddc44472e")}catch{}})();function Yt(e,t,n){let o=Qr.relative(e,n);return o!==""&&!V(e,n)||n===t||V(t,n)?!1:!o.split(Qr.sep).some(r=>r===".agents"||r==="node_modules"||r.startsWith(".pm-extension-install-backup-"))}import{randomUUID as pp}from"node:crypto";import M from"node:fs/promises";import up from"node:os";import j 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]="67e85146-6994-5c3b-bcaa-d7001b9b1703")}catch{}})();var ea=3,mp=120,ta=250,fp=12e4,hp=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),na=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,oa=e=>hp.has(String(na(e))),Xt=(e,t)=>na(e)===t,ia=e=>new Promise(t=>{setTimeout(t,e)}),ra=async e=>{let t=j.join(e,"package.json");await S(t)||await M.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
47
+ `,"utf8")},aa=async e=>{let t=ce(import.meta.url,["../../.."]),n=j.join(e,"node_modules","@unbrained"),o=j.join(n,"pm-cli");await M.mkdir(n,{recursive:!0}),await M.rm(o,{recursive:!0,force:!0}),await M.symlink(t,o,process.platform==="win32"?"junction":"dir")},wt=async e=>{let t=j.resolve(e),n=j.dirname(t),o=j.parse(n).root,i=await M.realpath(o).catch(()=>o),r=j.relative(o,n),a=r===""?[]:r.split(j.sep);for(let[s,c]of a.entries()){let l=j.join(i,c);try{i=await M.realpath(l)}catch{i=j.join(i,...a.slice(s));break}}return j.join(i,j.basename(t))},sa=async(e,t,n,o=up.tmpdir())=>Ue("extension_install_copy",async()=>{let i=j.resolve(e),r=await M.realpath(i).catch(()=>i),a=await wt(t);if(r===a)return;if(!V(r,a)){await n(r,t,{recursive:!0,force:!0});return}let s=await M.realpath(j.resolve(o)).catch(()=>wt(o)),c=V(r,s)?j.dirname(r):s;if(V(r,c))throw new f(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,h.USAGE,{code:"extension_install_source_contains_destination"});let l=await M.mkdtemp(j.join(c,"pm-extension-copy-")),d=j.join(l,"extension");try{await n(r,d,{recursive:!0,force:!0,filter:p=>Yt(r,a,j.resolve(p))}),await n(d,t,{recursive:!0,force:!0})}finally{await M.rm(l,{recursive:!0,force:!0})}}),ca=async(e,t,n=M.cp)=>{for(let o=1;o<=ea;o+=1)try{await Ue("extension_install_copy",async()=>{await M.rm(t,{recursive:!0,force:!0}),await sa(e,t,n)});return}catch(i){if(!oa(i)||o===ea)throw i;await ia(ta)}},Zn=async e=>{let t;try{t=await M.readFile(j.join(e,"owner.json"),"utf8")}catch(i){if(!xt(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let o=n.token;return typeof o=="string"&&o.length>0?o:null},la=async(e,t)=>await Zn(e)!==t?!1:(await M.rm(e,{recursive:!0,force:!0}),!0),gp=async(e,t)=>{let n;try{n=await M.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let o=await Zn(e);return o===null?(await M.rm(e,{recursive:!0,force:!0}),!0):la(e,o)},yp=(e,t,n)=>{let o=Promise.resolve(),i=setInterval(()=>{o=o.then(async()=>{if(await Zn(e)!==t)return;let r=new Date;await M.utimes(e,r,r)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await o}},_p=async(e,t)=>{await M.mkdir(e);try{await M.writeFile(j.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
48
+ `,"utf8")}catch(n){throw await M.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},wp=async(e,t,n,o,i)=>{for(let r=1;r<=n;r+=1)try{return await _p(e,t),!0}catch(a){if(!Xt(a,"EEXIST"))throw a;await gp(e,i)?r-=1:await ia(o)}return!1},Qn=async(e,t,n,o)=>{let i=j.join(e,"runtime","extension-install-locks"),r=j.join(i,"scope.lock");await M.mkdir(i,{recursive:!0});let{attempts:a=mp,delay_ms:s=ta,stale_ms:c=fp,heartbeat_ms:l}=o??{};if(![a,s,c,l].filter(_=>_!==void 0).every(Number.isFinite))throw new f("Extension install lock timings must be finite numbers.",h.USAGE);let d=Math.max(1,Math.floor(a)),p=Math.max(0,Math.floor(s)),u=Math.floor(c),g=Math.floor(l??u/3);if(u<=0||g<=0||g>=u)throw new f("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",h.USAGE);let y={pid:process.pid,token:pp(),created_at:T(),destination:t};if(!await wp(r,y,d,p,u))throw new f(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let m=yp(r,y.token,g);try{return await n()}finally{await m(),await la(r,y.token).catch(()=>!1)}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4b9502f-f742-5f11-b341-56763bbed7c2")}catch{}})();var vp=new Set(["node_modules",".git","dist","build","coverage"]);async function da(e,t,n,o){let i=e.source.kind==="local"?await Qt.stat(e.source.absolute_path):void 0,r=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,a=await bp(e.directory,t,o),s={source_mode:r,...r==="archive"?{archive_bytes:i.size}:{},copy:a},c=e.source_root??e.directory;return r==="directory"&&(!a.complete||a.development_entries>0||a.bytes>=16*1024*1024)&&await S(Zt.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),s}async function bp(e,t,n={}){let{maxEntries:o=1e4,maxDepth:i=64,signal:r}=n;if(![o,i].every(p=>Number.isSafeInteger(p)&&p>0))throw new f("maxEntries and maxDepth must be positive safe integers.",h.USAGE);r?.throwIfAborted();let a=await Qt.realpath(e),s=await wt(t),c=await Vt(a,s);r?.throwIfAborted();let l=c?"in_place":V(a,s)?"nested_filtered_snapshot":"directory_snapshot",d={copy_scope:l,source_directory:a,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:o,max_depth:i};return l==="in_place"||await pa(a,0,d,r),d}async function pa(e,t,n,o){o?.throwIfAborted();let i=await Qt.opendir(e);for await(let r of i){if(o?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let a=Zt.join(e,r.name);if(n.copy_scope==="nested_filtered_snapshot"&&!Yt(n.source_directory,n.destination_directory,a)){n.excluded_entries+=1;continue}if(Zt.relative(n.source_directory,a).split(Zt.sep).some(s=>vp.has(s))&&(n.development_entries+=1),await kp(a,t,n,o),!n.complete)return}}async function kp(e,t,n,o){let i=await Qt.lstat(e);if(o?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await pa(e,t+1,n,o)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcdfdabd-8862-502f-8cd1-298c08825985")}catch{}})();async function ua(e,t,n){let o=typeof t=="string"?null:await gt(e),i=o===null?null:e.trim().toLowerCase(),r=i===null?null:await br(i),a=Ht(o??e,{forceGithub:typeof t=="string",ref:n}),s=i===null?null:await $r(e);return{bundledAliasName:i,bundledPackageName:r,installSource:a,sourceResolution:{requested:e,selected:{kind:i===null?a.kind:"builtin",input:i??a.input,...r===null?{}:{package:r}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...r===null?{}:{package:r},command:`pm install ${i}`}],...s===null?[]:[{kind:"npm",input:`npm:${s.package}`,package:s.package,...s.version===void 0?{}:{version:s.version},directory:s.directory,command:`pm install npm:${s.package}`}]]}}}import Oe from"node:fs/promises";import ne 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]="df60255d-fdd6-594a-9e17-547d53f7b3bb")}catch{}})();function eo(e){return e.map(({layer:t,name:n,error:o})=>({layer:t,name:n,error:o}))}function en(e,t,n){let o=b(t),i=n.trim();if(o.length===0||i.length===0)return;let r=e.get(o)??new Set;r.add(i),e.set(o,r)}function xp(e){let t=new Map,n=new Map;for(let o of e.registrations.commands)en(t,o.name,o.command),en(n,o.name,o.action);for(let o of e.commands.handlers)en(t,o.name,o.command);for(let o of e.commands.overrides)en(t,o.name,o.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function ma(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Sp(e){let{enabled:t,normalizedName:n,loadedNames:o,loadFailedNames:i,activationFailedNames:r}=e;return t?i.has(n)||r.has(n)?{runtime_active:!1,activation_status:"failed"}:o.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function tn(e,t,n){let o=new Set(t.loaded.map(c=>b(c.name))),i=new Set(t.failed.map(c=>b(c.name))),r=new Set(n.failed.map(c=>b(c.name))),{commandPathsByExtension:a,actionPathsByExtension:s}=xp(n);return e.map(c=>{let l=b(c.name),d=ma(a.get(l)),p=ma(s.get(l)),u={...d?{command_paths:d}:{},...p?{action_paths:p}:{}},g=Sp({enabled:c.enabled,normalizedName:l,loadedNames:o,loadFailedNames:i,activationFailedNames:r});return{...c,...g,...u}})}function Ep(e){let t=0,n=0,o=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(o+=1)}return{warning_count:t,violation_count:n,blocked_count:o}}function z(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var ga=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function $p(e){return ga.has(ka(e))}function fa(e){return e==="project"||e==="global"}function ya(e){let t=e.split(":"),n=t[0];if(!n||!ga.has(n))return null;let o=t.at(-4),i=t.at(-3)?.trim(),r=t.at(-2),a=t.at(-1)?.trim();return!fa(o)||!fa(r)||!i||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:o,name:i},displaced:{layer:r,name:a}}}function Ip(e){let t=new Set;for(let n of e){let o=ya(n);o&&(t.add(o.winner.name),t.add(o.displaced.name))}return[...t].sort((n,o)=>n.localeCompare(o))}function Ap(e,t){let n=e.filter($p);if(n.length===0)return null;let o=Ip(n);return`Extension registration collisions or handler/override overlaps detected.${o.length>0?` Conflicting extensions: ${o.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function Tp(e,t,n,o){let i=t.map(p=>ya(p)).filter(p=>p!==null).sort((p,u)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`));if(i.length===0)return;let r=e==="global"?"--global":"--project",a=z(o,"deactivate"),s=`${z(o,"doctor")} ${r} --detail deep --trace`,c=new Map(n.map(p=>[b(p.name),p])),l=new Map;for(let p of i)for(let u of[p.winner.name,p.displaced.name]){let g=b(u);l.set(g,(l.get(g)??0)+1)}let d=[...l.entries()].map(([p,u])=>{let g=c.get(p),y=g?.name??p,w=g?.command_paths??[],m=g?.action_paths??[];return{action:"deactivate",extension:y,command:`${a} ${y} ${r}`,affected_collisions:u,feature_loss:{command_paths:[...w].sort((_,v)=>_.localeCompare(v)),action_paths:[...m].sort((_,v)=>_.localeCompare(v))}}}).sort((p,u)=>{let g=u.affected_collisions-p.affected_collisions;if(g!==0)return g;let y=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,w=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length;return y!==w?y-w:p.extension.localeCompare(u.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:l.size,next_best_command:s,collisions:i,remediation_candidates:d}}function _a(e){let t=[];for(let n of e){let o=n.error.toLowerCase();(o.includes("cannot find package '@unbrained/pm-cli'")||o.includes('cannot find module "@unbrained/pm-cli"')||o.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(o.includes("cannot use import statement outside a module")||o.includes("to load an es module")||o.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,o)=>n.localeCompare(o))}function wa(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let o of t){if(!o||typeof o.name!="string")continue;let i=o.trace?.missing_capability??o.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${o.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function va(e,t){let n=[];for(let o of Lo(e.loaded,t))for(let i of o.unused)n.push(`extension_capability_unused:${o.layer}:${o.name}:${i}`);return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}var Op=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${z(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${yo.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${z(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${z(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${z(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function Cp(e){let{normalizedWarnings:t,options:n,scope:o,scopeFlag:i,updateCheckFailedTotal:r,policyWarningCount:a,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,p=[],u={options:n,scope:o,scopeFlag:i,updateCheckFailedTotal:r,policyWarningCount:a};if(t.length>0){let g=Ap(t,{deactivate:`${z(n,"deactivate")} <name> ${i}`,doctor:`${z(n,"doctor")} ${i} --detail deep --trace`});g&&p.push(g);for(let y of Op)y.matches(t,u)&&p.push(y.build(u))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${z(n,"manage")} ${i} --fix-managed-state (or ${z(n,"adopt-all")} ${i}, ${z(n,"adopt")} <name> ${i}, or reinstall via ${z(n,"install")} ${i} <source>).`),l>0&&p.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${z(n,"manage")} ${i} to request update checks.`),d>0&&p.push(`Update available managed extensions via ${z(n,"install")} ${i} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${z(n,"manage")} ${i} after extension changes.`),p}function nn(e,t,n,o={}){let i=[...new Set(t)].sort((E,q)=>E.localeCompare(q)),r=n.filter(E=>E.managed).length,a=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,c=n.filter(E=>E.update_check_status==="checked"&&E.update_available===!0).length,l=n.filter(E=>E.managed===!1),d=l.filter(E=>ha(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),p=l.filter(E=>!ha(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)u[E.update_check_status]+=1;let g=u.failed,y=n.filter(E=>E.update_check_status==="skipped_non_github"&&E.source?.kind!=="builtin").length,w=Object.entries({skipped_unmanaged:p.length,skipped_non_github:y,failed:g,not_checked:u.not_checked}).filter(([,E])=>E>0).map(([E,q])=>`extension_update_health_partial_coverage:${E}:${q}`),m=w.length>0,_=m?"partial":"full",v=[...new Set([...i,...w])].sort((E,q)=>E.localeCompare(q)),k=[...new Set(v.map(E=>ka(E)))].sort((E,q)=>E.localeCompare(q)),x=Ep(v),C=e==="global"?"--global":"--project",U=Tp(e,i,n,o),F=Cp({normalizedWarnings:v,options:o,scope:e,scopeFlag:C,updateCheckFailedTotal:g,policyWarningCount:x.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:u.not_checked,skippedNonGithubTotal:y,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:k,warnings:v,policy_warning_count:x.warning_count,policy_violation_count:x.violation_count,policy_blocked_count:x.blocked_count,total_extensions:n.length,managed_total:r,enabled_total:a,active_total:s,update_available_total:c,update_health_coverage:_,update_health_partial:m,unmanaged_loaded_extension_count:l.length,unmanaged_loaded_extensions:l.map(E=>E.name).sort((E,q)=>E.localeCompare(q)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:u,update_check_failed_total:g,top_warnings:v.slice(0,8),remediation:F,...U?{collision_plan:U}:{}}}function ba(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new f(`Invalid --detail value "${e}". Expected summary or deep.`,h.USAGE)}function ka(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function xa(e){let t=new Set,n=[];for(let o of e){let i=(()=>{let r=Ao(o);return r?[r]:To(o)})();for(let r of i){let a=`${r.layer}:${r.name}:${r.capability}`;t.has(a)||(t.add(a),n.push(r))}}return n}function Sa(){return{version:St.version,capabilities:[...St.capabilities],legacy_aliases:{...St.legacy_aliases}}}function ha(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Ea(e,t,n,o,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let r=[...new Set(t.filter(d=>d.active).map(d=>b(d.name)))].sort((d,p)=>d.localeCompare(p)),a=[...new Set(n.filter(d=>d.layer==="project").map(d=>b(d.name)))].sort((d,p)=>d.localeCompare(p)),s=new Set(o.map(d=>b(d.name))),c=r.filter(d=>!a.includes(d)&&!s.has(d)).sort((d,p)=>d.localeCompare(p));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:r.length,loaded_project_count:a.length,active_project_names:r,loaded_project_names:a,missing_active_project_names:c}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96a05fa4-b833-56ca-b501-40a427d03201")}catch{}})();var $a=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let o=new Array(e.length),i=0,r=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let a=i;i+=1,o[a]=await n(e[a])}});return await Promise.all(r),o};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="37f2dced-3b93-5c64-85ae-56e62c95e8eb")}catch{}})();function Ia(e,t){let n=b(e),o=t.find(i=>b(i.name)===n);return{command_paths:[...o?.command_paths??[]].sort((i,r)=>i.localeCompare(r)),action_paths:[...o?.action_paths??[]].sort((i,r)=>i.localeCompare(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]="fcc97434-1ef5-5c47-b491-f00e9d19b2c6")}catch{}})();function Aa(e,t){let n=new Set((t?.loaded??[]).flatMap(r=>(r.activation?.commands?.length??0)>0?[`${r.layer}:${b(r.name)}`]:[])),o=e.services.overrides.filter(r=>r.service==="output_format").filter(r=>r.passThrough!==!0).filter(r=>!n.has(`${r.layer}:${b(r.name)}`)).map(r=>`extension_output_service_override_global:${r.service}:${r.layer}:${r.name}`),i=e.renderers.overrides.filter(r=>(r.commands?.length??0)===0&&r.resultDiscriminator===void 0).map(r=>`extension_output_renderer_override_global:${r.format}:${r.layer}:${r.name}`);return[...new Set([...o,...i])].sort((r,a)=>r.localeCompare(a))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var Ta=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Rt(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,o)=>o.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8507f364-e079-5743-a54b-bb3a68ab66d0")}catch{}})();var Rp=1e4,Pp=(e,t,n)=>{let o=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),i=o.find(a=>a.ref.endsWith("^{}"))??o[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let r=t?.trim();return r?{checked_at:n,remote_commit:i.commit,available:i.commit!==r}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},Oa=async(e,t=Wt)=>{let n=T();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let o=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,o,`${o}^{}`],void 0,Rp);return Pp(i,e.commit,n)}catch(o){return{checked_at:n,available:null,error:o instanceof Error?o.message:String(o)}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ee1bfa77-6687-578c-9cd6-639fc702c48c")}catch{}})();function Ca(e,t){let n=e.filter(o=>o.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:o,result:i})=>{let r=i.details;return{alias:o,ok:i.ok,extension:r.extension,source:r.source,source_resolution:r.source_resolution,install_plan:r.install_plan,dry_run:r.dry_run,destination_path:r.destination_path,activated:r.activated,settings_changed:r.settings_changed,command_paths:r.command_paths,action_paths:r.action_paths,command_discovery:r.command_discovery,verification:r.verification,runtime_activation_status:r.runtime_activation_status,activation_diagnostics:r.activation_diagnostics,warnings:i.warnings}})}}import Np from"node:fs/promises";import Dp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1bf79a0-1f04-590f-b613-45ca1b534d5d")}catch{}})();function jp(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Lp(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function Fp(e){let t=Dp.join(e,"manifest.json"),n;try{n=await Np.readFile(t,"utf8")}catch(s){if(xt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let o;try{o=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof o!="object"||o===null||Array.isArray(o))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=o,r=Ro(i),a=jp(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:r.findings,warnings:r.findings.map(s=>Lp(a,s)),remediation:r.findings.map(s=>s.message)}}function Ra(e){return Fp(Eo(e))}import Me from"node:fs/promises";import Mp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7afb9a1-be35-5dfd-a52e-2525598b68d8")}catch{}})();var to=async e=>Me.readFile(e).catch(t=>{if(Xt(t,"ENOENT"))return null;throw t}),Pa=async(e,t,n,o,i)=>Ue("extension_install_backup",async()=>{let r=mt(e),a=Io(t),[s,c]=await Promise.all([to(r),to(a)]);return o&&await Me.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:o,managedStatePath:r,managedStateContents:s,settingsPath:a,settingsContents:c}}),Na=async e=>Ue("extension_install_rollback",async()=>{await Me.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Me.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await Me.rm(t,{force:!0}):(await Me.mkdir(Mp.dirname(t),{recursive:!0}),await Me.writeFile(t,n))});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f8fc1a7-748d-559d-9de8-835d0428c6a7")}catch{}})();var Up=4,Fa=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],Gp=Fa.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),zp={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},Jp="__pm_native_output",qp=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Ma=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Wp=["disabled","require_trusted","require_provenance"],Ua={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},Bp=e=>{let t=e??Ua,n={};for(let o of qp)n[o]=ee(t[o]??[]);return n},Hp=(e,t)=>{for(let n of Ma)t[n].length>0&&(e[n]=t[n]);return e},Kp=(e,t)=>{for(let n of Wp)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Vp=e=>{let t={};for(let n of Ma)t[n]=ee(e[n]??[]);return t},Yp=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Hp(Kp({name:t},e),Vp(e))},Xp=e=>(e??[]).map(t=>Yp(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Zp=e=>{let t=Object.assign({},Ua,e??{}),n=Bp(e),o=Xp(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:o}},Ga=async(e,t)=>{let n=[t],o=await kr(t);o&&n.push(o);let i=[...new Set(n.map(r=>b(r)).filter(r=>r.length>0))];for(let r of i){let a=e.find(c=>b(c.name)===r);if(a)return a;let s=e.find(c=>b(c.directory)===r);if(s)return s}},za=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled));return new Set(ee(e.extensions.disabled)).has(n)?!1:o.size===0?!0:o.has(n)},Ja=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),i=new Set(ee(e.extensions.disabled)),r=[...o],a=[...i];return i.delete(n),o.size>0&&o.add(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Qp=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),i=new Set(ee(e.extensions.disabled)),r=[...o],a=[...i];return o.delete(n),i.add(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},eu=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),i=new Set(ee(e.extensions.disabled)),r=[...o],a=[...i];return o.delete(n),i.delete(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},tu=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),o=Fa.map(([i,r,a])=>({action:r,flag:a,distance:bo(t,i,n)})).filter(i=>i.distance!==null).sort((i,r)=>i.distance-r.distance)[0];return o?{action:o.action,flag:o.flag}:null},nu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=tu(e);if(!o)return new f(`One action flag is required. Use one of: ${Gp}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let i=`pm ${n} ${o.flag}`;return ko({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(qa),retry_command:i,message_suffix:`. Did you mean "${o.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},ou=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],qa={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},iu=e=>qa[e]??null,ru=(e,t)=>{let n=[...new Set(ou.filter(([o])=>t[o]===!0).map(([,o])=>o))];if(n.length===0){if(e===void 0)return"explore";let o=iu(e.trim().toLowerCase());if(o)return o;throw nu(e,t)}if(n.length>1)throw new f("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},au=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new f('Options "--project/--local" and "--global" are mutually exclusive.',h.USAGE);return n?"global":"project"},su=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&e.source.kind!=="github"?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],Wa=e=>{for(let t of su){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Ba=(e,t,n,o)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,update_error:i.update_error,update_check_status:o.status,update_check_reason:o.reason}},cu=(e,t,n,o)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},o),r=o?za(n,o.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Ba({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:r},t,o,Wa(o))}},lu=async(e,t,n,o,i,r)=>{let a=ne.join(e,t),s=ne.join(a,"manifest.json"),c=r.get(b(t));if(!await S(s))return cu(t,n,o,c);let l=Symbol("invalid-extension-manifest-json"),d=await Oe.readFile(s,"utf8").then(g=>JSON.parse(g)).catch(()=>l);if(d===l)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Fn(d);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=i.get(b(p.name))??r.get(b(t));return{summary:Ba({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:za(o,p.name)},n,u,Wa(u))}},me=async(e,t,n,o)=>{if(!await S(e))return{extensions:[],warnings:[]};let r=(await Oe.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,p)=>d.localeCompare(p)),a=new Map(o.entries.map(d=>[b(d.name),d])),s=new Map(o.entries.map(d=>[b(d.directory),d])),c=[],l=[];for(let d of r){let p=await lu(e,d,t,n,a,s);p.warning&&c.push(p.warning),p.summary&&l.push(p.summary)}return{extensions:l.sort((d,p)=>d.name.localeCompare(p.name)),warnings:c.sort((d,p)=>d.localeCompare(p))}},du=Do(),pu=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,uu=(e,t,n,o)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),r=o?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return r&&a.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:pu(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:a,...r?{sdk_dependency_status:"missing"}:{}}},mu=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,o])=>o!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},Ha=e=>e.map(t=>mu(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),Ka=(e,t,n)=>{let o=b(e);return t.find(i=>(n===void 0||i.layer===n)&&b(i.name)===o)},fu=(e,t,n,o)=>n.find(r=>r.scope===t&&b(r.name)===b(e))?.activation_status??(o?"failed":"unknown"),Va=(e,t,n,o,i)=>du.enqueue(async()=>{let r=process.env.PM_CLI_PACKAGE_ROOT,a=await Oe.mkdtemp(ne.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=ce(import.meta.url,["../.."]);try{let s=await ve({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:mn(),cache_bust:!0,module_graph_snapshot_root:a}),c=await be({...s}),l=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...Ha(c.failed)],d=Object.fromEntries(s.loaded.map(p=>[b(p.name),Co(Je(c,{extensionName:p.name}))]));return{installed:tn(o,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:l,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:d}}finally{await Oe.rm(a,{recursive:!0,force:!0}),r===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=r}}),oo=async(e,t,n,o)=>{let i=n.filter(c=>!c.managed),r=[...i].sort((c,l)=>{let d=c.name.localeCompare(l.name);return d!==0?d:c.directory.localeCompare(l.directory)}),a=o,s=[];for(let c of r){let l=ne.join(e,c.directory),d=await Ze(l),p=T(),u={kind:"local",input:c.name,location:l};a=ht(a,{name:d.manifest.name,directory:c.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:p,updated_at:p,source:u}),s.push({name:d.manifest.name,directory:c.directory,version:d.manifest.version,entry:d.manifest.entry,source:u})}return s.length>0&&await Le(e,a),{state:a,adopted_entries:s,unmanaged_candidates:r,already_managed_count:n.length-i.length}},hu=(e,t)=>{let n=N(process.cwd(),t.path),o=$t(n,process.cwd()),i=e==="global"?$o(process.cwd()):n,r=e==="global"?o.global:o.project;return{pm_root:n,scope:e,settings_root:i,selected_root:r,roots:o}},on=e=>{let t=[e.gh,e.github].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new f('Options "--gh" and "--github" must match when both are provided.',h.USAGE);return n[0]},gu=e=>zp[e],yu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=e==="install"?"source":"name",i=`${n} ${o}`,r=gu(e),a=`<${o}>`,s=`pm ${n} ${r} ${a}`;throw new f(`Action "${e}" requires ${i} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${o} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${o} target`}]}})},rn=(e,t,n={})=>{let o=e?.trim();if(o)return o;if(t==="init")throw new f('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',h.USAGE);return yu(t,n)},_u=(e,t)=>{let n=new Set([...t.registrations.item_types.map(o=>({entry:o,count:o.types.length})),...t.registrations.item_fields.map(o=>({entry:o,count:o.fields.length}))].filter(({count:o})=>o>0).map(({entry:o})=>`${o.layer}:${b(o.name)}`));return e.loaded.filter(o=>(o.activation?.commands??[]).length>0).filter(o=>n.has(`${o.layer}:${b(o.name)}`)).map(o=>`extension_schema_narrow_activation:${o.layer}:${o.name}`).filter((o,i,r)=>r.indexOf(o)===i).sort((o,i)=>o.localeCompare(i))},wu=(e,t)=>{let o=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(i=>i.triggered&&!i.allowed);if(o)throw new f(o.message,h.USAGE)},vu=(e,t,n)=>{let o=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(o)?void 0:e},bu=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},ku=(e,t,n)=>{let o={ok:n,action:e.action,scope:e.scope,roots:bu(e),warnings:[...new Set(e.warnings)].sort((i,r)=>i.localeCompare(r)),details:t};return e.action==="doctor"&&Object.defineProperty(o,Jp,{value:!0,enumerable:!1,configurable:!1}),o},io=async(e,t,n)=>{let o=ru(e,t);wu(o,t);let i=vu(e,o,t),r=au(t),a=hu(r,n),c={action:o,normalizedTarget:i,scope:r,resolvedRoots:a,warnings:[],options:t,global:n},d={...c,withResult:(p,u=!0)=>ku(c,p,u)};return await tm(d)},xu=(e,t)=>{let n=t.vocabulary??"extension",o=e.target_path.replace(/\\/g,"/"),i=Go(o),r={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},a={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[r[n],...s,`Install the scaffold: ${ot(n==="package"?["install","--project",o]:["extension","--install","--project",o])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},Su=async e=>{let{action:t,normalizedTarget:n,options:o,withResult:i}=e;if([on(o),o.ref].filter(l=>typeof l=="string").map(l=>l.trim()).filter(Boolean).length>0)throw new f('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let s=rn(n,t,o),c=await qr(s,o.vocabulary??"extension",o.capability,o.declarative===!0);return i({scaffolded:c.created_directory||c.files.some(l=>l.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:xu(c,o)})},Eu=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:o,options:i,global:r,withResult:a}=e;if(t!==void 0)throw new f('Action "reload" does not accept a target argument.',h.USAGE);let s=await A(n.settings_root),c=mn(),l=await ve({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:r.noExtensions,reload_token:c,cache_bust:!0});o.push(...l.warnings);let d=await be(l);o.push(...d.warnings);let p={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:l.loaded.length,failed_count:l.failed.length,activated_count:Math.max(0,l.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:l.loaded.map(u=>({name:u.name,layer:u.layer,version:u.version})),failed_extensions:l.failed.map(u=>({name:u.name,layer:u.layer,error:u.error})),activation_failures:d.failed.map(u=>({name:u.name,layer:u.layer,error:u.error}))};return i.watch===!0&&o.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},$u=async e=>{let{normalizedTarget:t,scope:n,options:o,global:i,withResult:r}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new f('Action "catalog" does not accept a package target.',h.USAGE);return r(await xr(n,i,o))},Iu=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Au=e=>({kind:"local",input:e.input,location:e.absolute_path}),Tu=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),Ou=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),Cu=(e,t,n,o)=>e?Iu(e,t):n.kind==="local"?Au(n):n.kind==="npm"?Tu(n,o):Ou(n,o),Ru=(e,t,n,o)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:o}:gr(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:o}:{installed_at:o,updated_at:o},Pu=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:i}=e,{validated:r,destinationDirectoryName:a}=t,s=await A(o.settings_root),c=await _e(o.selected_root);i.push(...c.warnings);let l=ne.join(o.selected_root,a),d=await S(l),p=await Vt(r.directory,l);await Oe.mkdir(o.selected_root,{recursive:!0});let u=await Oe.mkdtemp(ne.join(o.selected_root,".pm-extension-install-backup-")),g=ne.join(u,"destination");try{let y=await Pa(o.selected_root,o.settings_root,l,d,g),w=Cu(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),m=c.state.entries.find(x=>b(x.name)===b(r.manifest.name)),_=Ru(m,r.manifest.version,w,T()),v=ht(c.state,{name:r.manifest.name,directory:a,scope:n,manifest_version:r.manifest.version,manifest_entry:r.manifest.entry,capabilities:[...r.manifest.capabilities],contributions:r.manifest.contributions,..._,source:w}),k=Ja(s,r.manifest.name);try{p||await ca(r.directory,l),await ra(l),await aa(l),await Le(o.selected_root,v),k&&await xe(o.settings_root,s,"settings:write")}catch(x){try{await Na(y)}catch(C){throw new AggregateError([x,C],`Extension install failed: ${String(x)}; rollback failed: ${String(C)}`,{cause:C})}throw x}return{settings:s,managedState:v,sourceRecord:w,destinationDirectory:l,destinationExists:d,installInPlace:p,activationChanged:k}}finally{await Oe.rm(u,{recursive:!0,force:!0}).catch(()=>{})}},Nu=async(e,t,n)=>{let o=n.filter(i=>b(i.name)===b(t)).flatMap(i=>i.types.map(r=>({name:r.name,folder:r.folder})));return e.scope==="project"&&o.length>0&&await dt(e.resolvedRoots.pm_root,o,e.warnings,"install:type-folder"),o},Du=(e,t,n,o,i)=>{let r=Ka(t,n.activation_failures,e.scope),a=fu(t,e.scope,n.installed,r),s=[!n.extensions_disabled,a==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${a}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:a,failure:r,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:a,activated:s,registered_commands:o.command_paths,registered_actions:o.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},ju=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:i,global:r,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,l=await Pu(e,t),d=await me(o.selected_root,n,l.settings,l.managedState);i.push(...d.warnings);let p=await Va(o.pm_root,ne.dirname(o.selected_root),l.settings,d.extensions,r);i.push(...p.warnings);let u=await Nu(e,s.manifest.name,p.item_type_registrations),g=Ia(s.manifest.name,p.installed),y=Du(e,s.manifest.name,p,g,u),w=p.contribution_inventories[b(s.manifest.name)];return w&&(l.managedState=await yr(o.selected_root,l.managedState,s.manifest.name,w)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:l.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:l.destinationDirectory,overwritten:[l.destinationExists,!l.installInPlace].every(Boolean),installed_in_place:l.installInPlace,activated:y.activated,settings_changed:l.activationChanged,runtime_activation_status:y.status,command_paths:g.command_paths,action_paths:g.action_paths,contributions:w,command_discovery:uu(s.manifest.name,l.sourceRecord,g,y.failure),verification:y.verification,activation_diagnostics:{failed_count:p.activation_failures.length,failed:p.activation_failures,installed_extension_failed:y.failure??null}},y.activated)},Lu=async e=>{let{options:t,global:n,warnings:o,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new f('Action "install all" does not accept --ref.',h.USAGE);let r=[],a=new Map;for(let s of await qt()){let c=await gt(s),l=ne.resolve(c),d=a.get(l);d===void 0&&(d=await io(s,{...t,install:!0},n),a.set(l,d)),r.push({alias:s,result:d})}return o.push(...r.flatMap(s=>s.result.warnings)),i(Ca(r,t.dryRun===!0),r.every(s=>s.result.ok))},Fu=async(e,t,n)=>{let{resolvedRoots:o}=e,{bundledAliasName:i,bundledPackageName:r,installSource:a,sourceResolution:s}=await ua(t,n,e.options.ref);if(s.ambiguous){let l=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${l.package}`)}let c=await Rr(a);try{let l=await Ze(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),d=zt(l.manifest.name),p=e.options.dryRun===!0||a.kind==="local"&&i===null?await da(c,ne.join(o.selected_root,d),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:l.manifest.name,version:l.manifest.version},source_resolution:s,install_plan:p}):await Qn(o.settings_root,d,()=>ju(e,{validated:l,destinationDirectoryName:d,bundledAliasName:i,bundledPackageName:r,sourceResolution:s,installSource:a,resolvedSource:c,installPlan:p}))}finally{c.cleanup&&await c.cleanup()}},Mu=async e=>{let t=on(e.options),n=t??rn(e.normalizedTarget,e.action,e.options);return[t===void 0,wr(n)].every(Boolean)?Lu(e):Fu(e,n,t)},Uu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:i,options:r,withResult:a}=e;if(t!==void 0)throw new f('Action "adopt-all" does not accept a target argument.',h.USAGE);if(on(r)!==void 0||typeof r.ref=="string"&&r.ref.trim().length>0)throw new f('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let c=await A(o.settings_root),l=await _e(o.selected_root);i.push(...l.warnings);let d=await me(o.selected_root,n,c,l.state);i.push(...d.warnings);let p=await oo(o.selected_root,n,d.extensions,l.state),u=await me(o.selected_root,n,c,p.state);i.push(...u.warnings);let g=nn(n,i,u.extensions,r);i.push(...g.warnings);let y=new Map(u.extensions.map(_=>[`${b(_.name)}:${b(_.directory)}`,_])),w=new Map(u.extensions.map(_=>[b(_.directory),_])),m=p.adopted_entries.map(_=>{let v=b(_.directory),k=y.get(`${b(_.name)}:${v}`)??w.get(v);return{..._,...Ya(k)}});return a({adopted_all:m.length>0,adopted_count:m.length,already_managed_count:p.already_managed_count,extensions:m,triage:g,warning_codes:g.warning_codes,update_health_partial:g.update_health_partial,update_health_coverage:g.update_health_coverage})},Ya=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Gu=(e,t,n,o)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=Ht(e,{forceGithub:!0,ref:o});if(i.kind!=="github")throw new f(`Invalid GitHub shorthand "${e}".`,h.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},zu=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:i,warnings:r,options:a,withResult:s}=e,c=rn(n,t,a),l=on(a),d=await A(i.settings_root),p=await _e(i.selected_root);r.push(...p.warnings);let u=await me(i.selected_root,o,d,p.state);r.push(...u.warnings);let g=await Ga(u.extensions,c);if(!g)throw new f(`Installed extension "${c}" was not found in ${o} scope.`,h.NOT_FOUND);if(g.managed)return s({adopted:!1,already_managed:!0,extension:{name:g.name,directory:g.directory}});let y=ne.join(i.selected_root,g.directory),w=await Ze(y),m=T(),_=Gu(l,c,y,a.ref),v=ht(p.state,{name:w.manifest.name,directory:g.directory,scope:o,manifest_version:w.manifest.version,manifest_entry:w.manifest.entry,capabilities:[...w.manifest.capabilities],contributions:w.manifest.contributions,installed_at:m,updated_at:m,source:_});await Le(i.selected_root,v);let k=await me(i.selected_root,o,d,v);r.push(...k.warnings);let x=k.extensions.find(C=>b(C.name)===b(w.manifest.name))??k.extensions.find(C=>b(C.directory)===b(g.directory));return s({adopted:!0,extension:{name:w.manifest.name,directory:g.directory,version:w.manifest.version,entry:w.manifest.entry},source:_,...Ya(x)})},Xa=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:i,warnings:r,options:a}=e,s=rn(n,t,a),c=await A(i.settings_root),l=await _e(i.selected_root);r.push(...l.warnings);let d=await me(i.selected_root,o,c,l.state);r.push(...d.warnings);let p=await Ga(d.extensions,s);if(!p)throw new f(`Installed extension "${s}" was not found in ${o} scope.`,h.NOT_FOUND);return{settings:c,managedStateRead:l,candidate:p}},Ju=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:o,managedStateRead:i,candidate:r}=await Xa(e),a=ne.join(t.selected_root,r.directory);await Oe.rm(a,{recursive:!0,force:!0});let s={...i.state,updated_at:T(),entries:i.state.entries.filter(l=>b(l.name)!==b(r.name)&&b(l.directory)!==b(r.directory))};await Le(t.selected_root,s);let c=eu(o,r.name);return c&&await xe(t.settings_root,o,"settings:write"),n({removed:!0,extension:{name:r.name,directory:r.directory},destination_path:a,settings_changed:c})},Da=async e=>{let{action:t,resolvedRoots:n,warnings:o,global:i,withResult:r}=e,{settings:a,candidate:s}=await Xa(e),c=t==="activate"?Ja(a,s.name):Qp(a,s.name);c&&await xe(n.settings_root,a,"settings:write");let l=t==="activate"?await Va(n.pm_root,ne.dirname(n.selected_root),a,[s],i).then(d=>(o.push(...d.warnings),Ka(s.name,d.activation_failures,e.scope))):void 0;return l&&o.push(`extension_activate_failed:${e.scope}:${s.name}`),r({extension:{name:s.name,directory:s.directory},active:t==="activate"&&l===void 0,runtime_active:t==="activate"&&l===void 0,activation_failure:l??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},l===void 0)},qu=(e,t,n,o,i,r)=>{let a=o==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=i?.adopted_entries.length??0,l=[[r!==null,r??""],[t>0,`Run pm ${a} explore --project and pm ${a} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${a} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...l.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},no=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Wu=(e,t,n,o)=>{if(e!=="project"||t||!no(o))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Bu=(e,t,n)=>{if(String(e??"").trim().length>0)throw new f('Action "doctor" does not accept a target argument.',h.USAGE);let o=[n.isolated,n.ignoreGlobal].includes(!0);if([o,t==="global"].every(Boolean))throw new f("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let i=ba(n.detail),r=n.trace===!0;if([r,i!=="deep"].every(Boolean))throw new f("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:o,detailMode:i,includeTrace:r}},Hu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let o=await oo(e.resolvedRoots.selected_root,e.scope,t,n);return{state:o.state,fix:o}},Ku=(e,t,n,o)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:no(o),rerun_command:null,pm_global_path_recipe:null};let r=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:no(o),rerun_command:t?null:r,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},Vu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:i,options:r,global:a,withResult:s}=e,{isolated:c,detailMode:l,includeTrace:d}=Bu(t,n,r),p=await A(o.settings_root),u=await _e(o.selected_root);i.push(...u.warnings);let g=await me(o.selected_root,n,p,u.state);i.push(...g.warnings);let{state:y,fix:w}=await Hu(e,g.extensions,u.state),m=await me(o.selected_root,n,p,y);i.push(...m.warnings);let _=await ve({pmRoot:o.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await be({..._,loaded:_.loaded}),k=await Ra(o.pm_root);i.push(...k.warnings,..._.warnings),i.push(..._a(_.failed)),i.push(...v.warnings),i.push(...wa(v.failed)),i.push(...va(_,v)),i.push(...Aa(v,_)),i.push(..._u(_,v)),i.push(...Ta(v));let x=tn(m.extensions,_,v),C=Ea(n,x,_.loaded.map(O=>({layer:O.layer,name:O.name})),_.failed.map(O=>({name:O.name})),_.disabled_by_flag);i.push(...C.warnings);let U=x.filter(O=>O.update_check_status==="failed").map(O=>`extension_update_check_failed:${O.name}`);i.push(...U);let F=nn(n,i,x,r);i.push(...F.warnings);let E=[...F.warnings],q={mode:_.policy.mode,trust_mode:_.policy.trust_mode,require_provenance:_.policy.require_provenance,default_sandbox_profile:_.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:_.policy.trusted_extensions.length,allowed_extensions_count:_.policy.allowed_extensions.length,blocked_extensions_count:_.policy.blocked_extensions.length,allowed_capabilities_count:_.policy.allowed_capabilities.length,blocked_capabilities_count:_.policy.blocked_capabilities.length,allowed_surfaces_count:_.policy.allowed_surfaces.length,blocked_surfaces_count:_.policy.blocked_surfaces.length,allowed_commands_count:_.policy.allowed_commands.length,blocked_commands_count:_.policy.blocked_commands.length,allowed_actions_count:_.policy.allowed_actions.length,blocked_actions_count:_.policy.blocked_actions.length,allowed_services_count:_.policy.allowed_services.length,blocked_services_count:_.policy.blocked_services.length,extension_override_count:_.policy.extension_overrides.length},tt=xa(E),sn=Sa(),fo=F.warning_codes,Rs=Wu(n,c,r.vocabulary,_),Ps=qu(F.remediation,_.failed.length,v.failed.length,r.vocabulary,w,Rs),ho=Ku(n,c,r.vocabulary,_),Ns={status:F.status,scope:n,warning_count:F.warning_count,warning_codes:fo,total_extensions:x.length,managed_total:x.filter(O=>O.managed).length,enabled_total:x.filter(O=>O.enabled).length,active_total:x.filter(O=>O.active).length,unmanaged_loaded_extension_count:F.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:F.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:F.unmanaged_expected_extension_count,runtime_active_total:x.filter(O=>O.runtime_active===!0).length,activation_status_totals:{ok:x.filter(O=>O.activation_status==="ok").length,failed:x.filter(O=>O.activation_status==="failed").length,not_loaded:x.filter(O=>O.activation_status==="not_loaded").length,unknown:x.filter(O=>O.activation_status==="unknown").length},unknown_capability_count:tt.length,capability_contract_version:sn.version,update_available_total:F.update_available_total,update_check_status_totals:F.update_check_status_totals,update_health_coverage:F.update_health_coverage,update_health_partial:F.update_health_partial,update_check_failed_total:x.filter(O=>O.update_check_status==="failed").length,load_failure_count:_.failed.length,activation_failure_count:v.failed.length,load_failures:eo(_.failed),activation_failures:eo(v.failed),blocking_failure_count:_.failed.length+v.failed.length,has_blocking_failures:_.failed.length+v.failed.length>0,consistency_warning_count:C.warnings.length,trace_enabled:d,isolation:ho,policy:q,remediation:Ps},Ds=w?{requested:!0,applied:w.adopted_entries.length>0,adopted_count:w.adopted_entries.length,already_managed_count:w.already_managed_count,adopted_extensions:w.adopted_entries.map(O=>O.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:m.extensions.filter(O=>O.managed).length,adopted_extensions:[]},cn={mode:l,summary:Ns,triage:F,trace_enabled:d,capability_contract:sn,capability_guidance:tt,managed_state_fix:Ds,author_manifest:k,isolation:ho,policy:_.policy};if(l==="deep"){let O=d?v.failed:v.failed.map(D=>{let{trace:Um,...js}=D;return js});cn.deep={warnings:E,warning_codes:fo,capability_contract:sn,capability_guidance:tt,trace_enabled:d,managed_state:{path:u.path,count:y.entries.length,entries:y.entries},installed_extensions:x,load:{roots:_.roots,policy:_.policy,warnings:_.warnings,failed:_.failed,loaded:_.loaded.map(D=>({layer:D.layer,directory:D.directory,name:D.name,version:D.version,entry:D.entry,priority:D.priority}))},activation:{failed:O,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:C.summary},d&&(cn.deep.trace={activation_failures:v.failed.filter(D=>D.trace!==void 0).map(D=>({layer:D.layer,name:D.name,entry_path:D.entry_path,error:D.error,method:D.trace.method,command:D.trace.command,capability:D.trace.capability,missing_capability:D.trace.missing_capability,registration_index:D.trace.registration_index,expected_schema:D.trace.expected_schema,hint:D.trace.hint,received:D.trace.received}))})}return s(cn)},Yu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:i,options:r,global:a,withResult:s}=e,c=await A(o.settings_root),l=await ve({pmRoot:o.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),d=await be(l);i.push(...l.warnings),i.push(...d.warnings);let p=Vr(t,l,d);if(t!==void 0&&p.extensions.length===0){let u=r.vocabulary==="package"?"package":"extension",g=[...new Set(l.loaded.map(w=>r.vocabulary==="package"&&typeof w.source_package=="string"&&w.source_package.trim().length>0?w.source_package.trim():w.name))].sort((w,m)=>w.localeCompare(m)),y=g.length>0?` Loaded ${u} names: ${g.join(", ")}.`:"";throw new f(`No loaded ${u} named "${t}" was found in ${n} scope.${y} Run pm ${u} explore to list discovered ${u}s.`,h.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},Xu=async(e,t,n)=>{let o=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await oo(e.resolvedRoots.selected_root,e.scope,t,n),o=i.state),e.action==="manage"){let r=await $a(o.entries,Up,async a=>{if(a.source.kind!=="github")return a;let s=await Oa(a.source);return{...a,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});o={...o,updated_at:T(),entries:ft(r)},await Le(e.resolvedRoots.selected_root,o)}return{state:o,fix:i}},Zu=async(e,t,n)=>{let o=await ve({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await be({...o,loaded:o.loaded});return e.warnings.push(...o.warnings,...i.warnings),{installed:tn(n,o,i),failures:Ha(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:o.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...o.warnings,...i.warnings])].length,policy:o.policy}}},Qu=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},ja=async e=>{let{action:t,scope:n,resolvedRoots:o,warnings:i,options:r,withResult:a}=e,s=await A(o.settings_root),c=Zp(s.extensions.policy),l=await _e(o.selected_root);i.push(...l.warnings);let d=await me(o.selected_root,n,s,l.state);i.push(...d.warnings);let{state:p,fix:u}=await Xu(e,d.extensions,l.state),g=await me(o.selected_root,n,s,p);if(i.push(...g.warnings),t==="manage"){let v=g.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);i.push(...v)}let y=await Zu(e,s,g.extensions),w=y.installed,m=nn(n,i,w,r);i.push(...m.warnings);let _={total:w.length,managed_total:w.filter(v=>v.managed).length,enabled_total:w.filter(v=>v.enabled).length,active_total:w.filter(v=>v.active).length,extensions:w,triage:m,policy:c};return y.failures!==void 0&&(_.activation_diagnostics={failed_count:y.failures.length,failed:y.failures}),t==="explore"&&(_.runtime_probe=y.summary),t==="manage"&&(_.runtime_probe=y.summary,_.managed_state_fix=Qu(u,w)),a(_)},La={init:Su,install:Mu,uninstall:Ju,explore:ja,manage:ja,describe:Yu,reload:Eu,doctor:Vu,catalog:$u,adopt:zu,"adopt-all":Uu,activate:Da,deactivate:Da,migrate:Zr},em=e=>[e.action==="uninstall",e.action==="manage",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[e.action==="doctor",e.options.fixManagedState===!0].every(Boolean)].some(Boolean),tm=e=>em(e)?Qn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>La[e.action](e)):La[e.action](e);import so from"node:fs/promises";import J from"node:path";import Za from"node:readline/promises";import{stdin as Qa,stdout as vt}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5ae3e66-4a45-5c62-9144-46f8f5bff7cf")}catch{}})();var es=["ask","add","skip","status"],nm=["AGENTS.md","CLAUDE.md"],om=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],im=8,co=1,rm="<!-- pm-cli:agent-guidance:start:",am=`<!-- pm-cli:agent-guidance:start:v${co} -->`,ro="<!-- pm-cli:agent-guidance:end -->",kt="Add workflow guidance later: pm init --agent-guidance add",Zw={toPortableRelativePath:Qe,ensureTrailingNewline:ao,detectLineEnding:ns,findGuidanceBlockRange:lo,buildAgentGuidanceBlock:os,upsertAgentGuidanceBlock:is,resolveProjectRoot:rs,resolveTargetGuidancePath:as,parsePromptChoice:ss,pushUnique:et,promptForGuidanceWrite:cs,normalizeAgentGuidanceState:po,applyAgentGuidanceState:ds,writeGuidanceFile:ps,setAgentGuidanceReadlineFactoryForTests:sm},ts=()=>Za.createInterface({input:Qa,output:vt});function sm(e){ts=e??(()=>Za.createInterface({input:Qa,output:vt}))}function Qe(e,t){let n=J.relative(e,t);return n.length===0?J.basename(t):n.split(J.sep).join("/")}function ao(e){return e.endsWith(`
49
49
  `)?e:`${e}
50
50
  `}function ns(e){return e.includes(`\r
51
51
  `)?`\r
52
52
  `:`
53
- `}function lo(e){let t=e.indexOf(om);if(t===-1)return null;let n=e.indexOf(ro,t);return n===-1?null:{start_index:t,end_index:n+ro.length}}function am(e){return lo(e)!==null}function os(e,t="<your project test command>"){return[im,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",ro,""].join(e)}function is(e,t="<your project test command>"){let n=ns(e),o=os(n,t),i=lo(e);if(i){let s=e.slice(i.end_index),c=s.startsWith(`\r
53
+ `}function lo(e){let t=e.indexOf(rm);if(t===-1)return null;let n=e.indexOf(ro,t);return n===-1?null:{start_index:t,end_index:n+ro.length}}function cm(e){return lo(e)!==null}function os(e,t="<your project test command>"){return[am,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",ro,""].join(e)}function is(e,t="<your project test command>"){let n=ns(e),o=os(n,t),i=lo(e);if(i){let s=e.slice(i.end_index),c=s.startsWith(`\r
54
54
  `)?s.slice(2):s.startsWith(`
55
55
  `)?s.slice(1):s,l=ao(`${e.slice(0,i.start_index)}${o}${c}`);return{next_content:l,changed:l!==e}}let r=e.length===0?"":e.endsWith(`
56
56
  `)?`
57
57
  `:`
58
58
 
59
- `,a=ao(`${e}${r}${o}`);return{next_content:a,changed:a!==e}}async function sm(e){if(await S(J.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await so.readFile(J.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=cm(t);if(n===void 0)return"<your project test command>";let o=n.packageManager?.split("@")[0];return o==="pnpm"?"pnpm test":o==="bun"?"bun run test":o==="yarn"?"yarn test":o==="npm"?"npm test":await S(J.join(e,"pnpm-lock.yaml"))?"pnpm test":await S(J.join(e,"bun.lock"))||await S(J.join(e,"bun.lockb"))?"bun run test":await S(J.join(e,"yarn.lock"))?"yarn test":"npm test"}function cm(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function rs(e,t){let n=J.dirname(e);return J.basename(e)==="pm"&&J.basename(n)===".agents"?J.dirname(n):J.resolve(t,e)}function as(e,t){let n=e.find(i=>J.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let o=e.find(i=>i.exists);return o?o.file_path:J.join(t,"AGENTS.md")}function ss(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function cs(e){let t=ts();try{_t.write(`
59
+ `,a=ao(`${e}${r}${o}`);return{next_content:a,changed:a!==e}}async function lm(e){if(await S(J.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await so.readFile(J.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=dm(t);if(n===void 0)return"<your project test command>";let o=n.packageManager?.split("@")[0];return o==="pnpm"?"pnpm test":o==="bun"?"bun run test":o==="yarn"?"yarn test":o==="npm"?"npm test":await S(J.join(e,"pnpm-lock.yaml"))?"pnpm test":await S(J.join(e,"bun.lock"))||await S(J.join(e,"bun.lockb"))?"bun run test":await S(J.join(e,"yarn.lock"))?"yarn test":"npm test"}function dm(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function rs(e,t){let n=J.dirname(e);return J.basename(e)==="pm"&&J.basename(n)===".agents"?J.dirname(n):J.resolve(t,e)}function as(e,t){let n=e.find(i=>J.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let o=e.find(i=>i.exists);return o?o.file_path:J.join(t,"AGENTS.md")}function ss(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function cs(e){let t=ts();try{vt.write(`
60
60
  Agent guidance check
61
- `),_t.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
62
- `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return _t.write(`
63
- `),ss(n,!0)}finally{t.close()}}function po(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:co,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o)):[]}}async function ls(e){let t=[];for(let n of em){let o=J.join(e,n),i=await S(o);if(!i){t.push({file_path:o,exists:i,has_guidance:!1,has_marker:!1});continue}let r=await so.readFile(o,"utf8"),a=r.toLowerCase(),s=tm.filter(l=>a.includes(l)),c=am(r);t.push({file_path:o,exists:i,has_guidance:c||s.length>=nm,has_marker:c})}return t}function et(e,t){e.includes(t)||e.push(t)}function ds(e,t){let n=po(e),o=JSON.stringify(n)!==JSON.stringify(t);return o&&(e.agent_guidance=t),{changed:o,state:t}}async function ps(e,t=J.dirname(e)){let o=await S(e)?await so.readFile(e,"utf8"):"",i=is(o,await sm(t));return i.changed?(await fe(e,i.next_content),{changed:!0,warnings:await K({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function lm(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Qe(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Qe(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Qe(e.projectRoot,t.file_path))}}async function dm(e,t,n){return e?await ls(n):t}function wt(e,t,n){e.state={...e.state,...n,template_version:co,last_checked_files:t}}async function us(e,t){if(t.presentBefore)return;let n=await ps(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function pm(e,t){t||(e.warnings.push("agent_guidance:missing"),et(e.nextSteps,vt))}function um(e,t){e.skipped=!0,wt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),et(e.nextSteps,vt)}async function mm(e,t){await us(e,t),wt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function fm(e,t){e.state.declined&&wt(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function hm(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),et(e.nextSteps,vt)}async function gm(e,t){if(e.prompted=!0,await cs(t.targetRelativePath)){await us(e,t),wt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,wt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),et(e.nextSteps,vt)}function ym(e){e.warnings.push("agent_guidance:missing_non_interactive"),et(e.nextSteps,vt)}async function _m(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(pm(n,t.presentBefore),n):t.mode==="skip"?(um(n,t.checkedFiles),n):t.mode==="add"?(await mm(n,t),n):t.presentBefore?(fm(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(hm(n),n):t.interactive?(await gm(n,t),n):(ym(n),n)}async function ms(e){let t=rs(e.pm_root,e.cwd),n=await ls(t),o=as(n,t),i=Qe(t,o),r=n.map(d=>Qe(t,d.file_path)),a=n.some(d=>d.has_guidance),s=await _m(po(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:o,targetRelativePath:i,checkedFiles:r,presentBefore:a,projectRoot:t}),c=ds(e.settings,s.state);return n=await dm(s.applied,n,t),{summary:lm({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import wm from"node:fs/promises";import j from"node:path";import hs from"node:readline/promises";import{stdin as gs,stdout as Z}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="55f7a34f-05d6-507f-a46c-1da0d957f2e3")}catch{}})();var vm=Symbol.for("pm.sdk.init-invocation-cwd");function wv(e){return{ok:e.ok,path:e.path,target:e.target,id_prefix:e.settings.id_prefix,governance_preset:e.governance_preset,telemetry:{enabled:e.settings.telemetry.enabled,capture_level:e.settings.telemetry.capture_level},output_format:e.settings.output.default_format,created_dirs_count:e.created_dirs.length,created_dirs:e.created_dirs,warnings:e.warnings,wizard_used:e.wizard_used,...e.registered_type_preset?{registered_type_preset:e.registered_type_preset}:{},...e.installed_packages?{installed_packages:e.installed_packages}:{},next_steps:e.next_steps,agent_guidance:e.agent_guidance,hint:"Re-run with --verbose for the full settings tree."}}var vv={normalizeInitGovernancePreset:uo,normalizeInitTypePreset:_s,normalizeOptionalInitAuthor:ws,normalizeInitAgentGuidanceMode:ks,isPathLikeInitTarget:rn,resolveInitInvocation:vs,resolveInitPrefixInput:bs,parseYesNoChoice:xs,applyGovernancePreset:mo,runInitWizard:Ts,setInitReadlineFactoryForTests:bm,summarizeInstalledPackages:Ss,buildInitNextSteps:Os,registerInitTypePreset:Es,assertExplicitTrackerPathIsNotWorkspaceRoot:Is,isLikelyWorkspaceRoot:$s,installInitMergeFence:Cs},ys=()=>hs.createInterface({input:gs,output:Z});function bm(e){ys=e??(()=>hs.createInterface({input:gs,output:Z}))}function km(){return structuredClone(ln)}var xm=["minimal","default","strict"];function uo(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new f("--preset must not be empty",h.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new f(`Invalid --preset value "${e}". Allowed: ${xm.join(", ")}`,h.USAGE)}function _s(e){if(e!==void 0){if(e.trim().length===0)throw new f("--type-preset must not be empty",h.USAGE);try{return jt(e)}catch{throw new f(`Invalid --type-preset value "${e}". Allowed: ${at.join(", ")}`,h.USAGE)}}}function ws(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new f("--author must not be empty",h.USAGE);return t}function rn(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:j.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function vs(e,t,n,o){let i=o?.trim();if(o!==void 0&&i?.length===0)throw new f("--workspace must not be empty",h.USAGE);if(i!==void 0){if(t.path!==void 0||rn(n))throw new f("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",h.USAGE);let l=j.resolve(e,i),d=j.join(l,".agents","pm");return{pmRoot:d,prefixArg:n,target:{mode:"workspace-path",tracker_root:d,workspace_root:l}}}if(t.path===void 0&&rn(n)){let l=j.resolve(e,n.trim());return{pmRoot:l,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:l}}}let r=P(e,t.path),a=j.join(j.resolve(e),".agents","pm"),s=j.dirname(j.dirname(r)),c=j.resolve(r)===a?"current":"ancestor";return{pmRoot:r,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:r,workspace_root:s,discovery:c,requested_cwd:j.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:r}}}function bs(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new f("--id-prefix must not be empty",h.USAGE);if(rn(t))throw new f(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,h.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&ke(e)!==ke(t))throw new f(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,h.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${ke(e)}`,`pm init --id-prefix ${ke(t)}`]});return t}function ks(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new f("--agent-guidance must not be empty",h.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new f(`Invalid --agent-guidance value "${e}". Allowed: ${es.join(", ")}`,h.USAGE)}function xs(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function mo(e,t){let n=wo[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function Sm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ss(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(Sm).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Es(e,t,n){let o=Y(t.schema),i=oe(e,o.files.types,X.types),a=re(await W(i)),s=[],c=[];for(let l of st(n)){let d=ze(a,l);a=d.file,(d.replaced?c:s).push(d.definition.name)}return await Ge({pmRoot:e,filePath:i,raw:le(a),op:"init:type-preset",author:H(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:s,updated:c,file:i}}async function $s(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",j.join(".agents","pm")];for(let n of t)if(await S(j.join(e,n)))return!0;return!1}async function Is(e,t,n){if(!t||n||await S(j.join(e,"settings.json"))||!await $s(e))return;let o=j.join(e,".agents","pm");throw new f(`Refusing to initialize tracker files directly in workspace root "${e}".`,h.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${o} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${o} init --yes`}})}async function As(e,t){let n=[],o=[];for(let i of t){let r=i?j.join(e,i):e,a=await S(r);await wm.mkdir(r,{recursive:!0}),a?o.push(`already_exists:${r}`):n.push(r),o.push(...await K({path:r,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:o}}async function Ts(e,t){let n=ys();try{Z.write(`pm init setup wizard (agent-optimized)
61
+ `),vt.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
62
+ `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return vt.write(`
63
+ `),ss(n,!0)}finally{t.close()}}function po(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:co,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o)):[]}}async function ls(e){let t=[];for(let n of nm){let o=J.join(e,n),i=await S(o);if(!i){t.push({file_path:o,exists:i,has_guidance:!1,has_marker:!1});continue}let r=await so.readFile(o,"utf8"),a=r.toLowerCase(),s=om.filter(l=>a.includes(l)),c=cm(r);t.push({file_path:o,exists:i,has_guidance:c||s.length>=im,has_marker:c})}return t}function et(e,t){e.includes(t)||e.push(t)}function ds(e,t){let n=po(e),o=JSON.stringify(n)!==JSON.stringify(t);return o&&(e.agent_guidance=t),{changed:o,state:t}}async function ps(e,t=J.dirname(e)){let o=await S(e)?await so.readFile(e,"utf8"):"",i=is(o,await lm(t));return i.changed?(await fe(e,i.next_content),{changed:!0,warnings:await K({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function pm(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Qe(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Qe(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Qe(e.projectRoot,t.file_path))}}async function um(e,t,n){return e?await ls(n):t}function bt(e,t,n){e.state={...e.state,...n,template_version:co,last_checked_files:t}}async function us(e,t){if(t.presentBefore)return;let n=await ps(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function mm(e,t){t||(e.warnings.push("agent_guidance:missing"),et(e.nextSteps,kt))}function fm(e,t){e.skipped=!0,bt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),et(e.nextSteps,kt)}async function hm(e,t){await us(e,t),bt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function gm(e,t){e.state.declined&&bt(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function ym(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),et(e.nextSteps,kt)}async function _m(e,t){if(e.prompted=!0,await cs(t.targetRelativePath)){await us(e,t),bt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,bt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),et(e.nextSteps,kt)}function wm(e){e.warnings.push("agent_guidance:missing_non_interactive"),et(e.nextSteps,kt)}async function vm(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(mm(n,t.presentBefore),n):t.mode==="skip"?(fm(n,t.checkedFiles),n):t.mode==="add"?(await hm(n,t),n):t.presentBefore?(gm(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(ym(n),n):t.interactive?(await _m(n,t),n):(wm(n),n)}async function ms(e){let t=rs(e.pm_root,e.cwd),n=await ls(t),o=as(n,t),i=Qe(t,o),r=n.map(d=>Qe(t,d.file_path)),a=n.some(d=>d.has_guidance),s=await vm(po(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:o,targetRelativePath:i,checkedFiles:r,presentBefore:a,projectRoot:t}),c=ds(e.settings,s.state);return n=await um(s.applied,n,t),{summary:pm({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import bm from"node:fs/promises";import L from"node:path";import hs from"node:readline/promises";import{stdin as gs,stdout as Z}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="231597cc-2166-5029-9b3a-476587a33941")}catch{}})();var km=Symbol.for("pm.sdk.init-invocation-cwd");function kv(e,t=!1){if(t){let n=e.warnings.filter(o=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(o));return{ok:e.ok,path:e.path,governance_preset:e.governance_preset,telemetry:`${e.settings.telemetry.enabled?"enabled":"disabled"} (${e.settings.telemetry.capture_level})`,created_count:e.created_dirs.length,next_steps:e.next_steps.slice(0,3),...n.length>0?{warnings:n.join("; ")}:{},details:`${ot(["--pm-path",e.path,"init","--verbose"])} for full setup details and notices (or --json)`}}return{ok:e.ok,path:e.path,target:e.target,id_prefix:e.settings.id_prefix,governance_preset:e.governance_preset,telemetry:{enabled:e.settings.telemetry.enabled,capture_level:e.settings.telemetry.capture_level},output_format:e.settings.output.default_format,created_dirs_count:e.created_dirs.length,created_dirs:e.created_dirs,warnings:e.warnings,wizard_used:e.wizard_used,...e.registered_type_preset?{registered_type_preset:e.registered_type_preset}:{},...e.installed_packages?{installed_packages:e.installed_packages}:{},next_steps:e.next_steps,agent_guidance:e.agent_guidance,hint:"Re-run with --verbose for the full settings tree."}}var xv={normalizeInitGovernancePreset:uo,normalizeInitTypePreset:_s,normalizeOptionalInitAuthor:ws,normalizeInitAgentGuidanceMode:ks,isPathLikeInitTarget:an,resolveInitInvocation:vs,resolveInitPrefixInput:bs,parseYesNoChoice:xs,applyGovernancePreset:mo,runInitWizard:Ts,setInitReadlineFactoryForTests:xm,summarizeInstalledPackages:Ss,buildInitNextSteps:Os,registerInitTypePreset:Es,assertExplicitTrackerPathIsNotWorkspaceRoot:Is,isLikelyWorkspaceRoot:$s,installInitMergeFence:Cs},ys=()=>hs.createInterface({input:gs,output:Z});function xm(e){ys=e??(()=>hs.createInterface({input:gs,output:Z}))}function Sm(){return structuredClone(dn)}var Em=["minimal","default","strict"];function uo(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new f("--preset must not be empty",h.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new f(`Invalid --preset value "${e}". Allowed: ${Em.join(", ")}`,h.USAGE)}function _s(e){if(e!==void 0){if(e.trim().length===0)throw new f("--type-preset must not be empty",h.USAGE);try{return Lt(e)}catch{throw new f(`Invalid --type-preset value "${e}". Allowed: ${ct.join(", ")}`,h.USAGE)}}}function ws(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new f("--author must not be empty",h.USAGE);return t}function an(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:L.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function vs(e,t,n,o){let i=o?.trim();if(o!==void 0&&i?.length===0)throw new f("--workspace must not be empty",h.USAGE);if(i!==void 0){if(t.path!==void 0||an(n))throw new f("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",h.USAGE);let l=L.resolve(e,i),d=L.join(l,".agents","pm");return{pmRoot:d,prefixArg:n,target:{mode:"workspace-path",tracker_root:d,workspace_root:l}}}if(t.path===void 0&&an(n)){let l=L.resolve(e,n.trim());return{pmRoot:l,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:l}}}let r=N(e,t.path),a=L.join(L.resolve(e),".agents","pm"),s=L.dirname(L.dirname(r)),c=L.resolve(r)===a?"current":"ancestor";return{pmRoot:r,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:r,workspace_root:s,discovery:c,requested_cwd:L.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:r}}}function bs(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new f("--id-prefix must not be empty",h.USAGE);if(an(t))throw new f(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,h.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&ke(e)!==ke(t))throw new f(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,h.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${ke(e)}`,`pm init --id-prefix ${ke(t)}`]});return t}function ks(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new f("--agent-guidance must not be empty",h.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new f(`Invalid --agent-guidance value "${e}". Allowed: ${es.join(", ")}`,h.USAGE)}function xs(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function mo(e,t){let n=wo[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function $m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ss(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter($m).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Es(e,t,n){let o=Y(t.schema),i=oe(e,o.files.types,X.types),a=re(await W(i)),s=[],c=[];for(let l of lt(n)){let d=ze(a,l);a=d.file,(d.replaced?c:s).push(d.definition.name)}return await Ge({pmRoot:e,filePath:i,raw:le(a),op:"init:type-preset",author:H(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:s,updated:c,file:i}}async function $s(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",L.join(".agents","pm")];for(let n of t)if(await S(L.join(e,n)))return!0;return!1}async function Is(e,t,n){if(!t||n||await S(L.join(e,"settings.json"))||!await $s(e))return;let o=L.join(e,".agents","pm");throw new f(`Refusing to initialize tracker files directly in workspace root "${e}".`,h.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${o} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${o} init --yes`}})}async function As(e,t){let n=[],o=[];for(let i of t){let r=i?L.join(e,i):e,a=await S(r);await bm.mkdir(r,{recursive:!0}),a?o.push(`already_exists:${r}`):n.push(r),o.push(...await K({path:r,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:o}}async function Ts(e,t){let n=ys();try{Z.write(`pm init setup wizard (agent-optimized)
64
64
  `),Z.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
65
65
 
66
66
  `),Z.write(`1/3 Item ID prefix
@@ -75,5 +75,5 @@ Agent guidance check
75
75
  3/3 Project telemetry
76
76
  `),Z.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
77
77
  `);let c=t?"Y/n":"y/N",l=await n.question(`Enable telemetry for this project? [${c}] `),d=xs(l,t);return Z.write(`
78
- `),{prefix:i,preset:s,telemetry_enabled:d}}finally{n.close()}}function Em(e){return{presetFromOption:uo(e.preset),useDefaults:e.defaults===!0,authorFromOption:ws(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:ks(e.agentGuidance),typePreset:_s(e.typePreset)}}function $m(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function Im(e,t,n,o){if(t.length===0||n)return;let i=o.discovery==="ancestor";throw new f(`${i?`No tracker exists in ${o.requested_cwd}; pm init found an ancestor tracker at ${o.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,h.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:i?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:o.tracker_root,requested_path:o.requested_cwd,suggested_path:o.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...i?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...i?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function Am(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(mo(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function Tm(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=$m({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return Im(e.settingsPath,n,e.options.force===!0,e.target),Am({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await xe(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function Om(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,o,i=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await Ts(t,ln.telemetry.enabled);t=c.prefix,n=c.preset,o=c.telemetry_enabled,i=!0}let r=n??"minimal",a=km();a.id_prefix=t,mo(a,r);let s=Uo()?.trim()||void 0;return a.author_default=e.normalizedOptions.authorFromOption??s??"",o!==void 0&&(a.telemetry.enabled=o,a.telemetry.first_run_prompt_completed=!0),await xe(e.pmRoot,a),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:i}}async function fs(e){return e.settingsExists?await Tm(e):await Om({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function Cm(e){let t=await ms({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await xe(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function Rm(e,t){let n=[],o=[],i=await Mo(e,t.schema);for(let r of i.created_paths)n.push(r),o.push(...await K({path:r,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:o}}async function Pm(e){if(e.typePreset===void 0)return;let t=await Es(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await K({path:t.file,scope:"project",op:"init:type_preset"})),t}async function Nm(e){let n=G(e.settings,B()).folders.filter(i=>!cn.includes(i)),o=await As(e.pmRoot,n);e.createdDirs.push(...o.createdDirs),e.warnings.push(...o.warnings)}function Dm(e){let t=j.resolve(e.tracker_root),n=j.dirname(t);return j.basename(t)==="pm"&&j.basename(n)===".agents"?j.dirname(n):e.workspace_root}async function jm(e,t,n,o){if(!e)return;let i=await io("all",{install:!0,project:!0},{...t,path:n});o.push(...i.warnings);let r=Ss(i),a=r.packages.filter(s=>!s.ok).map(s=>s.alias);if(!r.installed_all||a.length>0)throw new f(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,h.GENERIC_FAILURE);return r}function Os(e){let t=o=>It([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...o]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let o of e.agentGuidanceNextSteps){let i=e.target.mode==="workspace-discovery"?o:o.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(i)||n.push(i)}return n}async function Cs(e,t,n,o=Tn){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let i=await o({pmRoot:e,workspaceRoot:t});i.gitattributes.changed&&n.push(`updated:merge_fence:${i.gitattributes.path}`)}catch(i){if(!(i instanceof f))throw i;n.push(`merge_fence_skipped:install_failed:${i.context.code??"pm_error"}:${i.message}:run pm merge install after resolving the Git repository error`)}}async function Lm(e,t,n,o){if(e==null||n==="status")return;let i=await wi(e,{pmRoot:t});i.changed&&o.push(`updated:gitignore:${i.path}`)}async function bv(e,t,n={}){let o=t[vm],i=typeof o=="string"?o:process.cwd(),r=vs(i,t,e,n.workspace),a=r.pmRoot;e=bs(r.prefixArg,n.idPrefix);let s=Em(n);await Is(a,r.target.mode==="tracker-path",n.force===!0);let c=[],l=[],d=j.join(a,"settings.json"),p=await S(d),u;p&&(u=await fs({pmRoot:a,settingsPath:d,settingsExists:p,normalizedPrefix:ke(e),prefixArg:e,options:n,normalizedOptions:s,warnings:l,target:r.target}));let g=await As(a,cn);c.push(...g.createdDirs),l.push(...g.warnings),u??=await fs({pmRoot:a,settingsPath:d,settingsExists:p,normalizedPrefix:ke(e),prefixArg:e,options:n,normalizedOptions:s,warnings:l,target:r.target});let{settings:y}=u,w=Dm(r.target),m=await $n(w??j.dirname(a)),_=w??m,v=await Cm({pmRoot:a,cwd:_??i,agentGuidanceMode:s.agentGuidanceMode,settings:y,warnings:l}),k=await Rm(a,y);c.push(...k.createdDirs),l.push(...k.warnings);let x=await Pm({pmRoot:a,settings:y,typePreset:s.typePreset,warnings:l});x&&(y=await A(a)),await Nm({pmRoot:a,settings:y,createdDirs:c,warnings:l}),await Lm(_,a,s.agentGuidanceMode,l),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await Cs(a,m,l);let C=await jm(s.installBundledPackages,t,a,l),U=Os({installBundledPackages:s.installBundledPackages,registeredTypePreset:x,agentGuidanceNextSteps:v.next_steps,target:r.target});return{ok:!0,path:a,target:r.target,settings:y,created_dirs:c,warnings:l,governance_preset:y.governance.preset,wizard_used:u.wizardUsed,...x?{registered_type_preset:x}:{},...C?{installed_packages:C}:{},next_steps:U,agent_guidance:v}}export{_n as a,fi as b,gi as c,bn as d,Qs as e,tc as f,wi as g,Je as h,oc as i,ic as j,bi as k,Rt as l,Ei as m,qe as n,Sn as o,lc as p,$n as q,An as r,Oi as s,wf as t,vf as u,Ci as v,bf as w,Tn as x,Wi as y,He as z,Ke as A,Bi as B,zi as C,We as D,Be as E,Ji as F,tl as G,pc as H,Sf as I,Af as J,Pi as K,fc as L,Wf as M,Zi as N,nr as O,Qc as P,el as Q,og as R,rg as S,ag as T,ct as U,sg as V,cg as W,lg as X,dg as Y,pg as Z,ug as _,mg as $,fg as aa,hg as ba,gg as ca,yg as da,_g as ea,wg as fa,vg as ga,bg as ha,kg as ia,xg as ja,Sg as ka,Eg as la,$g as ma,Ig as na,Ag as oa,Tg as pa,Og as qa,Cg as ra,b as sa,_e as ta,Mt as ua,_l as va,dt as wa,Ut as xa,$r as ya,Dr as za,Yn as Aa,Vr as Ba,By as Ca,$p as Da,xa as Ea,Sa as Fa,$a as Ga,Xn as Ha,ap as Ia,sp as Ja,cp as Ka,Zr as La,da as Ma,wp as Na,jp as Oa,ua as Pa,io as Qa,es as Ra,Vw as Sa,ms as Ta,vm as Ua,wv as Va,vv as Wa,bv as Xa};
79
- //# sourceMappingURL=chunk-3AHONKLL.js.map
78
+ `),{prefix:i,preset:s,telemetry_enabled:d}}finally{n.close()}}function Im(e){return{presetFromOption:uo(e.preset),useDefaults:e.defaults===!0,authorFromOption:ws(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:ks(e.agentGuidance),typePreset:_s(e.typePreset)}}function Am(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function Tm(e,t,n,o){if(t.length===0||n)return;let i=o.discovery==="ancestor";throw new f(`${i?`No tracker exists in ${o.requested_cwd}; pm init found an ancestor tracker at ${o.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,h.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:i?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:o.tracker_root,requested_path:o.requested_cwd,suggested_path:o.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...i?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...i?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function Om(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(mo(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function Cm(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=Am({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return Tm(e.settingsPath,n,e.options.force===!0,e.target),Om({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await xe(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function Rm(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,o,i=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await Ts(t,dn.telemetry.enabled);t=c.prefix,n=c.preset,o=c.telemetry_enabled,i=!0}let r=n??"minimal",a=Sm();a.id_prefix=t,mo(a,r);let s=Uo()?.trim()||void 0;return a.author_default=e.normalizedOptions.authorFromOption??s??"",o!==void 0&&(a.telemetry.enabled=o,a.telemetry.first_run_prompt_completed=!0),await xe(e.pmRoot,a),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:i}}async function fs(e){return e.settingsExists?await Cm(e):await Rm({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function Pm(e){let t=await ms({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await xe(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function Nm(e,t){let n=[],o=[],i=await Mo(e,t.schema);for(let r of i.created_paths)n.push(r),o.push(...await K({path:r,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:o}}async function Dm(e){if(e.typePreset===void 0)return;let t=await Es(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await K({path:t.file,scope:"project",op:"init:type_preset"})),t}async function jm(e){let n=G(e.settings,B()).folders.filter(i=>!ln.includes(i)),o=await As(e.pmRoot,n);e.createdDirs.push(...o.createdDirs),e.warnings.push(...o.warnings)}function Lm(e){let t=L.resolve(e.tracker_root),n=L.dirname(t);return L.basename(t)==="pm"&&L.basename(n)===".agents"?L.dirname(n):e.workspace_root}async function Fm(e,t,n,o){if(!e)return;let i=await io("all",{install:!0,project:!0},{...t,path:n});o.push(...i.warnings);let r=Ss(i),a=r.packages.filter(s=>!s.ok).map(s=>s.alias);if(!r.installed_all||a.length>0)throw new f(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,h.GENERIC_FAILURE);return r}function Os(e){let t=o=>ot([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...o]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let o of e.agentGuidanceNextSteps){let i=e.target.mode==="workspace-discovery"?o:o.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(i)||n.push(i)}return n}async function Cs(e,t,n,o=Tn){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let i=await o({pmRoot:e,workspaceRoot:t});i.gitattributes.changed&&n.push(`updated:merge_fence:${i.gitattributes.path}`)}catch(i){if(!(i instanceof f))throw i;n.push(`merge_fence_skipped:install_failed:${i.context.code??"pm_error"}:${i.message}:run pm merge install after resolving the Git repository error`)}}async function Mm(e,t,n,o){if(e==null||n==="status")return;let i=await wi(e,{pmRoot:t});i.changed&&o.push(`updated:gitignore:${i.path}`)}async function Sv(e,t,n={}){let o=t[km],i=typeof o=="string"?o:process.cwd(),r=vs(i,t,e,n.workspace),a=r.pmRoot;e=bs(r.prefixArg,n.idPrefix);let s=Im(n);await Is(a,r.target.mode==="tracker-path",n.force===!0);let c=[],l=[],d=L.join(a,"settings.json"),p=await S(d),u;p&&(u=await fs({pmRoot:a,settingsPath:d,settingsExists:p,normalizedPrefix:ke(e),prefixArg:e,options:n,normalizedOptions:s,warnings:l,target:r.target}));let g=await As(a,ln);c.push(...g.createdDirs),l.push(...g.warnings),u??=await fs({pmRoot:a,settingsPath:d,settingsExists:p,normalizedPrefix:ke(e),prefixArg:e,options:n,normalizedOptions:s,warnings:l,target:r.target});let{settings:y}=u,w=Lm(r.target),m=await $n(w??L.dirname(a)),_=w??m,v=await Pm({pmRoot:a,cwd:_??i,agentGuidanceMode:s.agentGuidanceMode,settings:y,warnings:l}),k=await Nm(a,y);c.push(...k.createdDirs),l.push(...k.warnings);let x=await Dm({pmRoot:a,settings:y,typePreset:s.typePreset,warnings:l});x&&(y=await A(a)),await jm({pmRoot:a,settings:y,createdDirs:c,warnings:l}),await Mm(_,a,s.agentGuidanceMode,l),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await Cs(a,m,l);let C=await Fm(s.installBundledPackages,t,a,l),U=Os({installBundledPackages:s.installBundledPackages,registeredTypePreset:x,agentGuidanceNextSteps:v.next_steps,target:r.target});return{ok:!0,path:a,target:r.target,settings:y,created_dirs:c,warnings:l,governance_preset:y.governance.preset,wizard_used:u.wizardUsed,...x?{registered_type_preset:x}:{},...C?{installed_packages:C}:{},next_steps:U,agent_guidance:v}}export{wn as a,fi as b,gi as c,kn as d,Qs as e,tc as f,wi as g,Je as h,oc as i,ic as j,bi as k,Pt as l,Ei as m,qe as n,Sn as o,pc as p,$n as q,An as r,Oi as s,kf as t,xf as u,Ci as v,Sf as w,Tn as x,Wi as y,He as z,Ke as A,Bi as B,zi as C,We as D,Be as E,Ji as F,ol as G,mc as H,If as I,Cf as J,Pi as K,gc as L,Kf as M,Zi as N,nr as O,tl as P,nl as Q,ag as R,cg as S,lg as T,dt as U,dg as V,pg as W,ug as X,mg as Y,fg as Z,hg as _,gg as $,yg as aa,_g as ba,wg as ca,vg as da,bg as ea,kg as fa,xg as ga,Sg as ha,Eg as ia,$g as ja,Ig as ka,Ag as la,Tg as ma,Og as na,Cg as oa,Rg as pa,Pg as qa,Ng as ra,b as sa,_e as ta,Ut as ua,vl as va,ut as wa,Gt as xa,$r as ya,Dr as za,Yn as Aa,Vr as Ba,Vy as Ca,Ap as Da,xa as Ea,Sa as Fa,$a as Ga,Xn as Ha,cp as Ia,lp as Ja,dp as Ka,Zr as La,da as Ma,bp as Na,Fp as Oa,ua as Pa,io as Qa,es as Ra,Zw as Sa,ms as Ta,km as Ua,kv as Va,xv as Wa,Sv as Xa};
79
+ //# sourceMappingURL=chunk-G2IJF244.js.map