@unbrained/pm-cli 2026.10.5 → 2026.10.6

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 (114) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +26 -1
  3. package/dist/cli/register-setup.js +1 -1
  4. package/dist/cli/runtime/projection-retry.js +1 -1
  5. package/dist/cli-bundle/bundle-manifest.json +158 -158
  6. package/dist/cli-bundle/chunks/{chunk-Z66DWDAU.js → chunk-25EW53VO.js} +39 -38
  7. package/dist/cli-bundle/chunks/{chunk-YVBRASXO.js → chunk-3CCVTV6Q.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-5MNOWZPN.js → chunk-3REXBTST.js} +2 -2
  9. package/dist/cli-bundle/chunks/chunk-4WB55TBC.js +80 -0
  10. package/dist/cli-bundle/chunks/{chunk-OOLYASYJ.js → chunk-6STTPXOC.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-AJ7H6XUF.js → chunk-ATB4ZZBQ.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-N4YGSG6F.js → chunk-D4G43LBV.js} +38 -38
  13. package/dist/cli-bundle/chunks/{chunk-HRJ6G6ZG.js → chunk-K6D6DMRT.js} +28 -28
  14. package/dist/cli-bundle/chunks/chunk-KIRHWPZB.js +2 -0
  15. package/dist/cli-bundle/chunks/chunk-O67BH435.js +6 -0
  16. package/dist/cli-bundle/chunks/{chunk-3CYOBJUK.js → chunk-RJHLD64E.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-WFZ4UEOB.js → chunk-TUKO5NF7.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-VZ63DEVJ.js → chunk-XJD47LUH.js} +2 -2
  19. package/dist/cli-bundle/chunks/{register-list-query-75QXHIFH.js → register-list-query-53WYLNZT.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-mutation-YS54SCHG.js → register-mutation-34XXUBVI.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-operations-6KHZQSYJ.js → register-operations-WANO6EIM.js} +2 -2
  22. package/dist/cli-bundle/chunks/register-setup-WT37UPBQ.js +2 -0
  23. package/dist/cli-bundle/focused-chunks/{chunk-GITOYRUW.js → chunk-6KFKQD2D.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-UDYRVBOZ.js → chunk-FOHRPFIT.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-DDRN42PB.js → chunk-GRQXL5G5.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-ABV67XCC.js → chunk-JZ4WGUVH.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-B5RSLVE6.js → chunk-NM3PM6O6.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/chunk-OT7HK7SG.js +2 -0
  29. package/dist/cli-bundle/focused-chunks/{chunk-2CVX3KR3.js → chunk-PCLU34KB.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-5C3IDDW7.js → chunk-QQIE4L42.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/chunk-RPUNVKXK.js +2 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-LE4JUCRR.js → chunk-RXSVJPZ7.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-SPN5QTZ3.js +30 -0
  34. package/dist/cli-bundle/focused-chunks/{chunk-CLDPTMQY.js → chunk-SUZJNPGB.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-YMU42COG.js → chunk-W4BG5HHS.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-C224METM.js → chunk-Y5HXFDTZ.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-ECBOPEJE.js → chunk-ZK5SOOPC.js} +61 -61
  38. package/dist/cli-bundle/focused-chunks/chunk-ZQK2XUSS.js +12 -0
  39. package/dist/cli-bundle/main.js +21 -21
  40. package/dist/cli-bundle/sdk-authoring.js +1 -1
  41. package/dist/cli-bundle/sdk-contracts.js +1 -1
  42. package/dist/cli-bundle/sdk-core.js +31 -30
  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 +42 -42
  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/extensions/extension-types.d.ts +2 -0
  51. package/dist/core/extensions/extension-types.js +1 -1
  52. package/dist/sdk/cli-bootstrap.d.ts +5 -1
  53. package/dist/sdk/cli-bootstrap.js +1 -1
  54. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  55. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  56. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  57. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  58. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  59. package/dist/sdk/extension/managed-state.d.ts +2 -0
  60. package/dist/sdk/extension/managed-state.js +1 -1
  61. package/dist/sdk/extension/managed-update-status.d.ts +3 -0
  62. package/dist/sdk/extension/managed-update-status.js +2 -0
  63. package/dist/sdk/extension/source-resolution.d.ts +2 -6
  64. package/dist/sdk/extension/source-resolution.js +1 -1
  65. package/dist/sdk/extension/update-check.d.ts +10 -0
  66. package/dist/sdk/extension/update-check.js +1 -1
  67. package/dist/sdk/extension-command-context.js +2 -1
  68. package/dist/sdk/extension.d.ts +4 -0
  69. package/dist/sdk/extension.js +1 -1
  70. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  71. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  72. package/dist/sdk/public-surface.json +1 -1
  73. package/dist/sdk/query/get.js +1 -1
  74. package/dist/sdk/read-output-contracts.js +1 -1
  75. package/dist/sdk/runtime-input.js +1 -1
  76. package/dist/sdk/test/execution.d.ts +2 -1
  77. package/dist/sdk/test/execution.js +3 -3
  78. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +36 -0
  79. package/docs/GET_READ_EVIDENCE.md +17 -1
  80. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
  81. package/docs/PR_REVIEW_LOOP.md +21 -4
  82. package/docs/README.md +1 -0
  83. package/docs/RELEASING.md +18 -0
  84. package/docs/SDK_CONFIGURATION_SAFETY.md +123 -0
  85. package/docs/generated/FLAG_LEXICON_BUDGETS.md +3 -3
  86. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
  87. package/marketplace.json +2 -2
  88. package/package.json +3 -3
  89. package/packages/pm-beads/package.json +1 -1
  90. package/packages/pm-calendar/package.json +1 -1
  91. package/packages/pm-command-kit/package.json +1 -1
  92. package/packages/pm-digital-twin/package.json +1 -1
  93. package/packages/pm-governance-audit/package.json +1 -1
  94. package/packages/pm-guide-shell/package.json +1 -1
  95. package/packages/pm-kanban/package.json +1 -1
  96. package/packages/pm-lifecycle-hooks/package.json +1 -1
  97. package/packages/pm-linked-test-adapters/package.json +1 -1
  98. package/packages/pm-search-advanced/package.json +1 -1
  99. package/packages/pm-templates/package.json +1 -1
  100. package/packages/pm-todos/package.json +1 -1
  101. package/packages/pm-vcs/package.json +1 -1
  102. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  103. package/plugins/pm-claude/package.json +2 -2
  104. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  105. package/plugins/pm-codex/package.json +2 -2
  106. package/plugins/pm-codex/plugin.json +1 -1
  107. package/dist/cli-bundle/chunks/chunk-D332RXZ7.js +0 -80
  108. package/dist/cli-bundle/chunks/chunk-KRVI56QE.js +0 -6
  109. package/dist/cli-bundle/chunks/chunk-TGMONGWX.js +0 -2
  110. package/dist/cli-bundle/chunks/register-setup-RTATEN2M.js +0 -2
  111. package/dist/cli-bundle/focused-chunks/chunk-DOVTUKJQ.js +0 -2
  112. package/dist/cli-bundle/focused-chunks/chunk-GUIF3WVC.js +0 -30
  113. package/dist/cli-bundle/focused-chunks/chunk-RHIH6XIW.js +0 -12
  114. package/dist/cli-bundle/focused-chunks/chunk-XV5RV4ZT.js +0 -2
@@ -0,0 +1,80 @@
1
+ import{A as G,C as se,Ci as da,Dc as W,Di as pa,E as K,Ei as Ie,Fi as ma,Gi as ua,Hb as Kr,Hn as ka,I as me,Jb as Vr,Ld as jt,Mb as Ne,Mc as H,Md as ta,N as Nr,Nd as Sn,Od as En,Pd as $n,Pi as fa,Qf as Se,Rd as na,Sa as Fr,Sd as ra,Ta as Mr,U as Dr,Ua as U,Vd as aa,Vi as ha,X as Pt,Yi as Ft,Zi as Mt,ab as N,ae as ia,aj as De,bb as Gr,bd as ea,bi as In,ca as jr,cb as Ur,cd as st,cg as I,db as zr,dg as Z,dh as ca,di as la,eg as oa,ei as Be,ff as T,fg as V,fj as ga,gc as xn,gg as ae,gj as An,ha as wn,hc as Yr,ic as Nt,ig as sa,ih as B,ja as Lr,k as Rr,kc as ke,kg as ct,li as ce,ma as vn,mc as xe,mf as X,mg as Lt,na as h,pa as f,pc as Xr,pm as _a,qi as A,qm as je,rc as Dt,ri as Ee,rm as lt,sc as Zr,sm as wa,ta as Rt,tb as Jr,tc as Qr,tm as va,ua as bn,ub as qr,um as le,va as kn,vb as Wr,vm as He,wm as ba,wo as Gt,x as k,xm as ue,y as Ct,yb as Br,yi as $e,yl as ya,z as re,zb as Hr}from"./chunk-D4G43LBV.js";import{mkdir as ic,readFile as oc}from"node:fs/promises";import Ia from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0bd9a904-c076-5c2a-a9d8-42a543625e33")}catch{}})();var Tn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},sc="sdk-workspace-transaction",cc=/^[a-zA-Z0-9._-]+$/,lc=30,dc=3e3;function Aa(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!cc.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function xa(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 pc(e){return{pmRoot:xa(e.pmRoot,"Transaction pmRoot"),transactionId:Aa(e.transactionId,"Transaction id"),author:xa(e.author,"Transaction author")}}function Sa(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function Ta(e,t){return Ia.join(e,"transactions","sdk",`${t}.json`)}async function Ae(e,t){t.updatedAt=T();let n=Ta(e,t.transactionId);await ic(Ia.dirname(n),{recursive:!0}),await se(n,`${JSON.stringify(t,null,2)}
2
+ `)}function mc(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Le(e){return Object.assign(Object.create(null),e)}function uc(e,t){try{let n=JSON.stringify(e,(r,a)=>{if(typeof a=="number"&&!Number.isFinite(a))throw new TypeError(`${t} contains a non-finite number`);if(a===void 0||typeof a=="function"||typeof a=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return a});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function On(e,t){return e===void 0?void 0:uc(e,t)}function Cn(e,t,n,r){let a=On(n,r);a===void 0?delete e[t]:e[t]=a}function Ea(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $a(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function fc(e,t){if(!$a(e.startedStepIds,t)||!$a(e.completedStepIds,t)||!Ea(e.results)||!Ea(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),a=e.completedStepIds,i=new Set(a);return Object.keys(e.compensationData).some(o=>!r.has(o))||Object.keys(e.results).some(o=>!i.has(o))?!1:e.status==="committed"?t.every(o=>i.has(o)):e.status!=="compensated"||i.size===0&&r.size===0}function hc(e,t,n){let r;try{r=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let a=r,i=a.schemaVersion===1&&a.transactionId===t,o=Array.isArray(a.stepIds)&&a.stepIds.length===n.length&&a.stepIds.every((d,p)=>d===n[p]),s=fc(a,n),l=mc(a),c=["applying","compensating","compensated","committed"].includes(String(a.status));if(!i||!o||!s||!l||!c)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...a,results:Le(a.results),compensationData:Le(a.compensationData)}}async function gc(e,t,n,r,a){let i=a,o=i!==void 0;if(i?.status==="compensating"&&await Oa(e,i),i===void 0||i.status==="compensated"){let s=T();i={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(i?.attempt??0)+1,createdAt:i?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:Le(),compensationData:Le()},await Ae(e.pmRoot,i),await _e(e,i,"prepared")}return{journal:i,recovered:o}}async function yc(e,t,n){try{await wc(t,e.steps),await Ae(e.pmRoot,t);let r=new Set(t.completedStepIds),a=new Set(t.startedStepIds);for(let i of e.steps){if(r.has(i.id))continue;let o=await i.inspect(),s=On(o.result,`Step ${i.id} result`);if(o.state!=="applied"){let l=await i.prepareCompensation?.();Cn(t.compensationData,i.id,l,`Step ${i.id} compensation data`),a.add(i.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>a.has(d)),await Ae(e.pmRoot,t);let c=await i.apply();s=On(c,`Step ${i.id} result`)}await _e(e,t,"step_applied",i.id),r.add(i.id),t.completedStepIds=e.steps.map(l=>l.id).filter(l=>r.has(l)),Cn(t.results,i.id,s,`Step ${i.id} result`),await Ae(e.pmRoot,t),await _e(e,t,"step_recorded",i.id)}return await _e(e,t,"committing"),t.status="committed",await Ae(e.pmRoot,t),await _e(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Le(t.results)}}catch(r){if(r instanceof Tn||t.status==="committed")throw r;try{await Oa(e,t)}catch(a){throw new AggregateError([r,a],`Workspace transaction failed and compensation failed: ${String(a)}`,{cause:a})}throw r}}async function _c(e,t,n){try{return hc(await oc(Ta(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&re(r))return;throw r}}async function _e(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function wc(e,t){let n=new Set,r=Le();for(let a of t){let i=await a.inspect();i.state==="applied"&&(n.add(a.id),Cn(r,a.id,i.result,`Step ${a.id} result`))}e.results=r,e.completedStepIds=t.map(a=>a.id).filter(a=>n.has(a))}async function Oa(e,t){t.status="compensating",await Ae(e.pmRoot,t),await _e(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let a of[...e.steps].reverse()){if(!r.has(a.id)&&!n.has(a.id))continue;let i;try{i=r.has(a.id)&&(await a.inspect()).state==="applied"}catch{i=r.has(a.id)}i&&(await _e(e,t,"step_compensating",a.id),await a.compensate(t.compensationData[a.id])),n.delete(a.id),r.delete(a.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>r.has(o)),delete t.results[a.id],delete t.compensationData[a.id],await Ae(e.pmRoot,t),await _e(e,t,"step_compensated",a.id)}t.status="compensated",await Ae(e.pmRoot,t),await _e(e,t,"compensated")}async function Ca(e){let{pmRoot:t,transactionId:n,author:r}=pc(e),a=Sa(e.lockTtlSeconds,lc,"Transaction lock TTL"),i=Sa(e.lockWaitMs,dc,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(d=>{let p=Aa(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 l={...e,pmRoot:t,transactionId:n,author:r,steps:o,lockTtlSeconds:a,lockWaitMs:i},c=await X(t,sc,a,r,!1,!1,i);try{let d=await _c(t,n,s),p=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Le(d.results)};let m=await gc(l,n,r,s,d);return await yc(l,m.journal,p||m.recovered)}finally{await c()}}import vc from"node:fs/promises";import bc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function Pn(e){return bc.join(e,"extension-migrations.json")}function Pa(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 Ra(e,t){return`${e.layer}:${e.name}:${t}`}async function kc(e){let t=Pn(e);if(!await k(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await vc.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function xc(e,t){let n=await kc(e),r=new Map(n.entries.map(a=>[a.key,a]));return t.forEach((a,i)=>{let o=Pa(a,i),s=r.get(Ra(a,o));s&&(a.definition.status=s.status,s.status==="failed"?a.definition.reason=s.error:(delete a.definition.reason,delete a.definition.error,delete a.definition.message))}),n}async function Sc(e){let t=await xc(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),r=[],a=!1,i=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 i){let m=Pa(d,p),g=Ra(d,m),y=n.get(g),_=String(d.definition.status??"pending").toLowerCase(),u=y?.status??(_==="applied"||_==="failed"?_:"pending");if(u==="applied"){r.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"pending"});continue}let w=d.runtime_definition?.run??d.definition.run;if(typeof w!="function"){r.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:u}));let x={key:g,layer:d.layer,extension:d.name,id:m,status:"applied",attempted_at:v};n.set(g,x),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,r.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"applied"}),a=!0}catch(x){let S=x instanceof Error?x.message:String(x),O={key:g,layer:d.layer,extension:d.name,id:m,status:"failed",attempted_at:v,error:S};n.set(g,O),d.definition.status="failed",d.definition.reason=S,r.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"failed",error:S}),a=!0}}if(a){let d=await A(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,g)=>m.key.localeCompare(g.key))};await Be({pmRoot:e.pmRoot,filePath:Pn(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
3
+ `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let o=r.filter(d=>d.outcome==="pending").length,s=r.filter(d=>d.outcome==="applied").length,l=r.filter(d=>d.outcome==="skipped").length,c=r.filter(d=>d.outcome==="failed").length;return{ok:c===0,dry_run:e.dryRun===!0,state_path:Pn(e.pmRoot),total:r.length,pending_count:o,applied_count:s,skipped_count:l,failed_count:c,migrations:r}}async function Na(e){let t=await A(e.resolvedRoots.settings_root),n=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await xe(n);e.warnings.push(...n.warnings,...r.warnings);let a=await Sc({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:a,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},a.ok)}import{readFile as Ec,writeFile as $c}from"node:fs/promises";import dt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1de99e25-e132-5071-833e-37361b4cc7e6")}catch{}})();var ja="# pm-cli:runtime-cache:start",Rn="# pm-cli:runtime-cache:end",La=".agents/pm",Ic=["runtime/","search/","locks/","transactions/","checkpoints/"],Ac=["search/eval-queries.json"];async function Da(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 Fa(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function Nn(e){let t=e.replaceAll("\\","/");return dt.isAbsolute(e)||t===".."||t.startsWith("../")}function Tc(e=La){let t=Fa(e);return[ja,...Ic.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Ac.map(n=>`!${t}/${n}`),Rn].join(`
4
+ `)}async function Ma(e,t={}){let n=dt.join(e,".gitignore"),r=La;if(t.pmRoot!==void 0){let c=Fa(dt.relative(dt.resolve(e),dt.resolve(t.pmRoot)));if(Nn(c))return{path:n,changed:!1};c.length>0&&(r=c)}let a="";try{a=await Da(()=>Ec(n,"utf8"))}catch(c){if(!(c instanceof Error&&"code"in c&&re(c)))throw c}let i=a.indexOf(ja),o=a.indexOf(Rn),s=(i>=0&&o>=i?`${a.slice(0,i)}${a.slice(o+Rn.length)}`:a).trimEnd(),l=`${s.length>0?`${s}
5
+
6
+ `:""}${Tc(r)}
7
+ `;return l===a?{path:n,changed:!1}:(await Da(()=>$c(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]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var Oc=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Ke(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Dt(t.extensionName));for(let u of t.extensionNames??[])n.add(Dt(u));let r=u=>n.size===0||n.has(Dt(u)),a=(u,w)=>Ga(u.filter(v=>r(v.name)).map(w)),i=(u,w)=>Ga(u.filter(v=>r(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:l,preflight:c,services:d,renderers:p,hooks:m}=e,g=i(o.relationship_kinds??[],u=>u.definitions.map(w=>w.kind)),y=p.overrides.filter(u=>r(u.name)&&((u.commands?.length??0)>0||u.resultDiscriminator!==void 0)).map(u=>({format:u.format,commands:[...u.commands??[]],result_discriminator:u.resultDiscriminator!==void 0})).sort((u,w)=>u.format.localeCompare(w.format)),_=a(o.assurance_providers??[],u=>u.definition.id);return{capabilities:Zr(e,t),commands:a(o.commands,u=>u.command),command_overrides:a(s.overrides,u=>u.command),command_handlers:a(s.handlers,u=>u.command),hooks:Oc.filter(([u])=>m[u].some(w=>r(w.name))).map(([,u])=>u),flag_commands:a(o.flags,u=>u.target_command),item_types:i(o.item_types,u=>u.types.map(w=>w.name)),item_fields:i(o.item_fields,u=>u.fields.map(w=>w.name)),...g.length>0?{relationship_kinds:g}:{},migrations:i(o.migrations,u=>typeof u.definition.id=="string"?[u.definition.id]:[]),profiles:a(o.profiles,u=>u.profile.name),importers:a(o.importers,u=>u.importer),exporters:a(o.exporters,u=>u.exporter),search_providers:a(o.search_providers,u=>u.definition.name),vector_store_adapters:a(o.vector_store_adapters,u=>u.definition.name),..._.length>0?{assurance_providers:_}:{},parser_overrides:a(l.overrides,u=>u.command),service_overrides:a(d.overrides,u=>u.service),renderer_overrides:a(p.overrides,u=>u.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:c.overrides.filter(u=>r(u.name)).length,preflight_ownership:c.overrides.filter(u=>r(u.name)).map(u=>({commands:[...u.commands??[]]}))}}function Ga(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]="6d1f8e03-97b4-5d83-b85c-e47f39c07d48")}catch{}})();var Cc="PM_SOURCE_CONTEXT_ACCESS",Pc="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Ua(e){let t=e[Cc],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[Pc]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}import za from"node:fs";import zt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2d40ac36-0627-5636-9679-5669dbacf06b")}catch{}})();var pt="@unbrained/pm-cli",Rc=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]),Ja=new Set(["--author","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),Ln=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,qt="2026.8.31";function Y(e,t){return e.some(n=>t.includes(n.split("=",1)[0]))}function Dn(e,t){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(t[0]??"")||Y(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var Nc={changelog:(e,t)=>{if(t[0]==="generate")return!Y(e,["--check"]);let n=e.indexOf("export");return t[0]==="export"&&(Y(e,["--output"])||n>=0&&e[n+1]!==void 0&&!e[n+1].startsWith("-"))},comments:e=>Y(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>Y(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:Dn,files:(e,t)=>Y(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&Y(e,["--apply"]),health:e=>!Y(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>Y(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>Y(e,["--add","--delete","--edit","--file","--stdin"]),package:Dn,packages:Dn,profile:(e,t)=>t[0]==="apply",schema:(e,t)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(t[0]??"")&&!(Y(e,["--infer"])&&!Y(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(n=>["clear","flush"].includes(n)),templates:(e,t)=>t[0]==="save",test:e=>Y(e,["--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>Y(e,["--auto-fix","--prune-missing"]),vcs:(e,t)=>["abandon","create","merge","propose","ref-create"].includes(t[0]??""),workspace:(e,t)=>t[0]==="snapshot"&&["create","delete","restore"].includes(t[1]??"")};function Jt(e){let t=e.match(Ln);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function Fe(e,t){let n=Jt(e),r=Jt(t);if(!n||!r)return null;for(let a=0;a<n.length;a+=1){let i=n[a]-r[a];if(i!==0)return Math.sign(i)}return 0}function Ut(e){return Fe(e,qt)!==-1?3:2}function Dc(e,t){if(t===3)return e.filter(n=>n.history_epoch_compatible===!1).map(n=>({...n,declaration:n.declaration??n.version})).sort((n,r)=>Fe(n.version,r.version))[0]}function jn(e){try{let t=JSON.parse(za.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function jc(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(r=>({inclusive:r[1]==="<=",version:r[2]})),n=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...t,{inclusive:!0,version:n[1]}]:t}function Lc(e){let t=e.split("||").map(n=>jc(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(r=>{let a=Fe(qt,r.version);return a!==null&&(r.inclusive?a!==1:a===-1)}))}}function Fc(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let r=n[pt],a=typeof r=="string"?r.trim():"",i=/^[<!]/u.test(a)?void 0:a.match(Ln)?.[0];if(!i)return[];let o=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(a),s=Lc(a);return[{version:i,constraint:o?"exact":s.bounded?"range":"minimum",...o?{}:{declaration:a},history_epoch_compatible:o?Fe(i,qt)!==-1:s.compatible}]})}function Mc(e){let t=jn(zt.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let n=t["node_modules/@unbrained/pm-cli"];if(typeof n!="object"||n===null)return;let r=n.version;return typeof r=="string"?r:void 0}function Gc(e,t){try{let n=za.readFileSync(zt.join(e,t),"utf8").split(/\r?\n/u),r=n.findIndex(o=>o.includes(pt));if(r<0)return;let a=n[r].match(/^\s*/u)[0].length,i=[n[r]];for(let o=r+1;o<n.length;o+=1){let s=n[o],l=s.trim(),c=s.match(/^\s*/u)[0].length;if(l.length>0&&c<=a)break;i.push(s)}return i.join(`
8
+ `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match(Ln)?.[0]}catch{return}}function Fn(e){let t=[],n=jn(zt.join(e,"package.json"));n&&t.push(...Fc(n).map(i=>({...i,source:"package.json"})));let r=jn(zt.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof r=="string"&&Jt(r)&&t.push({version:r,source:"installed-package",constraint:"exact",history_epoch_compatible:Ut(r)===3});let a=Mc(e);a&&Jt(a)&&t.push({version:a,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Ut(a)===3});for(let i of["pnpm-lock.yaml","yarn.lock"]){let o=Gc(e,i);o&&t.push({version:o,source:i,constraint:"exact",history_epoch_compatible:Ut(o)===3})}return t}function qa(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Ja.has(n)){t+=1;continue}if(!n.startsWith("-"))return{command:n.toLowerCase(),index:t}}}function Uc(e){let t=qa(e);if(!t||Y(e,["--help","-h","--dry-run"]))return!1;let{command:n,index:r}=t,a=[];for(let o=r+1;o<e.length;o+=1){let s=e[o];if(Ja.has(s)){o+=1;continue}s.startsWith("-")||a.push(s.toLowerCase())}let i=Nc[n];return i?i(e,a):Rc.has(n)}function zc(e){let t=qa(e.argv)?.command,n=Uc(e.argv),r=Fn(e.projectRoot).filter(d=>Fe(d.version,e.executingVersion)!==null).sort((d,p)=>Fe(p.version,d.version)),a=r[0],i=a!==void 0&&Fe(e.executingVersion,a.version)===-1,o=Ut(e.executingVersion),s=Dc(r,o),l=n&&s!==void 0,c=i&&!n?{code:"project_runtime_stale_read",executing_version:e.executingVersion,project_version:a.version,source:a.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${pt} ${a.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!n||!i&&!l||e.allowStale===!0,executing_version:e.executingVersion,...a?{project_version:a.version,source:a.source}:{},...t?{command:t}:{},mutating:n,stale:i,history_epoch_incompatible:l,writer_item_hash_version:o,...s?{incompatible_project_version:s.declaration,incompatible_source:s.source}:{},...c?{warning:c}:{},override_applied:n&&(i||l)&&e.allowStale===!0}}function ah(e){let t=zc(e);if(t.compatible)return t;throw t.history_epoch_incompatible?new f(`pm ${t.executing_version} cannot write item-hash epoch ${t.writer_item_hash_version} into a project pinned to pm ${t.incompatible_project_version}.`,h.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:t.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${t.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${pt} pin to ${qt} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new f(`pm ${t.executing_version} cannot mutate a project pinned to newer pm ${t.project_version}.`,h.CONFLICT,{code:"project_runtime_stale_mutation",reason:t.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${pt} ${t.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}import{access as Bc,readFile as Gn,realpath as Te}from"node:fs/promises";import{constants as Hc}from"node:fs";import{execFile as Kc}from"node:child_process";import P from"node:path";import{promisify as Vc}from"node:util";import{execFile as Jc}from"node:child_process";import qc from"node:path";import{promisify as Wc}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]="ed89ee24-d57b-5964-a95b-742c4f4f28a8")}catch{}})();var Ve=Wc(Jc);function ie(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"])delete e[t];return e}async function Mn(e,t){try{return(await Ve("git",["config","--local",...t==="core.bare"||t==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",t],{cwd:e,env:ie(),timeout:1e4})).stdout.trim()}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code===1)return;throw n}}async function Wa(e){if(await Mn(e,"extensions.worktreeConfig")==="true")return"--worktree";let{stdout:t}=await Ve("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"],{cwd:e,env:ie(),timeout:1e4}),[n,r]=t.trim().split(/\r?\n/);if(n===r)return"--local";let a=qc.join(r,"config.worktree");for(let i of["core.bare","core.worktree"]){let o=await Mn(e,i);o===void 0||i==="core.bare"&&o!=="true"||(await Ve("git",["config","--file",a,i,o],{cwd:e,env:ie(),timeout:1e4}),await Ve("git",["config","--local","--unset-all",i],{cwd:e,env:ie(),timeout:1e4}))}for(let i of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(let o of["name","driver"]){let s=`merge.${i}.${o}`,l=await Mn(e,s);l!==void 0&&await Ve("git",["config","--file",a,s,l],{cwd:e,env:ie(),timeout:1e4})}return await Ve("git",["config","--local","extensions.worktreeConfig","true"],{cwd:e,env:ie(),timeout:1e4}),"--worktree"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5bcde7f0-1785-530a-91bb-80f2793fb8cf")}catch{}})();var Ye=Vc(Kc),Wt="# pm-cli:merge-drivers:start",Yc="# pm-cli:merge-drivers:end",mt="# pm-cli:merge-drivers:v2:start",Ka="# pm-cli:merge-drivers:v2:end",Xc="merge-fence",Zc="merge-attributes";function Ba(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function Qc(e,t){let n=await Te(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(n))return;let{stdout:r}=await Ye(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return r.trim()===t?n:void 0}async function el(){let e=me(import.meta.url,["../../.."]),t=process.execPath,n=!1,r=await Te(process.execPath),a=process.versions.bun,i=(process.env.PATH??"").split(P.delimiter).filter(s=>P.isAbsolute(s)).map(s=>P.join(s,a===void 0?P.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),o=a===void 0?i:[process.env.npm_execpath??"",...i,r].filter(s=>P.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(P.basename(s)));for(let s of o)try{if(await Bc(s,Hc.X_OK),a!==void 0){let l=await Qc(s,a);if(l!==void 0){t=l,n=!0;break}continue}if(s!==r&&await Te(s)===r){t=s;break}}catch{}if(a!==void 0&&!n)throw new f("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",h.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${Ba(t)} ${Ba(P.join(e,"dist","cli.js"))}`}var Va=[{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 tl(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),a=Ua(e.environment),i=!!(n&&r),o=t===void 0&&i&&(e.dryRun||a.source_writes_allowed);if(t!==void 0){let s=N(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:i,source_context_selected:!1,source_policy:a}}return o?{pm_root:P.resolve(r),workspace_start:P.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:a}:{pm_root:i?N(e.cwd,".agents/pm"):N(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:a}}async function Bt(e){try{let{stdout:t}=await Ye("git",["rev-parse","--show-toplevel"],{cwd:e,env:ie(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await Te(t.trim())}catch{return null}}async function Ya(e){let t=await Bt(e);if(t===null)throw new f("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function Un(e,t){return P.relative(e,t).replaceAll("\\","/")}function de(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Ha(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function nl(e,t,n){if(Fn(t).filter(a=>a.constraint==="exact").some(a=>a.version!==n))return!1;let r=await Bt(e);if(r!==null&&r!==await Te(t)){let a=await Promise.all([r,t].map(async i=>{let o=await Ye("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:i,env:ie(),timeout:1e4});return Te(o.stdout.trim())}));if(a[0]===a[1])return!1}return!0}async function rl(e,t,n){let r=Ha(e,0);if(r===null||e[r.nextOffset]!==" ")return!1;let a=Ha(e,r.nextOffset+1);if(a===null||e.slice(a.nextOffset)!==t||!/^(?:node|bun)(?:\.exe)?$/iu.test(P.basename(r.value))||P.basename(a.value)!=="cli.js"||P.basename(P.dirname(a.value))!=="dist"||!await k(r.value)||!await k(a.value))return!1;try{let i=P.dirname(P.dirname(a.value)),o=JSON.parse(await Gn(P.join(i,"package.json"),"utf8")),s=typeof o.bin=="string"?o.bin:o.bin?.pm;return await nl(i,n,o.version)?o.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function zn(e,t){let n=e.length>0?`${e}/`:"",r=[`${de(`${n}**/*.toon`)} merge=pm-item-toon`,`${de(`${n}**/*.md`)} merge=pm-item-markdown`];for(let a of t)r.push(`${de(`${n}${a}/*.toon`)} merge=pm-item-toon`),r.push(`${de(`${n}${a}/*.md`)} merge=pm-item-markdown`);return r.push(`${de(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${de(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${de(`${n}settings.json`)} merge=pm-json`),r.push(`${de(`${n}**/*.json`)} merge=pm-json`),r.push(`${de(`${n}extensions/**`)} -merge`),r.push(`${de(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function Xa(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(Wt,n),a=e.indexOf(mt,n),i=r===-1?a:a===-1?r:Math.min(r,a);if(i===-1)break;let o=i===a,s=o?mt:Wt,l=o?Ka:Yc,c=e.indexOf(l,i+s.length),d=c===-1?e.length:c+l.length;t.push({start:i,end:d,closed:c!==-1,lines:e.slice(i+s.length,c===-1?d:c).split(`
9
+ `).map(p=>p.trim()).filter(Boolean)}),n=d}return t}function Za(e,t,n){let r=new Set(t),a=de(n.length>0?`${n}/`:"").slice(0,-1);return e.some(i=>r.has(i)||i.startsWith(a)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(i.slice(a.length)))}async function Qa(e,t,n,r){let a=P.join(e,".gitattributes"),i=r?null:(await Ye("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:ie(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),o=i===null?null:await X(i,Zc,120,"merge-fence",!1,!0,5e3);try{let s=await G(a)??"",l=[mt,...n,Ka].join(`
10
+ `),c=Xa(s),d=c.filter(m=>Za(m.lines,n,t));d.length===0&&t===".agents/pm"&&c.length===1&&c[0].lines.every(m=>!m.includes(".agents/pm/"))&&d.push(c[0]);let p;if(d.length>0){let m=d[0];p=s;for(let g of d.slice(1).reverse())p=`${p.slice(0,g.start)}${p.slice(g.end)}`;p=`${p.slice(0,m.start)}${l}${p.slice(m.end)}`}else{let m=s.trimEnd();p=`${m.length>0?`${m}
11
+
12
+ `:""}${l}
13
+ `}return p===s?{path:a,changed:!1}:(r||await se(a,p),{path:a,changed:!0})}finally{await o?.()}}function ei(e){let t=U(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function Ch(e,t){let n=P.resolve(e),r=null,a="",i=n;for(let u=0;u<8;u+=1){let w=P.join(i,".gitattributes");try{let x=await Gn(w,"utf8");if(x.includes(mt)||x.includes(Wt)){r=i,a=x;break}}catch{}let v=P.dirname(i);if(v===i)break;i=v}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=P.join(r,".gitattributes"),s=Un(r,n),l=Xa(a),c=zn(s,t),d=l.filter(u=>Za(u.lines,c,s)),p=d.flatMap(u=>u.closed?u.lines:[]),m=new Set(p),g=new Set(c),y=c.filter(u=>!m.has(u)),_=p.filter(u=>!g.has(u));return{status:d.length!==1||!d[0].closed||y.length>0||_.length>0?"drift":"ok",path:o,missing_patterns:y,stale_patterns:_,schema_scope:"project"}}async function Ph(e){let t=[],n=[];for(let r of Va){let a=`merge.${r.key}.driver`,i=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`;try{let{stdout:o}=await Ye("git",["config","--get",a],{cwd:e,env:ie(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=o.trim();await rl(s,i,e)||n.push(a)}catch{t.push(a)}}return{status:t.length>0?"missing":n.length>0?"drift":"ok",missing_keys:t,drifted_keys:n}}async function ti(e){let t;try{t=await Ya(P.resolve(e))}catch{return{status:"no_git"}}let n=Un(t,P.resolve(e)),r=await A(e),a=B(void 0,r.author_default),i=await X(e,Xc,r.locks.ttl_seconds,a,!1,ce(r).force_required_for_stale_lock,r.locks.wait_ms);try{let o=P.join(t,".gitattributes"),s;try{s=await Gn(o,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&re(p))return{status:"not_installed",path:o};throw p}if(!s.includes(mt)&&!s.includes(Wt))return{status:"not_installed",path:o};let l=await A(e),c=ei(l),d=await Qa(t,n,zn(n,c),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await i()}}async function Rh(e,t){let n=tl({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await Se(r);let a=await Ya(n.workspace_start);return Jn({pmRoot:r,workspaceRoot:a,dryRun:e.dryRun===!0})}async function Jn(e){let t=P.resolve(e.pmRoot),n=P.resolve(e.workspaceRoot),r=e.dryRun===!0,a,i;try{[a,i]=await Promise.all([Te(t),Te(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 o=Un(i,a);if(Nn(o))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(a),l=ei(s),c=zn(o,l),d=[],p=await el();for(let g of Va)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(!r)try{let g=await Wa(i);for(let y of d)await Ye("git",["config",g,y.key,y.value],{cwd:i,env:ie(),encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new f(`Cannot install repository-local merge drivers in ${i}. 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 m=await Qa(i,o,c,r);return{ok:!0,dry_run:r,workspace_root:i,pm_root:a,gitattributes:{path:m.path,changed:m.changed,patterns:c,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]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var ut={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Ht={type:"array",minItems:1,maxItems:Sn,items:ut},ni={...Ht,items:{...ut,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},al={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,Ht])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:ut,id:ut}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:ni}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Ht}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:ni,authors:Ht}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Sn,items:{type:"array",minItems:2,maxItems:2,items:ut}}}}]}}},jh={$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:ta,items:al}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function Gh(e,t,n,r){let a=await Ie(e).catch(()=>null);return a===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"]}:ri(a,t,n,r)}function il(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function ri(e,t,n=5,r=!1){let a=[],i=new Map,o=e.policies.filter(u=>u.rule.kind==="require_fields"),s=o.filter(u=>u.subject?.operations===void 0),l=new Set,c=0,d=0,p=0,m=0,g=0,y=aa(e);for(let u of t){let w=y({operation:"",author:"",before:u,after:u,completeness_only:!0});c+=+(w.decisions.length>0),d+=w.decisions.length,w.decisions.forEach(S=>l.add(S.policy_id));let v=w.decisions.filter(S=>!S.satisfied);if(v.length===0)continue;m+=1;let x=i.get(u.type)??{items:0,violations:0,missing_fields:0};x.items+=1;for(let S of v)p+=1,x.violations+=1,x.missing_fields+=S.missing_fields.length,S.effect==="refuse"&&(g+=1),a.length<n&&a.push({id:u.id,type:u.type,status:u.status,decision:S});i.set(u.type,x)}let _=r||g>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:_,ok:_==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:l.size,requirement_application_count:d,governed_items:c,ungoverned_items:t.length-c,contract_status:il(o.length,t.length,c),applied_policy_ids:[...l].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:l.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:p,refused_violations:g,missing_by_type:Object.fromEntries(i),violations:a,violations_truncated:a.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}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]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function sl(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function oi(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 cl(e,t){let n=N(process.cwd(),e.path);await Se(n);let r=await A(n);return{pmRoot:n,settings:r,author:B(t,r.author_default)}}function ai(e,t,n,r){if(e==="policy-mode")return $n({...n,enforcement:t});let a=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:a};let i=En(r.definition),o=$n({...n,policies:[...a,i].sort((s,l)=>s.id.localeCompare(l.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
14
+ `)>da)throw new f("Policy registry exceeds its byte ceiling.",h.USAGE);return o}async function ii(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:ai(e,t,await Ie(r.pmRoot),n)};let a=await la({pmRoot:r.pmRoot,filePath:ol.join(r.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:r.author,message:n.message,lockTtlSeconds:r.settings.locks.ttl_seconds,lockWaitMs:r.settings.locks.wait_ms,mutate(i){let o=ai(e,t,pa(i),n);return{raw:`${JSON.stringify(o,null,2)}
15
+ `,result:o}}});return{policy_result:!0,action:e,changed:a.changed,result:a.result}}async function ll(e,t,n){let r,a=await ga({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(i){let o=(await Ie(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!o||o.rule.kind!=="approval")throw new f("--policy must name an approval rule.",h.USAGE);if(!o.rule.authors.includes(n.author))throw new f("This actor is not a declared approver.",h.CONFLICT);return await ma(n.pmRoot,i.metadata.id),r={policy_id:o.id,policy_fingerprint:na(o),content_fingerprint:ra(o,{...i.metadata,body:i.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:a.item.id,...r,warnings:a.warnings}}}function dl(e,t){let n=oi(t),r=En({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==r.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 r}async function rg(e,t,n={},r={}){if(!jt.includes(e))throw new f("Unknown workflow policy action.",h.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:sl()};let a=await cl(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Ie(a.pmRoot)};if(e==="policy-put"){let d=dl(t,n.definition);return ii(e,d.id,{...n,definition:d},a)}if(!t?.trim())throw new f(`schema ${e} requires an operand.`,h.USAGE);if(["policy-remove","policy-mode"].includes(e))return ii(e,t,n,a);if(e==="policy-approve"){if(n.dryRun)throw new f("Use policy-check to preview; policy-approve records an approval.",h.USAGE);return ll(t,n,a)}let i=U(a.settings,W()),o=await Ft(a.pmRoot,t,a.settings.id_prefix,a.settings.item_format,i.type_to_folder);if(!o)throw new f(`Item ${t} not found.`,h.NOT_FOUND);let{document:s}=await Mt(o,{schema:a.settings.schema}),l={...s.metadata,body:s.body},c=n.definition===void 0?l:{...l,...oi(n.definition)};if(c.id!==l.id)throw new f("Policy preview cannot change the item id.",h.USAGE);return{policy_result:!0,action:e,changed:!1,result:await ua(a.pmRoot,await Ie(a.pmRoot),{operation:"update",author:a.author,before:l,after:c,completeness_only:n.definition===void 0})}}import{createHash as vi}from"node:crypto";import Ge from"node:fs/promises";import nt 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]="68be16cc-4cb4-5df6-90f0-897d4fe82339")}catch{}})();var pl=new Set(bn),ml=new Set(kn),si=new Set([...jr.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"]),ul=["create","update"];function pi(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function ci(e){return e.replaceAll("_","-")}function fl(e,t){let n=new Set;for(let r of e){let a=pi(r);a.length>0&&a!==t&&n.add(a)}return[...n].sort((r,a)=>r.localeCompare(a))}function hl(e){let t=new Set;for(let n of e??[]){let r=n.trim();r.length>0&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function gl(e){let t=new Set,n=[];for(let r of e??[]){let a=r.trim().toLowerCase();if(a.length!==0){if(!ml.has(a))throw new Error(`Invalid field command "${r}". Allowed: ${kn.join(", ")}.`);t.has(a)||(t.add(a),n.push(a))}}return e===void 0||n.length===0?[...ul]:n}function mi(e){let t=I(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(si.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: ${[...si].sort((d,p)=>d.localeCompare(p)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!pl.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${bn.join(", ")}.`);let r=n,a=gl(e.commands),i=pi(e.cliFlag),o=i.length>0&&i!==ci(t)?i:void 0,s=o??ci(t),l=fl(e.aliases??[],s),c=e.description?.trim();return{key:t,type:r,commands:a,description:c&&c.length>0?c:void 0,cliFlag:o,cliAliases:l,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:hl(e.requiredTypes)}}function yl(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 _l(e){let t=yl(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let a=r;typeof a.key!="string"||a.key.trim().length===0||n.push(a)}return n}function Xe(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:_l(t)}}function Ze(e){return`${JSON.stringify({fields:e.fields},null,2)}
16
+ `}function ui(e,t){let n=e.fields.find(o=>I(o.key)===t.key),r=n!==void 0,a=e.fields.filter(o=>I(o.key)!==t.key),i={...n,key:t.key,type:t.type,commands:[...t.commands]};return li(i,"description",t.description),li(i,"cli_flag",t.cliFlag),t.cliAliases.length>0?i.cli_aliases=[...t.cliAliases]:delete i.cli_aliases,di(i,"required",t.required),di(i,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?i.allow_unset=!1:delete i.allow_unset,t.requiredTypes.length>0?i.required_types=[...t.requiredTypes]:delete i.required_types,a.push(i),a.sort((o,s)=>I(o.key).localeCompare(I(s.key))),{file:{fields:a},definition:i,replaced:r}}function fi(e,t){let n=I(t);if(n.length===0)throw new Error("Field key must not be empty.");let r=[],a=e.fields.filter(i=>I(i.key)===n?(r.push(i),!1):!0);return r.length===0?{file:{fields:a},removed:!1}:{file:{fields:a},removed:!0,definition:r[0]}}function li(e,t,n){let r=e;n!==void 0&&n.length>0?r[t]=n:delete r[t]}function di(e,t,n){let r=e;n?r[t]=!0:delete r[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]="b1e4c04e-0ade-5d24-95e3-b8dca3832c5a")}catch{}})();var wl=new Set(Rt),Me=new Set(oa.map(e=>I(e.id)).filter(e=>e.length>0));function vl(e){let t=new Set;for(let n of e){let r=I(n);r.length>0&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function hi(e){let t=I(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(Me.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...Me].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let o=new Set;for(let s of e.roles){let l=typeof s=="string"?s.trim().toLowerCase():"";if(l.length!==0){if(!wl.has(l))throw new Error(`Invalid status role "${s}". Allowed roles: ${Rt.join(", ")}.`);o.has(l)||(o.add(l),n.push(l))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${Rt.join(", ")}.`)}let r=e.aliases===void 0?void 0:vl(e.aliases).filter(o=>o!==t),a=e.description?.trim(),i=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:r,description:a&&a.length>0?a:void 0,order:i}}function bl(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 kl(e){let t=bl(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let a=r;typeof a.id!="string"||a.id.trim().length===0||n.push(a)}return n}function Qe(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:kl(t)}}function et(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
17
+ `}function gi(e,t,n){let r=e.statuses.slice(),a=r.findIndex(s=>I(s.id)===t.id),i=a>=0?r[a]:n,o={...i,id:t.id};return t.roles!==void 0&&(t.roles.length>0?o.roles=[...t.roles]:o.roles!==void 0&&delete o.roles),t.aliases!==void 0&&(t.aliases.length>0?o.aliases=[...t.aliases]:o.aliases!==void 0&&delete o.aliases),t.description!==void 0&&(o.description=t.description),t.order!==void 0&&(o.order=t.order),a>=0?r[a]=o:r.push(o),{file:{statuses:r},definition:o,replaced:i!==void 0}}function yi(e,t){let n=I(t);if(n.length===0)throw new Error("Status id must not be empty.");if(Me.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...Me].join(", ")}.`);let r=e.statuses.slice(),a=r.findIndex(o=>I(o.id)===n);if(a<0)return{file:{statuses:r},removed:!1};let[i]=r.splice(a,1);return{file:{statuses:r},removed:!0,definition:i}}function qn(e,t){let n=[e.id,...e.aliases??[]];for(let r of n){let a=I(r);if(a.length===0)continue;let i=t.get(a);if(i!==void 0&&i!==e.id)throw new Error(`Status token "${a}" already belongs to status "${i}". 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]="8d04c087-62e4-51d3-8832-6cbcfd3ed993")}catch{}})();function we(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function bi(e){let t=we(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function ki(e,t){let n=Bn(e),r=we(t,"migrationScope");return`auto-${vi("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function Bn(e){let t=e.kind==="rename-type"?{kind:e.kind,from:we(e.from,"source"),to:we(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:I(we(e.from,"source")),to:I(we(e.to,"target")),...e.type===void 0?{}:{type:we(e.type,"type")}}:{kind:e.kind,from:I(we(e.from,"source")),to:I(we(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function xl(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Sl(e,t,n){let r=V(t.schema),a=xl(n);return ae(e,r.files[a],Z[a])}function xi(e,t){return nt.join(e,"transactions","schema",`${t}-plan.json`)}function Kt(e){return e.length===0?null:JSON.parse(e)}async function tt(e){let t=await G(e);return{exists:t!==null,raw:t??""}}async function Si(e,t){t.exists?await se(e,t.raw):await Ge.rm(e,{force:!0})}function El(e,t,n){let r=le(e),a=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),i=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(i>=0)return ue(r);if(a<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[a],name:t.to})}else a>=0&&r.definitions.splice(a,1);return ue(r)}function $l(e,t,n){let r=Xe(e),a=r.fields.findIndex(o=>o.key===t.from),i=r.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(i>=0)return Ze(r);if(a<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=r.fields[a];r.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else a>=0&&r.fields.splice(a,1);return Ze(r)}function Il(e,t,n){let r=Qe(e),a=r.statuses.findIndex(o=>o.id===t.from),i=r.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(i>=0)return et(r);if(a<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[a],id:t.to})}else a>=0&&r.statuses.splice(a,1);return et(r)}function Al(e,t,n){return t.kind==="rename-type"?El(e,t,n):t.kind==="rename-field"?$l(e,t,n):Il(e,t,n)}function Oe(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Hn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function rt(e){return Array.isArray(e)?e.map(t=>Hn(t)).filter(t=>t!==void 0):[]}function Tl(e,t){for(let n of rt(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>Oe(r,t)));for(let n of rt(e.type_workflows))n.type=Oe(n.type,t)}function Ol(e,t){for(let r of rt(e.definitions))r.default_status=Oe(r.default_status,t);let n=Hn(e.workflow);if(n)for(let[r,a]of Object.entries(n))n[r]=Oe(a,t);for(let r of rt(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(a=>Array.isArray(a)?a.map(i=>Oe(i,t)):a))}function Cl(e,t){for(let n of rt(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(a=>Oe(a,t)));for(let r of["options","command_option_policies"])for(let a of rt(n[r])){let i=r==="options"?"key":"option";a[i]=Oe(a[i],t)}}}function Pl(e,t){let n=Hn(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=Oe(n[r],t)}function Wn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?Tl(r,t):t.kind==="rename-field"?Cl(r,t):Ol(r,t),Pl(r,t),`${JSON.stringify(r,null,2)}
18
+ `}function Ei(e,t){if(t.kind==="rename-type"){let r=le(e).definitions;return{source:r.some(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(a=>a.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=Xe(e).fields;return{source:r.some(a=>a.key===t.from),target:r.some(a=>a.key===t.to)}}let n=Qe(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function Rl(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 Nl(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 $i(e,t){let n=Bn(t.request),r=t.migrationId===void 0?ki(n,t.migrationScope??"plan"):bi(t.migrationId),a=e.map(l=>Nl(l,n)).filter(l=>l!==null).sort((l,c)=>l.id.localeCompare(c.id)),i=vi("sha256").update(JSON.stringify({migrationId:r,request:n,items:a})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(l=>l.trim()).filter(l=>l.length>0)),s=a.filter(l=>!o.has(l.id));return Object.freeze({migration_id:r,request:n,fingerprint:i,affected_item_count:a.length,pending_item_count:s.length,skipped_completed_count:a.length-s.length,items:Object.freeze(s)})}async function Dl(e){let t=U(e.settings,W()),n=[...new Set(Object.values(t.type_to_folder))],r=await ha(e.pmRoot,n),a=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]}},i=r?await fa({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:a}):null;return i?{items:i.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await De(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function jl(e,t){let n=await G(xi(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new f(`Stored schema migration plan "${t}" is invalid: ${Nr(r)}`,h.GENERIC_FAILURE)}}async function Ll(e,t){let n=xi(e,t.migration_id);await Ge.mkdir(nt.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await se(n,`${JSON.stringify(r,null,2)}
19
+ `)}function Fl(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Ml(e){let t=await Ft(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 Mt(t,{schema:e.settings.schema})).document.metadata}function _i(e,t,n){let r=n==="forward"?t.from:t.to,a=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===a.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=a,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===a.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=a,["status"]}let i=e.metadata;if(Object.prototype.hasOwnProperty.call(i,a)&&!Object.prototype.hasOwnProperty.call(i,r))return[];if(!Object.prototype.hasOwnProperty.call(i,r)||Object.prototype.hasOwnProperty.call(i,a))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return i[a]=i[r],delete i[r],[r,a]}function wi(e){return{id:e.id,inspect:async()=>{let t=await tt(e.filePath),n=Ei(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await tt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await tt(e.filePath);return await se(e.filePath,Al(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 Si(e.filePath,{exists:t.exists,raw:t.raw})}}}function Gl(e){return{id:e.stepId,inspect:async()=>{let t=await tt(e.filePath);return{state:Wn(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await tt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await tt(e.filePath);return await se(e.filePath,Wn(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 Si(e.filePath,{exists:t.exists,raw:t.raw})}}}function Ul(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await A(e.pmRoot),n=U(t,W()).type_to_folder,r=await Ml({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),a=Rl(r,e.request).length===0;return{state:a?"applied":"pending",...a?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await A(e.pmRoot),n=U(t,W()).type_to_folder,r=await An({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(a){return{changedFields:_i(a,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await A(e.pmRoot),n=U(t,W()).type_to_folder;await An({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:_i(r,e.request,"reverse")}}})}}}async function zl(e){let t=await jl(e.pmRoot,e.migrationId);if(t){if(!Fl(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 Dl({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...$i(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Jl(e){let t=Ei(await G(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 Ll(e.pmRoot,e.plan)}async function ql(e){let t=V(e.settings.schema),n=[...new Set([["types",Z.types],["fields",Z.fields],["workflows",Z.workflows]].map(([a,i])=>ae(e.pmRoot,t.files[a],i)).filter(a=>a!==e.schemaPath))];try{let a=nt.join(e.pmRoot,"templates"),i=await Ge.readdir(a,{withFileTypes:!0});n.push(...i.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>nt.join(a,o.name)))}catch(a){if(typeof a!="object"||a===null||!("code"in a)||!re(a))throw a}n.sort((a,i)=>a.localeCompare(i));let r=[];for(let a of n){let i=await G(a);i!==null&&Wn(i,e.request)!==i&&r.push({filePath:a,beforeRaw:i})}return{paths:n,snapshots:r}}async function Wl(e){for(let t of e.snapshots){let n=await Ge.readFile(t.filePath,"utf8"),r=nt.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await In({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Kt(t.beforeRaw),after:Kt(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function Bl(e,t,n){let r=Bn(e),a=N(process.cwd(),n.path);await Se(a);let i=t.migrationId===void 0?ki(r,await Ge.realpath(a)):bi(t.migrationId),o=await A(a),s=B(t.author,o.author_default),l=await zl({pmRoot:a,settings:o,migrationId:i,request:r}),c=l.plan;if(t.dryRun===!0)return{...c,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=Sl(a,o,r),p=await Ge.readFile(d,"utf8");l.stored||await Jl({pmRoot:a,schemaPath:d,request:r,plan:c});let m=await ql({pmRoot:a,schemaPath:d,settings:o,request:r}),g=[wi({id:"stage-schema",filePath:d,request:r,phase:"stage"}),...m.paths.map((w,v)=>Gl({filePath:w,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...c.items.map(w=>Ul({pmRoot:a,id:w.id,request:r,author:s,force:t.force===!0})),wi({id:"retire-source",filePath:d,request:r,phase:"retire"})],y=await Ca({pmRoot:a,transactionId:`schema-${i}`,author:s,steps:g,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),_=await Ge.readFile(d,"utf8"),{historyPath:u}=await In({pmRoot:a,author:s,documentPath:nt.relative(a,d).replaceAll("\\","/"),before:Kt(p),after:Kt(_),op:"schema_migration",idempotencyKey:`${c.migration_id}:${c.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${c.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await Wl({pmRoot:a,author:s,settings:o,request:r,plan:c,snapshots:m.snapshots}),{...c,action:r.kind,applied:!0,recovered:y.recovered,migrated_item_count:c.affected_item_count,workspace_history_path:u}}function Hl(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(`
20
+ `)}import Ti from"node:fs/promises";import Ue 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]="74b72dd8-0877-55a4-9c80-d043f19e1f96")}catch{}})();var Vt=["extensions","docs","examples","assets","prompts"],Kl=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 Vl(e){return Vt.includes(e)}function Yl(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],r=[];for(let a of n){if(typeof a!="string"||a.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);r.push(a.trim())}return[...new Set(r)].sort((a,i)=>a.localeCompare(i))}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[r,a]of Object.entries(n)){if(!Vl(r))continue;let i=Yl(r,a);i.length>0&&(t[r]=i)}return t}function fe(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function Kn(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,r)=>n.localeCompare(r)):void 0}function Ii(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 Zl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:fe(t,"docs"),npm:fe(t,"npm"),repository:fe(t,"repository"),report:fe(t,"report")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function Ql(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:fe(t,"image"),video:fe(t,"video")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function ed(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:fe(t,"display_name")??fe(t,"displayName"),category:fe(t,"category"),summary:fe(t,"summary"),links:Zl(t.links),media:Ql(t.media),tags:Kn(t.tags)};return Object.values(n).some(r=>r!==void 0)?n:void 0}async function ft(e){let t=Ue.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await Ti.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 r=n,a=r.pm,i=a!=null,o=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{};return{source:i?"pm":"convention",package_json_path:t,package_name:typeof r.name=="string"?r.name:void 0,package_version:typeof r.version=="string"?r.version:void 0,package_private:r.private===!0,package_description:typeof r.description=="string"?r.description:void 0,package_keywords:Kn(r.keywords),package_homepage:typeof r.homepage=="string"?r.homepage:void 0,package_repository_url:Ii(r.repository),package_bugs_url:Ii(r.bugs),aliases:Kn(o.aliases),resources:Xl(a),catalog:ed(o.catalog)}}async function Ai(e){if(!await k(e))return[];let t=await Ti.readdir(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let a=Ue.join(e,r.name);await k(Ue.join(a,"manifest.json"))&&n.push(a)}return n.sort((r,a)=>r.localeCompare(a))}async function Yt(e){if(await k(Ue.join(e,"manifest.json")))return[e];let t=(await ft(e)).resources.extensions??[],n=new Set;for(let r of t){if(r.includes("*")||r.startsWith("!"))throw new f(`Package extension entry "${r}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let a=Ue.resolve(e,r);if(!K(e,a))throw new f(`Package extension entry "${r}" resolves outside package root.`,h.USAGE);if(await k(Ue.join(a,"manifest.json"))){n.add(a);continue}for(let i of await Ai(a))n.add(i)}if(t.length===0)for(let r of Kl.extensions)for(let a of await Ai(Ue.join(e,r)))n.add(a);return[...n].sort((r,a)=>r.localeCompare(a))}import{execFile as bd}from"node:child_process";import R from"node:fs/promises";import rr from"node:os";import $ from"node:path";import{fileURLToPath as kd}from"node:url";import{promisify as xd}from"node:util";import Sd from"npm-package-arg";import{extract as Ed,list as $d}from"tar";import pd from"node:fs/promises";import pe from"node:path";import Oi from"node:fs/promises";import Vn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cf1403b0-7b07-5f00-9523-87bc727dd7fa")}catch{}})();function te(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 Xt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let a=t.slice(n,r);if(a.length===0)throw new f("Extension manifest name must resolve to a non-empty directory name.",h.USAGE);if(a==="."||a==="..")throw new f('Extension manifest name must not resolve to "." or "..".',h.USAGE);return a}function Yn(e){return Kr(e)}async function td(e){try{let t=JSON.parse(await Oi.readFile(Vn.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(r=>typeof t.scripts?.[r]=="string")}}catch{return{has_build_script:!1}}}async function nd(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 r=await td(n.source_root),a=r.package_name?`pm install npm:${r.package_name}`:void 0,i=n.source_input??n.source_root;return new f(`Extension entry "${e.entry}" is absent from GitHub source "${i}". pm install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${a?`Try "${a}" 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:a?[a,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:a?[`Retry with ${a}.`,"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 ${i}`,normalized_args:["install",i],...a?{next_best_command:a}:{}}})}async function at(e,t={}){let n=Vn.join(e,"manifest.json");if(!await k(n))throw new f(`Extension manifest is missing at "${n}".`,h.USAGE);let r;try{r=JSON.parse(await Oi.readFile(n,"utf8"))}catch(o){throw new f(`Failed to parse extension manifest at "${n}": ${rd(o)}`,h.USAGE)}let a=Yn(r);if(!a)throw new f(`Extension manifest at "${n}" is invalid.`,h.USAGE);let i=Vn.resolve(e,a.entry);if(!K(e,i))throw new f(`Extension entry "${a.entry}" resolves outside extension directory "${e}".`,h.USAGE);if(!await k(i))throw await nd(a,i,t);if(!await Yr(e,i))throw new f(`Extension entry "${a.entry}" resolves outside extension directory after symlink resolution.`,h.USAGE);return{directory:e,manifest_path:n,entry_path:i,manifest:a}}function rd(e){return e instanceof Error?e.message:String(e)}import Xn from"node:fs/promises";import ad from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5181479f-469f-525b-add2-914a9934afbd")}catch{}})();var id=".managed-extensions.json",Zt=1;function ht(e){return ad.join(e,id)}function od(){return{version:Zt,updated_at:T(),entries:[]}}function gt(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let a=t.name.localeCompare(n.name);return a!==0?a:t.directory.localeCompare(n.directory)})}function Ci(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 Q(e){return typeof e=="string"?e:void 0}function sd(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 cd(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:Q(t.name),package:Q(t.package),version:Q(t.version),repository:Q(t.repository),owner:Q(t.owner),repo:Q(t.repo),ref:Q(t.ref),subpath:Q(t.subpath),commit:Q(t.commit)}}function ld(e){if(typeof e!="object"||e===null)return null;let t=e;if(!sd(t))return null;let n=cd(t.source);if(!n)return null;let r=Jr(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:te(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Q(t.last_update_check_at),last_update_remote_commit:Q(t.last_update_remote_commit),last_update_remote_version:Q(t.last_update_remote_version),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Q(t.update_error)}}function dd(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 r of t.entries){let a=ld(r);a&&n.push(a)}return{version:Zt,updated_at:Q(t.updated_at)??T(),entries:gt(n)}}async function he(e){let t=ht(e),n=od();try{let r=await Xn.readFile(t,"utf8"),a=JSON.parse(r),i=dd(a);if(!i)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:i,warnings:[]}}catch(r){if(r instanceof f)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&re(r))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 it(e,t){let n=ht(e),r={version:Zt,updated_at:T(),entries:gt(t.entries)};await Xn.mkdir(e,{recursive:!0}),await Xn.writeFile(n,`${JSON.stringify(r,null,2)}
21
+ `,"utf8")}function yt(e,t){let n=e.entries.filter(r=>b(r.name)!==b(t.name)&&b(r.directory)!==b(t.directory));return n.push(t),{...e,updated_at:T(),entries:gt(n)}}async function Pi(e,t,n,r){let a=t.entries.find(o=>b(o.name)===b(n));if(!a)return t;let i=yt(t,{...a,contributions:r});return await it(e,i),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var md="PM_CLI_PACKAGE_ROOT",Ri={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},ud=new Set(["*","all"]);function Zn(){let e=[],t=process.env[md];return typeof t=="string"&&t.trim().length>0&&e.push(pe.resolve(t.trim())),e.push(me(import.meta.url,["../../.."])),[...new Set(e)]}async function _t(e){let t=e.trim().toLowerCase(),n=await Di(t);if(n)return n;let r=Ri[t];if(!r)return null;for(let a of Zn()){let i=pe.join(a,".agents","pm","extensions",r.legacy_extension_directory);if(await k(pe.join(i,"manifest.json")))return i}return null}function Ni(e){return ud.has(e.trim().toLowerCase())}function fd(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function hd(e,t){let n=await pd.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let a=pe.join(e,r.name);if(!await k(pe.join(a,"package.json")))continue;let i=await ft(a),o=i.aliases&&i.aliases.length>0?i.aliases:[fd(r.name)];for(let s of o){let l=s.trim().toLowerCase();l.length===0||t.has(l)||t.set(l,{alias:l,package_directory:r.name,package_root:a,package_name:i.package_name??null})}}}async function Qn(){let e=new Map;for(let t of Zn()){let n=pe.join(t,"packages");await k(n)&&await hd(n,e)}for(let[t,n]of Object.entries(Ri))if(!e.has(t))for(let r of Zn()){let a=pe.join(r,"packages",n.package_directory);if(await k(pe.join(a,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:a,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Qt(){return(await Qn()).map(e=>e.alias)}async function Di(e){let t=e.trim().toLowerCase();return(await Qn()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function ji(e){let t=await Di(e);return t?(await ft(t)).package_name??null:null}async function Li(e){let t=await _t(e);if(!t)return null;try{let n=await Yt(t);return n.length!==1?null:(await at(n[0])).manifest.name}catch{return null}}function gd(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 yd(e,t,n,r,a,i){let o=r==="global"?"--global":"--project",s=Object.fromEntries(Vt.filter(l=>l!=="extensions").map(l=>[l,e.resources[l]??[]]).filter(([,l])=>Array.isArray(l)&&l.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(l=>a.has(l))||i.has(pe.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:gd(e),media:e.catalog?.media}}}async function Fi(e,t,n={}){let r=Nt(N(process.cwd(),t.path),process.cwd()),a=e==="global"?r.global:r.project,i=await he(a),o=new Set(i.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>pe.resolve(m.source.location))),s=new Set(i.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),l=[],c=new Map;for(let m of await Qn()){let g=pe.resolve(m.package_root),y=c.get(g)??[];y.push(m),c.set(g,y)}for(let m of c.values()){let g=m[0],y=m.map(u=>u.alias).sort((u,w)=>u.localeCompare(w)),_=await ft(g.package_root);l.push(yd(_,g,y,e,s,o))}let d=wd(n.fields),p=d?l.map(m=>vd(m,d)):l;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Vt.filter(m=>m!=="extensions"),packages:p}}var _d=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 wd(e){if(e===void 0)return;let t=ka(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(r=>!_d.has(r));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 vd(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="db10bb85-f21c-58b1-8b78-8ce1024b3e08")}catch{}})();var Gi=xd(bd),tn="@unbrained/pm-cli",Id={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},er;async function Ui(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=$.resolve(t);for(;;){let a=$.join(r,"node_modules",...n.split("/")),i=$.join(a,"package.json");if(await k(i))try{let s=JSON.parse(await R.readFile(i,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:a}}catch{return null}let o=$.dirname(r);if(o===r)return null;r=o}}function tr(e,t,n){let r=e.split("/").map(c=>c.trim()).filter(c=>c.length>0);if(r.length<2)return null;let a=r[0],i=r[1].replace(/\.git$/i,"");if(a.length===0||i.length===0)return null;let o=r.slice(2),s,l;return o[0]==="tree"&&o.length>=2?(s=o[1],l=o.slice(2).join("/")):o.length>0&&(l=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:a,repo:i,repository:`https://github.com/${a}/${i}.git`,ref:s,subpath:l&&l.length>0?l:void 0}}function Ad(e,t,n){let r=e.slice(4).trim();if(r.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:r}}function wt(e,t={}){let n=e.trim();if(n.length===0)throw new f("Extension source is required for --install.",h.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Ad(n,t.forceGithub===!0,r);let a=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return tr(s,n,r)}catch{return null}})();if(a)return a;let i=n.startsWith("github.com/")?n.slice(11):null;if(i){let o=tr(i,n,r);if(!o)throw new f(`Invalid GitHub source "${n}".`,h.USAGE);return o}if(t.forceGithub){let o=tr(n,n,r);if(!o)throw new f(`Invalid GitHub shorthand "${n}".`,h.USAGE);return o}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 en(e,t=Gi,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let a=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",i=a.trim().length>0?a.trim():r instanceof Error?r.message:String(r);throw new f(`Git command failed: git ${e.join(" ")}
22
+ ${i}`,h.GENERIC_FAILURE)}}function ar(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function ir(e=process.platform){return e==="win32"}async function zi(e,t,n=Gi,r=process.platform,a=process.env){let i=ar(r),o=Object.fromEntries(Object.entries(a).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));o.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(i,e,{cwd:t,encoding:"utf8",env:o,shell:ir(r)})).stdout??"").trim()}catch(s){let l=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",c=l.trim().length>0?l.trim():s instanceof Error?s.message:String(s);throw new f(`npm command failed: ${i} ${e.join(" ")}
23
+ ${c}`,h.GENERIC_FAILURE)}}function Ji(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 qi(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 t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("npm err! code e404")||t.includes("404 not found")||t.includes("is not in this registry")}function Od(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return Td(e)||t.includes("not found")}function Cd(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Pd(e){let t=Ji(e),n=Cd(t),r=t.replace(/^.*\//,""),a=n?`github.com/unbraind/${r}`:void 0,i=a?`pm install --project ${a}`: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:i?[i,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:i?[`Try ${i} 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}`],...a&&i?{fallback_candidates:[{source:a,command:i,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:i}:{}}}}}function Rd(e,t){if(!Od(t))return null;let n=Pd(e);return new f(n.message,h.NOT_FOUND,n.context)}async function Wi(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await k(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=kd(t);return await k(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await k(t))return t}return null}async function Nd(e){let t=await Wi(e);if(t)return t;let n=Dd(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Dd(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!qi(e))return e;let a=e.slice(0,r),i=e.slice(r+n.length);if(i.startsWith("//")&&!i.startsWith("///"))return e;if(!i.startsWith("/"))return`${a}@${$.resolve(t,i)}`;let o;try{o=decodeURIComponent(new URL(`file:${i}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${a}@${s}`}function Mi(e,t){let n=$.resolve(e,t),r=$.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${$.sep}`)||$.isAbsolute(r))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 jd(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(t=>({value:t})):typeof e=="object"&&e!==null?Object.entries(e).map(([t,n])=>({key:t,value:n})):[]).flatMap(({key:t,value:n})=>{let r=jd(n,t);return r?[r]:[]})}function Fd(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(o=>{let s=o.name?.trim().toLowerCase();return s!==void 0?s===n:o.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let a=e[0],i=a.name??a.key;return n&&i!==void 0&&i.trim().toLowerCase()!==n?void 0:a}function Md(e,t,n){let r;try{r=JSON.parse(e)}catch{let o=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!o)throw new f("npm pack did not report a tarball filename.",h.GENERIC_FAILURE);return{tarball:Mi(t,o)}}let a=Ld(r),i=Fd(a,n);if(!i)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 ${a.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Mi(t,i.filename),package:i.name??i.key,version:i.version}}async function Gd(e){return Ud(e,zi)}async function Ud(e,t){let n=await Wi(e.spec);if(n){if((await R.stat(n)).isFile()&&Bi(n))return nr(n);let i=$.join(n,"package.json"),o=await k(i)?JSON.parse(await R.readFile(i,"utf8")):{};return{directory:await nn(n,e.input),package:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,cleanup:async()=>{}}}let r=await R.mkdtemp($.join(rr.tmpdir(),"pm-npm-package-source-")),a=$.join(r,"pack");await R.mkdir(a,{recursive:!0});try{let i=await Nd(e.spec),o=await t(["pack",i,"--json","--pack-destination",a]),s=Md(o,a,qi(e.spec)?void 0:Ji(e.spec));if(!await k(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 l=await nr(s.tarball);return{directory:l.directory,package:s.package??l.package,version:s.version??l.version,cleanup:async()=>{try{await l.cleanup()}finally{await R.rm(r,{recursive:!0,force:!0})}}}}catch(i){throw await R.rm(r,{recursive:!0,force:!0}),Rd(e.spec,i)||i}}function Bi(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ve(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 zd(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&ve(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,a=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||a.some(i=>i===".."))&&ve(`Local package archive contains an escaping path: "${r}".`),a[0]!=="package"&&ve(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ve(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ve(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ve(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&ve(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function nr(e,t=Id){(await R.stat(e)).size>t.maxArchiveBytes&&ve(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await R.mkdtemp($.join(rr.tmpdir(),"pm-local-package-archive-")),r=$.join(n,"extract");await R.mkdir(r,{recursive:!0});let a={entries:0,expandedBytes:0,packageJsonEntries:0},i;try{if(await $d({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:c=>{if(i===void 0)try{zd(c,t,a)}catch(d){i=d}}}),i!==void 0)throw i;a.packageJsonEntries!==1&&ve(`Local package archive must contain exactly one package/package.json entry; found ${a.packageJsonEntries}.`),await Ed({file:e,cwd:r,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let o=$.join(r,"package"),s=$.join(o,"package.json"),l=JSON.parse(await R.readFile(s,"utf8"));return await Jd(o),{directory:await nn(o,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.version:void 0,cleanup:async()=>{await R.rm(n,{recursive:!0,force:!0})}}}catch(o){throw await R.rm(n,{recursive:!0,force:!0}),o}}async function Jd(e,t=zi){let n=$.join(e,"package.json");if(!await k(n))return;let r;try{r=JSON.parse(await R.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let a=r,i=Vd(a),o=qd(a);if(i.length===0&&!o)return;let s={...r};delete s.devDependencies;let l={...s};Wd(l),await R.writeFile(n,`${JSON.stringify(l,null,2)}
24
+ `,"utf8");try{await Promise.all([R.rm($.join(e,"package-lock.json"),{force:!0}),R.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),i.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await Bd(e)}finally{await R.writeFile(n,`${JSON.stringify(s,null,2)}
25
+ `,"utf8")}}function qd(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&tn 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 r={...n};delete r[tn],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function Bd(e){let t=me(import.meta.url,["../../.."]),[n,r]=tn.split("/"),a=$.join(e,"node_modules",n),i=$.join(a,r);await R.mkdir(a,{recursive:!0}),await R.rm(i,{recursive:!0,force:!0}),await R.symlink(t,i,Hd(process.platform))}function Hd(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(n=>{let r=n.charCodeAt(0);return r<=31||r===127||"&|;()`\"'".includes(n)}))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{Sd.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 Vd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,a]of Object.entries(n)){if(r===tn||typeof a!="string"||a.trim().length===0||t.has(r))continue;let i=a.trim();t.set(r,Kd(r,i))}return[...t.values()]}async function nn(e,t){let n=await Yt(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(a=>$.relative(e,a).replaceAll($.sep,"/")).sort((a,i)=>a.localeCompare(i));throw new f(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.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 Yd(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 a of n){let i=$.resolve(e,a);if(K(e,i)&&await k($.join(i,"manifest.json")))return{directory:i,resolved_subpath:a}}if(await k($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await nn(e,t.input);return{directory:r,resolved_subpath:$.relative(e,r).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 Zd(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 r=[];try{let i=process.env.PM_CLI_PACKAGE_ROOT,o=typeof i=="string"&&i.trim().length>0?$.resolve(i.trim()):"";er?.key!==o&&(er={key:o,aliases:await Qt()}),r=er.aliases}catch{}let a=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${r.join(", ")}`];return new 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:a,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Hi(e){if(e.kind==="local"){let r;try{r=await R.stat(e.absolute_path)}catch{throw await Zd(e)}if(r.isFile()&&Bi(e.absolute_path)){let i=await nr(e.absolute_path);return{source:e,directory:i.directory,source_root:$.dirname(i.directory),resolved_subpath:$.relative($.dirname(i.directory),i.directory).replaceAll($.sep,"/"),npm_package:i.package,npm_version:i.version,cleanup:i.cleanup}}if(!r.isDirectory())throw new f(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let a=await nn(e.absolute_path,e.input);return{source:e,directory:a,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await Gd(e);return{source:e,directory:r.directory,source_root:$.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:$.relative($.dirname(r.directory),r.directory).replaceAll($.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await R.mkdtemp($.join(rr.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await en(n);let r=await en(["-C",t,"rev-parse","HEAD"]),a=await Yd(t,e);return{source:e,directory:a.directory,source_root:t,resolved_subpath:a.resolved_subpath,commit:r,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await R.rm(t,{recursive:!0,force:!0}),r}}async function rn(e,t){if(!await k(e)||!await k(t))return!1;let[n,r]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===r}import vt from"node:fs/promises";import bt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var or=1,ze="2026.6.24",Qd=">=22.18.0",ep={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Ki=new Set([...ia.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Rr).map(e=>e.toLowerCase()),"scaffold"]),tp="^6.0.0",np="^22.0.0",Xi=["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."," }"," }","}",""],ge=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Vi(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Zi(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 Qi(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 rp={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Yi=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],eo={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"]},ap={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"]'},ip={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."},op={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."},to="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",sp={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."]},cp={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."]},lp={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`."]},dp={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 no(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 ro(e,t){return e==="schema"?lp[t]:e==="profile"?dp[t]:cp[t]}function pp(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(o=>o.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let a=t[r]?.toLowerCase(),i=r>0&&(r===t.length||a!==void 0&&Ki.has(a));return`${(Ki.has(n)||i?["starter",...t]:t).join(" ")} ping`}function ao(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),a=r===t?[]:[r],i=`${e.replace(/-/g,"_")}_owner`,o="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(a)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(i)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function mp(e,t,n){let r=`${e}-search`,a=`${e}-vector`,i=`${e.replace(/-/g," ")} items`,o=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(a)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,l=`${e}s`,c=e.replace(/-/g,""),d=c===s?[]:[c],p=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...ao(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(i)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} 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(i)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...o,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...o,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function up(e,t,n){let r=n==="hooks",a=n==="search",i=n==="importers",o=n==="schema",s=n==="profile",l=n==="renderers",c=n==="parser",d=n==="preflight",p=n==="services",m=ap[n],g=e,y=`${e}s`,_=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],x=a?sr(e,t,"search",m):[],S=i?sr(e,t,"importers",m):[],O=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Vi(Zi({extensionName:e,itemTypeName:g,itemTypeFolder:y,fieldName:_,migrationId:u,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],oe=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Vi(Qi(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],L=l?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],E=c?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],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: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],ot=p?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...a?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Xi,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...c?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});","",...v,...x,...S,...O,...oe,...L,...E,...q,...ot,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
26
+ `)}function fp(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var hp={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"},gp={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 yp(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function _p(e,t,n){let r=[],a=[...yp(e,t,n)],i=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,l=`${e.replace(/-/g," ")} items`,c=e,d=`${e}s`,p=e.replace(/-/g,""),m=p===c?[]:[p],g=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),a.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... */ }","});"),i.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),a.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),i.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),a.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,","}));"),i.push(" importers: ["," {",` name: ${JSON.stringify(l)},`," importer,"," options: {",` action: ${JSON.stringify(`${l} 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(l)},`," exporter,"," options: {",` action: ${JSON.stringify(`${l} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),a.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(c)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(y)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),i.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),a.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({",...ao(e),"});"),i.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),a.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);`," },","});"),i.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),a.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 };","});"),i.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),a.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,","});"),i.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),a.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 };`,"});"),i.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:a,blueprintFields:i}}function wp(e,t,n){let r=_p(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((a,i)=>a.localeCompare(i)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
27
+ `)}function sr(e,t,n,r){if(n==="commands")return[];let a=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,l=`${e}s`,c=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],m=g=>[...p," let deactivated = false;"," try {",...g.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(i)}, 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(a)},`,' 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(a)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(i)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(Zi({extensionName:e,itemTypeName:s,itemTypeFolder:l,fieldName:c,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Qi(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function vp(e,t,n){let r=n==="parser",a=JSON.stringify([...eo[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" };',"",...Xi,`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(ze)},`," },",` target: { pmVersion: ${JSON.stringify(ze)} },`," });"," // 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, ${a});`,` assert.deepEqual(report.manifest?.capabilities, ${a});`,"});","",`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: ${a},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});","",...sr(e,t,n,a)].join(`
28
+ `)}function bp(e,t,n){let r=no(n,"package"),a=ro(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${hp[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`.",to,"- `.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 ${gp[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.",...a,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${or}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${ze}\`. 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(`
29
+ `)}function kp(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 xp(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 Sp(e,t,n,r){let a=["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"&&a.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&a.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&a.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"&&a.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&a.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&a.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&a.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&a.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"&&a.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),a}function Ep(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function $p(e,t,n,r="commands",a=!1){let i=`pm-${e}`,o=eo[r],s=fp(e,t,r),l=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:or,pm_min_version:ze,trusted:!0,sandbox_profile:"strict",permissions:{...ep},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
30
+ `,c=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...mp(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
31
+ `),d=`${JSON.stringify(rp,null,2)}
32
+ `,p=ip[r],m=no(r,"package"),g=`${JSON.stringify({name:i,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Qd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${ze}`},devDependencies:{"@types/node":np,typescript:tp},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)}
33
+ `,y=up(e,t,r),_=op[r],u=["node_modules/","*.log","*.tsbuildinfo",""].join(`
34
+ `),w=kp(e),v=["```ts",`import { ${xp(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Sp(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Ep(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],x=[`# ${i}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,p,_,to,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...v,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...sp[r],...ro(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${ze}\`. 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 \`${or}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${ze}\`. 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(`
35
+ `);return{"package.json":g,"manifest.json":l,"index.ts":a?wp(e,t,r):c,"index.test.ts":a?vp(e,t,r):y,"tsconfig.json":d,".gitignore":u,"README.md":a?bp(i,t,r):x}}async function io(e,t="extension",n="commands",r=!1){let a=n.trim().toLowerCase();if(!Yi.includes(a))throw new f(`Unknown scaffold capability "${n}". Supported capabilities: ${Yi.join(", ")}.`,h.USAGE);let i=a;if(r&&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 o=r?"declarative":"imperative",s=e.trim(),l=bt.resolve(process.cwd(),s),c=Xt(bt.basename(l)).replace(/^(?:pm-)+/u,""),d=pp(c),p=$p(c,d,t,i,r),m=!1;if(await k(l)){if(!(await vt.stat(l)).isDirectory())throw new f(`Scaffold target "${l}" exists and is not a directory.`,h.CONFLICT)}else await vt.mkdir(l,{recursive:!0}),m=!0;for(let[y,_]of Object.entries(p)){let u=bt.join(l,y);if(await k(u)&&await vt.readFile(u,"utf8")!==_)throw new f(`Scaffold file "${y}" already exists with different content in "${l}". Choose a new target path or remove conflicting files.`,h.CONFLICT)}let g=[];for(let[y,_]of Object.entries(p)){let u=bt.join(l,y);if(await k(u)){g.push({path:y,status:"unchanged"});continue}await vt.mkdir(bt.dirname(u),{recursive:!0}),await vt.writeFile(u,_,"utf8"),g.push({path:y,status:"created"})}return{extension_name:c,package_name:`pm-${c}`,command_name:d,invocation_command:`pm ${d}`,capability:i,style:o,target_path:l,created_directory:m,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]="3984f1ef-1703-5a83-a4fa-ec1cdc738572")}catch{}})();var oo=[["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 cr(e){return"#".repeat(e)}function so(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let i of e)n=i==="`"?n+1:0,t=Math.max(t,n);let r="`".repeat(t+1),a=e.startsWith("`")||e.endsWith("`")?" ":"";return`${r}${a}${e}${a}${r}`}function Ip(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(so).join(", ")}`}function Ap(e,t,n){let r=[`${cr(t)} ${e}`,""];return n.length===0?(r.push("_None._",""),r):(r.push(...n.map(a=>`- ${so(a)}`),""),r)}function Tp(e,t,n){return e===0&&!n?[]:[`${cr(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function lr(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<1||n>6)throw new RangeError(`headingLevel must be an integer in [1, 6], received ${String(t.headingLevel)}`);let r=Math.min(n+1,6),a=t.includeEmpty===!0,i=t.title??"Extension surfaces",o=[`${cr(n)} ${i}`,""];(a||e.capabilities.length>0)&&o.push(Ip(e.capabilities),"");for(let[s,l]of oo){let c=e[s]??[];c.length===0&&!a||o.push(...Ap(l,r,c))}return o.push(...Tp(e.preflight_overrides,r,a)),!(e.preflight_overrides>0||oo.some(([s])=>(e[s]?.length??0)>0))&&!a&&o.push("_This extension registers no surfaces._",""),`${o.join(`
36
+ `).trimEnd()}
37
+ `}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function co(e,t){return`${e}:${b(t)}`}function Op(e,t){let n=[];for(let[r,a]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let i=new Map;for(let o of a){let s=i.get(o.command)??[];i.set(o.command,[...s,o])}for(let[o,s]of i){if(t!==null&&!s.some(c=>t.has(b(c.name))))continue;let l=s.at(-1);n.push({command:o,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(c=>({name:c.name,layer:c.layer,winner:c===l}))})}}return n.sort((r,a)=>r.command.localeCompare(a.command)||r.surface.localeCompare(a.surface))}function lo(e,t,n){let r=new Set(n.failed.map(c=>co(c.layer,c.name))),a=[...t.loaded.map(c=>({name:c.name,layer:c.layer,version:c.version,activation_status:r.has(co(c.layer,c.name))?"failed":"ok",surfaces:Ke(n,{extensionName:c.name})})),...t.failed.map(c=>({name:c.name,layer:c.layer,version:"unknown",activation_status:"not_loaded",surfaces:Ke(n,{extensionName:c.name})}))].sort((c,d)=>c.name.localeCompare(d.name)||c.layer.localeCompare(d.layer)),i=typeof e=="string"?b(e):null,o=i===null?null:new Set(t.loaded.filter(c=>b(c.name)===i||typeof c.source_package=="string"&&b(c.source_package)===i||(c.source_aliases??[]).some(d=>b(d)===i)).map(c=>b(c.name)).concat(i)),s=o===null?a:a.filter(c=>o.has(b(c.name))),l=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Ke(n,l),command_ownership:Op(n,o)}}var Cp={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function Xy(e,t){let n=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(n.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),n.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){n.push("## Command ownership","");for(let r of e.command_ownership){let a=r.claimants.find(o=>o.winner),i=r.claimants.map(o=>`${o.layer}:${o.name}`).join(", ");n.push(`- \`${r.command}\` (${r.surface}): ${a.layer}:${a.name}; policy=${r.policy}; collision=${String(r.collision)}; claimants=${i}`)}n.push("")}if(e.extensions.length===0)return n.push(`_No ${t}s are loaded._`,""),`${n.join(`
38
+ `).trimEnd()}
39
+ `;for(let r of e.extensions){let a=`${r.name} (${r.layer} v${r.version}, ${Cp[r.activation_status]})`;n.push(lr(r.surfaces,{title:a,headingLevel:2}))}return e.extensions.length>1&&n.push(lr(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${n.join(`
40
+ `).trimEnd()}
41
+ `}import sn from"node:fs/promises";import on from"node:path";import po from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function kt(e,t,n,r){let a=po.relative(e,n);if(a!==""&&!K(e,n)||n===t||K(t,n))return!1;let i=a.split(po.sep);return i.includes(".git")?!1:r?!i.some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as Pp}from"node:crypto";import M from"node:fs/promises";import Rp 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]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var mo=3,Np=120,uo=250,Dp=12e4,jp=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),fo=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,ho=e=>jp.has(String(fo(e))),an=(e,t)=>fo(e)===t,go=e=>new Promise(t=>{setTimeout(t,e)}),yo=async e=>{let t=j.join(e,"package.json");await k(t)||await M.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
42
+ `,"utf8")},_o=async e=>{let t=me(import.meta.url,["../../.."]),n=j.join(e,"node_modules","@unbrained"),r=j.join(n,"pm-cli");await M.mkdir(n,{recursive:!0}),await M.rm(r,{recursive:!0,force:!0}),await M.symlink(t,r,process.platform==="win32"?"junction":"dir")},xt=async e=>{let t=j.resolve(e),n=j.dirname(t),r=j.parse(n).root,a=await M.realpath(r).catch(()=>r),i=j.relative(r,n),o=i===""?[]:i.split(j.sep);for(let[s,l]of o.entries()){let c=j.join(a,l);try{a=await M.realpath(c)}catch{a=j.join(a,...o.slice(s));break}}return j.join(a,j.basename(t))},wo=async(e,t,n,r=Rp.tmpdir())=>Ne("extension_install_copy",async()=>{let a=j.resolve(e),i=await M.realpath(a).catch(()=>a),o=await xt(t);if(i===o)return;if(!K(i,o)){await n(i,t,{recursive:!0,force:!0,filter:p=>kt(i,o,j.resolve(p),!1)});return}let s=await M.realpath(j.resolve(r)).catch(()=>xt(r)),l=K(i,s)?j.dirname(i):s;if(K(i,l))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 c=await M.mkdtemp(j.join(l,"pm-extension-copy-")),d=j.join(c,"extension");try{await n(i,d,{recursive:!0,force:!0,filter:p=>kt(i,o,j.resolve(p),!0)}),await n(d,t,{recursive:!0,force:!0})}finally{await M.rm(c,{recursive:!0,force:!0})}}),vo=async(e,t,n=M.cp)=>{for(let r=1;r<=mo;r+=1)try{await Ne("extension_install_copy",async()=>{await M.rm(t,{recursive:!0,force:!0}),await wo(e,t,n)});return}catch(a){if(!ho(a)||r===mo)throw a;await go(uo)}},dr=async e=>{let t;try{t=await M.readFile(j.join(e,"owner.json"),"utf8")}catch(a){if(!Ct(a))throw a;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},bo=async(e,t)=>await dr(e)!==t?!1:(await M.rm(e,{recursive:!0,force:!0}),!0),Lp=async(e,t)=>{let n;try{n=await M.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await dr(e);return r===null?(await M.rm(e,{recursive:!0,force:!0}),!0):bo(e,r)},Fp=(e,t,n)=>{let r=Promise.resolve(),a=setInterval(()=>{r=r.then(async()=>{if(await dr(e)!==t)return;let i=new Date;await M.utimes(e,i,i)}).catch(()=>{})},n);return a.unref(),async()=>{clearInterval(a),await r}},Mp=async(e,t)=>{await M.mkdir(e);try{await M.writeFile(j.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
43
+ `,"utf8")}catch(n){throw await M.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Gp=async(e,t,n,r,a)=>{for(let i=1;i<=n;i+=1)try{return await Mp(e,t),!0}catch(o){if(!an(o,"EEXIST"))throw o;await Lp(e,a)?i-=1:await go(r)}return!1},pr=async(e,t,n,r)=>Ne("extension_install",async()=>{let a=j.join(e,"runtime","extension-install-locks"),i=j.join(a,"scope.lock");await M.mkdir(a,{recursive:!0});let{attempts:o=Np,delay_ms:s=uo,stale_ms:l=Dp,heartbeat_ms:c}=r??{};if(![o,s,l,c].filter(w=>w!==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(o)),p=Math.max(0,Math.floor(s)),m=Math.floor(l),g=Math.floor(c??m/3);if(m<=0||g<=0||g>=m)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 Gp(i,y,d,p,m))throw new f(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let _=Fp(i,y.token,g),u=!1;try{let w=await n();return u=!0,w}finally{await _(),await bo(i,y.token).catch(w=>{if(u)throw w})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var Up=new Set(["node_modules",".git","dist","build","coverage"]);async function ko(e,t,n,r){let a=e.source.kind==="local"?await sn.stat(e.source.absolute_path):void 0,i=e.source.kind==="local"?a.isDirectory()?"directory":"archive":e.source.kind,o=await zp(e.directory,t,r),s={source_mode:i,...i==="archive"?{archive_bytes:a.size}:{},copy:o},l=e.source_root??e.directory;if(i==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await k(on.join(l,"package.json"))&&(s.packed_alternative={cwd:l,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),i==="directory"&&!o.complete){let c=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new f(`Local extension source scan stopped at ${c}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,h.USAGE,{code:"extension_install_incomplete_source_scan",reason:o.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function zp(e,t,n={}){let{maxEntries:r=1e4,maxDepth:a=64,signal:i}=n;if(![r,a].every(p=>Number.isSafeInteger(p)&&p>0))throw new f("maxEntries and maxDepth must be positive safe integers.",h.USAGE);i?.throwIfAborted();let o=await sn.realpath(e),s=await xt(t),l=await rn(o,s);i?.throwIfAborted();let c=l?"in_place":K(o,s)?"nested_filtered_snapshot":"directory_snapshot",d={copy_scope:c,source_directory:o,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:r,max_depth:a};return c==="in_place"||await xo(o,0,d,i),d}async function xo(e,t,n,r){r?.throwIfAborted();let a=await sn.opendir(e);for await(let i of a){if(r?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=on.join(e,i.name);if(!kt(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(on.relative(n.source_directory,o).split(on.sep).some(s=>Up.has(s))&&(n.development_entries+=1),await Jp(o,t,n,r),!n.complete)return}}async function Jp(e,t,n,r){let a=await sn.lstat(e);if(r?.throwIfAborted(),a.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await xo(e,t+1,n,r)}else a.isFile()?(n.files+=1,n.bytes+=a.size):a.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import qp from"node:fs/promises";import Wp from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bef4424-f5b8-511b-91f7-0b39cf11f515")}catch{}})();async function Bp(e,t){if(e.kind!=="local"||e.input.startsWith(".")||e.input.includes("\\")||e.input.includes("/")&&!/^@[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/u.test(e.input))return e;try{return await qp.lstat(e.absolute_path),e}catch(i){if(!re(i))throw i}let n=e.input.trim(),r=t.filter(i=>i.source.kind==="npm"),a=(r.find(i=>i.name===n)??r.find(i=>i.directory===n)??r.find(i=>i.source.package===n))?.source.package;if(a===void 0)return e;try{let i=Wp(a);if(!i.registry||i.name!==a)return e}catch{return e}return wt(`npm:${a}`,{})}async function So(e,t,n,r=[]){let a=typeof t=="string"?null:await _t(e),i=a===null?null:e.trim().toLowerCase(),o=i===null?null:await ji(i),s=await Bp(wt(a??e,{forceGithub:typeof t=="string",ref:n}),r),l=i===null?null:await Ui(e);return{bundledAliasName:i,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:i===null?s.kind:"builtin",input:i??s.input,...o===null?{}:{package:o}},ambiguous:l!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...o===null?{}:{package:o},command:`pm install ${i}`}],...l===null?[]:[{kind:"npm",input:`npm:${l.package}`,package:l.package,...l.version===void 0?{}:{version:l.version},directory:l.directory,command:`pm install npm:${l.package}`}]]}}}import Re from"node:fs/promises";import ne from"node:path";import Xp from"node:path";import{mkdir as Zp}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]="abb182c9-6d6c-5be4-a2ad-c91b00a098d0")}catch{}})();var St=["agile","ops","research"],Hp={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 cn(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: ${St.join(", ")}.`)}function Et(e){return Hp[e].map(t=>lt(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]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var Kp=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Vp(e){let t=Kp.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Yp(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Eo(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,a=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let l=Vp(s);if(l===void 0)continue;let c=a.get(l)??{count:0,examples:[]};c.count+=1,c.examples.length<r&&c.examples.push(s),a.set(l,c)}let i=[];for(let[o,s]of a.entries()){if(s.count<n)continue;let l=Yp(o);i.push({name:l,prefix:o,count:s.count,examples:s.examples,shadows_builtin:_a(l)!==void 0})}return i.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var iw=[...jt,"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"],ln="schema-types",$o="schema-statuses",Io="schema-fields";function Ce(e){return Be({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 cw(e,t,n){let r=N(process.cwd(),n.path);await be(r);let a;try{a=lt({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 i=await A(r),o=V(i.schema),s=ae(r,o.files.types,Z.types),l=[],c=B(t.author,i.author_default),d=ce(i),p=await X(r,ln,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),m;try{let g=await G(s),y;try{y=le(g)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}try{wa(a,y);let _=new Map,u=U(i,W());for(let[w,v]of Object.entries(u.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!_.has(x)&&_.set(x,w)}va(a,y,_)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}m=He(y,a),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&l.push(`type_recased:${m.previousName}->${m.definition.name}`),await Ce({pmRoot:r,filePath:s,raw:ue(m.file),op:"schema:add-type",author:c,settings:i}),await $t(r,[m.definition],l,"schema:add-type-folder"),l.push(...await H({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await Ao(r,l),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Pe(l),generated_at:T()}}async function be(e){await Se(e)}async function Ao(e,t){try{let n=await ti(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 Pe(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Qp(e,t,n,r){let a=U(t,W()),i=r.trim().toLowerCase();return(await De(e,t.item_format,a.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===i).length}async function em(e,t,n,r){let a=U(t,W()),i=ct(n),o=I(r);return(await De(e,t.item_format,a.type_to_folder,[],n)).filter(s=>{let l=typeof s.status=="string"?s.status:"";return(i.alias_to_id.get(I(l))??I(l))===o}).length}async function tm(e,t,n,r,a){if(a.length===0||Me.has(a))return;let i=await em(t,n,r,a);i>0&&e.push(`items_using_status:${i}`);let o=To(r.workflow,a);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function To(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&I(n)===t).map(([n])=>n)}async function lw(e,t,n){let r=N(process.cwd(),n.path);await be(r);let a=await A(r),i=V(a.schema),o=ae(r,i.files.types,Z.types),s=[],l=B(t.author,a.author_default),c=ce(a),d=await X(r,ln,a.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,a.locks.wait_ms),p;try{let m=await G(o),g;try{g=le(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=ba(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 _=await Qp(r,a,i,y);_>0&&s.push(`items_using_type:${_}`)}await Ce({pmRoot:r,filePath:o,raw:ue(p.file),op:"schema:remove-type",author:l,settings:a}),s.push(...await H({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return p.removed&&await Ao(r,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:o,definitions:p.file.definitions.length},warnings:Pe(s),generated_at:T()}}function mr(e,t){return ae(e,t.files.statuses,Z.statuses)}function dn(e,t){return ae(e,t.files.fields,Z.fields)}function Oo(e,t){return ae(e,t.files.types,Z.types)}async function $t(e,t,n,r){for(let a of t){let i=Mr(a.folder??Fr(a.name)),o=Xp.join(e,i);await k(o)||(await Zp(o,{recursive:!0}),n.push(...await H({path:o,scope:"project",op:r})))}}function ur(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 nm(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 rm(e){let t=new Map;for(let n of e){let r=I(n.id);if(r.length!==0){t.set(r,r);for(let a of Array.isArray(n.aliases)?n.aliases:[]){let i=I(a);i.length>0&&!t.has(i)&&t.set(i,r)}}}return t}async function dw(e,t,n){let r=N(process.cwd(),n.path);await be(r);let a;try{a=hi({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let i=await A(r),o=V(i.schema),s=mr(r,o),l=ct(o);try{qn(a,l.alias_to_id)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let c=nm(l.by_id.get(a.id));if((a.roles??c?.roles??[]).length===0)throw new f(`Status "${a.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 "${je(a.id)}" --role active`,`pm schema add-status "${je(a.id)}" --role blocked`]});let d=[],p=B(t.author,i.author_default),m=ce(i),g=await X(r,$o,i.locks.ttl_seconds,p,!!t.force,m.force_required_for_stale_lock,i.locks.wait_ms),y;try{let _=await G(s),u;try{u=Qe(_)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=rm(u.statuses);try{qn(a,w)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.USAGE)}y=gi(u,a,c),await Ce({pmRoot:r,filePath:s,raw:et(y.file),op:"schema:add-status",author:p,settings:i}),d.push(...await H({path:s,scope:"project",op:"schema:add-status"}))}finally{await g()}return{action:"add-status",registered:!0,replaced:y.replaced,status:y.definition,file:{path:s,statuses:y.file.statuses.length},warnings:Pe(d),generated_at:T()}}async function pw(e,t,n){let r=N(process.cwd(),n.path);await be(r);let a=await A(r),i=V(a.schema),o=mr(r,i),s=[],l=B(t.author,a.author_default),c=ce(a),d=await X(r,$o,a.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,a.locks.wait_ms),p;try{let m=await G(o),g;try{g=Qe(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=yi(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 tm(s,r,a,i,y),await Ce({pmRoot:r,filePath:o,raw:et(p.file),op:"schema:remove-status",author:l,settings:a}),s.push(...await H({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:o,statuses:p.file.statuses.length},warnings:Pe(s),generated_at:T()}}function Co(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 am(e,t,n){return{...Co(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 Po(e){return{id:e.id,source:Me.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 Ro(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function im(){let e=new Map,t=W();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let a of r){if(typeof a!="object"||a===null||Array.isArray(a))continue;let i=a.name;typeof i=="string"&&i.trim().length>0&&e.set(i.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function om(e){let t=ct(e),n=[],r=[];for(let a of t.definitions){let i=Po(a);i.source==="builtin"?n.push(i):r.push(i)}return{builtin:n,custom:r}}async function It(e){let t=N(process.cwd(),e.path);await be(t);let n=await A(t),r=V(n.schema),a=ae(t,r.files.types,Z.types),i=mr(t,r),o=U(n,W()),s=im(),l=new Set((n.item_types?.definitions??[]).map(c=>c.name.trim().toLowerCase()).filter(c=>c.length>0&&!s.has(c)));return{pmRoot:t,typesPath:a,statusesPath:i,byType:o.by_type,customNames:l,extensionProvenance:s,schema:r}}async function mw(e){let t=await It(e),n=[],r=[],a=[];for(let s of Object.values(t.byType).sort((l,c)=>l.name.localeCompare(c.name))){let l=Ro(s.name,t.customNames,new Set(t.extensionProvenance.keys())),c=Co(s);l==="extension"?a.push(c):l==="custom"?r.push(c):n.push(c)}let i=om(t.schema),o=Lt(t.schema).definitions.map(ur);return{action:"list",builtin:n,custom:r,extension:a,counts:{builtin:n.length,custom:r.length,extension:a.length,total:n.length+r.length+a.length},statuses:{builtin:i.builtin,custom:i.custom,counts:{builtin:i.builtin.length,custom:i.custom.length,total:i.builtin.length+i.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:T()}}async function uw(e,t){let n=(e??"").trim();if(n.length===0)throw new f("Type name must not be empty.",h.USAGE);let r=await It(t),a=Object.values(r.byType).find(i=>i.name.toLowerCase()===n.toLowerCase()||i.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!a)throw new f(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${je(n)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:am(a,Ro(a.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(a.name.toLowerCase())),file:{path:r.typesPath},generated_at:T()}}async function fw(e,t){let n=I(e);if(n.length===0)throw new f("Status id must not be empty.",h.USAGE);let r=await It(t),a=ct(r.schema),i=a.alias_to_id.get(n)??n,o=a.by_id.get(i);if(!o)throw new f(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${je(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Po(o),file:{path:r.statusesPath},generated_at:T()}}async function hw(e,t,n){let r=N(process.cwd(),n.path);await be(r);let a;try{a=mi({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 i=await A(r),o=V(i.schema),s=dn(r,o),l=[],c=Gt(a.key);c&&l.push(`custom_field_mcp_input_collision:${c.field}:${c.property}:${c.owner}:use=${c.nested_path}`);let d=B(t.author,i.author_default),p=ce(i),m=await X(r,Io,i.locks.ttl_seconds,d,!!t.force,p.force_required_for_stale_lock,i.locks.wait_ms),g;try{let y=await G(s),_;try{_=Xe(y)}catch(u){throw new f(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}g=ui(_,a),await Ce({pmRoot:r,filePath:s,raw:Ze(g.file),op:"schema:add-field",author:d,settings:i}),l.push(...await H({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:g.replaced,field:g.definition,file:{path:s,fields:g.file.fields.length},warnings:Pe(l),generated_at:T()}}async function sm(e,t,n,r){let a=U(t,W());return(await De(e,t.item_format,a.type_to_folder,[],n)).filter(i=>{let o=i[r];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function gw(e,t,n){let r=N(process.cwd(),n.path);await be(r);let a=await A(r),i=V(a.schema),o=dn(r,i),s=[],l=B(t.author,a.author_default),c=ce(a),d=await X(r,Io,a.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,a.locks.wait_ms),p;try{let m=await G(o),g;try{g=Xe(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=fi(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),_=I(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(_.length>0){let u=await sm(r,a,i,_);u>0&&s.push(`items_using_field:${u}`)}await Ce({pmRoot:r,filePath:o,raw:Ze(p.file),op:"schema:remove-field",author:l,settings:a}),s.push(...await H({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:o,fields:p.file.fields.length},warnings:Pe(s),generated_at:T()}}async function yw(e){let t=await It(e),n=Lt(t.schema).definitions.map(ur);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:dn(t.pmRoot,t.schema)},generated_at:T()}}async function _w(e,t){let n=I(e);if(n.length===0)throw new f("Field key must not be empty.",h.USAGE);let r=await It(t),a=Lt(r.schema).by_key.get(n);if(!a)throw new f(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${je(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:ur(a),file:{path:dn(r.pmRoot,r.schema)},generated_at:T()}}async function ww(e,t,n){let r=N(process.cwd(),n.path);await be(r);let a;try{let _=cn(e);if(_===void 0)throw new Error(`Type preset name is required. Allowed: ${St.join(", ")}.`);a=_}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let i=await A(r),o=V(i.schema),s=Oo(r,o),l=[],c=B(t.author,i.author_default),d=ce(i),p=[],m=[],g,y=await X(r,ln,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms);try{let _=await G(s),u;try{u=le(_)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=u;for(let v of Et(a)){let x=He(w,v);w=x.file,(x.replaced?m:p).push(x.definition.name)}g=w.definitions.length,await Ce({pmRoot:r,filePath:s,raw:ue(w),op:"schema:apply-preset",author:c,settings:i}),await $t(r,Et(a),l,"schema:apply-preset-folder"),l.push(...await H({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:a,registered:p,replaced:m,file:{path:s,definitions:g},warnings:Pe(l),generated_at:T()}}function cm(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 vw(e,t){let n=N(process.cwd(),t.path);await be(n);let r=await A(n),a=V(r.schema),i=Oo(n,a),o=cm(e.minCount),s=U(r,W()),l=(await De(n,r.item_format,s.type_to_folder,[],a)).map(v=>typeof v.title=="string"?v.title:""),c=Eo(l,{minCount:o}),d=[],p=[],m=[],g=[],y;if(!e.apply){let v;try{v=le(await G(i))}catch(x){throw new f(x instanceof Error?x.message:String(x),h.GENERIC_FAILURE)}return y=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:c,registered:p,replaced:m,skipped:g,file:{path:i,definitions:y},warnings:d,generated_at:T()}}let _=B(e.author,r.author_default),u=ce(r),w=await X(n,ln,r.locks.ttl_seconds,_,!!e.force,u.force_required_for_stale_lock,r.locks.wait_ms);try{let v=await G(i),x;try{x=le(v)}catch(O){throw new f(O instanceof Error?O.message:String(O),h.GENERIC_FAILURE)}let S=x;for(let O of c){if(O.shadows_builtin){g.push({name:O.name,reason:"shadows_builtin"});continue}let oe;try{oe=lt({name:O.name})}catch{g.push({name:O.name,reason:"invalid_type_token"});continue}let L=He(S,oe);S=L.file,(L.replaced?m:p).push(L.definition.name)}y=S.definitions.length,await Ce({pmRoot:n,filePath:i,raw:ue(S),op:"schema:infer-types",author:_,settings:r}),await $t(n,S.definitions.filter(O=>p.includes(O.name)||m.includes(O.name)),d,"schema:infer-types-folder"),d.push(...await H({path:i,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:o,candidates:c,registered:p,replaced:m,skipped:g,file:{path:i,definitions:y},warnings:Pe(d),generated_at:T()}}function bw(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 "${je(e.type.name)}" "<title>"`}function kw(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 xw(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",r=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${r} in ${e.file.path}.`}function Sw(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 Ew(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,r]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])r.length!==0&&t.push(`${n}: ${r.map(a=>a.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,r]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])r.length!==0&&t.push(`${n}: ${r.map(a=>a.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(`
44
+ `)}function $w(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(`
45
+ `)}function Iw(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(`
46
+ `)}function lm(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 Aw(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 Tw(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 Ow(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${lm(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
47
+ `)}function Cw(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(`
48
+ `)}function Pw(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",r=[t,n].filter(a=>a.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${r.length>0?` (${r})`:""}.`}function Rw(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 r=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${r}`)}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(`
49
+ `)}var Nw={workflowSlotsReferencing:To};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e6087f2-01b5-59c3-a471-433c722316b0")}catch{}})();function fr(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function pn(e,t,n){let r=b(t),a=n.trim();if(r.length===0||a.length===0)return;let i=e.get(r)??new Set;i.add(a),e.set(r,i)}function dm(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)pn(t,r.name,r.command),pn(n,r.name,r.action);for(let r of e.commands.handlers)pn(t,r.name,r.command);for(let r of e.commands.overrides)pn(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function No(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function pm(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:a,activationFailedNames:i}=e;return t?a.has(n)||i.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function mn(e,t,n){let r=new Set(t.loaded.map(l=>b(l.name))),a=new Set(t.failed.map(l=>b(l.name))),i=new Set(n.failed.map(l=>b(l.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=dm(n);return e.map(l=>{let c=b(l.name),d=No(o.get(c)),p=No(s.get(c)),m={...d?{command_paths:d}:{},...p?{action_paths:p}:{}},g=pm({enabled:l.enabled,normalizedName:c,loadedNames:r,loadFailedNames:a,activationFailedNames:i});return{...l,...g,...m}})}function mm(e){let t=0,n=0,r=0;for(let a of e)if(a.startsWith("extension_policy_")){if(t+=1,a.startsWith("extension_policy_violation_")){n+=1;continue}a.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function z(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Lo=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 um(e){return Lo.has(Jo(e))}function Do(e){return e==="project"||e==="global"}function Fo(e){let t=e.split(":"),n=t[0];if(!n||!Lo.has(n))return null;let r=t.at(-4),a=t.at(-3)?.trim(),i=t.at(-2),o=t.at(-1)?.trim();return!Do(r)||!Do(i)||!a||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:a},displaced:{layer:i,name:o}}}function fm(e){let t=new Set;for(let n of e){let r=Fo(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function hm(e,t){let n=e.filter(um);if(n.length===0)return null;let r=fm(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function gm(e,t,n,r){let a=t.map(p=>Fo(p)).filter(p=>p!==null).sort((p,m)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(a.length===0)return;let i=e==="global"?"--global":"--project",o=z(r,"deactivate"),s=`${z(r,"doctor")} ${i} --detail deep --trace`,l=new Map(n.map(p=>[b(p.name),p])),c=new Map;for(let p of a)for(let m of[p.winner.name,p.displaced.name]){let g=b(m);c.set(g,(c.get(g)??0)+1)}let d=[...c.entries()].map(([p,m])=>{let g=l.get(p),y=g?.name??p,_=g?.command_paths??[],u=g?.action_paths??[];return{action:"deactivate",extension:y,command:`${o} ${y} ${i}`,affected_collisions:m,feature_loss:{command_paths:[..._].sort((w,v)=>w.localeCompare(v)),action_paths:[...u].sort((w,v)=>w.localeCompare(v))}}}).sort((p,m)=>{let g=m.affected_collisions-p.affected_collisions;if(g!==0)return g;let y=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,_=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return y!==_?y-_:p.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:a.length,extension_count:c.size,next_best_command:s,collisions:a,remediation_candidates:d}}function Mo(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function Go(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let a=r.trace?.missing_capability??r.trace?.capability;typeof a=="string"&&a.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${a.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,a)=>r.localeCompare(a))}function Uo(e,t){let n=[];for(let r of Qr(e.loaded,t))for(let a of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${a}`);return[...new Set(n)].sort((r,a)=>r.localeCompare(a))}var ym=[{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: ${Dr.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 _m(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:a,updateCheckFailedTotal:i,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:l,skippedNonGithubTotal:c,updateAvailableTotal:d}=e,p=[],m={options:n,scope:r,scopeFlag:a,updateCheckFailedTotal:i,policyWarningCount:o};if(t.length>0){let g=hm(t,{deactivate:`${z(n,"deactivate")} <name> ${a}`,doctor:`${z(n,"doctor")} ${a} --detail deep --trace`});g&&p.push(g);for(let y of ym)y.matches(t,m)&&p.push(y.build(m))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${z(n,"manage")} ${a} --fix-managed-state (or ${z(n,"adopt-all")} ${a}, ${z(n,"adopt")} <name> ${a}, or reinstall via ${z(n,"install")} ${a} <source>).`),c>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."),l>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${z(n,"manage")} ${a} to request update checks.`),d>0&&p.push(`Update available managed extensions via ${z(n,"install")} ${a} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${z(n,"manage")} ${a} after extension changes.`),p}function un(e,t,n,r={}){let a=[...new Set(t)].sort((E,q)=>E.localeCompare(q)),i=n.filter(E=>E.managed).length,o=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,l=n.filter(E=>E.update_check_status==="checked"&&E.update_available===!0).length,c=n.filter(E=>E.managed===!1),d=c.filter(E=>jo(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),p=c.filter(E=>!jo(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)m[E.update_check_status]+=1;let g=m.failed,y=n.filter(E=>E.update_check_status==="skipped_non_github"&&E.source?.kind!=="builtin").length,_=Object.entries({skipped_unmanaged:p.length,skipped_non_github:y,failed:g,not_checked:m.not_checked}).filter(([,E])=>E>0).map(([E,q])=>`extension_update_health_partial_coverage:${E}:${q}`),u=_.length>0,w=u?"partial":"full",v=[...new Set([...a,..._])].sort((E,q)=>E.localeCompare(q)),x=[...new Set(v.map(E=>Jo(E)))].sort((E,q)=>E.localeCompare(q)),S=mm(v),O=e==="global"?"--global":"--project",oe=gm(e,a,n,r),L=_m({normalizedWarnings:v,options:r,scope:e,scopeFlag:O,updateCheckFailedTotal:g,policyWarningCount:S.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:y,updateAvailableTotal:l});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:x,warnings:v,policy_warning_count:S.warning_count,policy_violation_count:S.violation_count,policy_blocked_count:S.blocked_count,total_extensions:n.length,managed_total:i,enabled_total:o,active_total:s,update_available_total:l,update_health_coverage:w,update_health_partial:u,unmanaged_loaded_extension_count:c.length,unmanaged_loaded_extensions:c.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:m,update_check_failed_total:g,top_warnings:v.slice(0,8),remediation:L,...oe?{collision_plan:oe}:{}}}function zo(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 Jo(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function qo(e){let t=new Set,n=[];for(let r of e){let a=(()=>{let i=Br(r);return i?[i]:Hr(r)})();for(let i of a){let o=`${i.layer}:${i.name}:${i.capability}`;t.has(o)||(t.add(o),n.push(i))}}return n}function Wo(){return{version:Pt.version,capabilities:[...Pt.capabilities],legacy_aliases:{...Pt.legacy_aliases}}}function jo(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Bo(e,t,n,r,a){if(e!=="project"||a)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let i=[...new Set(t.filter(c=>c.active).map(c=>b(c.name)))].sort((c,d)=>c.localeCompare(d)),o=[...new Set(n.filter(c=>c.layer==="project").map(c=>b(c.name)))].sort((c,d)=>c.localeCompare(d)),s=new Set(r.map(c=>b(c.name))),l=i.filter(c=>!o.includes(c)&&!s.has(c)).sort((c,d)=>c.localeCompare(d));return{warnings:l.length>0?[`extension_doctor_consistency_active_not_loaded:${l.join(",")}`]:[],summary:{active_project_count:i.length,loaded_project_count:o.length,active_project_names:i,loaded_project_names:o,missing_active_project_names:l}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var hr=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),a=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;a<e.length;){let o=a;a+=1,r[o]=await n(e[o])}});return await Promise.all(i),r};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function Ho(e,t){let n=b(e),r=t.find(a=>b(a.name)===n);return{command_paths:[...r?.command_paths??[]].sort((a,i)=>a.localeCompare(i)),action_paths:[...r?.action_paths??[]].sort((a,i)=>a.localeCompare(i))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function Ko(e,t){let n=new Set((t?.loaded??[]).flatMap(i=>(i.activation?.commands?.length??0)>0?[`${i.layer}:${b(i.name)}`]:[])),r=e.services.overrides.filter(i=>i.service==="output_format").filter(i=>i.passThrough!==!0).filter(i=>!n.has(`${i.layer}:${b(i.name)}`)).map(i=>`extension_output_service_override_global:${i.service}:${i.layer}:${i.name}`),a=e.renderers.overrides.filter(i=>(i.commands?.length??0)===0&&i.resultDiscriminator===void 0).map(i=>`extension_output_renderer_override_global:${i.format}:${i.layer}:${i.name}`);return[...new Set([...r,...a])].sort((i,o)=>i.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var Vo=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=Gt(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{execFile as wm}from"node:child_process";import{promisify as vm}from"node:util";import bm from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b67e46f9-51ff-501b-98da-74353b4c66d9")}catch{}})();var km=vm(wm),Xo=1e4;function Yo(e,t,n){if(typeof t=="string")try{let r=bm.resolve(e,t);if(r.type==="version")return r.fetchSpec}catch{}throw new Error(n)}async function xm(e,t){try{return(await km(ar(),e,{encoding:"utf8",timeout:t,maxBuffer:65536,shell:ir(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function Zo(e,t=xm){let n=T();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let r=Yo(e.package,e.version,"missing_or_invalid_installed_npm_version"),a=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],Xo),i;try{i=JSON.parse(a)}catch{throw new Error("invalid_npm_registry_metadata")}let o=Array.isArray(i)&&i.length===1?i[0]:i,s=Yo(e.package,o,"invalid_npm_registry_version");return{checked_at:n,available:s!==r,remote_version:s}}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}}var Sm=(e,t,n)=>{let r=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,l=""]=o.split(/\s+/);return{commit:s,ref:l}}),a=r.find(o=>o.ref.endsWith("^{}"))??r[0];if(!a)return{checked_at:n,available:null,error:"no_remote_reference_found"};let i=t?.trim();return i?{checked_at:n,remote_commit:a.commit,available:a.commit!==i}:{checked_at:n,remote_commit:a.commit,available:null,error:"missing_installed_commit"}},gr=async(e,t=en)=>{let n=T();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let r=[e.ref?.trim(),"HEAD"].find(Boolean),a=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,Xo);return Sm(a,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d34e2cc0-5e58-5534-8480-a9ab47ec4a88")}catch{}})();var Em=4;async function Qo(e,t=!1){let n=await hr(e.entries,Em,async r=>{if(!["github","npm"].includes(r.source.kind))return r;if(t)return{...r,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0};let a=r.source.kind==="github"?await gr(r.source):await Zo(r.source);return{...r,last_update_check_at:a.checked_at,last_update_remote_commit:"remote_commit"in a?a.remote_commit:void 0,last_update_remote_version:"remote_version"in a?a.remote_version:void 0,update_available:a.available,update_error:a.error}});return{...e,entries:gt(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]="fcf7df06-e3b8-5476-a76a-cd391839c13d")}catch{}})();function es(e,t){let n=e.filter(r=>r.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:r,result:a})=>{let i=a.details;return{alias:r,ok:a.ok,extension:i.extension,source:i.source,source_resolution:i.source_resolution,install_plan:i.install_plan,dry_run:i.dry_run,destination_path:i.destination_path,activated:i.activated,settings_changed:i.settings_changed,command_paths:i.command_paths,action_paths:i.action_paths,command_discovery:i.command_discovery,verification:i.verification,runtime_activation_status:i.runtime_activation_status,activation_diagnostics:i.activation_diagnostics,warnings:a.warnings}})}}import $m from"node:fs/promises";import Im from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function Am(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Tm(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 Om(e){let t=Im.join(e,"manifest.json"),n;try{n=await $m.readFile(t,"utf8")}catch(s){if(Ct(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let a=r,i=Vr(a),o=Am(a);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:i.findings,warnings:i.findings.map(s=>Tm(o,s)),remediation:i.findings.map(s=>s.message)}}function ts(e){return Om(Gr(e))}import Je from"node:fs/promises";import Cm from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="776854e4-6df4-507e-b21b-a4d320946642")}catch{}})();var yr=async e=>Je.readFile(e).catch(t=>{if(an(t,"ENOENT"))return null;throw t}),ns=async(e,t,n,r,a)=>Ne("extension_install_backup",async()=>{let i=ht(e),o=zr(t),[s,l]=await Promise.all([yr(i),yr(o)]);return r&&await Je.cp(n,a,{recursive:!0,force:!0}),{backupDirectory:a,destinationDirectory:n,destinationExists:r,managedStatePath:i,managedStateContents:s,settingsPath:o,settingsContents:l}}),rs=async e=>Ne("extension_install_rollback",async()=>{await Je.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Je.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 Je.rm(t,{force:!0}):(await Je.mkdir(Cm.dirname(t),{recursive:!0}),await Je.writeFile(t,n))});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="549164da-d760-52bc-9950-25dacf286775")}catch{}})();var ss=[["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"]],Pm=ss.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Rm={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"},Nm="__pm_native_output",Dm=["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"],cs=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],jm=["disabled","require_trusted","require_provenance"],ls={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:[]},Lm=e=>{let t=e??ls,n={};for(let r of Dm)n[r]=te(t[r]??[]);return n},Fm=(e,t)=>{for(let n of cs)t[n].length>0&&(e[n]=t[n]);return e},Mm=(e,t)=>{for(let n of jm)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Gm=e=>{let t={};for(let n of cs)t[n]=te(e[n]??[]);return t},Um=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Fm(Mm({name:t},e),Gm(e))},zm=e=>(e??[]).map(t=>Um(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Jm=e=>{let t=Object.assign({},ls,e??{}),n=Lm(e),r=zm(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},ds=async(e,t)=>{let n=[t],r=await Li(t);r&&n.push(r);let a=[...new Set(n.map(i=>b(i)).filter(i=>i.length>0))];for(let i of a){let o=e.find(l=>b(l.name)===i);if(o)return o;let s=e.find(l=>b(l.directory)===i);if(s)return s}},ps=(e,t)=>{let n=t.trim(),r=new Set(te(e.extensions.enabled));return new Set(te(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},ms=(e,t)=>{let n=t.trim(),r=new Set(te(e.extensions.enabled)),a=new Set(te(e.extensions.disabled)),i=[...r],o=[...a];return a.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...a].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},qm=(e,t)=>{let n=t.trim(),r=new Set(te(e.extensions.enabled)),a=new Set(te(e.extensions.disabled)),i=[...r],o=[...a];return r.delete(n),a.add(n),e.extensions.enabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...a].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Wm=(e,t)=>{let n=t.trim(),r=new Set(te(e.extensions.enabled)),a=new Set(te(e.extensions.disabled)),i=[...r],o=[...a];return r.delete(n),a.delete(n),e.extensions.enabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...a].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Bm=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=ss.map(([a,i,o])=>({action:i,flag:o,distance:Wr(t,a,n)})).filter(a=>a.distance!==null).sort((a,i)=>a.distance-i.distance)[0];return r?{action:r.action,flag:r.flag}:null},Hm=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=Bm(e);if(!r)return new f(`One action flag is required. Use one of: ${Pm}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let a=`pm ${n} ${r.flag}`;return ya({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(us),retry_command:a,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:a,reason:`nearest lifecycle action for "${e}"`}]})},Km=[["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"]],us={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Vm=e=>us[e]??null,Ym=(e,t)=>{let n=[...new Set(Km.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=Vm(e.trim().toLowerCase());if(r)return r;throw Hm(e,t)}if(n.length>1)throw new f("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},Xm=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"},Zm=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],fs=e=>{for(let t of Zm){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},hs=(e,t,n,r)=>{let a=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:a.contributions,managed:!!n,source:a.source,update_available:a.update_available,last_update_check_at:a.last_update_check_at,last_update_remote_commit:a.last_update_remote_commit,last_update_remote_version:a.last_update_remote_version,update_error:a.update_error,update_check_status:r.status,update_check_reason:r.reason}},Qm=(e,t,n,r)=>{let a=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),i=r?ps(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:hs({name:a.name,directory:e,version:a.manifest_version,entry:a.manifest_entry,enabled:i},t,r,fs(r))}},eu=async(e,t,n,r,a,i)=>{let o=ne.join(e,t),s=ne.join(o,"manifest.json"),l=i.get(b(t));if(!await k(s))return Qm(t,n,r,l);let c=Symbol("invalid-extension-manifest-json"),d=await Re.readFile(s,"utf8").then(g=>JSON.parse(g)).catch(()=>c);if(d===c)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Yn(d);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=a.get(b(p.name))??i.get(b(t));return{summary:hs({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:ps(r,p.name)},n,m,fs(m))}},ye=async(e,t,n,r)=>{if(!await k(e))return{extensions:[],warnings:[]};let a=(await Re.readdir(e,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name).sort((c,d)=>c.localeCompare(d)),i=new Map(r.entries.map(c=>[b(c.name),c])),o=new Map(r.entries.map(c=>[b(c.directory),c])),s=[],l=[];for(let c of a){let d=await eu(e,c,t,n,i,o);d.warning&&s.push(d.warning),d.summary&&l.push(d.summary)}return{extensions:l.sort((c,d)=>c.name.localeCompare(d.name)),warnings:s.sort((c,d)=>c.localeCompare(d))}},tu=Xr(),nu=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,ru=(e,t,n,r)=>{let a=n.command_paths.map(s=>`pm ${s} --help`),i=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...a]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return i&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:nu(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:a,next_steps:o,...i?{sdk_dependency_status:"missing"}:{}}},au=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},gs=e=>e.map(t=>au(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),ys=(e,t,n)=>{let r=b(e);return t.find(a=>(n===void 0||a.layer===n)&&b(a.name)===r)},iu=(e,t,n,r)=>n.find(a=>a.scope===t&&b(a.name)===b(e))?.activation_status??(r?"failed":"unknown"),_s=(e,t,n,r,a)=>tu.enqueue(async()=>{let i=process.env.PM_CLI_PACKAGE_ROOT,o=await Re.mkdtemp(ne.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=me(import.meta.url,["../.."]);try{let s=await ke({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:a.noExtensions===!0,reload_token:xn(),cache_bust:!0,module_graph_snapshot_root:o}),l=await xe({...s}),c=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...gs(l.failed)],d=Object.fromEntries(s.loaded.map(p=>[b(p.name),qr(Ke(l,{extensionName:p.name}))]));return{installed:mn(r,s,l),warnings:[...s.warnings,...l.warnings],activation_failures:c,extensions_disabled:s.disabled_by_flag,item_type_registrations:l.registrations.item_types,contribution_inventories:d}}finally{await Re.rm(o,{recursive:!0,force:!0}),i===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=i}}),wr=async(e,t,n,r)=>{let a=n.filter(l=>!l.managed),i=[...a].sort((l,c)=>{let d=l.name.localeCompare(c.name);return d!==0?d:l.directory.localeCompare(c.directory)}),o=r,s=[];for(let l of i){let c=ne.join(e,l.directory),d=await at(c),p=T(),m={kind:"local",input:l.name,location:c};o=yt(o,{name:d.manifest.name,directory:l.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:m}),s.push({name:d.manifest.name,directory:l.directory,version:d.manifest.version,entry:d.manifest.entry,source:m})}return s.length>0&&await it(e,o),{state:o,adopted_entries:s,unmanaged_candidates:i,already_managed_count:n.length-a.length}},ou=(e,t)=>{let n=N(process.cwd(),t.path),r=Nt(n,process.cwd()),a=e==="global"?Ur(process.cwd()):n,i=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:a,selected_root:i,roots:r}},fn=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new f('Options "--gh" and "--github" must match when both are provided.',h.USAGE);return n[0]},su=e=>Rm[e],cu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",a=`${n} ${r}`,i=su(e),o=`<${r}>`,s=`pm ${n} ${i} ${o}`;throw new f(`Action "${e}" requires ${a} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},hn=(e,t,n={})=>{let r=e?.trim();if(r)return r;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 cu(t,n)},lu=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${b(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${b(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,a,i)=>i.indexOf(r)===a).sort((r,a)=>r.localeCompare(a))},du=(e,t)=>{let n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(r=>r.triggered&&!r.allowed);if(n)throw new f(n.message,h.USAGE)},pu=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),a=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:a?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},mu=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},uu=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:mu(e),warnings:[...new Set(e.warnings)].sort((a,i)=>a.localeCompare(i)),details:t};return e.action==="doctor"&&Object.defineProperty(r,Nm,{value:!0,enumerable:!1,configurable:!1}),r},vr=async(e,t,n)=>{let r=Ym(e,t);du(r,t);let a=pu(e,r,t),i=Xm(t),o=ou(i,n),s={action:r,normalizedTarget:a,scope:i,resolvedRoots:o,warnings:[],options:t,global:n},l={...s,withResult:(c,d=!0)=>uu(s,c,d)};return await Bu(l)},fu=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),a=ea(r),i={package:`Install dependencies: cd ${a}, then run "npm install"`,extension:`Install type-check dependencies: cd ${a}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${a}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${a}, 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."),[i[n],...s,`Install the scaffold: ${st(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},hu=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:a}=e;if([fn(r),r.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new f('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let i=hn(n,t,r),o=await io(i,r.vocabulary??"extension",r.capability,r.declarative===!0);return a({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:fu(o,r)})},gu=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:a,global:i,withResult:o}=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),l=xn(),c=await ke({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:i.noExtensions,reload_token:l,cache_bust:!0});r.push(...c.warnings);let d=await xe(c);r.push(...d.warnings);let p={reload:{token:l,cache_bust:!0,watch:a.watch===!0},loaded_count:c.loaded.length,failed_count:c.failed.length,activated_count:Math.max(0,c.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:c.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:c.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return a.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(p)},yu=async e=>{let{normalizedTarget:t,scope:n,options:r,global:a,withResult:i}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new f('Action "catalog" does not accept a package target.',h.USAGE);return i(await Fi(n,a,r))},_u=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),wu=e=>({kind:"local",input:e.input,location:e.absolute_path}),vu=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),bu=(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}),ku=(e,t,n,r)=>e?_u(e,t):n.kind==="local"?wu(n):n.kind==="npm"?vu(n,r):bu(n,r),xu=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:Ci(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},Su=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:a}=e,{validated:i,destinationDirectoryName:o}=t,s=await A(r.settings_root),l=await he(r.selected_root);a.push(...l.warnings);let c=ne.join(r.selected_root,o),d=await k(c),p=await rn(i.directory,c);await Re.mkdir(r.selected_root,{recursive:!0});let m=await Re.mkdtemp(ne.join(r.selected_root,".pm-extension-install-backup-")),g=ne.join(m,"destination");try{let y=await ns(r.selected_root,r.settings_root,c,d,g),_=ku(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),u=l.state.entries.find(S=>b(S.name)===b(i.manifest.name)),w=xu(u,i.manifest.version,_,T()),v=yt(l.state,{name:i.manifest.name,directory:o,scope:n,manifest_version:i.manifest.version,manifest_entry:i.manifest.entry,capabilities:[...i.manifest.capabilities],contributions:i.manifest.contributions,...w,source:_}),x=ms(s,i.manifest.name);try{p||await vo(i.directory,c),await yo(c),await _o(c),await it(r.selected_root,v),x&&await Ee(r.settings_root,s,"settings:write")}catch(S){try{await rs(y)}catch(O){throw new AggregateError([S,O],`Extension install failed: ${String(S)}; rollback failed: ${String(O)}`,{cause:O})}throw S}return{settings:s,managedState:v,sourceRecord:_,destinationDirectory:c,destinationExists:d,installInPlace:p,activationChanged:x}}finally{await Re.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},Eu=async(e,t,n)=>{let r=n.filter(a=>b(a.name)===b(t)).flatMap(a=>a.types.map(i=>({name:i.name,folder:i.folder})));return e.scope==="project"&&r.length>0&&await $t(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},$u=(e,t,n,r,a)=>{let i=ys(t,n.activation_failures,e.scope),o=iu(t,e.scope,n.installed,i),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let l={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:i,verification:{status:l[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:a,module_graph_verification:"fresh_in_topology_snapshot",health:l[String(s)]}}},Iu=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:a,global:i,withResult:o}=e,{validated:s,destinationDirectoryName:l}=t,c=await Su(e,t),d=await ye(r.selected_root,n,c.settings,c.managedState);a.push(...d.warnings);let p=await _s(r.pm_root,ne.dirname(r.selected_root),c.settings,d.extensions,i);a.push(...p.warnings);let m=await Eu(e,s.manifest.name,p.item_type_registrations),g=Ho(s.manifest.name,p.installed),y=$u(e,s.manifest.name,p,g,m),_=p.contribution_inventories[b(s.manifest.name)];return _&&(c.managedState=await Pi(r.selected_root,c.managedState,s.manifest.name,_)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:l},source:c.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:c.destinationDirectory,overwritten:[c.destinationExists,!c.installInPlace].every(Boolean),installed_in_place:c.installInPlace,activated:y.activated,settings_changed:c.activationChanged,runtime_activation_status:y.status,command_paths:g.command_paths,action_paths:g.action_paths,contributions:_,command_discovery:ru(s.manifest.name,c.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)},Au=async e=>{let{options:t,global:n,warnings:r,withResult:a}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new f('Action "install all" does not accept --ref.',h.USAGE);let i=[],o=new Map;for(let s of await Qt()){let l=await _t(s),c=ne.resolve(l),d=o.get(c);d===void 0&&(d=await vr(s,{...t,install:!0},n),o.set(c,d)),i.push({alias:s,result:d})}return r.push(...i.flatMap(s=>s.result.warnings)),a(es(i,t.dryRun===!0),i.every(s=>s.result.ok))},Tu=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:a,bundledPackageName:i,installSource:o,sourceResolution:s}=await So(t,n,e.options.ref,(await he(r.selected_root)).state.entries);if(s.ambiguous){let c=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${a}:npm:${c.package}`)}let l=await Hi(o);try{let c=await at(l.directory,{source_kind:o.kind,source_input:o.input,source_root:l.source_root}),d=Xt(c.manifest.name),p=e.options.dryRun===!0||o.kind==="local"&&a===null?await ko(l,ne.join(r.selected_root,d),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:c.manifest.name,version:c.manifest.version},source_resolution:s,install_plan:p}):await pr(r.settings_root,d,()=>Iu(e,{validated:c,destinationDirectoryName:d,bundledAliasName:a,bundledPackageName:i,sourceResolution:s,installSource:o,resolvedSource:l,installPlan:p}))}finally{l.cleanup&&await l.cleanup()}},Ou=async e=>{let t=fn(e.options),n=t??hn(e.normalizedTarget,e.action,e.options);return[t===void 0,Ni(n)].every(Boolean)?Au(e):Tu(e,n,t)},Cu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:a,options:i,withResult:o}=e;if(t!==void 0)throw new f('Action "adopt-all" does not accept a target argument.',h.USAGE);if(fn(i)!==void 0||typeof i.ref=="string"&&i.ref.trim().length>0)throw new f('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let s=await A(r.settings_root),l=await he(r.selected_root);a.push(...l.warnings);let c=await ye(r.selected_root,n,s,l.state);a.push(...c.warnings);let d=await wr(r.selected_root,n,c.extensions,l.state),p=await ye(r.selected_root,n,s,d.state);a.push(...p.warnings);let m=un(n,a,p.extensions,i);a.push(...m.warnings);let g=new Map(p.extensions.map(u=>[`${b(u.name)}:${b(u.directory)}`,u])),y=new Map(p.extensions.map(u=>[b(u.directory),u])),_=d.adopted_entries.map(u=>{let w=b(u.directory),v=g.get(`${b(u.name)}:${w}`)??y.get(w);return{...u,...ws(v)}});return o({adopted_all:_.length>0,adopted_count:_.length,already_managed_count:d.already_managed_count,extensions:_,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},ws=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Pu=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let a=wt(e,{forceGithub:!0,ref:r});if(a.kind!=="github")throw new f(`Invalid GitHub shorthand "${e}".`,h.USAGE);return{kind:"github",input:a.input,location:a.subpath??".",repository:a.repository,owner:a.owner,repo:a.repo,ref:a.ref,subpath:a.subpath}},Ru=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:a,warnings:i,options:o,withResult:s}=e,l=hn(n,t,o),c=fn(o),d=await A(a.settings_root),p=await he(a.selected_root);i.push(...p.warnings);let m=await ye(a.selected_root,r,d,p.state);i.push(...m.warnings);let g=await ds(m.extensions,l);if(!g)throw new f(`Installed extension "${l}" was not found in ${r} 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(a.selected_root,g.directory),_=await at(y),u=T(),w=Pu(c,l,y,o.ref),v=yt(p.state,{name:_.manifest.name,directory:g.directory,scope:r,manifest_version:_.manifest.version,manifest_entry:_.manifest.entry,capabilities:[..._.manifest.capabilities],contributions:_.manifest.contributions,installed_at:u,updated_at:u,source:w});await it(a.selected_root,v);let x=await ye(a.selected_root,r,d,v);i.push(...x.warnings);let S=x.extensions.find(O=>b(O.name)===b(_.manifest.name))??x.extensions.find(O=>b(O.directory)===b(g.directory));return s({adopted:!0,extension:{name:_.manifest.name,directory:g.directory,version:_.manifest.version,entry:_.manifest.entry},source:w,...ws(S)})},vs=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:a,warnings:i,options:o}=e,s=hn(n,t,o),l=await A(a.settings_root),c=await he(a.selected_root);i.push(...c.warnings);let d=await ye(a.selected_root,r,l,c.state);i.push(...d.warnings);let p=await ds(d.extensions,s);if(!p)throw new f(`Installed extension "${s}" was not found in ${r} scope.`,h.NOT_FOUND);return{settings:l,managedStateRead:c,candidate:p}},Nu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:a,candidate:i}=await vs(e),o=ne.join(t.selected_root,i.directory);await Re.rm(o,{recursive:!0,force:!0});let s={...a.state,updated_at:T(),entries:a.state.entries.filter(c=>b(c.name)!==b(i.name)&&b(c.directory)!==b(i.directory))};await it(t.selected_root,s);let l=Wm(r,i.name);return l&&await Ee(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:i.name,directory:i.directory},destination_path:o,settings_changed:l})},as=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:a,withResult:i}=e,{settings:o,candidate:s}=await vs(e),l=t==="activate"?ms(o,s.name):qm(o,s.name);l&&await Ee(n.settings_root,o,"settings:write");let c=t==="activate"?await _s(n.pm_root,ne.dirname(n.selected_root),o,[s],a).then(d=>(r.push(...d.warnings),ys(s.name,d.activation_failures,e.scope))):void 0;return c&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),i({extension:{name:s.name,directory:s.directory},active:t==="activate"&&c===void 0,runtime_active:t==="activate"&&c===void 0,activation_failure:c??null,settings_changed:l,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},c===void 0)},Du=(e,t,n,r,a,i)=>{let o=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],l=a?.adopted_entries.length??0,c=[[i!==null,i??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[l>0,`Managed-state fix adopted ${l} extension(s).`]];return[...new Set([...e,...c.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},_r=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,r)=>{if(e!=="project"||t||!_r(r))return null;let a=n==="package"?"package":"extension";return`Global ${a} registrations are included in project diagnostics. For hermetic ${a} smoke tests, rerun pm ${a} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Lu=(e,t,n)=>{if(String(e??"").trim().length>0)throw new f('Action "doctor" does not accept a target argument.',h.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new f("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let a=zo(n.detail),i=n.trace===!0;if([i,a!=="deep"].every(Boolean))throw new f("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:r,detailMode:a,includeTrace:i}},Fu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await wr(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},Mu=(e,t,n,r)=>{let a=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:_r(r),rerun_command:null,pm_global_path_recipe:null};let i=`pm ${a} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:_r(r),rerun_command:t?null:i,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${a} doctor --project --detail deep --trace`}},Gu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:a,options:i,global:o,withResult:s}=e,{isolated:l,detailMode:c,includeTrace:d}=Lu(t,n,i),p=await A(r.settings_root),m=await he(r.selected_root);a.push(...m.warnings);let g=await ye(r.selected_root,n,p,m.state);a.push(...g.warnings);let{state:y,fix:_}=await Fu(e,g.extensions,m.state),u=await ye(r.selected_root,n,p,y);a.push(...u.warnings);let w=await ke({pmRoot:r.pm_root,settings:p,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:l}),v=await xe({...w,loaded:w.loaded}),x=await ts(r.pm_root);a.push(...x.warnings,...w.warnings),a.push(...Mo(w.failed)),a.push(...v.warnings),a.push(...Go(v.failed)),a.push(...Uo(w,v)),a.push(...Ko(v,w)),a.push(...lu(w,v)),a.push(...Vo(v));let S=mn(u.extensions,w,v),O=Bo(n,S,w.loaded.map(C=>({layer:C.layer,name:C.name})),w.failed.map(C=>({name:C.name})),w.disabled_by_flag);a.push(...O.warnings);let oe=S.filter(C=>C.update_check_status==="failed").map(C=>`extension_update_check_failed:${C.name}`);a.push(...oe);let L=un(n,a,S,i);a.push(...L.warnings);let E=[...L.warnings],q={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},ot=qo(E),yn=Wo(),Cr=L.warning_codes,ec=ju(n,l,i.vocabulary,w),tc=Du(L.remediation,w.failed.length,v.failed.length,i.vocabulary,_,ec),Pr=Mu(n,l,i.vocabulary,w),nc={status:L.status,scope:n,warning_count:L.warning_count,warning_codes:Cr,total_extensions:S.length,managed_total:S.filter(C=>C.managed).length,enabled_total:S.filter(C=>C.enabled).length,active_total:S.filter(C=>C.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:S.filter(C=>C.runtime_active===!0).length,activation_status_totals:{ok:S.filter(C=>C.activation_status==="ok").length,failed:S.filter(C=>C.activation_status==="failed").length,not_loaded:S.filter(C=>C.activation_status==="not_loaded").length,unknown:S.filter(C=>C.activation_status==="unknown").length},unknown_capability_count:ot.length,capability_contract_version:yn.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:S.filter(C=>C.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:fr(w.failed),activation_failures:fr(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:O.warnings.length,trace_enabled:d,isolation:Pr,policy:q,remediation:tc},rc=_?{requested:!0,applied:_.adopted_entries.length>0,adopted_count:_.adopted_entries.length,already_managed_count:_.already_managed_count,adopted_extensions:_.adopted_entries.map(C=>C.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:u.extensions.filter(C=>C.managed).length,adopted_extensions:[]},_n={mode:c,summary:nc,triage:L,trace_enabled:d,capability_contract:yn,capability_guidance:ot,managed_state_fix:rc,author_manifest:x,isolation:Pr,policy:w.policy};if(c==="deep"){let C=d?v.failed:v.failed.map(D=>{let{trace:Cf,...ac}=D;return ac});_n.deep={warnings:E,warning_codes:Cr,capability_contract:yn,capability_guidance:ot,trace_enabled:d,managed_state:{path:m.path,count:y.entries.length,entries:y.entries},installed_extensions:S,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(D=>({layer:D.layer,directory:D.directory,name:D.name,version:D.version,entry:D.entry,priority:D.priority}))},activation:{failed:C,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:O.summary},d&&(_n.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(_n)},Uu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:a,options:i,global:o,withResult:s}=e,l=await A(r.settings_root),c=await ke({pmRoot:r.pm_root,settings:l,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),d=await xe(c);a.push(...c.warnings),a.push(...d.warnings);let p=lo(t,c,d);if(t!==void 0&&p.extensions.length===0){let m=i.vocabulary==="package"?"package":"extension",g=[...new Set(c.loaded.map(_=>i.vocabulary==="package"&&typeof _.source_package=="string"&&_.source_package.trim().length>0?_.source_package.trim():_.name))].sort((_,u)=>_.localeCompare(u)),y=g.length>0?` Loaded ${m} names: ${g.join(", ")}.`:"";throw new f(`No loaded ${m} named "${t}" was found in ${n} scope.${y} Run pm ${m} explore to list discovered ${m}s.`,h.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},zu=async(e,t,n)=>{let r=n,a=null;return[e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(a=await wr(e.resolvedRoots.selected_root,e.scope,t,n),r=a.state),e.action==="manage"&&(r=await Qo(r,e.options.offline)),{state:r,fix:a}},Ju=async(e,t,n)=>{let r=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),a=await xe({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...a.warnings),{installed:mn(n,r,a),failures:gs(a.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:a.failed.length,warning_count:[...new Set([...r.warnings,...a.warnings])].length,policy:r.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},is=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:a,options:i,withResult:o}=e,s=await A(r.settings_root),l=Jm(s.extensions.policy),c=await he(r.selected_root);a.push(...c.warnings);let d=await ye(r.selected_root,n,s,c.state);a.push(...d.warnings);let{state:p,fix:m}=await zu(e,d.extensions,c.state),g=await ye(r.selected_root,n,s,p);if(a.push(...g.warnings),t==="manage"&&i.offline===!0)for(let v of g.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=g.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);a.push(...v)}let y=await Ju(e,s,g.extensions),_=y.installed,u=un(n,a,_,i);a.push(...u.warnings);let w={total:_.length,managed_total:_.filter(v=>v.managed).length,enabled_total:_.filter(v=>v.enabled).length,active_total:_.filter(v=>v.active).length,extensions:_,triage:u,policy:l};return y.failures!==void 0&&(w.activation_diagnostics={failed_count:y.failures.length,failed:y.failures}),t==="explore"&&(w.runtime_probe=y.summary),t==="manage"&&(w.runtime_probe=y.summary,w.managed_state_fix=qu(m,_)),o(w)},os={init:hu,install:Ou,uninstall:Nu,explore:is,manage:is,describe:Uu,reload:gu,doctor:Gu,catalog:yu,adopt:Ru,"adopt-all":Cu,activate:as,deactivate:as,migrate:Na},Wu=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Bu=e=>Wu(e)?pr(e.resolvedRoots.settings_root,`${e.action}-state`,()=>os[e.action](e)):os[e.action](e);import xr from"node:fs/promises";import J from"node:path";import bs from"node:readline/promises";import{stdin as ks,stdout as At}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]="04a94059-e242-58a6-9138-bc48a24e267e")}catch{}})();var xs=["ask","add","skip","status"],Hu=["AGENTS.md","CLAUDE.md"],Ku=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Vu=8,Sr=1,Yu="<!-- pm-cli:agent-guidance:start:",Xu=`<!-- pm-cli:agent-guidance:start:v${Sr} -->`,br="<!-- pm-cli:agent-guidance:end -->",Ot="Add workflow guidance later: pm init --agent-guidance add",db={toPortableRelativePath:qe,ensureTrailingNewline:kr,detectLineEnding:Es,findGuidanceBlockRange:Er,buildAgentGuidanceBlock:$s,upsertAgentGuidanceBlock:$r,resolveProjectRoot:As,resolveTargetGuidancePath:Ts,parsePromptChoice:Os,pushUnique:We,promptForGuidanceWrite:Cs,normalizeAgentGuidanceState:Ir,applyAgentGuidanceState:Rs,writeGuidanceFile:Ar,setAgentGuidanceReadlineFactoryForTests:Zu},Ss=()=>bs.createInterface({input:ks,output:At});function Zu(e){Ss=e??(()=>bs.createInterface({input:ks,output:At}))}function qe(e,t){let n=J.relative(e,t);return n.length===0?J.basename(t):n.split(J.sep).join("/")}function kr(e){return e.endsWith(`
50
+ `)?e:`${e}
51
+ `}function Es(e){return e.includes(`\r
52
+ `)?`\r
53
+ `:`
54
+ `}function Er(e){let t=e.indexOf(Yu);if(t===-1)return null;let n=e.indexOf(br,t);return n===-1?null:{start_index:t,end_index:n+br.length}}function Qu(e){return Er(e)!==null}function $s(e,t="<your project test command>"){return[Xu,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and start atomically: `pm claim <id> --start`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",br,""].join(e)}function $r(e,t="<your project test command>"){let n=Es(e),r=$s(n,t),a=Er(e);if(a){let s=e.slice(a.end_index),l=s.startsWith(`\r
55
+ `)?s.slice(2):s.startsWith(`
56
+ `)?s.slice(1):s,c=kr(`${e.slice(0,a.start_index)}${r}${l}`);return{next_content:c,changed:c!==e}}let i=e.length===0?"":e.endsWith(`
57
+ `)?`
58
+ `:`
59
+
60
+ `,o=kr(`${e}${i}${r}`);return{next_content:o,changed:o!==e}}async function Is(e){if(await k(J.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await xr.readFile(J.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=ef(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await k(J.join(e,"pnpm-lock.yaml"))?"pnpm test":await k(J.join(e,"bun.lock"))||await k(J.join(e,"bun.lockb"))?"bun run test":await k(J.join(e,"yarn.lock"))?"yarn test":"npm test"}function ef(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 As(e,t){let n=J.dirname(e);return J.basename(e)==="pm"&&J.basename(n)===".agents"?J.dirname(n):J.resolve(t,e)}function Ts(e,t){let n=e.find(a=>J.basename(a.file_path)==="AGENTS.md"&&a.exists);if(n)return n.file_path;let r=e.find(a=>a.exists);return r?r.file_path:J.join(t,"AGENTS.md")}function Os(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=Ss();try{At.write(`
61
+ Agent guidance check
62
+ `),At.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
63
+ `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return At.write(`
64
+ `),Os(n,!0)}finally{t.close()}}function Ir(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:Sr,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function Ps(e){let t=[],n=await Is(e);for(let r of Hu){let a=J.join(e,r),i=await k(a);if(!i){t.push({file_path:a,exists:i,has_guidance:!1,has_marker:!1});continue}let o=await xr.readFile(a,"utf8"),s=o.toLowerCase(),l=Ku.filter(d=>s.includes(d)),c=Qu(o);t.push({file_path:a,exists:i,has_guidance:c||l.length>=Vu,has_marker:c,outdated:c&&$r(o,n).changed})}return t}function We(e,t){e.includes(t)||e.push(t)}function Rs(e,t){let n=Ir(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function Ar(e,t=J.dirname(e)){let n=await k(e)?await xr.readFile(e,"utf8"):"",r=$r(n,await Is(t));return r.changed?(await se(e,r.next_content),{changed:!0,warnings:await H({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function tf(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 nf(e,t,n){return e?await Ps(n):t}function Tt(e,t,n){e.state={...e.state,...n,template_version:Sr,last_checked_files:t}}async function Ns(e,t){if(t.presentBefore)return;let n=await Ar(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function rf(e,t){t||(e.warnings.push("agent_guidance:missing"),We(e.nextSteps,Ot))}function af(e,t){e.skipped=!0,Tt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),We(e.nextSteps,Ot)}async function of(e,t){await Ns(e,t),Tt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function sf(e,t){e.state.declined&&Tt(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function cf(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),We(e.nextSteps,Ot)}async function lf(e,t){if(e.prompted=!0,await Cs(t.targetRelativePath)){await Ns(e,t),Tt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,Tt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),We(e.nextSteps,Ot)}function df(e){e.warnings.push("agent_guidance:missing_non_interactive"),We(e.nextSteps,Ot)}async function pf(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(rf(n,t.presentBefore),n):t.mode==="skip"?(af(n,t.checkedFiles),n):t.mode==="add"?(await of(n,t),n):t.presentBefore?(sf(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(cf(n),n):t.interactive?(await lf(n,t),n):(df(n),n)}async function Ds(e){let t=As(e.pm_root,e.cwd),n=await Ps(t),r=Ts(n,t),a=qe(t,r),i=n.map(d=>qe(t,d.file_path)),o=n.some(d=>d.has_guidance),s=await pf(Ir(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:a,checkedFiles:i,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let d of n.filter(p=>p.outdated)){let p=await Ar(d.file_path,t);s.applied||=p.changed,s.warnings.push(...p.warnings)}let l=Rs(e.settings,s.state);n=await nf(s.applied,n,t);let c=n.filter(d=>d.outdated).map(d=>qe(t,d.file_path));return c.length>0&&(s.warnings.push(`agent_guidance_outdated:${c.join(",")}`),We(s.nextSteps,"pm init --agent-guidance add")),{summary:tf({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:a,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:l.changed}}import mf from"node:fs/promises";import F from"node:path";import Ls from"node:readline/promises";import{stdin as Fs,stdout as ee}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]="95053097-fc76-5587-ab41-8cb05b9d3cd9")}catch{}})();var uf=Symbol.for("pm.sdk.init-invocation-cwd");function Nb(e,t=!1){if(t){let n=e.warnings.filter(r=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(r));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:`${st(["--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 Db={normalizeInitGovernancePreset:Tr,normalizeInitTypePreset:Gs,normalizeOptionalInitAuthor:Us,normalizeInitAgentGuidanceMode:qs,isPathLikeInitTarget:gn,resolveInitInvocation:zs,resolveInitPrefixInput:Js,parseYesNoChoice:Ws,applyGovernancePreset:Or,runInitWizard:Xs,setInitReadlineFactoryForTests:ff,summarizeInstalledPackages:Bs,buildInitNextSteps:Zs,registerInitTypePreset:Hs,assertExplicitTrackerPathIsNotWorkspaceRoot:Vs,isLikelyWorkspaceRoot:Ks,installInitMergeFence:Qs},Ms=()=>Ls.createInterface({input:Fs,output:ee});function ff(e){Ms=e??(()=>Ls.createInterface({input:Fs,output:ee}))}function hf(){return structuredClone(vn)}var gf=["minimal","default","strict"];function Tr(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: ${gf.join(", ")}`,h.USAGE)}function Gs(e){if(e!==void 0){if(e.trim().length===0)throw new f("--type-preset must not be empty",h.USAGE);try{return cn(e)}catch{throw new f(`Invalid --type-preset value "${e}". Allowed: ${St.join(", ")}`,h.USAGE)}}}function Us(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 gn(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:F.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function zs(e,t,n,r){let a=r?.trim();if(r!==void 0&&a?.length===0)throw new f("--workspace must not be empty",h.USAGE);if(a!==void 0){if(t.path!==void 0||gn(n))throw new f("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",h.USAGE);let c=F.resolve(e,a),d=F.join(c,".agents","pm");return{pmRoot:d,prefixArg:n,target:{mode:"workspace-path",tracker_root:d,workspace_root:c}}}if(t.path===void 0&&gn(n)){let c=F.resolve(e,n.trim());return{pmRoot:c,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:c}}}let i=N(e,t.path),o=F.join(F.resolve(e),".agents","pm"),s=F.dirname(F.dirname(i)),l=F.resolve(i)===o?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:l,requested_cwd:F.resolve(e),...l==="ancestor"?{suggested_current_tracker_root:o}:{}}:{mode:"tracker-path",tracker_root:i}}}function Js(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(gn(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&&$e(e)!==$e(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 ${$e(e)}`,`pm init --id-prefix ${$e(t)}`]});return t}function qs(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: ${xs.join(", ")}`,h.USAGE)}function Ws(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Or(e,t){let n=Lr[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function yf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bs(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(yf).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Hs(e,t,n){let r=V(t.schema),a=ae(e,r.files.types,Z.types),i=le(await G(a)),o=[],s=[];for(let l of Et(n)){let c=He(i,l);i=c.file,(c.replaced?s:o).push(c.definition.name)}return await Be({pmRoot:e,filePath:a,raw:ue(i),op:"init:type-preset",author:B(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:o,updated:s,file:a}}async function Ks(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",F.join(".agents","pm")];for(let n of t)if(await k(F.join(e,n)))return!0;return!1}async function Vs(e,t,n){if(!t||n||await k(F.join(e,"settings.json"))||!await Ks(e))return;let r=F.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 ${r} 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 ${r} init --yes`}})}async function Ys(e,t){let n=[],r=[];for(let a of t){let i=a?F.join(e,a):e,o=await k(i);await mf.mkdir(i,{recursive:!0}),o?r.push(`already_exists:${i}`):n.push(i),r.push(...await H({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function Xs(e,t){let n=Ms();try{ee.write(`pm init setup wizard (agent-optimized)
65
+ `),ee.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
66
+
67
+ `),ee.write(`1/3 Item ID prefix
68
+ `),ee.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
69
+ `);let r=await n.question(`Item ID prefix [${e}]: `),a=r.trim().length>0?$e(r):e;ee.write(`
70
+ 2/3 Governance preset
71
+ `),ee.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
72
+ `),ee.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
73
+ `),ee.write(`strict: ownership blocking, strict create defaults, close validation strict.
74
+ `);let i=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),o=i.trim().length>0?i.trim():"minimal",s="minimal";try{s=Tr(o)}catch{ee.write(`Unrecognized governance preset "${o}"; using minimal.
75
+ `)}ee.write(`
76
+ 3/3 Project telemetry
77
+ `),ee.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
78
+ `);let l=t?"Y/n":"y/N",c=await n.question(`Enable telemetry for this project? [${l}] `),d=Ws(c,t);return ee.write(`
79
+ `),{prefix:a,preset:s,telemetry_enabled:d}}finally{n.close()}}function _f(e){return{presetFromOption:Tr(e.preset),useDefaults:e.defaults===!0,authorFromOption:Us(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:qs(e.agentGuidance),typePreset:Gs(e.typePreset)}}function wf(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 vf(e,t,n,r){if(t.length===0||n)return;let a=r.discovery==="ancestor";throw new f(`${a?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.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:a?"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:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...a?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...a?['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 bf(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&&(Or(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 kf(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=wf({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return vf(e.settingsPath,n,e.options.force===!0,e.target),bf({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Ee(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function xf(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,a=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let l=await Xs(t,vn.telemetry.enabled);t=l.prefix,n=l.preset,r=l.telemetry_enabled,a=!0}let i=n??"minimal",o=hf();o.id_prefix=t,Or(o,i);let s=ca()?.trim()||void 0;return o.author_default=e.normalizedOptions.authorFromOption??s??"",r!==void 0&&(o.telemetry.enabled=r,o.telemetry.first_run_prompt_completed=!0),await Ee(e.pmRoot,o),{settings:o,normalizedPrefix:t,chosenPreset:n,wizardUsed:a}}async function js(e){return e.settingsExists?await kf(e):await xf({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function Sf(e){let t=await Ds({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 Ee(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function Ef(e,t){let n=[],r=[],a=await sa(e,t.schema);for(let i of a.created_paths)n.push(i),r.push(...await H({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function $f(e){if(e.typePreset===void 0)return;let t=await Hs(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await H({path:t.file,scope:"project",op:"init:type_preset"})),t}async function If(e){let t=U(e.settings,W()).folders.filter(r=>!wn.includes(r)),n=await Ys(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function Af(e){let t=F.resolve(e.tracker_root),n=F.dirname(t);return F.basename(t)==="pm"&&F.basename(n)===".agents"?F.dirname(n):e.workspace_root}async function Tf(e,t,n,r){if(!e)return;let a=await vr("all",{install:!0,project:!0},{...t,path:n});r.push(...a.warnings);let i=Bs(a),o=i.packages.filter(s=>!s.ok).map(s=>s.alias);if(!i.installed_all||o.length>0)throw new f(`pm init --with-packages did not install all bundled packages successfully${o.length>0?`: ${o.join(", ")}`:"."}`,h.GENERIC_FAILURE);return i}function Zs(e){let t=r=>st([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),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 r of e.agentGuidanceNextSteps){let a=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(a)||n.push(a)}return n}async function Qs(e,t,n,r=Jn){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 a=await r({pmRoot:e,workspaceRoot:t});a.gitattributes.changed&&n.push(`updated:merge_fence:${a.gitattributes.path}`)}catch(a){if(!(a instanceof f))throw a;n.push(`merge_fence_skipped:install_failed:${a.context.code??"pm_error"}:${a.message}:run pm merge install after resolving the Git repository error`)}}async function Of(e,t,n,r){if(e==null||n==="status")return;let a=await Ma(e,{pmRoot:t});a.changed&&r.push(`updated:gitignore:${a.path}`)}async function jb(e,t,n={}){let r=t[uf],a=typeof r=="string"?r:process.cwd(),i=zs(a,t,e,n.workspace),o=i.pmRoot;e=Js(i.prefixArg,n.idPrefix);let s=_f(n);await Vs(o,i.target.mode==="tracker-path",n.force===!0);let l=[],c=[],d=F.join(o,"settings.json"),p=await k(d),m;p&&(m=await js({pmRoot:o,settingsPath:d,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:i.target}));let g=await Ys(o,wn);l.push(...g.createdDirs),c.push(...g.warnings),m??=await js({pmRoot:o,settingsPath:d,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:i.target});let{settings:y}=m,_=Af(i.target),u=await Bt(_??F.dirname(o)),w=_??u,v=await Sf({pmRoot:o,cwd:w??a,agentGuidanceMode:s.agentGuidanceMode,settings:y,warnings:c}),x=await Ef(o,y);l.push(...x.createdDirs),c.push(...x.warnings);let S=await $f({pmRoot:o,settings:y,typePreset:s.typePreset,warnings:c});S&&(y=await A(o)),await If({pmRoot:o,settings:y,createdDirs:l,warnings:c}),await Of(w,o,s.agentGuidanceMode,c),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await Qs(o,u,c);let O=await Tf(s.installBundledPackages,t,o,c),oe=Zs({installBundledPackages:s.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:v.next_steps,target:i.target});return{ok:!0,path:o,target:i.target,settings:y,created_dirs:l,warnings:c,governance_preset:y.governance.preset,wizard_used:m.wizardUsed,...S?{registered_type_preset:S}:{},...O?{installed_packages:O}:{},next_steps:oe,agent_guidance:v}}export{Tn as a,pc as b,Ca as c,Pn as d,kc as e,xc as f,Sc as g,Na as h,Hp as i,ja as j,Rn as k,Ic as l,Tc as m,Ma as n,Ke as o,Cc as p,Pc as q,Ua as r,qt as s,Fe as t,Ut as u,Fn as v,Uc as w,zc as x,ah as y,Wt as z,Yc as A,mt as B,Ka as C,tl as D,Bt as E,zn as F,ei as G,Ch as H,Ph as I,ti as J,Rh as K,Jn as L,hi as M,Qe as N,et as O,gi as P,mi as Q,Xe as R,Ze as S,ui as T,al as U,jh as V,Gh as W,ri as X,sl as Y,rg as Z,ki as _,$i as $,Bl as aa,Hl as ba,iw as ca,cw as da,lw as ea,$t as fa,dw as ga,pw as ha,mw as ia,uw as ja,fw as ka,hw as la,gw as ma,yw as na,_w as oa,ww as pa,vw as qa,bw as ra,kw as sa,xw as ta,Sw as ua,Ew as va,$w as wa,Iw as xa,Aw as ya,Tw as za,Ow as Aa,Cw as Ba,Pw as Ca,Rw as Da,Nw as Ea,te as Fa,b as Ga,Yn as Ha,dd as Ia,he as Ja,Vt as Ka,Kl as La,ft as Ma,Yt as Na,Ui as Oa,Yi as Pa,lr as Qa,lo as Ra,Xy as Sa,hm as Ta,qo as Ua,Wo as Va,hr as Wa,ko as Xa,zp as Ya,Om as Za,So as _a,vr as $a,xs as ab,db as bb,Ds as cb,uf as db,Nb as eb,Db as fb,jb as gb};
80
+ //# sourceMappingURL=chunk-4WB55TBC.js.map