@unbrained/pm-cli 2026.11.18 → 2026.11.19

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 (93) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli-bundle/bundle-manifest.json +1 -1
  3. package/dist/cli-bundle/chunks/chunk-2UTJ5QIE.js +71 -0
  4. package/dist/cli-bundle/chunks/{chunk-T3E3WNHO.js → chunk-4FNMPZ7Y.js} +2 -2
  5. package/dist/cli-bundle/chunks/{chunk-2VH6COJE.js → chunk-723PMYNX.js} +37 -37
  6. package/dist/cli-bundle/chunks/{chunk-S3RMFLEG.js → chunk-AGPFANRX.js} +3 -3
  7. package/dist/cli-bundle/chunks/{chunk-TS2CZE3O.js → chunk-AMHD7WIV.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-VETSGCF4.js → chunk-AOV5HG3Y.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-WKHS4QC6.js → chunk-CNMGGAZO.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-LGWP5D7V.js → chunk-CTOE26W4.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-7LCJA54R.js → chunk-GQCMICAL.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-JBPXNG6P.js → chunk-IQKCRLQP.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-SSZBVRIN.js → chunk-IUTN67EB.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-7ETRLLK3.js → chunk-M76BEWTT.js} +30 -30
  15. package/dist/cli-bundle/chunks/{chunk-TA5VN4ME.js → chunk-N2CPCFSN.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-MUGGRKK3.js → chunk-NMVPQTZI.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-YJI2Y5N6.js → chunk-O7IFAJ76.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-CGTVDSAR.js → chunk-OESI2ETD.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-FJQCORYR.js → chunk-P4A5RFLX.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-L2ZLH3LZ.js → chunk-PRVT7ITI.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-XDIJK6VW.js → chunk-Q32Q3LRH.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-AGU7632B.js → chunk-XPBPGDFW.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-QK7RAN7R.js → chunk-Z5LHCEXG.js} +2 -2
  24. package/dist/cli-bundle/chunks/{item-revision-BV5BUBCR.js → item-revision-YJKGOYBR.js} +2 -2
  25. package/dist/cli-bundle/chunks/item-transaction-K4YZ7GWR.js +2 -0
  26. package/dist/cli-bundle/chunks/{mutation-admission-5AWMXMCB.js → mutation-admission-JLMQJ2M5.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-list-query-RJT7YBRF.js → register-list-query-4AXLLXK7.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-mutation-6KTMJGYF.js → register-mutation-FJIXGGF4.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-operations-W24TA3HZ.js → register-operations-W4E2KEMA.js} +2 -2
  30. package/dist/cli-bundle/chunks/{register-setup-QK67WUX6.js → register-setup-RYRIBNSN.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-LZR3JKYT.js → chunk-2XULTI5B.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-3H3SVHAT.js → chunk-4S7I342K.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-6OZ7BKWJ.js → chunk-77CDWGBW.js} +55 -54
  34. package/dist/cli-bundle/focused-chunks/{chunk-IGMFXB5W.js → chunk-7A4VIRIU.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-EO4XM3XJ.js → chunk-D72EQN7Z.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-PNCCTZKI.js → chunk-GAOWBALE.js} +23 -23
  37. package/dist/cli-bundle/focused-chunks/{chunk-T3NMYMW4.js → chunk-N64BUB63.js} +24 -24
  38. package/dist/cli-bundle/focused-chunks/{chunk-DWCFZVT2.js → chunk-OF4UM5B6.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-ONHUG7IL.js → chunk-P4TG4VMJ.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{item-revision-NS2V4WON.js → item-revision-32HFGFYG.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{item-transaction-NENC4HYI.js → item-transaction-C4VW3SHX.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{mutation-admission-DZIBDJAE.js → mutation-admission-PNK6ORZR.js} +2 -2
  43. package/dist/cli-bundle/main.js +2 -2
  44. package/dist/cli-bundle/sdk-authoring.js +1 -1
  45. package/dist/cli-bundle/sdk-core.js +1 -1
  46. package/dist/cli-bundle/sdk-governance.js +1 -1
  47. package/dist/cli-bundle/sdk-merge.js +53 -53
  48. package/dist/cli-bundle/sdk-query.js +1 -1
  49. package/dist/cli-bundle/sdk-runtime.js +1 -1
  50. package/dist/cli-bundle/sdk-testing.js +1 -1
  51. package/dist/cli-bundle/sdk.js +11 -11
  52. package/dist/core/shared/process-tree.js +3 -0
  53. package/dist/core/shared/secret-rules.d.ts +12 -1
  54. package/dist/core/shared/secret-rules.js +2 -2
  55. package/dist/sdk/extension/managed-state.d.ts +3 -1
  56. package/dist/sdk/extension/managed-state.js +1 -1
  57. package/dist/sdk/extension/managed-update-status.js +1 -1
  58. package/dist/sdk/extension/update-check.d.ts +42 -6
  59. package/dist/sdk/extension/update-check.js +1 -1
  60. package/dist/sdk/extension.d.ts +3 -1
  61. package/dist/sdk/extension.js +1 -1
  62. package/dist/sdk/index.d.ts +1 -1
  63. package/dist/sdk/index.js +1 -1
  64. package/dist/sdk/mutation-guard.d.ts +121 -1
  65. package/dist/sdk/mutation-guard.js +1 -1
  66. package/dist/sdk/public-surface.json +1 -1
  67. package/dist/sdk/test/execution.js +2 -2
  68. package/docs/CONFIGURATION.md +1 -0
  69. package/docs/MUTATION_INTEGRITY.md +72 -0
  70. package/docs/PACKAGE_EVIDENCE.md +66 -0
  71. package/marketplace.json +1 -1
  72. package/package.json +1 -1
  73. package/packages/pm-beads/package.json +1 -1
  74. package/packages/pm-calendar/package.json +1 -1
  75. package/packages/pm-command-kit/package.json +1 -1
  76. package/packages/pm-digital-twin/package.json +1 -1
  77. package/packages/pm-governance-audit/package.json +1 -1
  78. package/packages/pm-guide-shell/package.json +1 -1
  79. package/packages/pm-kanban/package.json +1 -1
  80. package/packages/pm-lifecycle-hooks/package.json +1 -1
  81. package/packages/pm-linked-test-adapters/package.json +1 -1
  82. package/packages/pm-search-advanced/package.json +1 -1
  83. package/packages/pm-templates/package.json +1 -1
  84. package/packages/pm-todos/package.json +1 -1
  85. package/packages/pm-vcs/package.json +1 -1
  86. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  87. package/plugins/pm-claude/package.json +1 -1
  88. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  89. package/plugins/pm-codex/package.json +1 -1
  90. package/plugins/pm-codex/plugin.json +1 -1
  91. package/runtime-dependencies.json +1 -1
  92. package/dist/cli-bundle/chunks/chunk-OD2I3SFQ.js +0 -70
  93. package/dist/cli-bundle/chunks/item-transaction-E2ST3A3X.js +0 -2
@@ -0,0 +1,71 @@
1
+ import{i as ya,n as _a,p as wa}from"./chunk-H64BNM4A.js";import{f as ga}from"./chunk-Y4LXVPA5.js";import{lc as Dt}from"./chunk-AOV5HG3Y.js";import{$a as sa,Ab as wn,Ca as na,Da as Ne,Ea as ot,Fa as ia,Ga as aa,Ha as ae,Ia as ze,Ja as ra,Ka as ce,R as ji,Vc as vn,ab as ca,bb as Ie,cb as da,db as la,ec as fa,hb as pa,ia as $e,nb as ma,od as ha,qb as Rt,rb as Nt,ub as De,zb as ua}from"./chunk-723PMYNX.js";import{I as Ge,a as Zi,b as Qi,d as yn,e as ea,f as ta,g as Ee,m as oa,p as he,r as _n,v as I,w as ge}from"./chunk-CR5GC3VO.js";import{$h as Gi,Ac as Mi,Cc as rt,Ec as Ot,H as Ai,Hi as gn,Ia as Oi,Ii as Ki,Ja as Ci,Ji as Ct,Ka as W,Lb as Di,Li as Se,Ni as xe,Qi as Vi,Sa as F,Si as Pt,Ta as Pi,Ti as Yi,Ua as Pe,Ui as Xi,Va as Ri,Vd as Ui,Xb as A,Xh as ke,ae as J,ai as Ji,ce as zi,cj as q,di as qi,e as It,ei as Wi,f as xi,fa as At,g as pn,ga as fn,gc as Li,h as mn,ha as hn,i as un,ib as H,k as Ei,kb as Ni,l as $i,lb as se,mi as Bi,nj as B,o as Ii,oi as Hi,ri as Re,uc as T,vc as V,wc as Fi,xc as K,y as Ti,yc as Q,zd as ee}from"./chunk-7UUPLMCU.js";import{A as h,C as u,E as k,F as Tt,G as be,H as M,K as fe,a as vi,d as $t,m as bi,t as ln,v as ki,y as Si}from"./chunk-5OFMWP3Q.js";import{AsyncLocalStorage as rc}from"node:async_hooks";import va 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]="c8fb265a-c747-5387-8504-adfa325b14d5")}catch{}})();var ba=new rc;function ka(e,t){return ba.run({...e,pmRoot:va.resolve(e.pmRoot)},t)}function Of(e,t){let n=ba.getStore();return n!==void 0&&n.pmRoot===va.resolve(e)&&n.transactionId===t?n.step:void 0}import{mkdir as oc,readFile as sc}from"node:fs/promises";import xa from"node:path";import{createHash as cc}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f100554a-d0e9-54c1-9dca-7ea5b79b0dc2")}catch{}})();var bn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Ea="sdk-workspace-transaction",$a=/^[a-zA-Z0-9._-]+$/,Ia=30,Ta=3e3;function $n(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!$a.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function kn(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 In(e){return{pmRoot:kn(e.pmRoot,"Transaction pmRoot"),transactionId:$n(e.transactionId,"Transaction id"),author:kn(e.author,"Transaction author")}}function jt(e,t,n){let i=e??t;if(!Number.isInteger(i)||i<=0)throw new TypeError(`${n} must be a positive integer`);return i}function Aa(e,t){return xa.join(e,"transactions","sdk",`${t}.json`)}async function de(e,t){t.updatedAt=A();let n=Aa(e,t.transactionId);await oc(xa.dirname(n),{recursive:!0}),await fe(n,`${JSON.stringify(t,null,2)}
2
+ `)}function dc(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"&&lc(e)}function lc(e){let t=e.abandonment;return t===void 0?e.schemaVersion===1&&e.status!=="abandoned":e.schemaVersion!==2||t===null||typeof t!="object"||e.status==="committed"?!1:typeof t.reason=="string"&&t.reason.trim().length>0&&typeof t.author=="string"&&t.author.trim().length>0&&(t.supersededBy===void 0||typeof t.supersededBy=="string"&&$a.test(t.supersededBy)&&t.supersededBy!==e.transactionId)}function Le(e){return Object.assign(Object.create(null),e)}function Oa(e,t){try{let n=JSON.stringify(e,(i,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 Sn(e,t){return e===void 0?void 0:Oa(e,t)}function xn(e,t,n,i){let a=Sn(n,i);a===void 0?delete e[t]:e[t]=a}function Sa(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function En(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function pc(e,t){if(!En(e.startedStepIds,t)||!En(e.completedStepIds,t)||!Sa(e.results)||!Sa(e.compensationData))return!1;let n=e.startedStepIds,i=new Set(n),a=e.completedStepIds,r=new Set(a);return Object.keys(e.compensationData).some(o=>!i.has(o))||Object.keys(e.results).some(o=>!r.has(o))?!1:e.status==="committed"?t.every(o=>r.has(o)):!["compensated","abandoned"].includes(e.status??"")||r.size===0&&i.size===0}function Lt(e,t){return new u(`Workspace transaction ${e} journal is invalid (${t})`,h.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function Ca(e){return new u(`Workspace transaction ${e} journal does not match the supplied plan`,h.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function mc(e,t,n){return n===void 0||e.abandonment!==void 0||e.status==="compensated"||t.length===n.length&&t.every((i,a)=>i===n[a])}function uc(e,t,n){let i;try{i=JSON.parse(e)}catch{throw Lt(t,"invalid JSON")}if(!i||typeof i!="object"||Array.isArray(i))throw Lt(t,"expected an object");let a=i;if(!((a.schemaVersion===1||a.schemaVersion===2)&&a.transactionId===t))throw Lt(t,"schema version or transaction id does not match the journal file");let r=a.stepIds;if(!Array.isArray(r)||!En(r,r)||!pc(a,r)||!dc(a)||typeof a.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(a.status))throw Lt(t,"invalid lifecycle, metadata, status or step ids");if(!mc(a,r,n))throw Ca(t);return{...a,results:Le(a.results),compensationData:Le(a.compensationData)}}async function fc(e,t,n,i,a){let r=a,o=r!==void 0;if(r?.status==="compensating"&&await Tn(e,r),r===void 0||r.status==="compensated"){let s=A();r={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(r?.attempt??0)+1,createdAt:r?.createdAt??s,updatedAt:s,stepIds:i,startedStepIds:[],completedStepIds:[],results:Le(),compensationData:Le(),...e.recoveryData===void 0?{}:{recoveryData:Oa(e.recoveryData,"Transaction recovery data")}},await de(e.pmRoot,r),await ye(e,r,"prepared")}return{journal:r,recovered:o}}async function hc(e,t,n){try{await gc(t,e.steps),await de(e.pmRoot,t);let i=new Set(t.completedStepIds),a=new Set(t.startedStepIds);for(let r of e.steps){if(i.has(r.id))continue;let o=await r.inspect(),s=Sn(o.result,`Step ${r.id} result`);if(o.state!=="applied"){let d=await r.prepareCompensation?.();xn(t.compensationData,r.id,d,`Step ${r.id} compensation data`),a.add(r.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>a.has(l)),await de(e.pmRoot,t);let c=await r.apply();s=Sn(c,`Step ${r.id} result`)}await ye(e,t,"step_applied",r.id),i.add(r.id),t.completedStepIds=e.steps.map(d=>d.id).filter(d=>i.has(d)),xn(t.results,r.id,s,`Step ${r.id} result`),await de(e.pmRoot,t),await ye(e,t,"step_recorded",r.id)}return await ye(e,t,"committing"),t.status="committed",await de(e.pmRoot,t),await ye(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Le(t.results)}}catch(i){if(i instanceof bn||t.status==="committed")throw i;try{await Tn(e,t)}catch(a){throw new AggregateError([i,a],`Workspace transaction failed and compensation failed: ${String(a)}`,{cause:a})}throw i}}async function Ft(e,t,n){try{return uc(await sc(Aa(e,t),"utf8"),t,n)}catch(i){if(i!==null&&typeof i=="object"&&"code"in i&&be(i))return;throw i}}async function ye(e,t,n,i){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...i===void 0?{}:{stepId:i}})}async function gc(e,t){let n=new Set,i=Le();for(let a of t){let r=await a.inspect();r.state==="applied"&&(n.add(a.id),xn(i,a.id,r.result,`Step ${a.id} result`))}e.results=i,e.completedStepIds=t.map(a=>a.id).filter(a=>n.has(a))}async function Tn(e,t){t.status="compensating",await de(e.pmRoot,t),await ye(e,t,"compensating");let n=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let a of[...e.steps].reverse()){if(!i.has(a.id)&&!n.has(a.id))continue;let r;try{let o=(await a.inspect()).state;r=i.has(a.id)&&(o==="applied"||o==="pending"&&a.compensatePending===!0)}catch{r=i.has(a.id)}r&&(await ye(e,t,"step_compensating",a.id),await ka({pmRoot:e.pmRoot,transactionId:t.transactionId,step:a},()=>a.compensate(t.compensationData[a.id]))),n.delete(a.id),i.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=>i.has(o)),delete t.results[a.id],delete t.compensationData[a.id],await de(e.pmRoot,t),await ye(e,t,"step_compensated",a.id)}t.status="compensated",await de(e.pmRoot,t),await ye(e,t,"compensated")}async function Pa(e){let{pmRoot:t,transactionId:n,author:i}=In(e),a=jt(e.lockTtlSeconds,Ia,"Transaction lock TTL"),r=jt(e.lockWaitMs,Ta,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(l=>{let p=$n(l.id,"Transaction step id");if(p!==l.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 d={...e,pmRoot:t,transactionId:n,author:i,steps:o,lockTtlSeconds:a,lockWaitMs:r},c=await ee(t,Ea,a,i,!1,!1,r);try{let l=await Ft(t,n,s);if(l?.status==="abandoned"||l?.abandonment!==void 0)throw Ra(l);let p=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Le(l.results)};let m=await fc(d,n,i,s,l);return await hc(d,m.journal,p||m.recovered)}finally{await c()}}function Ra(e){let t=e.status!=="abandoned",n=e.abandonment.supersededBy,i=n===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(e.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(n)} to finish retirement of ${JSON.stringify(e.transactionId)}.`;return new u(t?`Transaction ${e.transactionId} retirement is incomplete`:`Transaction ${e.transactionId} has been abandoned`,h.CONFLICT,{code:"transaction_abandoned",required:t?i:"Use a new transactionId for the replacement plan.",why:t?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...t?{retirement:{state:"pending",superseded_by:n??null},nextSteps:[i]}:{}})}async function Jf(e,t){let n=In({pmRoot:e,transactionId:t,author:"reader"});return Ft(n.pmRoot,n.transactionId)}function yc(e){return cc("sha256").update(JSON.stringify(e.stepIds)).digest("hex")}async function qf(e){let t=In(e),n=kn(e.reason,"Abandonment reason"),i=e.supersededBy===void 0?void 0:$n(e.supersededBy,"Replacement transaction id");if(i===t.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");let a=jt(e.lockTtlSeconds,Ia,"Transaction lock TTL"),r=jt(e.lockWaitMs,Ta,"Transaction lock wait"),o=await ee(t.pmRoot,Ea,a,t.author,!1,!1,r);try{let s=await Ft(t.pmRoot,t.transactionId);if(s===void 0)throw new u(`Transaction ${t.transactionId} was not found`,h.NOT_FOUND);if(s.status==="committed")throw new u(`Transaction ${t.transactionId} is committed and cannot be abandoned`,h.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(s.abandonment!==void 0&&s.abandonment.supersededBy!==i)throw Ra(s);if(s.status==="abandoned")return s;let d=e.resolveSteps(structuredClone(s));if(JSON.stringify(d.map(c=>c.id))!==JSON.stringify(s.stepIds))throw Ca(t.transactionId);if(s.abandonment===void 0){if(i!==void 0&&await Ft(t.pmRoot,i)!==void 0)throw new u(`Replacement transaction ${i} already exists`,h.CONFLICT);s.schemaVersion=2,s.abandonment={reason:n,author:t.author,...i===void 0?{}:{supersededBy:i}},await de(t.pmRoot,s)}return s.status!=="compensated"&&await Tn({...e,...t,steps:d},s),await _c(s,t.pmRoot,a,r),s.status="abandoned",await de(t.pmRoot,s),s}finally{await o()}}async function _c(e,t,n,i){let a=yc(e);if((await zi(Qi(t),Zi)).some(o=>o.op==="transaction_abandon"&&o.context?.transaction_id===e.transactionId&&o.context?.attempt===e.attempt&&o.context?.plan_digest===a))return;let r=e.abandonment;await ea({pmRoot:t,author:r.author,lockTtlSeconds:n,lockWaitMs:i,op:"transaction_abandon",message:r.reason,context:{transaction_id:e.transactionId,attempt:e.attempt,plan_digest:a,...r.supersededBy===void 0?{}:{superseded_by:r.supersededBy}}})}import wc from"node:fs/promises";import vc 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 An(e){return vc.join(e,"extension-migrations.json")}function Na(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 Da(e,t){return`${e.layer}:${e.name}:${t}`}async function bc(e){let t=An(e);if(!await k(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await wc.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(i=>typeof i?.key=="string"&&(i.status==="applied"||i.status==="failed")):[]}}async function kc(e,t){let n=await bc(e),i=new Map(n.entries.map(a=>[a.key,a]));return t.forEach((a,r)=>{let o=Na(a,r),s=i.get(Da(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 kc(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),i=[],a=!1,r=e.migrations.map((l,p)=>({migration:l,index:p})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:p}of r){let m=Na(l,p),y=Da(l,m),g=n.get(y),_=String(l.definition.status??"pending").toLowerCase(),f=g?.status??(_==="applied"||_==="failed"?_:"pending");if(f==="applied"){i.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"skipped"});continue}if(e.dryRun===!0){i.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){i.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:f}));let S={key:y,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(y,S),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,i.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"applied"}),a=!0}catch(S){let x=S instanceof Error?S.message:String(S),C={key:y,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:x};n.set(y,C),l.definition.status="failed",l.definition.reason=x,i.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"failed",error:x}),a=!0}}if(a){let l=await I(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,y)=>m.key.localeCompare(y.key))};await Ee({pmRoot:e.pmRoot,filePath:An(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
3
+ `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let o=i.filter(l=>l.outcome==="pending").length,s=i.filter(l=>l.outcome==="applied").length,d=i.filter(l=>l.outcome==="skipped").length,c=i.filter(l=>l.outcome==="failed").length;return{ok:c===0,dry_run:e.dryRun===!0,state_path:An(e.pmRoot),total:i.length,pending_count:o,applied_count:s,skipped_count:d,failed_count:c,migrations:i}}async function La(e){let t=await I(e.resolvedRoots.settings_root),n=await Se({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await xe(n);e.warnings.push(...n.warnings,...i.warnings);let a=await Sc({pmRoot:e.resolvedRoots.pm_root,migrations:i.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:i.failed.length},a.ok)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var xc=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Je(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Pt(t.extensionName));for(let f of t.extensionNames??[])n.add(Pt(f));let i=f=>n.size===0||n.has(Pt(f)),a=(f,w)=>ja(f.filter(v=>i(v.name)).map(w)),r=(f,w)=>ja(f.filter(v=>i(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:d,preflight:c,services:l,renderers:p,hooks:m}=e,y=r(o.relationship_kinds??[],f=>f.definitions.map(w=>w.kind)),g=p.overrides.filter(f=>i(f.name)&&((f.commands?.length??0)>0||f.resultDiscriminator!==void 0)).map(f=>({format:f.format,commands:[...f.commands??[]],result_discriminator:f.resultDiscriminator!==void 0})).sort((f,w)=>f.format.localeCompare(w.format)),_=a(o.assurance_providers??[],f=>f.definition.id);return{capabilities:Yi(e,t),commands:a(o.commands,f=>f.command),command_overrides:a(s.overrides,f=>f.command),command_handlers:a(s.handlers,f=>f.command),hooks:xc.filter(([f])=>m[f].some(w=>i(w.name))).map(([,f])=>f),flag_commands:a(o.flags,f=>f.target_command),item_types:r(o.item_types,f=>f.types.map(w=>w.name)),item_fields:r(o.item_fields,f=>f.fields.map(w=>w.name)),...y.length>0?{relationship_kinds:y}:{},migrations:r(o.migrations,f=>typeof f.definition.id=="string"?[f.definition.id]:[]),profiles:a(o.profiles,f=>f.profile.name),importers:a(o.importers,f=>f.importer),exporters:a(o.exporters,f=>f.exporter),search_providers:a(o.search_providers,f=>f.definition.name),vector_store_adapters:a(o.vector_store_adapters,f=>f.definition.name),..._.length>0?{assurance_providers:_}:{},parser_overrides:a(d.overrides,f=>f.command),service_overrides:a(l.overrides,f=>f.service),renderer_overrides:a(p.overrides,f=>f.format),...g.length>0?{renderer_ownership:g}:{},preflight_overrides:c.overrides.filter(f=>i(f.name)).length,preflight_ownership:c.overrides.filter(f=>i(f.name)).map(f=>({commands:[...f.commands??[]]}))}}function ja(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]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var st={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Mt={type:"array",minItems:1,maxItems:pn,items:st},Fa={...Mt,items:{...st,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},Ec={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,Mt])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:st,id:st}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Fa}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Mt}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Fa,authors:Mt}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:pn,items:{type:"array",minItems:2,maxItems:2,items:st}}}}]}}},nh={$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:xi,items:Ec}}};(function(){try{var e=typeof window<"u"?window:typeof 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 oh(e,t,n,i){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"]}:Ma(a,t,n,i)}function $c(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Ma(e,t,n=5,i=!1){let a=[],r=new Map,o=e.policies.filter(f=>f.rule.kind==="require_fields"),s=o.filter(f=>f.subject?.operations===void 0),d=new Set,c=0,l=0,p=0,m=0,y=0,g=Ii(e);for(let f of t){let w=g({operation:"",author:"",before:f,after:f,completeness_only:!0});c+=+(w.decisions.length>0),l+=w.decisions.length,w.decisions.forEach(x=>d.add(x.policy_id));let v=w.decisions.filter(x=>!x.satisfied);if(v.length===0)continue;m+=1;let S=r.get(f.type)??{items:0,violations:0,missing_fields:0};S.items+=1;for(let x of v)p+=1,S.violations+=1,S.missing_fields+=x.missing_fields.length,x.effect==="refuse"&&(y+=1),a.length<n&&a.push({id:f.id,type:f.type,status:f.status,decision:x});r.set(f.type,S)}let _=i||y>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:d.size,requirement_application_count:l,governed_items:c,ungoverned_items:t.length-c,contract_status:$c(o.length,t.length,c),applied_policy_ids:[...d].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:d.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:p,refused_violations:y,missing_by_type:Object.fromEntries(r),violations:a,violations_truncated:a.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...i?["validate_completeness_source_incomplete"]:[]]}}import Ic 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 Tc(){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 Ga(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new u("Policy definition must be valid JSON.",h.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new u("Policy definition must be an object.",h.USAGE);return t}async function Ac(e,t){let n=F(process.cwd(),e.path);await Ge(n);let i=await I(n);return{pmRoot:n,settings:i,author:J(t,i.author_default)}}function Ua(e,t,n,i){if(e==="policy-mode")return un({...n,enforcement:t});let a=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:a};let r=mn(i.definition),o=un({...n,policies:[...a,r].sort((s,d)=>s.id.localeCompare(d.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
4
+ `)>sa)throw new u("Policy registry exceeds its byte ceiling.",h.USAGE);return o}async function za(e,t,n,i){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:Ua(e,t,await Ie(i.pmRoot),n)};let a=await ta({pmRoot:i.pmRoot,filePath:Ic.join(i.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:i.author,message:n.message,lockTtlSeconds:i.settings.locks.ttl_seconds,lockWaitMs:i.settings.locks.wait_ms,mutate(r){let o=Ua(e,t,ca(r),n);return{raw:`${JSON.stringify(o,null,2)}
5
+ `,result:o}}});return{policy_result:!0,action:e,changed:a.changed,result:a.result}}async function Oc(e,t,n){let i,a=await ua({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:i}),async mutate(r){let o=(await Ie(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!o||o.rule.kind!=="approval")throw new u("--policy must name an approval rule.",h.USAGE);if(!o.rule.authors.includes(n.author))throw new u("This actor is not a declared approver.",h.CONFLICT);return await da(n.pmRoot,r.metadata.id),i={policy_id:o.id,policy_fingerprint:Ei(o),content_fingerprint:$i(o,{...r.metadata,body:r.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:a.item.id,...i,warnings:a.warnings}}}function Cc(e,t){let n=Ga(t),i=mn({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==i.id)throw new u("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 i}async function Sh(e,t,n={},i={}){if(!It.includes(e))throw new u("Unknown workflow policy action.",h.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:Tc()};let a=await Ac(i,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Ie(a.pmRoot)};if(e==="policy-put"){let l=Cc(t,n.definition);return za(e,l.id,{...n,definition:l},a)}if(!t?.trim())throw new u(`schema ${e} requires an operand.`,h.USAGE);if(["policy-remove","policy-mode"].includes(e))return za(e,t,n,a);if(e==="policy-approve"){if(n.dryRun)throw new u("Use policy-check to preview; policy-approve records an approval.",h.USAGE);return Oc(t,n,a)}let r=W(a.settings,q()),o=await Rt(a.pmRoot,t,a.settings.id_prefix,a.settings.item_format,r.type_to_folder);if(!o)throw new u(`Item ${t} not found.`,h.NOT_FOUND);let{document:s}=await Nt(o,{schema:a.settings.schema}),d={...s.metadata,body:s.body},c=n.definition===void 0?d:{...d,...Ga(n.definition)};if(c.id!==d.id)throw new u("Policy preview cannot change the item id.",h.USAGE);return{policy_result:!0,action:e,changed:!1,result:await la(a.pmRoot,await Ie(a.pmRoot),{operation:"update",author:a.author,before:d,after:c,completeness_only:n.definition===void 0})}}import{createHash as nr}from"node:crypto";import Ve from"node:fs/promises";import Ye from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1abceae0-299e-5fff-aa8c-46c015115571")}catch{}})();var Pc=new Set(fn),Rc=new Set(hn),Ja=new Set([...bi.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"]),Nc=["create","update"];function Ha(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function qa(e){return e.replaceAll("_","-")}function Dc(e,t){let n=new Set;for(let i of e){let a=Ha(i);a.length>0&&a!==t&&n.add(a)}return[...n].sort((i,a)=>i.localeCompare(a))}function Lc(e){let t=new Set;for(let n of e??[]){let i=n.trim();i.length>0&&t.add(i)}return[...t].sort((n,i)=>n.localeCompare(i))}function jc(e){let t=new Set,n=[];for(let i of e??[]){let a=i.trim().toLowerCase();if(a.length!==0){if(!Rc.has(a))throw new Error(`Invalid field command "${i}". Allowed: ${hn.join(", ")}.`);t.has(a)||(t.add(a),n.push(a))}}return e===void 0||n.length===0?[...Nc]:n}function Ka(e){let t=T(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(t.includes(","))throw new Error(`Field key "${t}" must not contain commas: commas separate field names in list flags such as --unset and --fields.`);if(Ja.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: ${[...Ja].sort((p,m)=>p.localeCompare(m)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!Pc.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${fn.join(", ")}.`);let i=n,a=jc(e.commands),r=Ha(e.cliFlag),o=r.length>0&&r!==qa(t)?r:void 0,s=o??qa(t),d=Dc(e.aliases??[],s),c=[s,...d].find(p=>p.includes(","));if(c!==void 0)throw new Error(`Field flag "${c}" must not contain commas.`);let l=e.description?.trim();return{key:t,type:i,commands:a,description:l&&l.length>0?l:void 0,cliFlag:o,cliAliases:d,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:Lc(e.requiredTypes)}}function Fc(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 Mc(e){let t=Fc(e);if(!t)return[];let n=[];for(let i of t){if(typeof i!="object"||i===null||Array.isArray(i))continue;let a=i;typeof a.key!="string"||a.key.trim().length===0||n.push(a)}return n}function qe(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:Mc(t)}}function We(e){return`${JSON.stringify({fields:e.fields},null,2)}
6
+ `}function Va(e,t){let n=e.fields.find(o=>T(o.key)===t.key),i=n!==void 0,a=e.fields.filter(o=>T(o.key)!==t.key),r={...n,key:t.key,type:t.type,commands:[...t.commands]};return Wa(r,"description",t.description),Wa(r,"cli_flag",t.cliFlag),t.cliAliases.length>0?r.cli_aliases=[...t.cliAliases]:delete r.cli_aliases,Ba(r,"required",t.required),Ba(r,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?r.allow_unset=!1:delete r.allow_unset,t.requiredTypes.length>0?r.required_types=[...t.requiredTypes]:delete r.required_types,a.push(r),a.sort((o,s)=>T(o.key).localeCompare(T(s.key))),{file:{fields:a},definition:r,replaced:i}}function Ya(e,t){let n=T(t);if(n.length===0)throw new Error("Field key must not be empty.");let i=[],a=e.fields.filter(r=>T(r.key)===n?(i.push(r),!1):!0);return i.length===0?{file:{fields:a},removed:!1}:{file:{fields:a},removed:!0,definition:i[0]}}function Wa(e,t,n){let i=e;n!==void 0&&n.length>0?i[t]=n:delete i[t]}function Ba(e,t,n){let i=e;n?i[t]=!0:delete i[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 Uc=new Set(At),je=new Set(Fi.map(e=>T(e.id)).filter(e=>e.length>0));function zc(e){let t=new Set;for(let n of e){let i=T(n);i.length>0&&t.add(i)}return[...t].sort((n,i)=>n.localeCompare(i))}function Xa(e){let t=T(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(je.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...je].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let o=new Set;for(let s of e.roles){let d=typeof s=="string"?s.trim().toLowerCase():"";if(d.length!==0){if(!Uc.has(d))throw new Error(`Invalid status role "${s}". Allowed roles: ${At.join(", ")}.`);o.has(d)||(o.add(d),n.push(d))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${At.join(", ")}.`)}let i=e.aliases===void 0?void 0:zc(e.aliases).filter(o=>o!==t),a=e.description?.trim(),r=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:i,description:a&&a.length>0?a:void 0,order:r}}function Gc(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 Jc(e){let t=Gc(e);if(!t)return[];let n=[];for(let i of t){if(typeof i!="object"||i===null||Array.isArray(i))continue;let a=i;typeof a.id!="string"||a.id.trim().length===0||n.push(a)}return n}function Be(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:Jc(t)}}function He(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
7
+ `}function Za(e,t,n){let i=e.statuses.slice(),a=i.findIndex(s=>T(s.id)===t.id),r=a>=0?i[a]:n,o={...r,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?i[a]=o:i.push(o),{file:{statuses:i},definition:o,replaced:r!==void 0}}function Qa(e,t){let n=T(t);if(n.length===0)throw new Error("Status id must not be empty.");if(je.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...je].join(", ")}.`);let i=e.statuses.slice(),a=i.findIndex(o=>T(o.id)===n);if(a<0)return{file:{statuses:i},removed:!1};let[r]=i.splice(a,1);return{file:{statuses:i},removed:!0,definition:r}}function On(e,t){let n=[e.id,...e.aliases??[]];for(let i of n){let a=T(i);if(a.length===0)continue;let r=t.get(a);if(r!==void 0&&r!==e.id)throw new Error(`Status token "${a}" already belongs to status "${r}". Choose a different id/alias to avoid shadowing it.`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="09d88765-6283-5287-b293-43300251833f")}catch{}})();function _e(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function ir(e){let t=_e(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function ar(e,t){let n=Pn(e),i=_e(t,"migrationScope");return`auto-${nr("sha256").update(JSON.stringify({scope:i,request:n})).digest("hex").slice(0,20)}`}function Pn(e){let t=e.kind==="rename-type"?{kind:e.kind,from:_e(e.from,"source"),to:_e(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:T(_e(e.from,"source")),to:T(_e(e.to,"target")),...e.type===void 0?{}:{type:_e(e.type,"type")}}:{kind:e.kind,from:T(_e(e.from,"source")),to:T(_e(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function qc(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Wc(e,t,n){let i=K(t.schema),a=qc(n);return Q(e,i.files[a],V[a])}function rr(e,t){return Ye.join(e,"transactions","schema",`${t}-plan.json`)}function Ut(e){return e.length===0?null:JSON.parse(e)}async function Ke(e){let t=await M(e);return{exists:t!==null,raw:t??""}}async function or(e,t){t.exists?await fe(e,t.raw):await Ve.rm(e,{force:!0})}function Bc(e,t,n){let i=ae(e),a=i.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),r=i.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(r>=0)return ce(i);if(a<0)throw new TypeError(`Unknown custom type "${t.from}".`);i.definitions.push({...i.definitions[a],name:t.to})}else a>=0&&i.definitions.splice(a,1);return ce(i)}function Hc(e,t,n){let i=qe(e),a=i.fields.findIndex(o=>o.key===t.from),r=i.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(r>=0)return We(i);if(a<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=i.fields[a];i.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else a>=0&&i.fields.splice(a,1);return We(i)}function Kc(e,t,n){let i=Be(e),a=i.statuses.findIndex(o=>o.id===t.from),r=i.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(r>=0)return He(i);if(a<0)throw new TypeError(`Unknown custom status "${t.from}".`);i.statuses.push({...i.statuses[a],id:t.to})}else a>=0&&i.statuses.splice(a,1);return He(i)}function Vc(e,t,n){return t.kind==="rename-type"?Bc(e,t,n):t.kind==="rename-field"?Hc(e,t,n):Kc(e,t,n)}function Te(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Rn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Xe(e){return Array.isArray(e)?e.map(t=>Rn(t)).filter(t=>t!==void 0):[]}function Yc(e,t){for(let n of Xe(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(i=>Te(i,t)));for(let n of Xe(e.type_workflows))n.type=Te(n.type,t)}function Xc(e,t){for(let i of Xe(e.definitions))i.default_status=Te(i.default_status,t);let n=Rn(e.workflow);if(n)for(let[i,a]of Object.entries(n))n[i]=Te(a,t);for(let i of Xe(e.type_workflows))Array.isArray(i.allowed_transitions)&&(i.allowed_transitions=i.allowed_transitions.map(a=>Array.isArray(a)?a.map(r=>Te(r,t)):a))}function Zc(e,t){for(let n of Xe(e.definitions)){for(let i of["required_create_fields","required_create_repeatables"])Array.isArray(n[i])&&(n[i]=n[i].map(a=>Te(a,t)));for(let i of["options","command_option_policies"])for(let a of Xe(n[i])){let r=i==="options"?"key":"option";a[r]=Te(a[r],t)}}}function Qc(e,t){let n=Rn(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 i=t.kind==="rename-type"?"type":"status";n[i]=Te(n[i],t)}function Cn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let i=n;return t.kind==="rename-type"?Yc(i,t):t.kind==="rename-field"?Zc(i,t):Xc(i,t),Qc(i,t),`${JSON.stringify(i,null,2)}
8
+ `}function sr(e,t){if(t.kind==="rename-type"){let i=ae(e).definitions;return{source:i.some(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),target:i.some(a=>a.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let i=qe(e).fields;return{source:i.some(a=>a.key===t.from),target:i.some(a=>a.key===t.to)}}let n=Be(e).statuses;return{source:n.some(i=>i.id===t.from),target:n.some(i=>i.id===t.to)}}function ed(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 td(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 cr(e,t){let n=Pn(t.request),i=t.migrationId===void 0?ar(n,t.migrationScope??"plan"):ir(t.migrationId),a=e.map(d=>td(d,n)).filter(d=>d!==null).sort((d,c)=>d.id.localeCompare(c.id)),r=nr("sha256").update(JSON.stringify({migrationId:i,request:n,items:a})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(d=>d.trim()).filter(d=>d.length>0)),s=a.filter(d=>!o.has(d.id));return Object.freeze({migration_id:i,request:n,fingerprint:r,affected_item_count:a.length,pending_item_count:s.length,skipped_completed_count:a.length-s.length,items:Object.freeze(s)})}async function nd(e){let t=W(e.settings,q()),n=[...new Set(Object.values(t.type_to_folder))],i=await ma(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]}},r=i?await pa({pmRoot:e.pmRoot,expectedSourceCursor:i.source_cursor,query:a}):null;return r?{items:r.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 id(e,t){let n=await M(rr(e,t));if(n===null)return null;try{let i=JSON.parse(n);if(i.schema_version!==1||i.plan.migration_id!==t||!Array.isArray(i.plan.items))throw new TypeError("invalid plan envelope");return i.plan}catch(i){throw new u(`Stored schema migration plan "${t}" is invalid: ${Di(i)}`,h.GENERIC_FAILURE)}}async function ad(e,t){let n=rr(e,t.migration_id);await Ve.mkdir(Ye.dirname(n),{recursive:!0});let i={schema_version:1,plan:t,created_at:new Date().toISOString()};await fe(n,`${JSON.stringify(i,null,2)}
9
+ `)}function rd(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function od(e){let t=await Rt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new u(`Schema migration item "${e.id}" no longer exists.`,h.NOT_FOUND);return(await Nt(t,{schema:e.settings.schema})).document.metadata}function er(e,t,n){let i=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()!==i.toLowerCase())throw new TypeError(`Schema migration expected type "${i}" 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()!==i.toLowerCase())throw new TypeError(`Schema migration expected status "${i}" on item "${e.metadata.id}".`);return e.metadata.status=a,["status"]}let r=e.metadata;if(Object.prototype.hasOwnProperty.call(r,a)&&!Object.prototype.hasOwnProperty.call(r,i))return[];if(!Object.prototype.hasOwnProperty.call(r,i)||Object.prototype.hasOwnProperty.call(r,a))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return r[a]=r[i],delete r[i],[i,a]}function tr(e){return{id:e.id,inspect:async()=>{let t=await Ke(e.filePath),n=sr(t.raw,e.request),i=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:i?"applied":"pending",...i?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Ke(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ke(e.filePath);return await fe(e.filePath,Vc(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 or(e.filePath,{exists:t.exists,raw:t.raw})}}}function sd(e){return{id:e.stepId,inspect:async()=>{let t=await Ke(e.filePath);return{state:Cn(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Ke(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ke(e.filePath);return await fe(e.filePath,Cn(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await or(e.filePath,{exists:t.exists,raw:t.raw})}}}function cd(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await I(e.pmRoot),n=W(t,q()).type_to_folder,i=await od({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),a=ed(i,e.request).length===0;return{state:a?"applied":"pending",...a?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await I(e.pmRoot),n=W(t,q()).type_to_folder,i=await wn({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:er(a,e.request,"forward")}}});return{item_id:e.id,changed_fields:i.changedFields}},compensate:async()=>{let t=await I(e.pmRoot),n=W(t,q()).type_to_folder;await wn({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(i){return{changedFields:er(i,e.request,"reverse")}}})}}}async function dd(e){let t=await id(e.pmRoot,e.migrationId);if(t){if(!rd(t.request,e.request))throw new u(`Schema migration id "${e.migrationId}" already belongs to a different request.`,h.CONFLICT);return{plan:t,stored:!0}}let n=await nd({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...cr(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function ld(e){let t=sr(await M(e.schemaPath)??"",e.request);if(!t.source)throw new u(`Schema migration source "${e.request.from}" is not a custom definition.`,h.NOT_FOUND);if(t.target)throw new u(`Schema migration target "${e.request.to}" already exists.`,h.CONFLICT);await ad(e.pmRoot,e.plan)}async function pd(e){let t=K(e.settings.schema),n=[...new Set([["types",V.types],["fields",V.fields],["workflows",V.workflows]].map(([a,r])=>Q(e.pmRoot,t.files[a],r)).filter(a=>a!==e.schemaPath))];try{let a=Ye.join(e.pmRoot,"templates"),r=await Ve.readdir(a,{withFileTypes:!0});n.push(...r.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>Ye.join(a,o.name)))}catch(a){if(typeof a!="object"||a===null||!("code"in a)||!be(a))throw a}n.sort((a,r)=>a.localeCompare(r));let i=[];for(let a of n){let r=await M(a);r!==null&&Cn(r,e.request)!==r&&i.push({filePath:a,beforeRaw:r})}return{paths:n,snapshots:i}}async function md(e){for(let t of e.snapshots){let n=await Ve.readFile(t.filePath,"utf8"),i=Ye.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await yn({pmRoot:e.pmRoot,author:e.author,documentPath:i,before:Ut(t.beforeRaw),after:Ut(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${i}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function ud(e,t,n){let i=Pn(e),a=F(process.cwd(),n.path);await Ge(a);let r=t.migrationId===void 0?ar(i,await Ve.realpath(a)):ir(t.migrationId),o=await I(a),s=J(t.author,o.author_default),d=await dd({pmRoot:a,settings:o,migrationId:r,request:i}),c=d.plan;if(t.dryRun===!0)return{...c,action:i.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Wc(a,o,i),p=await M(l)??"";d.stored||await ld({pmRoot:a,schemaPath:l,request:i,plan:c});let m=await pd({pmRoot:a,schemaPath:l,settings:o,request:i}),y=[tr({id:"stage-schema",filePath:l,request:i,phase:"stage"}),...m.paths.map((w,v)=>sd({filePath:w,request:i,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...c.items.map(w=>cd({pmRoot:a,id:w.id,request:i,author:s,force:t.force===!0})),tr({id:"retire-source",filePath:l,request:i,phase:"retire"})],g=await Pa({pmRoot:a,transactionId:`schema-${r}`,author:s,steps:y,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),_=await Ve.readFile(l,"utf8"),{historyPath:f}=await yn({pmRoot:a,author:s,documentPath:Ye.relative(a,l).replaceAll("\\","/"),before:Ut(p),after:Ut(_),op:"schema_migration",idempotencyKey:`${c.migration_id}:${c.fingerprint}`,message:`${i.kind}: ${i.from} -> ${i.to}; affected=${c.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await md({pmRoot:a,author:s,settings:o,request:i,plan:c,snapshots:m.snapshots}),{...c,action:i.kind,applied:!0,recovered:g.recovered,migrated_item_count:c.affected_item_count,workspace_history_path:f}}function fd(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(`
10
+ `)}import pr from"node:fs/promises";import Fe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="74b72dd8-0877-55a4-9c80-d043f19e1f96")}catch{}})();var zt=["extensions","docs","examples","assets","prompts"],hd=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 gd(e){return zt.includes(e)}function yd(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],i=[];for(let a of n){if(typeof a!="string"||a.trim().length===0)throw new u(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);i.push(a.trim())}return[...new Set(i)].sort((a,r)=>a.localeCompare(r))}function _d(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new u("Package manifest field pm must be an object.",h.USAGE);let t={},n=e;for(let[i,a]of Object.entries(n)){if(!gd(i))continue;let r=yd(i,a);r.length>0&&(t[i]=r)}return t}function le(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function Nn(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,i)=>n.localeCompare(i)):void 0}function dr(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 wd(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:le(t,"docs"),npm:le(t,"npm"),repository:le(t,"repository"),report:le(t,"report")};return Object.values(n).some(i=>typeof i=="string")?n:void 0}function vd(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:le(t,"image"),video:le(t,"video")};return Object.values(n).some(i=>typeof i=="string")?n:void 0}function bd(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:le(t,"display_name")??le(t,"displayName"),category:le(t,"category"),summary:le(t,"summary"),links:wd(t.links),media:vd(t.media),tags:Nn(t.tags)};return Object.values(n).some(i=>i!==void 0)?n:void 0}async function ct(e){let t=Fe.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await pr.readFile(t,"utf8"))}catch(s){throw new u(`Failed to parse package manifest at "${t}": ${String(s)}`,h.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new u(`Package manifest at "${t}" must be a JSON object.`,h.USAGE);let i=n,a=i.pm,r=a!=null,o=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{};return{source:r?"pm":"convention",package_json_path:t,package_name:typeof i.name=="string"?i.name:void 0,package_version:typeof i.version=="string"?i.version:void 0,package_private:i.private===!0,package_description:typeof i.description=="string"?i.description:void 0,package_keywords:Nn(i.keywords),package_homepage:typeof i.homepage=="string"?i.homepage:void 0,package_repository_url:dr(i.repository),package_bugs_url:dr(i.bugs),aliases:Nn(o.aliases),resources:_d(a),catalog:bd(o.catalog)}}async function lr(e){if(!await k(e))return[];let t=await pr.readdir(e,{withFileTypes:!0}),n=[];for(let i of t){if(!i.isDirectory())continue;let a=Fe.join(e,i.name);await k(Fe.join(a,"manifest.json"))&&n.push(a)}return n.sort((i,a)=>i.localeCompare(a))}async function Gt(e){if(await k(Fe.join(e,"manifest.json")))return[e];let t=(await ct(e)).resources.extensions??[],n=new Set;for(let i of t){if(i.includes("*")||i.startsWith("!"))throw new u(`Package extension entry "${i}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let a=Fe.resolve(e,i);if(!H(e,a))throw new u(`Package extension entry "${i}" resolves outside package root.`,h.USAGE);if(await k(Fe.join(a,"manifest.json"))){n.add(a);continue}for(let r of await lr(a))n.add(r)}if(t.length===0)for(let i of hd.extensions)for(let a of await lr(Fe.join(e,i)))n.add(a);return[...n].sort((i,a)=>i.localeCompare(a))}import{execFile as Wd}from"node:child_process";import P from"node:fs/promises";import Jn from"node:os";import $ from"node:path";import{fileURLToPath as Bd}from"node:url";import{promisify as Hd}from"node:util";import Kd from"npm-package-arg";import{extract as Vd,list as Yd}from"tar";import Dd from"node:fs/promises";import re from"node:path";import mr from"node:fs/promises";import Dn 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]="9cf5a9e7-4a66-5e72-80a2-f8a9b5b6e412")}catch{}})();function Z(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 Jt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let i=t.length;for(;i>n&&t[i-1]==="-";)i-=1;let a=t.slice(n,i);if(a.length===0)throw new u("Extension manifest name must resolve to a non-empty directory name.",h.USAGE);if(a==="."||a==="..")throw new u('Extension manifest name must not resolve to "." or "..".',h.USAGE);return a}function Ln(e){return Bi(e)}async function kd(e){try{let t=JSON.parse(await mr.readFile(Dn.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(i=>typeof t.scripts?.[i]=="string")}}catch{return{has_build_script:!1}}}async function Sd(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new u(`Extension entry file is missing at "${t}".`,h.USAGE);let i=await kd(n.source_root),a=i.package_name?`pm package install npm:${i.package_name}`:void 0,r=n.source_input??n.source_root;return new u(`Extension entry "${e.entry}" is absent from GitHub source "${r}". pm package install copies GitHub repositories without running package scripts${i.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 package install ${n.source_root}`]:[`pm package 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 package install npm:<package-name>."],recovery:{attempted_command:`pm install ${r}`,normalized_args:["install",r],...a?{next_best_command:a}:{}}})}async function Ze(e,t={}){let n=Dn.join(e,"manifest.json");if(!await k(n))throw new u(`Extension manifest is missing at "${n}".`,h.USAGE);let i;try{i=JSON.parse(await mr.readFile(n,"utf8"))}catch(o){throw new u(`Failed to parse extension manifest at "${n}": ${xd(o)}`,h.USAGE)}let a=Ln(i);if(!a)throw new u(`Extension manifest at "${n}" is invalid.`,h.USAGE);let r=Dn.resolve(e,a.entry);if(!H(e,r))throw new u(`Extension entry "${a.entry}" resolves outside extension directory "${e}".`,h.USAGE);if(!await k(r))throw await Sd(a,r,t);if(!await Ki(e,r))throw new u(`Extension entry "${a.entry}" resolves outside extension directory after symlink resolution.`,h.USAGE);return{directory:e,manifest_path:n,entry_path:r,manifest:a}}function xd(e){return e instanceof Error?e.message:String(e)}import jn from"node:fs/promises";import Ed 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]="054bae8c-464f-5791-a78a-063588565393")}catch{}})();var $d=".managed-extensions.json",qt=1;function dt(e){return Ed.join(e,$d)}function Id(){return{version:qt,updated_at:A(),entries:[]}}function lt(e){return[...e].sort((t,n)=>{let i=t.scope.localeCompare(n.scope);if(i!==0)return i;let a=t.name.localeCompare(n.name);return a!==0?a:t.directory.localeCompare(n.directory)})}function ur(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 Y(e){return typeof e=="string"?e:void 0}var Td=/^(?:npm_registry|github_remote)_lookup_timed_out$/u;function Ad(e,t){let n=Y(t);return n===void 0||e.kind!=="github"||n.trim().length===0||/^[a-z0-9_]+$/u.test(n.trim())?n:"github_remote_lookup_failed"}function fr(e){return typeof e=="string"&&Td.test(e.trim())}function Od(e,t){return fr(e)&&typeof t=="number"&&Number.isSafeInteger(t)&&t>0?{update_check_timeout_ms:t}:{}}function Cd(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 Pd(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:Y(t.name),package:Y(t.package),version:Y(t.version),repository:Y(t.repository),owner:Y(t.owner),repo:Y(t.repo),ref:Y(t.ref),subpath:Y(t.subpath),commit:Y(t.commit)}}function Rd(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Cd(t))return null;let n=Pd(t.source);if(!n)return null;let i=Gi(t.contributions);return i===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Z(t.capabilities),contributions:i,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Y(t.last_update_check_at),last_update_remote_commit:Y(t.last_update_remote_commit),last_update_remote_version:Y(t.last_update_remote_version),update_available:fr(t.update_error)?null:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Ad(n,t.update_error),...Od(t.update_error,t.update_check_timeout_ms)}}function Nd(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==qt||!Array.isArray(t.entries))return null;let n=[];for(let i of t.entries){let a=Rd(i);a&&n.push(a)}return{version:qt,updated_at:Y(t.updated_at)??A(),entries:lt(n)}}async function pe(e){let t=dt(e),n=Id();try{let i=await jn.readFile(t,"utf8"),a=JSON.parse(i),r=Nd(a);if(!r)throw new u(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:r,warnings:[]}}catch(i){if(i instanceof u)throw i;if(typeof i=="object"&&i!==null&&"code"in i&&be(i))return{path:t,state:n,warnings:[]};throw new u(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}async function Qe(e,t){let n=dt(e),i={version:qt,updated_at:A(),entries:lt(t.entries)};await jn.mkdir(e,{recursive:!0}),await jn.writeFile(n,`${JSON.stringify(i,null,2)}
11
+ `,"utf8")}function pt(e,t){let n=e.entries.filter(i=>b(i.name)!==b(t.name)&&b(i.directory)!==b(t.directory));return n.push(t),{...e,updated_at:A(),entries:lt(n)}}async function hr(e,t,n,i){let a=t.entries.find(o=>b(o.name)===b(n));if(!a)return t;let r=pt(t,{...a,contributions:i});return await Qe(e,r),r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var Ld="PM_CLI_PACKAGE_ROOT",gr={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},jd=new Set(["*","all"]);function Fn(){let e=[],t=process.env[Ld];return typeof t=="string"&&t.trim().length>0&&e.push(re.resolve(t.trim())),e.push(ke(import.meta.url,["../../.."])),[...new Set(e)]}async function mt(e){let t=e.trim().toLowerCase(),n=await _r(t);if(n)return n;let i=gr[t];if(!i)return null;for(let a of Fn()){let r=re.join(a,".agents","pm","extensions",i.legacy_extension_directory);if(await k(re.join(r,"manifest.json")))return r}return null}function yr(e){return jd.has(e.trim().toLowerCase())}function Fd(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Md(e,t){let n=await Dd.readdir(e,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||!i.name.startsWith("pm-"))continue;let a=re.join(e,i.name);if(!await k(re.join(a,"package.json")))continue;let r=await ct(a),o=r.aliases&&r.aliases.length>0?r.aliases:[Fd(i.name)];for(let s of o){let d=s.trim().toLowerCase();d.length===0||t.has(d)||t.set(d,{alias:d,package_directory:i.name,package_root:a,package_name:r.package_name??null})}}}async function Mn(){let e=new Map;for(let t of Fn()){let n=re.join(t,"packages");await k(n)&&await Md(n,e)}for(let[t,n]of Object.entries(gr))if(!e.has(t))for(let i of Fn()){let a=re.join(i,"packages",n.package_directory);if(await k(re.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 Wt(){return(await Mn()).map(e=>e.alias)}async function _r(e){let t=e.trim().toLowerCase();return(await Mn()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function wr(e){let t=await _r(e);return t?(await ct(t)).package_name??null:null}async function vr(e){let t=await mt(e);if(!t)return null;try{let n=await Gt(t);return n.length!==1?null:(await Ze(n[0])).manifest.name}catch{return null}}function Ud(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 zd(e,t,n,i,a,r){let o=i==="global"?"--global":"--project",s=Object.fromEntries(zt.filter(d=>d!=="extensions").map(d=>[d,e.resources[d]??[]]).filter(([,d])=>Array.isArray(d)&&d.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(d=>a.has(d))||r.has(re.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:Ud(e),media:e.catalog?.media}}}async function br(e,t,n={}){let i=Ct(F(process.cwd(),t.path),process.cwd()),a=e==="global"?i.global:i.project,r=await pe(a),o=new Set(r.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>re.resolve(m.source.location))),s=new Set(r.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())),d=[],c=new Map;for(let m of await Mn()){let y=re.resolve(m.package_root),g=c.get(y)??[];g.push(m),c.set(y,g)}for(let m of c.values()){let y=m[0],g=m.map(f=>f.alias).sort((f,w)=>f.localeCompare(w)),_=await ct(y.package_root);d.push(zd(_,y,g,e,s,o))}let l=Jd(n.fields),p=l?d.map(m=>qd(m,l)):d;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:zt.filter(m=>m!=="extensions"),packages:p}}var Gd=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 Jd(e){if(e===void 0)return;let t=ha(e);if(t.length===0)throw new u("Package catalog --fields requires a comma-separated list of field names",h.USAGE);let n=t.filter(i=>!Gd.has(i));if(n.length>0)throw new u(`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 qd(e,t){let n={};for(let i of t)i==="category"?n[i]=e.catalog?.category??null:i==="display_name"?n[i]=e.catalog?.display_name??null:n[i]=e[i]??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]="fc993281-a2a0-59e8-9f4a-e520f1b94f3b")}catch{}})();var xr=Hd(Wd),Bt="@unbrained/pm-cli",Xd={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},Un;async function Er(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let i=$.resolve(t);for(;;){let a=$.join(i,"node_modules",...n.split("/")),r=$.join(a,"package.json");if(await k(r))try{let s=JSON.parse(await P.readFile(r,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:a}}catch{return null}let o=$.dirname(i);if(o===i)return null;i=o}}function zn(e,t,n){let i=e.split("/").map(c=>c.trim()).filter(c=>c.length>0);if(i.length<2)return null;let a=i[0],r=i[1].replace(/\.git$/i,"");if(a.length===0||r.length===0)return null;let o=i.slice(2),s,d;return o[0]==="tree"&&o.length>=2?(s=o[1],d=o.slice(2).join("/")):o.length>0&&(d=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:a,repo:r,repository:`https://github.com/${a}/${r}.git`,ref:s,subpath:d&&d.length>0?d:void 0}}function Zd(e,t,n){let i=e.slice(4).trim();if(i.length===0)throw new u('npm package source must include a package spec after "npm:".',h.USAGE);if(t)throw new u('Options "--gh/--github" cannot be combined with npm: package sources.',h.USAGE);if(n)throw new u('Option "--ref" cannot be combined with npm: package sources.',h.USAGE);return{kind:"npm",input:e,spec:i}}function ut(e,t={}){let n=e.trim();if(n.length===0)throw new u("Extension source is required for --install.",h.USAGE);let i=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Zd(n,t.forceGithub===!0,i);let a=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return zn(s,n,i)}catch{return null}})();if(a)return a;let r=n.startsWith("github.com/")?n.slice(11):null;if(r){let o=zn(r,n,i);if(!o)throw new u(`Invalid GitHub source "${n}".`,h.USAGE);return o}if(t.forceGithub){let o=zn(n,n,i);if(!o)throw new u(`Invalid GitHub shorthand "${n}".`,h.USAGE);return o}if(/^https?:\/\//i.test(n))throw new u(`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 kr(e,t=xr,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(i){let a=typeof i=="object"&&i!==null&&"stderr"in i?String(i.stderr):"",r=a.trim().length>0?a.trim():i instanceof Error?i.message:String(i);throw new u(`Git command failed: git ${e.join(" ")}
12
+ ${r}`,h.GENERIC_FAILURE)}}function qn(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Wn(e=process.platform){return e==="win32"}async function $r(e,t,n=xr,i=process.platform,a=process.env){let r=qn(i),o=Object.fromEntries(Object.entries(a).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));o.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(r,e,{cwd:t,encoding:"utf8",env:o,shell:Wn(i)})).stdout??"").trim()}catch(s){let d=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",c=d.trim().length>0?d.trim():s instanceof Error?s.message:String(s);throw new u(`npm command failed: ${r} ${e.join(" ")}
13
+ ${c}`,h.GENERIC_FAILURE)}}function Ir(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function Tr(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function Qd(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 el(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return Qd(e)||t.includes("not found")}function tl(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function nl(e){let t=Ir(e),n=tl(t),i=t.replace(/^.*\//,""),a=n?`github.com/unbraind/${i}`:void 0,r=a?`pm package 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:r?[r,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:r?[`Try ${r} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...a&&r?{fallback_candidates:[{source:a,command:r,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:r}:{}}}}}function il(e,t){if(!el(t))return null;let n=nl(e);return new u(n.message,h.NOT_FOUND,n.context)}async function Ar(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=Bd(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 al(e){let t=await Ar(e);if(t)return t;let n=rl(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function rl(e,t=process.cwd()){let n="@file:",i=e.lastIndexOf(n);if(!Tr(e))return e;let a=e.slice(0,i),r=e.slice(i+n.length);if(r.startsWith("//")&&!r.startsWith("///"))return e;if(!r.startsWith("/"))return`${a}@${$.resolve(t,r)}`;let o;try{o=decodeURIComponent(new URL(`file:${r}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${a}@${s}`}function Sr(e,t){let n=$.resolve(e,t),i=$.relative(e,n);if(i.length===0||i===".."||i.startsWith(`..${$.sep}`)||$.isAbsolute(i))throw new u("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 ol(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 sl(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 i=ol(n,t);return i?[i]:[]})}function cl(e,t){let n=t?.trim().toLowerCase(),i=n?e.filter(o=>{let s=o.name?.trim().toLowerCase();return s!==void 0?s===n:o.key?.trim().toLowerCase()===n}):[];if(i.length===1)return i[0];if(e.length!==1)return;let a=e[0],r=a.name??a.key;return n&&r!==void 0&&r.trim().toLowerCase()!==n?void 0:a}function dl(e,t,n){let i;try{i=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 u("npm pack did not report a tarball filename.",h.GENERIC_FAILURE);return{tarball:Sr(t,o)}}let a=sl(i),r=cl(a,n);if(!r)throw new u("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:Sr(t,r.filename),package:r.name??r.key,version:r.version}}async function ll(e){return pl(e,$r)}async function pl(e,t){let n=await Ar(e.spec);if(n){if((await P.stat(n)).isFile()&&Or(n))return Gn(n);let r=$.join(n,"package.json"),o=await k(r)?JSON.parse(await P.readFile(r,"utf8")):{};return{directory:await Ht(n,e.input),package:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,cleanup:async()=>{}}}let i=await P.mkdtemp($.join(Jn.tmpdir(),"pm-npm-package-source-")),a=$.join(i,"pack");await P.mkdir(a,{recursive:!0});try{let r=await al(e.spec),o=await t(["pack",r,"--json","--pack-destination",a]),s=dl(o,a,Tr(e.spec)?void 0:Ir(e.spec));if(!await k(s.tarball))throw new u("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 d=await Gn(s.tarball);return{directory:d.directory,package:s.package??d.package,version:s.version??d.version,cleanup:async()=>{try{await d.cleanup()}finally{await P.rm(i,{recursive:!0,force:!0})}}}}catch(r){throw await P.rm(i,{recursive:!0,force:!0}),il(e.spec,r)||r}}function Or(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function we(e){throw new u(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 ml(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&we(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let i=e.path,a=i.split("/");(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||a.some(r=>r===".."))&&we(`Local package archive contains an escaping path: "${i}".`),a[0]!=="package"&&we(`Local package archive entry "${i}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&we(`Local package archive link "${i}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&we(`Local package archive entry "${i}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&we(`Local package archive entry "${i}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&we(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),i==="package/package.json"&&(n.packageJsonEntries+=1)}async function Gn(e,t=Xd){(await P.stat(e)).size>t.maxArchiveBytes&&we(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await P.mkdtemp($.join(Jn.tmpdir(),"pm-local-package-archive-")),i=$.join(n,"extract");await P.mkdir(i,{recursive:!0});let a={entries:0,expandedBytes:0,packageJsonEntries:0},r;try{if(await Yd({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:c=>{if(r===void 0)try{ml(c,t,a)}catch(l){r=l}}}),r!==void 0)throw r;a.packageJsonEntries!==1&&we(`Local package archive must contain exactly one package/package.json entry; found ${a.packageJsonEntries}.`),await Vd({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let o=$.join(i,"package"),s=$.join(o,"package.json"),d=JSON.parse(await P.readFile(s,"utf8"));return await ul(o),{directory:await Ht(o,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await P.rm(n,{recursive:!0,force:!0})}}}catch(o){throw await P.rm(n,{recursive:!0,force:!0}),o}}async function ul(e,t=$r){let n=$.join(e,"package.json");if(!await k(n))return;let i;try{i=JSON.parse(await P.readFile(n,"utf8"))}catch{return}if(typeof i!="object"||i===null)return;let a=i,r=wl(a),o=fl(a);if(r.length===0&&!o)return;let s={...i};delete s.devDependencies;let d={...s};hl(d),await P.writeFile(n,`${JSON.stringify(d,null,2)}
14
+ `,"utf8");try{await Promise.all([P.rm($.join(e,"package-lock.json"),{force:!0}),P.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),r.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await gl(e)}finally{await P.writeFile(n,`${JSON.stringify(s,null,2)}
15
+ `,"utf8")}}function fl(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Bt in t)return!0;return!1}function hl(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let i={...n};delete i[Bt],Object.keys(i).length===0?delete e[t]:e[t]=i}}async function gl(e){let t=ke(import.meta.url,["../../.."]),[n,i]=Bt.split("/"),a=$.join(e,"node_modules",n),r=$.join(a,i);await P.mkdir(a,{recursive:!0}),await P.rm(r,{recursive:!0,force:!0}),await P.symlink(t,r,yl(process.platform))}function yl(e){return e==="win32"?"junction":"dir"}function _l(e,t){if(e.startsWith("-"))throw new u(`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 i=n.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(n)}))throw new u(`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{Kd.resolve(e,t)}catch{throw new u(`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 wl(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[i,a]of Object.entries(n)){if(i===Bt||typeof a!="string"||a.trim().length===0||t.has(i))continue;let r=a.trim();t.set(i,_l(i,r))}return[...t.values()]}async function Ht(e,t){let n=await Gt(e);if(n.length===1)return n[0];if(n.length>1){let i=n.map(a=>$.relative(e,a).replaceAll($.sep,"/")).sort((a,r)=>a.localeCompare(r));throw new u(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${i.join(", ")}`,h.USAGE)}throw new u(`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 vl(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 r=$.resolve(e,a);if(H(e,r)&&await k($.join(r,"manifest.json")))return{directory:r,resolved_subpath:a}}if(await k($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let i=await Ht(e,t.input);return{directory:i,resolved_subpath:$.relative(e,i).replaceAll($.sep,"/")}}function bl(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 kl(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!bl(n))return new u(t,h.NOT_FOUND);let i=[];try{let r=process.env.PM_CLI_PACKAGE_ROOT,o=typeof r=="string"&&r.trim().length>0?$.resolve(r.trim()):"";Un?.key!==o&&(Un={key:o,aliases:await Wt()}),i=Un.aliases}catch{}let a=[`Retry with pm package 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): ${i.join(", ")}`];return new u(`${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 package install npm:${n}`,"pm package catalog --project --json"],nextSteps:a,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm package install npm:${n}`}})}async function Cr(e){if(e.kind==="local"){let i;try{i=await P.stat(e.absolute_path)}catch{throw await kl(e)}if(i.isFile()&&Or(e.absolute_path)){let r=await Gn(e.absolute_path);return{source:e,directory:r.directory,source_root:$.dirname(r.directory),resolved_subpath:$.relative($.dirname(r.directory),r.directory).replaceAll($.sep,"/"),npm_package:r.package,npm_version:r.version,cleanup:r.cleanup}}if(!i.isDirectory())throw new u(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let a=await Ht(e.absolute_path,e.input);return{source:e,directory:a,source_root:e.absolute_path}}if(e.kind==="npm"){let i=await ll(e);return{source:e,directory:i.directory,source_root:$.dirname(i.directory),cleanup:i.cleanup,resolved_subpath:$.relative($.dirname(i.directory),i.directory).replaceAll($.sep,"/"),npm_package:i.package,npm_version:i.version}}let t=await P.mkdtemp($.join(Jn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await kr(n);let i=await kr(["-C",t,"rev-parse","HEAD"]),a=await vl(t,e);return{source:e,directory:a.directory,source_root:t,resolved_subpath:a.resolved_subpath,commit:i,cleanup:async()=>{await P.rm(t,{recursive:!0,force:!0})}}}catch(i){throw await P.rm(t,{recursive:!0,force:!0}),i}}async function et(e,t){if(!await k(e)||!await k(t))return!1;let[n,i]=await Promise.all([P.realpath(e),P.realpath(t)]);return n===i}import ft from"node:fs/promises";import ht 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 Bn=1,Me="2026.6.24",Sl=">=22.18.0",xl={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Pr=new Set([...Ai.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Ti).map(e=>e.toLowerCase()),"scaffold"]),El="^6.0.0",$l="^22.0.0",Dr=["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."," }"," }","}",""],me=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Rr(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Lr(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function jr(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 Il={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Nr=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Fr={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"]},Tl={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"]'},Al={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."},Ol={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."},Mr="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Cl={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."]},Pl={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."]},Rl={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`."]},Nl={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 Ur(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function zr(e,t){return e==="schema"?Rl[t]:e==="profile"?Nl[t]:Pl[t]}function Dl(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(),i=0;for(;t[i]?.toLowerCase()==="starter";)i+=1;let a=t[i]?.toLowerCase(),r=i>0&&(i===t.length||a!==void 0&&Pr.has(a));return`${(Pr.has(n)||r?["starter",...t]:t).join(" ")} ping`}function Gr(e){let t=e,n=`${e}s`,i=e.replace(/-/g,""),a=i===t?[]:[i],r=`${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(r)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(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 Ll(e,t,n){let i=`${e}-search`,a=`${e}-vector`,r=`${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(i)},`," 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,d=`${e}s`,c=e.replace(/-/g,""),l=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(d)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...Gr(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(r)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(r)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...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 jl(e,t,n){let i=n==="hooks",a=n==="search",r=n==="importers",o=n==="schema",s=n==="profile",d=n==="renderers",c=n==="parser",l=n==="preflight",p=n==="services",m=Tl[n],y=e,g=`${e}s`,_=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=i?[`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;",...me,"});",""]:[],S=a?Hn(e,t,"search",m):[],x=r?Hn(e,t,"importers",m):[],C=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 {",...Rr(Lr({extensionName:e,itemTypeName:y,itemTypeFolder:g,fieldName:_,migrationId:f,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],ie=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 {",...Rr(jr(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],L=d?[`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;",...me,"});",""]:[],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;",...me,"});",""]:[],G=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],at=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;",...me,"});",""]:[];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";',"",...Dr,`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;",...me,"});","",...v,...S,...x,...C,...ie,...L,...E,...G,...at,`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(`
16
+ `)}function Fl(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let i=`${e.replace(/-/g," ")} items`;return[t,`${i} import`,`${i} export`]}return[t]}var Ml={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"},Ul={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 zl(e,t,n){let i=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.",',...i?[" 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,",...i?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function Gl(e,t,n){let i=[],a=[...zl(e,t,n)],r=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,d=`${e.replace(/-/g," ")} items`,c=e,l=`${e}s`,p=e.replace(/-/g,""),m=p===c?[]:[p],y=`${e.replace(/-/g,"_")}_note`,g=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":i.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... */ }","});"),r.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":i.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 }),","});"),r.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":i.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,","}));"),r.push(" importers: ["," {",` name: ${JSON.stringify(d)},`," importer,"," options: {",` action: ${JSON.stringify(`${d} 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(d)},`," exporter,"," options: {",` action: ${JSON.stringify(`${d} 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":i.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(y)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(c)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(g)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),r.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":i.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({",...Gr(e),"});"),r.push(" profiles: [starterProfile],");break;case"renderers":i.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);`," },","});"),r.push(" renderers: { toon: toonRenderer },");break;case"parser":i.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 };","});"),r.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":i.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,","});"),r.push(" preflights: [preflightOverride],");break;case"services":i.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 };`,"});"),r.push(" services: { output_format: outputService },");break}return{builderImports:i,definitions:a,blueprintFields:r}}function Jl(e,t,n){let i=Gl(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...i.builderImports].sort((a,r)=>a.localeCompare(r)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...i.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({",...i.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(`
17
+ `)}function Hn(e,t,n,i){if(n==="commands")return[];let a=`${e}-search`,r=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,d=`${e}s`,c=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"],m=y=>[...p," let deactivated = false;"," try {",...y.map(g=>g===""?g:` ${g}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me];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(r)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(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(r)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...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(Lr({extensionName:e,itemTypeName:s,itemTypeFolder:d,fieldName:c,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(jr(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 ql(e,t,n){let i=n==="parser",a=JSON.stringify([...Fr[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" };',"",...Dr,`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(Me)},`," },",` target: { pmVersion: ${JSON.stringify(Me)} },`," });"," // 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)},`,...i?[" 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;",...me,"});","",...Hn(e,t,n,a)].join(`
18
+ `)}function Wl(e,t,n){let i=Ur(n,"package"),a=zr(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",i,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${Ml[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`.",Mr,"- `.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 ${Ul[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 \`${Bn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Me}\`. 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(`
19
+ `)}function Bl(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 Hl(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 Kl(e,t,n,i){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(i.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(i.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(i.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(i.itemTypeName)},`,` folder: ${JSON.stringify(i.itemTypeFolder)},`,` aliases: ${JSON.stringify(i.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(i.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(i.itemTypeName)}, folder: ${JSON.stringify(i.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 Vl(e,t,n){let i=[];return t==="renderers"&&i.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&i.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&i.push(" api.registerPreflight(preflightOverride);"),t==="services"&&i.push(' api.registerService("output_format", outputService);'),t==="hooks"&&i.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&i.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&i.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&i.push(" api.registerProfile(starterProfile);"),t==="importers"&&i.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.",'," },"," ],"," });"),i}function Yl(e,t,n,i="commands",a=!1){let r=`pm-${e}`,o=Fr[i],s=Fl(e,t,i),d=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Bn,pm_min_version:Me,trusted:!0,sandbox_profile:"strict",permissions:{...xl},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
20
+ `,c=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Ll(e,t,i),"}","","// `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(`
21
+ `),l=`${JSON.stringify(Il,null,2)}
22
+ `,p=Al[i],m=Ur(i,"package"),y=`${JSON.stringify({name:r,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Sl},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Me}`},devDependencies:{"@types/node":$l,typescript:El},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)}
23
+ `,g=jl(e,t,i),_=Ol[i],f=["node_modules/","*.log","*.tsbuildinfo",""].join(`
24
+ `),w=Bl(e),v=["```ts",`import { ${Hl(i)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Kl(e,t,i,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Vl(t,i,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],S=[`# ${r}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,p,_,Mr,"- `.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`.",...Cl[i],...zr(i,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Me}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Bn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Me}\`. 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(`
25
+ `);return{"package.json":y,"manifest.json":d,"index.ts":a?Jl(e,t,i):c,"index.test.ts":a?ql(e,t,i):g,"tsconfig.json":l,".gitignore":f,"README.md":a?Wl(r,t,i):S}}async function Jr(e,t="extension",n="commands",i=!1){let a=n.trim().toLowerCase();if(!Nr.includes(a))throw new u(`Unknown scaffold capability "${n}". Supported capabilities: ${Nr.join(", ")}.`,h.USAGE);let r=a;if(i&&t!=="package")throw new u("--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=i?"declarative":"imperative",s=e.trim(),d=ht.resolve(process.cwd(),s),c=Jt(ht.basename(d)).replace(/^(?:pm-)+/u,""),l=Dl(c),p=Yl(c,l,t,r,i),m=!1;if(await k(d)){if(!(await ft.stat(d)).isDirectory())throw new u(`Scaffold target "${d}" exists and is not a directory.`,h.CONFLICT)}else await ft.mkdir(d,{recursive:!0}),m=!0;for(let[g,_]of Object.entries(p)){let f=ht.join(d,g);if(await k(f)&&await ft.readFile(f,"utf8")!==_)throw new u(`Scaffold file "${g}" already exists with different content in "${d}". Choose a new target path or remove conflicting files.`,h.CONFLICT)}let y=[];for(let[g,_]of Object.entries(p)){let f=ht.join(d,g);if(await k(f)){y.push({path:g,status:"unchanged"});continue}await ft.mkdir(ht.dirname(f),{recursive:!0}),await ft.writeFile(f,_,"utf8"),y.push({path:g,status:"created"})}return{extension_name:c,package_name:`pm-${c}`,command_name:l,invocation_command:`pm ${l}`,capability:r,style:o,target_path:d,created_directory:m,files:y}}(function(){try{var e=typeof window<"u"?window:typeof 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 qr=[["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 Kn(e){return"#".repeat(e)}function Wr(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let r of e)n=r==="`"?n+1:0,t=Math.max(t,n);let i="`".repeat(t+1),a=e.startsWith("`")||e.endsWith("`")?" ":"";return`${i}${a}${e}${a}${i}`}function Xl(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(Wr).join(", ")}`}function Zl(e,t,n){let i=[`${Kn(t)} ${e}`,""];return n.length===0?(i.push("_None._",""),i):(i.push(...n.map(a=>`- ${Wr(a)}`),""),i)}function Ql(e,t,n){return e===0&&!n?[]:[`${Kn(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function Vn(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 i=Math.min(n+1,6),a=t.includeEmpty===!0,r=t.title??"Extension surfaces",o=[`${Kn(n)} ${r}`,""];(a||e.capabilities.length>0)&&o.push(Xl(e.capabilities),"");for(let[s,d]of qr){let c=e[s]??[];c.length===0&&!a||o.push(...Zl(d,i,c))}return o.push(...Ql(e.preflight_overrides,i,a)),!(e.preflight_overrides>0||qr.some(([s])=>(e[s]?.length??0)>0))&&!a&&o.push("_This extension registers no surfaces._",""),`${o.join(`
26
+ `).trimEnd()}
27
+ `}(function(){try{var e=typeof window<"u"?window:typeof 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 Br(e,t){return`${e}:${b(t)}`}function ep(e,t){let n=[];for(let[i,a]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let r=new Map;for(let o of a){let s=r.get(o.command)??[];r.set(o.command,[...s,o])}for(let[o,s]of r){if(t!==null&&!s.some(c=>t.has(b(c.name))))continue;let d=s.at(-1);n.push({command:o,surface:i,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(c=>({name:c.name,layer:c.layer,winner:c===d}))})}}return n.sort((i,a)=>i.command.localeCompare(a.command)||i.surface.localeCompare(a.surface))}function Hr(e,t,n){let i=new Set(n.failed.map(c=>Br(c.layer,c.name))),a=[...t.loaded.map(c=>({name:c.name,layer:c.layer,version:c.version,activation_status:i.has(Br(c.layer,c.name))?"failed":"ok",surfaces:Je(n,{extensionName:c.name})})),...t.failed.map(c=>({name:c.name,layer:c.layer,version:"unknown",activation_status:"not_loaded",surfaces:Je(n,{extensionName:c.name})}))].sort((c,l)=>c.name.localeCompare(l.name)||c.layer.localeCompare(l.layer)),r=typeof e=="string"?b(e):null,o=r===null?null:new Set(t.loaded.filter(c=>b(c.name)===r||typeof c.source_package=="string"&&b(c.source_package)===r||(c.source_aliases??[]).some(l=>b(l)===r)).map(c=>b(c.name)).concat(r)),s=o===null?a:a.filter(c=>o.has(b(c.name))),d=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Je(n,d),command_ownership:ep(n,o)}}var tp={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function yy(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 i of e.command_ownership){let a=i.claimants.find(o=>o.winner),r=i.claimants.map(o=>`${o.layer}:${o.name}`).join(", ");n.push(`- \`${i.command}\` (${i.surface}): ${a.layer}:${a.name}; policy=${i.policy}; collision=${String(i.collision)}; claimants=${r}`)}n.push("")}if(e.extensions.length===0)return n.push(`_No ${t}s are loaded._`,""),`${n.join(`
28
+ `).trimEnd()}
29
+ `;for(let i of e.extensions){let a=`${i.name} (${i.layer} v${i.version}, ${tp[i.activation_status]})`;n.push(Vn(i.surfaces,{title:a,headingLevel:2}))}return e.extensions.length>1&&n.push(Vn(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${n.join(`
30
+ `).trimEnd()}
31
+ `}import Yt from"node:fs/promises";import Vt from"node:path";import Kr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function gt(e,t,n,i){let a=Kr.relative(e,n);if(a!==""&&!H(e,n)||n===t||H(t,n))return!1;let r=a.split(Kr.sep);return r.includes(".git")?!1:i?!r.some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as np}from"node:crypto";import j from"node:fs/promises";import ip from"node:os";import D from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var Vr=3,ap=120,Yr=250,rp=12e4,op=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Xr=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Zr=e=>op.has(String(Xr(e))),Kt=(e,t)=>Xr(e)===t,Qr=e=>new Promise(t=>{setTimeout(t,e)}),eo=async e=>{let t=D.join(e,"package.json");await k(t)||await j.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
32
+ `,"utf8")},to=async e=>{let t=ke(import.meta.url,["../../.."]),n=D.join(e,"node_modules","@unbrained"),i=D.join(n,"pm-cli");await j.mkdir(n,{recursive:!0}),await j.rm(i,{recursive:!0,force:!0}),await j.symlink(t,i,process.platform==="win32"?"junction":"dir")},yt=async e=>{let t=D.resolve(e),n=D.dirname(t),i=D.parse(n).root,a=await j.realpath(i).catch(()=>i),r=D.relative(i,n),o=r===""?[]:r.split(D.sep);for(let[s,d]of o.entries()){let c=D.join(a,d);try{a=await j.realpath(c)}catch{a=D.join(a,...o.slice(s));break}}return D.join(a,D.basename(t))},no=async(e,t,n,i=ip.tmpdir())=>Re("extension_install_copy",async()=>{let a=D.resolve(e),r=await j.realpath(a).catch(()=>a),o=await yt(t);if(r===o)return;if(!H(r,o)){await n(r,t,{recursive:!0,force:!0,filter:p=>gt(r,o,D.resolve(p),!1)});return}let s=await j.realpath(D.resolve(i)).catch(()=>yt(i)),d=H(r,s)?D.dirname(r):s;if(H(r,d))throw new u(`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 j.mkdtemp(D.join(d,"pm-extension-copy-")),l=D.join(c,"extension");try{await n(r,l,{recursive:!0,force:!0,filter:p=>gt(r,o,D.resolve(p),!0)}),await n(l,t,{recursive:!0,force:!0})}finally{await j.rm(c,{recursive:!0,force:!0})}}),io=async(e,t,n=j.cp)=>{for(let i=1;i<=Vr;i+=1)try{await Re("extension_install_copy",async()=>{await j.rm(t,{recursive:!0,force:!0}),await no(e,t,n)});return}catch(a){if(!Zr(a)||i===Vr)throw a;await Qr(Yr)}},Yn=async e=>{let t;try{t=await j.readFile(D.join(e,"owner.json"),"utf8")}catch(a){if(!Tt(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 i=n.token;return typeof i=="string"&&i.length>0?i:null},ao=async(e,t)=>await Yn(e)!==t?!1:(await j.rm(e,{recursive:!0,force:!0}),!0),sp=async(e,t)=>{let n;try{n=await j.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let i=await Yn(e);return i===null?(await j.rm(e,{recursive:!0,force:!0}),!0):ao(e,i)},cp=(e,t,n)=>{let i=Promise.resolve(),a=setInterval(()=>{i=i.then(async()=>{if(await Yn(e)!==t)return;let r=new Date;await j.utimes(e,r,r)}).catch(()=>{})},n);return a.unref(),async()=>{clearInterval(a),await i}},dp=async(e,t)=>{await j.mkdir(e);try{await j.writeFile(D.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
33
+ `,"utf8")}catch(n){throw await j.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},lp=async(e,t,n,i,a)=>{for(let r=1;r<=n;r+=1)try{return await dp(e,t),!0}catch(o){if(!Kt(o,"EEXIST"))throw o;await sp(e,a)?r-=1:await Qr(i)}return!1},Xn=async(e,t,n,i)=>Re("extension_install",async()=>{let a=D.join(e,"runtime","extension-install-locks"),r=D.join(a,"scope.lock");await j.mkdir(a,{recursive:!0});let{attempts:o=ap,delay_ms:s=Yr,stale_ms:d=rp,heartbeat_ms:c}=i??{};if(![o,s,d,c].filter(w=>w!==void 0).every(Number.isFinite))throw new u("Extension install lock timings must be finite numbers.",h.USAGE);let l=Math.max(1,Math.floor(o)),p=Math.max(0,Math.floor(s)),m=Math.floor(d),y=Math.floor(c??m/3);if(m<=0||y<=0||y>=m)throw new u("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",h.USAGE);let g={pid:process.pid,token:np(),created_at:A(),destination:t};if(!await lp(r,g,l,p,m))throw new u(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let _=cp(r,g.token,y),f=!1;try{let w=await n();return f=!0,w}finally{await _(),await ao(r,g.token).catch(w=>{if(f)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 pp=new Set(["node_modules",".git","dist","build","coverage"]);async function ro(e,t,n,i){let a=e.source.kind==="local"?await Yt.stat(e.source.absolute_path):void 0,r=e.source.kind==="local"?a.isDirectory()?"directory":"archive":e.source.kind,o=await mp(e.directory,t,i),s={source_mode:r,...r==="archive"?{archive_bytes:a.size}:{},copy:o},d=e.source_root??e.directory;if(r==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await k(Vt.join(d,"package.json"))&&(s.packed_alternative={cwd:d,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),r==="directory"&&!o.complete){let c=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new u(`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 mp(e,t,n={}){let{maxEntries:i=1e4,maxDepth:a=64,signal:r}=n;if(![i,a].every(p=>Number.isSafeInteger(p)&&p>0))throw new u("maxEntries and maxDepth must be positive safe integers.",h.USAGE);r?.throwIfAborted();let o=await Yt.realpath(e),s=await yt(t),d=await et(o,s);r?.throwIfAborted();let c=d?"in_place":H(o,s)?"nested_filtered_snapshot":"directory_snapshot",l={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:i,max_depth:a};return c==="in_place"||await oo(o,0,l,r),l}async function oo(e,t,n,i){i?.throwIfAborted();let a=await Yt.opendir(e);for await(let r of a){if(i?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=Vt.join(e,r.name);if(!gt(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(Vt.relative(n.source_directory,o).split(Vt.sep).some(s=>pp.has(s))&&(n.development_entries+=1),await up(o,t,n,i),!n.complete)return}}async function up(e,t,n,i){let a=await Yt.lstat(e);if(i?.throwIfAborted(),a.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await oo(e,t+1,n,i)}else a.isFile()?(n.files+=1,n.bytes+=a.size):a.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import fp from"node:fs/promises";import hp 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 gp(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 fp.lstat(e.absolute_path),e}catch(r){if(!be(r))throw r}let n=e.input.trim(),i=t.filter(r=>r.source.kind==="npm"),a=(i.find(r=>r.name===n)??i.find(r=>r.directory===n)??i.find(r=>r.source.package===n))?.source.package;if(a===void 0)return e;try{let r=hp(a);if(!r.registry||r.name!==a)return e}catch{return e}return ut(`npm:${a}`,{})}async function so(e,t,n,i=[]){let a=typeof t=="string"?null:await mt(e),r=a===null?null:e.trim().toLowerCase(),o=r===null?null:await wr(r),s=await gp(ut(a??e,{forceGithub:typeof t=="string",ref:n}),i),d=r===null?null:await Er(e);return{bundledAliasName:r,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:r===null?s.kind:"builtin",input:r??s.input,...o===null?{}:{package:o}},ambiguous:d!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...r===null?[]:[{kind:"builtin",input:r,...o===null?{}:{package:o},command:`pm install ${r}`}],...d===null?[]:[{kind:"npm",input:`npm:${d.package}`,package:d.package,...d.version===void 0?{}:{version:d.version},directory:d.directory,command:`pm install npm:${d.package}`}]]}}}import it from"node:fs/promises";import ne from"node:path";import bp from"node:path";import{mkdir as kp}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 _t=["agile","ops","research"],yp={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 Xt(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: ${_t.join(", ")}.`)}function wt(e){return yp[e].map(t=>ot(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var _p=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function wp(e){let t=_p.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function vp(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function co(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,i=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 d=wp(s);if(d===void 0)continue;let c=a.get(d)??{count:0,examples:[]};c.count+=1,c.examples.length<i&&c.examples.push(s),a.set(d,c)}let r=[];for(let[o,s]of a.entries()){if(s.count<n)continue;let d=vp(o);r.push({name:d,prefix:o,count:s.count,examples:s.examples,shadows_builtin:na(d)!==void 0})}return r.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var E_=[...It,"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"],Zt="schema-types",lo="schema-statuses",po="schema-fields";function Ae(e){return Ee({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 T_(e,t,n){let i=F(process.cwd(),n.path);await ve(i);let a;try{a=ot({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(y){throw new u(y instanceof Error?y.message:String(y),h.USAGE)}let r=await I(i),o=K(r.schema),s=Q(i,o.files.types,V.types),d=[],c=J(t.author,r.author_default),l=he(r),p=await ee(i,Zt,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),m;try{let y=await M(s),g;try{g=ae(y)}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}try{ia(a,g);let _=new Map,f=W(r,q());for(let[w,v]of Object.entries(f.type_to_folder)){let S=v.trim().toLowerCase();S.length>0&&!_.has(S)&&_.set(S,w)}aa(a,g,_)}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}m=ze(g,a),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&d.push(`type_recased:${m.previousName}->${m.definition.name}`),await Ae({pmRoot:i,filePath:s,raw:ce(m.file),op:"schema:add-type",author:c,settings:r}),await vt(i,[m.definition],d,"schema:add-type-folder"),d.push(...await B({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await mo(i,d),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Oe(d),generated_at:A()}}async function ve(e){await Ge(e)}async function mo(e,t){try{let n=await _a(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 Oe(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Sp(e,t,n,i){let a=W(t,q()),r=i.trim().toLowerCase();return(await De(e,t.item_format,a.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===r).length}async function xp(e,t,n,i){let a=W(t,q()),r=rt(n),o=T(i);return(await De(e,t.item_format,a.type_to_folder,[],n)).filter(s=>{let d=typeof s.status=="string"?s.status:"";return(r.alias_to_id.get(T(d))??T(d))===o}).length}async function Ep(e,t,n,i,a){if(a.length===0||je.has(a))return;let r=await xp(t,n,i,a);r>0&&e.push(`items_using_status:${r}`);let o=uo(i.workflow,a);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function uo(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&&T(n)===t).map(([n])=>n)}async function A_(e,t,n){let i=F(process.cwd(),n.path);await ve(i);let a=await I(i),r=K(a.schema),o=Q(i,r.files.types,V.types),s=[],d=J(t.author,a.author_default),c=he(a),l=await ee(i,Zt,a.locks.ttl_seconds,d,!!t.force,c.force_required_for_stale_lock,a.locks.wait_ms),p;try{let m=await M(o),y;try{y=ae(m)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=ra(y,e)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=(p.definition?.name??e??"").trim();if(g.length>0){let _=await Sp(i,a,r,g);_>0&&s.push(`items_using_type:${_}`)}await Ae({pmRoot:i,filePath:o,raw:ce(p.file),op:"schema:remove-type",author:d,settings:a}),s.push(...await B({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return p.removed&&await mo(i,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:o,definitions:p.file.definitions.length},warnings:Oe(s),generated_at:A()}}function Zn(e,t){return Q(e,t.files.statuses,V.statuses)}function Qt(e,t){return Q(e,t.files.fields,V.fields)}function fo(e,t){return Q(e,t.files.types,V.types)}async function vt(e,t,n,i){for(let a of t){let r=Ci(a.folder??Oi(a.name)),o=bp.join(e,r);await k(o)||(await kp(o,{recursive:!0}),n.push(...await B({path:o,scope:"project",op:i})))}}function Qn(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 $p(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 Ip(e){let t=new Map;for(let n of e){let i=T(n.id);if(i.length!==0){t.set(i,i);for(let a of Array.isArray(n.aliases)?n.aliases:[]){let r=T(a);r.length>0&&!t.has(r)&&t.set(r,i)}}}return t}async function O_(e,t,n){let i=F(process.cwd(),n.path);await ve(i);let a;try{a=Xa({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}let r=await I(i),o=K(r.schema),s=Zn(i,o),d=rt(o);try{On(a,d.alias_to_id)}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}let c=$p(d.by_id.get(a.id));if((a.roles??c?.roles??[]).length===0)throw new u(`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 "${Ne(a.id)}" --role active`,`pm schema add-status "${Ne(a.id)}" --role blocked`]});let l=[],p=J(t.author,r.author_default),m=he(r),y=await ee(i,lo,r.locks.ttl_seconds,p,!!t.force,m.force_required_for_stale_lock,r.locks.wait_ms),g;try{let _=await M(s),f;try{f=Be(_)}catch(v){throw new u(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=Ip(f.statuses);try{On(a,w)}catch(v){throw new u(v instanceof Error?v.message:String(v),h.USAGE)}g=Za(f,a,c),await Ae({pmRoot:i,filePath:s,raw:He(g.file),op:"schema:add-status",author:p,settings:r}),l.push(...await B({path:s,scope:"project",op:"schema:add-status"}))}finally{await y()}return{action:"add-status",registered:!0,replaced:g.replaced,status:g.definition,file:{path:s,statuses:g.file.statuses.length},warnings:Oe(l),generated_at:A()}}async function C_(e,t,n){let i=F(process.cwd(),n.path);await ve(i);let a=await I(i),r=K(a.schema),o=Zn(i,r),s=[],d=J(t.author,a.author_default),c=he(a),l=await ee(i,lo,a.locks.ttl_seconds,d,!!t.force,c.force_required_for_stale_lock,a.locks.wait_ms),p;try{let m=await M(o),y;try{y=Be(m)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=Qa(y,e)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=T(p.definition?.id??e);await Ep(s,i,a,r,g),await Ae({pmRoot:i,filePath:o,raw:He(p.file),op:"schema:remove-status",author:d,settings:a}),s.push(...await B({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:o,statuses:p.file.statuses.length},warnings:Oe(s),generated_at:A()}}function ho(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 Tp(e,t,n){return{...ho(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 go(e){return{id:e.id,source:je.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 yo(e,t,n){let i=e.toLowerCase();return n.has(i)?"extension":t.has(i)?"custom":"builtin"}function Ap(){let e=new Map,t=q();for(let n of t?.item_types??[]){let i=n.types;if(Array.isArray(i))for(let a of i){if(typeof a!="object"||a===null||Array.isArray(a))continue;let r=a.name;typeof r=="string"&&r.trim().length>0&&e.set(r.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function Op(e){let t=rt(e),n=[],i=[];for(let a of t.definitions){let r=go(a);r.source==="builtin"?n.push(r):i.push(r)}return{builtin:n,custom:i}}async function bt(e){let t=F(process.cwd(),e.path);await ve(t);let n=await I(t),i=K(n.schema),a=Q(t,i.files.types,V.types),r=Zn(t,i),o=W(n,q()),s=Ap(),d=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:r,byType:o.by_type,customNames:d,extensionProvenance:s,schema:i}}async function P_(e){let t=await bt(e),n=[],i=[],a=[];for(let s of Object.values(t.byType).sort((d,c)=>d.name.localeCompare(c.name))){let d=yo(s.name,t.customNames,new Set(t.extensionProvenance.keys())),c=ho(s);d==="extension"?a.push(c):d==="custom"?i.push(c):n.push(c)}let r=Op(t.schema),o=Ot(t.schema).definitions.map(Qn);return{action:"list",builtin:n,custom:i,extension:a,counts:{builtin:n.length,custom:i.length,extension:a.length,total:n.length+i.length+a.length},statuses:{builtin:r.builtin,custom:r.custom,counts:{builtin:r.builtin.length,custom:r.custom.length,total:r.builtin.length+r.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:A()}}async function R_(e,t){let n=(e??"").trim();if(n.length===0)throw new u("Type name must not be empty.",h.USAGE);let i=await bt(t),a=Object.values(i.byType).find(r=>r.name.toLowerCase()===n.toLowerCase()||r.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!a)throw new u(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Ne(n)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Tp(a,yo(a.name,i.customNames,new Set(i.extensionProvenance.keys())),i.extensionProvenance.get(a.name.toLowerCase())),file:{path:i.typesPath},generated_at:A()}}async function N_(e,t){let n=T(e);if(n.length===0)throw new u("Status id must not be empty.",h.USAGE);let i=await bt(t),a=rt(i.schema),r=a.alias_to_id.get(n)??n,o=a.by_id.get(r);if(!o)throw new u(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Ne(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:go(o),file:{path:i.statusesPath},generated_at:A()}}async function D_(e,t,n){let i=F(process.cwd(),n.path);await ve(i);let a;try{a=Ka({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(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}let r=await I(i),o=K(r.schema),s=Qt(i,o),d=[],c=Dt(a.key);c&&d.push(`custom_field_mcp_input_collision:${c.field}:${c.property}:${c.owner}:use=${c.nested_path}`);let l=J(t.author,r.author_default),p=he(r),m=await ee(i,po,r.locks.ttl_seconds,l,!!t.force,p.force_required_for_stale_lock,r.locks.wait_ms),y;try{let g=await M(s),_;try{_=qe(g)}catch(f){throw new u(f instanceof Error?f.message:String(f),h.GENERIC_FAILURE)}y=Va(_,a),await Ae({pmRoot:i,filePath:s,raw:We(y.file),op:"schema:add-field",author:l,settings:r}),d.push(...await B({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:y.replaced,field:y.definition,file:{path:s,fields:y.file.fields.length},warnings:Oe(d),generated_at:A()}}async function Cp(e,t,n,i){let a=W(t,q());return(await De(e,t.item_format,a.type_to_folder,[],n)).filter(r=>{let o=r[i];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function L_(e,t,n){let i=F(process.cwd(),n.path);await ve(i);let a=await I(i),r=K(a.schema),o=Qt(i,r),s=[],d=J(t.author,a.author_default),c=he(a),l=await ee(i,po,a.locks.ttl_seconds,d,!!t.force,c.force_required_for_stale_lock,a.locks.wait_ms),p;try{let m=await M(o),y;try{y=qe(m)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=Ya(y,e)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=T(p.definition?.key??e),_=T(p.definition?.metadata_key??p.definition?.front_matter_key??g);if(_.length>0){let f=await Cp(i,a,r,_);f>0&&s.push(`items_using_field:${f}`)}await Ae({pmRoot:i,filePath:o,raw:We(p.file),op:"schema:remove-field",author:d,settings:a}),s.push(...await B({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:o,fields:p.file.fields.length},warnings:Oe(s),generated_at:A()}}async function j_(e){let t=await bt(e),n=Ot(t.schema).definitions.map(Qn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Qt(t.pmRoot,t.schema)},generated_at:A()}}async function F_(e,t){let n=T(e);if(n.length===0)throw new u("Field key must not be empty.",h.USAGE);let i=await bt(t),a=Ot(i.schema).by_key.get(n);if(!a)throw new u(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Ne(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Qn(a),file:{path:Qt(i.pmRoot,i.schema)},generated_at:A()}}async function M_(e,t,n){let i=F(process.cwd(),n.path);await ve(i);let a;try{let _=Xt(e);if(_===void 0)throw new Error(`Type preset name is required. Allowed: ${_t.join(", ")}.`);a=_}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}let r=await I(i),o=K(r.schema),s=fo(i,o),d=[],c=J(t.author,r.author_default),l=he(r),p=[],m=[],y,g=await ee(i,Zt,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms);try{let _=await M(s),f;try{f=ae(_)}catch(v){throw new u(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=f;for(let v of wt(a)){let S=ze(w,v);w=S.file,(S.replaced?m:p).push(S.definition.name)}y=w.definitions.length,await Ae({pmRoot:i,filePath:s,raw:ce(w),op:"schema:apply-preset",author:c,settings:r}),await vt(i,wt(a),d,"schema:apply-preset-folder"),d.push(...await B({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await g()}return{action:"apply-preset",preset:a,registered:p,replaced:m,file:{path:s,definitions:y},warnings:Oe(d),generated_at:A()}}function Pp(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new u("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function U_(e,t){let n=F(process.cwd(),t.path);await ve(n);let i=await I(n),a=K(i.schema),r=fo(n,a),o=Pp(e.minCount),s=W(i,q()),d=(await De(n,i.item_format,s.type_to_folder,[],a)).map(v=>typeof v.title=="string"?v.title:""),c=co(d,{minCount:o}),l=[],p=[],m=[],y=[],g;if(!e.apply){let v;try{v=ae(await M(r))}catch(S){throw new u(S instanceof Error?S.message:String(S),h.GENERIC_FAILURE)}return g=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:c,registered:p,replaced:m,skipped:y,file:{path:r,definitions:g},warnings:l,generated_at:A()}}let _=J(e.author,i.author_default),f=he(i),w=await ee(n,Zt,i.locks.ttl_seconds,_,!!e.force,f.force_required_for_stale_lock,i.locks.wait_ms);try{let v=await M(r),S;try{S=ae(v)}catch(C){throw new u(C instanceof Error?C.message:String(C),h.GENERIC_FAILURE)}let x=S;for(let C of c){if(C.shadows_builtin){y.push({name:C.name,reason:"shadows_builtin"});continue}let ie;try{ie=ot({name:C.name})}catch{y.push({name:C.name,reason:"invalid_type_token"});continue}let L=ze(x,ie);x=L.file,(L.replaced?m:p).push(L.definition.name)}g=x.definitions.length,await Ae({pmRoot:n,filePath:r,raw:ce(x),op:"schema:infer-types",author:_,settings:i}),await vt(n,x.definitions.filter(C=>p.includes(C.name)||m.includes(C.name)),l,"schema:infer-types-folder"),l.push(...await B({path:r,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:y,file:{path:r,definitions:g},warnings:Oe(l),generated_at:A()}}function z_(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 "${Ne(e.type.name)}" "<title>"`}function G_(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 J_(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",i=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${i} in ${e.file.path}.`}function q_(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 W_(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,i]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])i.length!==0&&t.push(`${n}: ${i.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,i]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])i.length!==0&&t.push(`${n}: ${i.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(`
34
+ `)}function B_(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(`
35
+ `)}function H_(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(`
36
+ `)}function Rp(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 K_(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 V_(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 Y_(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${Rp(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
37
+ `)}function X_(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(`
38
+ `)}function Z_(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",i=[t,n].filter(a=>a.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${i.length>0?` (${i})`:""}.`}function Q_(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 i=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${i}`)}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(`
39
+ `)}var ew={workflowSlotsReferencing:uo};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a8289336-e833-5617-9a32-0a21f28f294e")}catch{}})();function _o(e){let t=/^extension_(disabled_)?pm_(min|max)_version_([a-z_]+):(project|global):([^:]+):(.+)$/u.exec(e);if(!t)return;let[,n,i,a,r,o,s]=t,d=s.split(":")[0].replace(i==="min"?"required=":"allowed=",""),c=a==="invalid"?`a valid pm_${i}_version instead of ${d}`:`pm ${i==="min"?">=":"<="} ${d}`;return n?`Package ${o} is disabled and requires ${c} before activation. After satisfying the bound, run ${se(["package","activate",o,`--${r}`])}.`:`Package ${o} requires ${c}. Use a compatible host or package version, or keep it disabled with ${se(["package","deactivate",o,`--${r}`])}.`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="573b0fd6-f003-55d8-8f49-c2a5e81cbc31")}catch{}})();function ei(e){return e.map(({layer:t,name:n,error:i})=>({layer:t,name:n,error:i}))}function en(e,t,n){let i=b(t),a=n.trim();if(i.length===0||a.length===0)return;let r=e.get(i)??new Set;r.add(a),e.set(i,r)}function Np(e){let t=new Map,n=new Map;for(let i of e.registrations.commands)en(t,i.name,i.command),en(n,i.name,i.action);for(let i of e.commands.handlers)en(t,i.name,i.command);for(let i of e.commands.overrides)en(t,i.name,i.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function wo(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Dp(e){let{enabled:t,normalizedName:n,loadedNames:i,loadFailedNames:a,activationFailedNames:r}=e;return t?a.has(n)||r.has(n)?{runtime_active:!1,activation_status:"failed"}:i.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function tn(e,t,n){let i=new Set(t.loaded.map(d=>b(d.name))),a=new Set(t.failed.map(d=>b(d.name))),r=new Set(n.failed.map(d=>b(d.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=Np(n);return e.map(d=>{let c=b(d.name),l=wo(o.get(c)),p=wo(s.get(c)),m={...l?{command_paths:l}:{},...p?{action_paths:p}:{}},y=Dp({enabled:d.enabled,normalizedName:c,loadedNames:i,loadFailedNames:a,activationFailedNames:r});return{...d,...y,...m}})}function Lp(e){let t=0,n=0,i=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_")&&(i+=1)}return{warning_count:t,violation_count:n,blocked_count:i}}function U(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var ko=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 jp(e){return ko.has(To(e))}function vo(e){return e==="project"||e==="global"}function So(e){let t=e.split(":"),n=t[0];if(!n||!ko.has(n))return null;let i=t.at(-4),a=t.at(-3)?.trim(),r=t.at(-2),o=t.at(-1)?.trim();return!vo(i)||!vo(r)||!a||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:i,name:a},displaced:{layer:r,name:o}}}function Fp(e){let t=new Set;for(let n of e){let i=So(n);i&&(t.add(i.winner.name),t.add(i.displaced.name))}return[...t].sort((n,i)=>n.localeCompare(i))}function Mp(e,t){let n=e.filter(jp);if(n.length===0)return null;let i=Fp(n);return`Extension registration collisions or handler/override overlaps detected.${i.length>0?` Conflicting extensions: ${i.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 Up(e,t,n,i){let a=t.map(p=>So(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 r=e==="global"?"--global":"--project",o=U(i,"deactivate"),s=`${U(i,"doctor")} ${r} --detail deep --trace`,d=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 y=b(m);c.set(y,(c.get(y)??0)+1)}let l=[...c.entries()].map(([p,m])=>{let y=d.get(p),g=y?.name??p,_=y?.command_paths??[],f=y?.action_paths??[];return{action:"deactivate",extension:g,command:`${o} ${g} ${r}`,affected_collisions:m,feature_loss:{command_paths:[..._].sort((w,v)=>w.localeCompare(v)),action_paths:[...f].sort((w,v)=>w.localeCompare(v))}}}).sort((p,m)=>{let y=m.affected_collisions-p.affected_collisions;if(y!==0)return y;let g=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 g!==_?g-_: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:l}}function xo(e){let t=[];for(let n of e){let i=n.error.toLowerCase();(i.includes("cannot find package '@unbrained/pm-cli'")||i.includes('cannot find module "@unbrained/pm-cli"')||i.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(i.includes("cannot use import statement outside a module")||i.includes("to load an es module")||i.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}function Eo(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let i of t){if(!i||typeof i.name!="string")continue;let a=i.trace?.missing_capability??i.trace?.capability;typeof a=="string"&&a.trim().length>0&&n.push(`extension_capability_missing:${i.name}:${a.trim().toLowerCase()}`)}return[...new Set(n)].sort((i,a)=>i.localeCompare(a))}function $o(e,t){let n=[];for(let i of Xi(e.loaded,t))for(let a of i.unused)n.push(`extension_capability_unused:${i.layer}:${i.name}:${a}`);return[...new Set(n)].sort((i,a)=>i.localeCompare(a))}var zp=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${U(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: ${vi.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 ${U(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 ${U(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 ${U(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 ${U(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 ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${U(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 Gp(e){let{normalizedWarnings:t,options:n,scope:i,scopeFlag:a,updateCheckFailedTotal:r,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:d,skippedNonGithubTotal:c,updateAvailableTotal:l}=e,p=t.map(_o).filter(y=>y!==void 0),m={options:n,scope:i,scopeFlag:a,updateCheckFailedTotal:r,policyWarningCount:o};if(t.length>0){let y=Mp(t,{deactivate:`${U(n,"deactivate")} <name> ${a}`,doctor:`${U(n,"doctor")} ${a} --detail deep --trace`});y&&p.push(y);for(let g of zp)g.matches(t,m)&&p.push(g.build(m))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${U(n,"manage")} ${a} --fix-managed-state (or ${U(n,"adopt-all")} ${a}, ${U(n,"adopt")} <name> ${a}, or reinstall via ${U(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."),d>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${U(n,"manage")} ${a} to request update checks.`),l>0&&p.push(`Update available managed extensions via ${U(n,"install")} ${a} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${U(n,"manage")} ${a} after extension changes.`),p}function nn(e,t,n,i={}){let a=[...new Set(t)].sort((E,G)=>E.localeCompare(G)),r=n.filter(E=>E.managed).length,o=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,d=n.filter(E=>E.update_check_status==="checked"&&E.update_available===!0).length,c=n.filter(E=>E.managed===!1),l=c.filter(E=>bo(E)).map(E=>E.name).sort((E,G)=>E.localeCompare(G)),p=c.filter(E=>!bo(E)).map(E=>E.name).sort((E,G)=>E.localeCompare(G)),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 y=m.failed,g=n.filter(E=>E.update_check_status==="skipped_non_github"&&E.source?.kind!=="builtin").length,_=Object.entries({skipped_unmanaged:p.length,skipped_non_github:g,failed:y,not_checked:m.not_checked}).filter(([,E])=>E>0).map(([E,G])=>`extension_update_health_partial_coverage:${E}:${G}`),f=_.length>0,w=f?"partial":"full",v=[...new Set([...a,..._])].sort((E,G)=>E.localeCompare(G)),S=[...new Set(v.map(E=>To(E)))].sort((E,G)=>E.localeCompare(G)),x=Lp(v),C=e==="global"?"--global":"--project",ie=Up(e,a,n,i),L=Gp({normalizedWarnings:v,options:i,scope:e,scopeFlag:C,updateCheckFailedTotal:y,policyWarningCount:x.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:g,updateAvailableTotal:d});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:S,warnings:v,policy_warning_count:x.warning_count,policy_violation_count:x.violation_count,policy_blocked_count:x.blocked_count,total_extensions:n.length,managed_total:r,enabled_total:o,active_total:s,update_available_total:d,update_health_coverage:w,update_health_partial:f,unmanaged_loaded_extension_count:c.length,unmanaged_loaded_extensions:c.map(E=>E.name).sort((E,G)=>E.localeCompare(G)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:m,update_check_failed_total:y,top_warnings:v.slice(0,8),remediation:L,...ie?{collision_plan:ie}:{}}}function Io(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new u(`Invalid --detail value "${e}". Expected summary or deep.`,h.USAGE)}function To(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Ao(e){let t=new Set,n=[];for(let i of e){let a=(()=>{let r=qi(i);return r?[r]:Wi(i)})();for(let r of a){let o=`${r.layer}:${r.name}:${r.capability}`;t.has(o)||(t.add(o),n.push(r))}}return n}function Oo(){return{version:$t.version,capabilities:[...$t.capabilities],legacy_aliases:{...$t.legacy_aliases}}}function bo(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Co(e,t,n,i,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 r=[...new Set(t.filter(c=>c.active).map(c=>b(c.name)))].sort((c,l)=>c.localeCompare(l)),o=[...new Set(n.filter(c=>c.layer==="project").map(c=>b(c.name)))].sort((c,l)=>c.localeCompare(l)),s=new Set(i.map(c=>b(c.name))),d=r.filter(c=>!o.includes(c)&&!s.has(c)).sort((c,l)=>c.localeCompare(l));return{warnings:d.length>0?[`extension_doctor_consistency_active_not_loaded:${d.join(",")}`]:[],summary:{active_project_count:r.length,loaded_project_count:o.length,active_project_names:r,loaded_project_names:o,missing_active_project_names:d}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function Po(e,t){let n=b(e),i=t.find(a=>b(a.name)===n);return{command_paths:[...i?.command_paths??[]].sort((a,r)=>a.localeCompare(r)),action_paths:[...i?.action_paths??[]].sort((a,r)=>a.localeCompare(r))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function Ro(e,t){let n=new Set((t?.loaded??[]).flatMap(r=>(r.activation?.commands?.length??0)>0?[`${r.layer}:${b(r.name)}`]:[])),i=e.services.overrides.filter(r=>r.service==="output_format").filter(r=>r.passThrough!==!0).filter(r=>!n.has(`${r.layer}:${b(r.name)}`)).map(r=>`extension_output_service_override_global:${r.service}:${r.layer}:${r.name}`),a=e.renderers.overrides.filter(r=>(r.commands?.length??0)===0&&r.resultDiscriminator===void 0).map(r=>`extension_output_renderer_override_global:${r.format}:${r.layer}:${r.name}`);return[...new Set([...i,...a])].sort((r,o)=>r.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 No=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=Dt(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,i)=>i.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{spawn as tm}from"node:child_process";import{AsyncLocalStorage as nm}from"node:async_hooks";import{isMainThread as im}from"node:worker_threads";import am from"npm-package-arg";import{spawn as Jp}from"node:child_process";import{existsSync as an,readFileSync as qp}from"node:fs";import Do 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]="4b754f64-1bb8-54ef-a214-f1603b1711b8")}catch{}})();var Lo=2e3;function Wp(e,t){let n=new Map;for(let o of e.split(`
40
+ `)){let s=o.trim().split(/\s+/u);if(s.length!==2)continue;let[d,c]=s.map(Number);if(!Number.isSafeInteger(d)||!Number.isSafeInteger(c)||d<=0)continue;let l=n.get(c);l?l.push(d):n.set(c,[d])}let i=new Set([t]),a=[],r=(n.get(t)??[]).map(o=>({pid:o,parent:t}));for(let o=0;o<r.length;o+=1){let s=r[o];if(!i.has(s.pid)){i.add(s.pid),a.push(s);for(let d of n.get(s.pid)??[])r.push({pid:d,parent:s.pid})}}return a.reverse()}function ti(e,t=jo){let n=t(`/proc/${e.pid}/stat`);if(n===void 0)return!an("/proc/self/stat");let i=n.slice(n.lastIndexOf(")")+1).trim().split(/\s+/u);return Number(i[1])===e.parent}function Bp(e=jo,t=process.platform){let n=e("/proc/self/status");if(n===void 0)return t!=="linux"&&!an("/proc/self/status");let i=/^NSpid:\s*(.*)$/mu.exec(n)?.[1]?.trim().split(/\s+/u);return i?.length===1&&Number(i[0])===process.pid}function Hp(e,t,n,i=ti,a=new Map){let r=[],o=!0;for(let s=e;s!==t;){let d=a.get(s);if(d!==void 0){o=d;break}r.push(s);let c=n.get(s);if(c===void 0||!i({pid:s,parent:c})){o=!1;break}s=c}for(let s of r)a.set(s,o);return o}function jo(e){try{return qp(e,"utf8")}catch{return}}var Kp=["/bin/ps","/usr/bin/ps"],Vp={PATH:"/usr/bin:/bin",LC_ALL:"C"};function Yp(e=an){return Kp.find(t=>e(t))}var Xp="C:\\Windows";function Zp(e=process.env,t=an){let n=i=>Object.entries(e).find(([a])=>a.toLowerCase()===i)?.[1];return[n("systemroot"),n("windir"),Xp].find(i=>typeof i=="string"&&/^[A-Za-z]:[\\/]/u.test(i)&&t(Do.win32.join(i,"System32","taskkill.exe")))}function Fo(e){try{process.kill(e,"SIGKILL")}catch{}}function Mo(e,t,n,i=Lo){return new Promise(a=>{let r=!1,o="",s;try{s=Jp(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0,...n===void 0?{}:{env:n}})}catch{a(void 0);return}let d=i===null?void 0:setTimeout(()=>{c(void 0),s.stdout?.destroy(),s.kill("SIGKILL"),s.unref()},i);function c(l){r||(r=!0,clearTimeout(d),a(l))}if(s.on("error",()=>c(void 0)),!s.stdout){c(void 0);return}s.stdout.setEncoding("utf8"),s.stdout.on("data",l=>{o+=l}),s.on("close",l=>c({code:l,stdout:o}))})}async function Uo(e,t={kill:()=>Fo(e),alive:()=>!0},n={}){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await Qp(e,t,n.taskkillTimeoutMs===void 0?Lo:n.taskkillTimeoutMs);return}try{process.kill(-e,"SIGKILL");return}catch{}await em(e,t),t.kill()}}async function Qp(e,t,n){let i=Zp();if(i===void 0){t.alive()&&t.kill();return}let a=Do.win32.join(i,"System32","taskkill.exe");(await Mo(a,["/pid",String(e),"/T","/F"],void 0,n))?.code!==0&&t.alive()&&t.kill()}async function em(e,t){let n=Yp();if(n===void 0||!Bp())return;let i=await Mo(n,["-A","-o","pid=","-o","ppid="],Vp);if(i?.code!==0||!t.alive())return;let a=Wp(i.stdout,e),r=new Map(a.map(s=>[s.pid,s.parent])),o=new Map;for(let s of a)ti(s)&&Hp(s.parent,e,r,ti,o)&&Fo(s.pid)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c4f3228-d035-53ae-b279-3f33bd5323c8")}catch{}})();var rm="PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS",ni=1e4,om=1e3,sm=25e3,cm=2e3,dm="npm_registry_lookup_failed",lm="npm_registry_lookup_timed_out",pm="github_remote_lookup_failed",mm="github_remote_lookup_timed_out";function tt(e=process.env){let t=e[rm]?.trim(),n=t?Number(t):Number.NaN;return Number.isFinite(n)?Math.min(sm,Math.max(om,Math.trunc(n))):ni}var te=class extends Error{timeout_ms;teardown;constructor(t,n,i){super(t),this.name="UpdateQueryError",this.timeout_ms=n,this.teardown=i}},Jo=new WeakMap;function qo(e){return Jo.get(e)??Promise.resolve()}function Wo(e,t){let n={checked_at:e,available:null,error:t instanceof Error?t.message:String(t)};return t instanceof te&&t.timeout_ms!==void 0&&(n.timeout_ms=t.timeout_ms),t instanceof te&&t.teardown!==void 0&&Jo.set(n,t.teardown),n}var kt=new Set;function zo(){for(let e of kt)e()}var Bo=new nm;async function Ho(e){let t=new Set;try{return await Bo.run(t,e)}finally{im||await Promise.all(t)}}function um(e){return kt.size===0&&process.on("exit",zo),kt.add(e),()=>{kt.delete(e),kt.size===0&&process.off("exit",zo)}}function fm(e){let t=()=>e.exitCode!==null||e.signalCode!==null,n=()=>{t()||e.kill("SIGKILL")},i=()=>t()||e.pid===void 0?Promise.resolve():new Promise(r=>{let o=setTimeout(()=>{e.unref(),r()},cm);e.once("exit",()=>{clearTimeout(o),r()})}),a=()=>(n(),e.stdout?.destroy(),i());return{stop:()=>t()||e.pid===void 0?Promise.resolve().then(a):Uo(e.pid,{kill:n,alive:()=>!t()}).then(a,a),killNow:n}}function Ko(e,t,n,i){return new Promise((a,r)=>{let o;try{o=tm(e,t,{env:i.env,shell:i.shell,stdio:["ignore","pipe","ignore"]})}catch{r(new te(i.failed));return}let s=o,d=performance.now()+n,c=!1,l="",p=0,m=fm(s),y=Bo.getStore(),g,_=()=>{let v=um(m.killNow),S=new Promise(x=>{setTimeout(()=>{m.stop().then(x,x)},0)}).finally(v);return y?.add(S),g=S,S},f=setTimeout(()=>{w(new te(i.timedOut,n,_()))},n);function w(v){c||(c=!0,clearTimeout(f),performance.now()>=d?r(new te(i.timedOut,n,g)):v?r(v):a(l.trim()))}if(s.on("error",()=>w(new te(i.failed))),!s.stdout){w(new te(i.failed,void 0,_()));return}s.stdout.setEncoding("utf8"),s.stdout.on("data",v=>{if(!c){if(p+=Buffer.byteLength(v),p>i.maxBuffer){w(new te(i.failed,void 0,_()));return}l+=v}}),s.on("exit",(v,S)=>{v===0&&S===null||(w(new te(i.failed)),s.stdout.destroy())}),s.on("close",(v,S)=>w(v===0&&S===null?void 0:new te(i.failed)))})}function Go(e,t,n){if(typeof t=="string")try{let i=am.resolve(e,t);if(i.type==="version")return i.fetchSpec}catch{}throw new Error(n)}var hm=(e,t)=>Ko(qn(),e,t,{env:{...process.env,npm_config_ignore_scripts:"true"},shell:Wn(),maxBuffer:64*1024,timedOut:lm,failed:dm}),gm=(e,t)=>Ko("git",e,t,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never"},maxBuffer:1024*1024,timedOut:mm,failed:pm});async function Vo(e,t=hm,n=tt()){let i=A();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 a=Go(e.package,e.version,"missing_or_invalid_installed_npm_version"),r=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],n),o;try{o=JSON.parse(r)}catch{throw new Error("invalid_npm_registry_metadata")}let s=Array.isArray(o)&&o.length===1?o[0]:o,d=Go(e.package,s,"invalid_npm_registry_version");return{checked_at:i,available:d!==a,remote_version:d}}catch(a){return Wo(i,a)}}var ym=(e,t,n)=>{let i=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,d=""]=o.split(/\s+/);return{commit:s,ref:d}}),a=i.find(o=>o.ref.endsWith("^{}"))??i[0];if(!a)return{checked_at:n,available:null,error:"no_remote_reference_found"};let r=t?.trim();return r?{checked_at:n,remote_commit:a.commit,available:a.commit!==r}:{checked_at:n,remote_commit:a.commit,available:null,error:"missing_installed_commit"}},ii=async(e,t=gm,n=tt())=>{let i=A();if(e.kind!=="github"||!e.repository)return{checked_at:i,available:null,error:"not_a_github_managed_source"};try{let a=[e.ref?.trim(),"HEAD"].find(Boolean),r=await t(["ls-remote",e.repository,a,`${a}^{}`],n);return ym(r,e.commit,i)}catch(a){return Wo(i,a)}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f307be2-a113-558f-be2e-8b8f209285a5")}catch{}})();var Yo=4;function _m(e){let t=e,n=[];return{acquire:()=>t>0?(t-=1,Promise.resolve()):new Promise(i=>n.push(i)),release:()=>{let i=n.shift();i?i():t+=1}}}function Xo(e,t){let{update_check_timeout_ms:n,...i}=e;return t===void 0?i:{...i,update_check_timeout_ms:t}}async function Zo(e,t=!1,n=tt(),i=!0){let a=_m(Yo),r=await vn(e.entries,Yo,async o=>{if(!["github","npm"].includes(o.source.kind))return o;if(t)return Xo({...o,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},void 0);await a.acquire();let s=o.source.kind==="github"?await ii(o.source,void 0,n):await Vo(o.source,void 0,n);return i?qo(s).then(a.release):a.release(),Xo({...o,last_update_check_at:s.checked_at,last_update_remote_commit:"remote_commit"in s?s.remote_commit:void 0,last_update_remote_version:"remote_version"in s?s.remote_version:void 0,update_available:s.available,update_error:s.error},s.timeout_ms)});return{...e,entries:lt(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]="17cca82e-e9f9-5633-8d91-bc6c2b560d5f")}catch{}})();function Qo(e,t){let n=e.filter(i=>i.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:i,result:a})=>{let r=a.details;return{alias:i,ok:a.ok,extension:r.extension,source:r.source,source_resolution:r.source_resolution,install_plan:r.install_plan,dry_run:r.dry_run,destination_path:r.destination_path,activated:r.activated,settings_changed:r.settings_changed,previous_state_preserved:r.previous_state_preserved,rollback:r.rollback,command_paths:r.command_paths,action_paths:r.action_paths,command_discovery:r.command_discovery,verification:r.verification,runtime_activation_status:r.runtime_activation_status,activation_diagnostics:r.activation_diagnostics,warnings:a.warnings}})}}import wm from"node:fs/promises";import vm from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function bm(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function km(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 Sm(e){let t=vm.join(e,"manifest.json"),n;try{n=await wm.readFile(t,"utf8")}catch(s){if(Tt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let i;try{i=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 i!="object"||i===null||Array.isArray(i))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=i,r=Hi(a),o=bm(a);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:r.findings,warnings:r.findings.map(s=>km(o,s)),remediation:r.findings.map(s=>s.message)}}function es(e){return Sm(Pi(e))}import oe 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]="7c06c702-29ea-5552-aadc-52dfc9c238ef")}catch{}})();var ai=async e=>oe.readFile(e).catch(t=>{if(Kt(t,"ENOENT"))return null;throw t}),xm=async(e,t,n,i,a)=>Re("extension_install_backup",async()=>{let r=dt(e),o=Ri(t),[s,d]=await Promise.all([ai(r),ai(o)]);return i&&await oe.cp(n,a,{recursive:!0,force:!0}),{backupDirectory:a,destinationDirectory:n,destinationExists:i,managedStatePath:r,managedStateContents:s,settingsPath:o,settingsContents:d}}),ts=async e=>Re("extension_install_rollback",async()=>{await oe.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await oe.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])if(n===null)await oe.rm(t,{force:!0});else if(t===e.settingsPath){let i=nt.dirname(e.settingsPath),a=await I(i);try{await Ee({pmRoot:i,filePath:t,raw:n.toString("utf8"),op:"extension:install:rollback",author:J(void 0,a.author_default),lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms})}finally{oa(i)}}else await oe.mkdir(nt.dirname(t),{recursive:!0}),await oe.writeFile(t,n)});async function ns(e,t){let n=await k(e.destinationDirectory),i=await et(e.sourceDirectory,e.destinationDirectory);await oe.mkdir(e.selectedRoot,{recursive:!0});let a=nt.join(nt.dirname(e.selectedRoot),"runtime","extension-installs");await oe.mkdir(a,{recursive:!0});let r=await oe.mkdtemp(nt.join(a,".pm-extension-install-backup-")),o=nt.join(r,"destination"),s=["package","install",o,`--${e.scope}`],d=se(s),c=!1;try{let l=await xm(e.selectedRoot,e.settingsRoot,e.destinationDirectory,n,o),p;try{p=await t()}catch(m){try{await ts(l)}catch(y){c=!0;let g=new u(`Extension install failed: ${String(m)}; rollback failed: ${String(y)}`,h.GENERIC_FAILURE,{code:"extension_install_rollback_failed",original_code:m instanceof u?m.code:void 0,required:"Restore the previous package before retrying the replacement. Previous state was not preserved.",nextSteps:[n?d:"Repair the reported metadata write failure, then retry the original install."],...n?{recovery:{suggested_retry:d,suggested_retry_args:s}}:{}});throw Object.defineProperty(g,"cause",{value:m,configurable:!0,writable:!0}),g}throw m}if(p.ok)return p;if(!n||i)return{...p,details:{...p.details,previous_state_preserved:!1}};try{await ts(l)}catch(m){return c=!0,{...p,details:{...p.details,previous_state_preserved:!1,rollback:{status:"failed",error:String(m),backup_directory:o,recovery_command:d,recovery_args:s}}}}return{...p,details:{...p.details,overwritten:!1,settings_changed:!1,previous_state_preserved:!0,rollback:{status:"restored"}}}}finally{c||await oe.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f38f530-4e71-5b67-9073-0681198ff96d")}catch{}})();var os=[["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"]],Em=os.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),$m={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"},Im="__pm_native_output",Tm=["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"],ss=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Am=["disabled","require_trusted","require_provenance"],cs={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:[]},Om=e=>{let t=e??cs,n={};for(let i of Tm)n[i]=Z(t[i]??[]);return n},Cm=(e,t)=>{for(let n of ss)t[n].length>0&&(e[n]=t[n]);return e},Pm=(e,t)=>{for(let n of Am)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Rm=e=>{let t={};for(let n of ss)t[n]=Z(e[n]??[]);return t},Nm=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Cm(Pm({name:t},e),Rm(e))},Dm=e=>(e??[]).map(t=>Nm(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Lm=e=>{let t=Object.assign({},cs,e??{}),n=Om(e),i=Dm(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:i}},ds=async(e,t)=>{let n=[t],i=await vr(t);i&&n.push(i);let a=[...new Set(n.map(r=>b(r)).filter(r=>r.length>0))];for(let r of a){let o=e.find(d=>b(d.name)===r);if(o)return o;let s=e.find(d=>b(d.directory)===r);if(s)return s}},ls=(e,t)=>{let n=t.trim(),i=new Set(Z(e.extensions.enabled));return new Set(Z(e.extensions.disabled)).has(n)?!1:i.size===0?!0:i.has(n)},ps=(e,t)=>{let n=t.trim(),i=new Set(Z(e.extensions.enabled)),a=new Set(Z(e.extensions.disabled)),r=[...i],o=[...a];return a.delete(n),i.size>0&&i.add(n),e.extensions.enabled=[...i].sort((s,d)=>s.localeCompare(d)),e.extensions.disabled=[...a].sort((s,d)=>s.localeCompare(d)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},jm=(e,t)=>{let n=t.trim(),i=new Set(Z(e.extensions.enabled)),a=new Set(Z(e.extensions.disabled)),r=[...i],o=[...a];return i.delete(n),a.add(n),e.extensions.enabled=[...i].sort((s,d)=>s.localeCompare(d)),e.extensions.disabled=[...a].sort((s,d)=>s.localeCompare(d)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Fm=(e,t)=>{let n=t.trim(),i=new Set(Z(e.extensions.enabled)),a=new Set(Z(e.extensions.disabled)),r=[...i],o=[...a];return i.delete(n),a.delete(n),e.extensions.enabled=[...i].sort((s,d)=>s.localeCompare(d)),e.extensions.disabled=[...a].sort((s,d)=>s.localeCompare(d)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Mm=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),i=os.map(([a,r,o])=>({action:r,flag:o,distance:Li(t,a,n)})).filter(a=>a.distance!==null).sort((a,r)=>a.distance-r.distance)[0];return i?{action:i.action,flag:i.flag}:null},Um=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",i=Mm(e);if(!i)return new u(`One action flag is required. Use one of: ${Em}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let a=`pm ${n} ${i.flag}`;return ji({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(ms),retry_command:a,message_suffix:`. Did you mean "${i.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:a,reason:`nearest lifecycle action for "${e}"`}]})},zm=[["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"]],ms={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Gm=e=>ms[e]??null,Jm=(e,t)=>{let n=[...new Set(zm.filter(([i])=>t[i]===!0).map(([,i])=>i))];if(n.length===0){if(e===void 0)return"explore";let i=Gm(e.trim().toLowerCase());if(i)return i;throw Um(e,t)}if(n.length>1)throw new u("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},qm=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new u('Options "--project/--local" and "--global" are mutually exclusive.',h.USAGE);return n?"global":"project"},Wm=[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"}}],us=e=>{for(let t of Wm){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},fs=(e,t,n,i)=>{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,...i.status==="failed"&&a.update_check_timeout_ms!==void 0?{update_check_timeout_ms:a.update_check_timeout_ms}:{},update_check_status:i.status,update_check_reason:i.reason}},Bm=(e,t,n,i)=>{let a=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},i),r=i?ls(n,i.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:fs({name:a.name,directory:e,version:a.manifest_version,entry:a.manifest_entry,enabled:r},t,i,us(i))}},Hm=async(e,t,n,i,a,r)=>{let o=ne.join(e,t),s=ne.join(o,"manifest.json"),d=r.get(b(t));if(!await k(s))return Bm(t,n,i,d);let c=Symbol("invalid-extension-manifest-json"),l=await it.readFile(s,"utf8").then(y=>JSON.parse(y)).catch(()=>c);if(l===c)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Ln(l);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=a.get(b(p.name))??r.get(b(t));return{summary:fs({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:ls(i,p.name)},n,m,us(m))}},ue=async(e,t,n,i)=>{if(!await k(e))return{extensions:[],warnings:[]};let a=(await it.readdir(e,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name).sort((c,l)=>c.localeCompare(l)),r=new Map(i.entries.map(c=>[b(c.name),c])),o=new Map(i.entries.map(c=>[b(c.directory),c])),s=[],d=[];for(let c of a){let l=await Hm(e,c,t,n,r,o);l.warning&&s.push(l.warning),l.summary&&d.push(l.summary)}return{extensions:d.sort((c,l)=>c.name.localeCompare(l.name)),warnings:s.sort((c,l)=>c.localeCompare(l))}},Km=Vi(),Vm=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Ym=(e,t,n,i)=>{let a=n.command_paths.map(s=>`pm ${s} --help`),r=i?.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 r&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Vm(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:a,next_steps:o,...r?{sdk_dependency_status:"missing"}:{}}},Xm=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(([,i])=>i!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},hs=e=>e.map(t=>Xm(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),gs=(e,t,n)=>{let i=b(e);return t.find(a=>(n===void 0||a.layer===n)&&b(a.name)===i)},Zm=(e,t,n,i)=>n.find(a=>a.scope===t&&b(a.name)===b(e))?.activation_status??(i?"failed":"unknown"),ys=(e,t,n,i,a)=>Km.enqueue(async()=>{let r=process.env.PM_CLI_PACKAGE_ROOT,o=await it.mkdtemp(ne.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=ke(import.meta.url,["../.."]);try{let s=await Se({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:a.noExtensions===!0,reload_token:gn(),cache_bust:!0,module_graph_snapshot_root:o}),d=await xe({...s}),c=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...hs(d.failed)],l=Object.fromEntries(s.loaded.map(p=>[b(p.name),Ji(Je(d,{extensionName:p.name}))]));return{installed:tn(i,s,d),warnings:[...s.warnings,...d.warnings],activation_failures:c,extensions_disabled:s.disabled_by_flag,item_type_registrations:d.registrations.item_types,contribution_inventories:l}}finally{await it.rm(o,{recursive:!0,force:!0}),r===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=r}}),oi=async(e,t,n,i)=>{let a=n.filter(d=>!d.managed),r=[...a].sort((d,c)=>{let l=d.name.localeCompare(c.name);return l!==0?l:d.directory.localeCompare(c.directory)}),o=i,s=[];for(let d of r){let c=ne.join(e,d.directory),l=await Ze(c),p=A(),m={kind:"local",input:d.name,location:c};o=pt(o,{name:l.manifest.name,directory:d.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:p,updated_at:p,source:m}),s.push({name:l.manifest.name,directory:d.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return s.length>0&&await Qe(e,o),{state:o,adopted_entries:s,unmanaged_candidates:r,already_managed_count:n.length-a.length}},Qm=(e,t)=>{let n=F(process.cwd(),t.path),i=Ct(n,process.cwd()),a=e==="global"?Pe(process.cwd()):n,r=e==="global"?i.global:i.project;return{pm_root:n,scope:e,settings_root:a,selected_root:r,roots:i}},rn=e=>{let t=[e.gh,e.github].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new u('Options "--gh" and "--github" must match when both are provided.',h.USAGE);return n[0]},eu=e=>$m[e],tu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",i=e==="install"?"source":"name",a=`${n} ${i}`,r=eu(e),o=`<${i}>`,s=`pm ${n} ${r} ${o}`;throw new u(`Action "${e}" requires ${a} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${i} 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 ${i} target`}]}})},on=(e,t,n={})=>{let i=e?.trim();if(i)return i;if(t==="init")throw new u('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',h.USAGE);return tu(t,n)},nu=(e,t)=>{let n=new Set([...t.registrations.item_types.map(i=>({entry:i,count:i.types.length})),...t.registrations.item_fields.map(i=>({entry:i,count:i.fields.length}))].filter(({count:i})=>i>0).map(({entry:i})=>`${i.layer}:${b(i.name)}`));return e.loaded.filter(i=>(i.activation?.commands??[]).length>0).filter(i=>n.has(`${i.layer}:${b(i.name)}`)).map(i=>`extension_schema_narrow_activation:${i.layer}:${i.name}`).filter((i,a,r)=>r.indexOf(i)===a).sort((i,a)=>i.localeCompare(a))},iu=(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(i=>i.triggered&&!i.allowed);if(n)throw new u(n.message,h.USAGE)},au=(e,t,n)=>{let i=String(e??"").trim().toLowerCase(),a=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:a?[]:["init","scaffold"]}[t]??[]).includes(i)?void 0:e},ru=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},ou=(e,t,n)=>{let i={ok:n,action:e.action,scope:e.scope,roots:ru(e),warnings:[...new Set(e.warnings)].sort((a,r)=>a.localeCompare(r)),details:t};return e.action==="doctor"&&Object.defineProperty(i,Im,{value:!0,enumerable:!1,configurable:!1}),i},si=async(e,t,n)=>{let i=Jm(e,t);iu(i,t);let a=au(e,i,t),r=qm(t),o=Qm(r,n),s={action:i,normalizedTarget:a,scope:r,resolvedRoots:o,warnings:[],options:t,global:n},d={...s,withResult:(c,l=!0)=>ou(s,c,l)};return await Ho(()=>Mu(d))},su=(e,t)=>{let n=t.vocabulary??"extension",i=e.target_path.replace(/\\/g,"/"),a=Ni(i),r={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."),[r[n],...s,`Install the scaffold: ${se(n==="package"?["install","--project",i]:["extension","--install","--project",i])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},cu=async e=>{let{action:t,normalizedTarget:n,options:i,withResult:a}=e;if([rn(i),i.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new u('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let r=on(n,t,i),o=await Jr(r,i.vocabulary??"extension",i.capability,i.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:su(o,i)})},du=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:i,options:a,global:r,withResult:o}=e;if(t!==void 0)throw new u('Action "reload" does not accept a target argument.',h.USAGE);let s=await I(n.settings_root),d=gn(),c=await Se({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:r.noExtensions,reload_token:d,cache_bust:!0});i.push(...c.warnings);let l=await xe(c);i.push(...l.warnings);let p={reload:{token:d,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-l.failed.length),activation_failed_count:l.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:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return a.watch===!0&&i.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(p)},lu=async e=>{let{normalizedTarget:t,scope:n,options:i,global:a,withResult:r}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new u('Action "catalog" does not accept a package target.',h.USAGE);return r(await br(n,a,i))},pu=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),mu=e=>({kind:"local",input:e.input,location:e.absolute_path}),uu=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),fu=(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}),hu=(e,t,n,i)=>e?pu(e,t):n.kind==="local"?mu(n):n.kind==="npm"?uu(n,i):fu(n,i),gu=(e,t,n,i)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:i}:ur(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:i}:{installed_at:i,updated_at:i},yu=async(e,t)=>{let{scope:n,resolvedRoots:i,warnings:a}=e,{validated:r,destinationDirectoryName:o}=t,s=await I(i.settings_root),d=await pe(i.selected_root);a.push(...d.warnings);let c=ne.join(i.selected_root,o),l=await k(c),p=await et(r.directory,c);await it.mkdir(i.selected_root,{recursive:!0});let m=hu(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),y=d.state.entries.find(w=>b(w.name)===b(r.manifest.name)),g=gu(y,r.manifest.version,m,A()),_=pt(d.state,{name:r.manifest.name,directory:o,scope:n,manifest_version:r.manifest.version,manifest_entry:r.manifest.entry,capabilities:[...r.manifest.capabilities],contributions:r.manifest.contributions,...g,source:m}),f=ps(s,r.manifest.name);return p||await io(r.directory,c),await eo(c),await to(c),await Qe(i.selected_root,_),f&&await ge(i.settings_root,s,"settings:write"),{settings:s,managedState:_,sourceRecord:m,destinationDirectory:c,destinationExists:l,installInPlace:p,activationChanged:f}},_u=async(e,t,n)=>{let i=n.filter(a=>b(a.name)===b(t)).flatMap(a=>a.types.map(r=>({name:r.name,folder:r.folder})));return e.scope==="project"&&i.length>0&&await vt(e.resolvedRoots.pm_root,i,e.warnings,"install:type-folder"),i},wu=(e,t,n,i,a)=>{let r=gs(t,n.activation_failures,e.scope),o=Zm(t,e.scope,n.installed,r),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let d={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:r,verification:{status:d[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:i.command_paths,registered_actions:i.action_paths,registered_item_types:a,module_graph_verification:"fresh_in_topology_snapshot",health:d[String(s)]}}},vu=async(e,t)=>{let{scope:n,resolvedRoots:i,warnings:a,global:r,withResult:o}=e,{validated:s,destinationDirectoryName:d}=t;return ns({selectedRoot:i.selected_root,settingsRoot:i.settings_root,destinationDirectory:ne.join(i.selected_root,d),sourceDirectory:s.directory,scope:n},async()=>{let c=await yu(e,t),l=await ue(i.selected_root,n,c.settings,c.managedState);a.push(...l.warnings);let p=await ys(i.pm_root,ne.dirname(i.selected_root),c.settings,l.extensions,r);a.push(...p.warnings);let m=await _u(e,s.manifest.name,p.item_type_registrations),y=Po(s.manifest.name,p.installed),g=wu(e,s.manifest.name,p,y,m),_=p.contribution_inventories[b(s.manifest.name)];return _&&(c.managedState=await hr(i.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:d},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:g.activated,settings_changed:c.activationChanged,runtime_activation_status:g.status,command_paths:y.command_paths,action_paths:y.action_paths,contributions:_,command_discovery:Ym(s.manifest.name,c.sourceRecord,y,g.failure),verification:g.verification,activation_diagnostics:{failed_count:p.activation_failures.length,failed:p.activation_failures,installed_extension_failed:g.failure??null}},g.activated)})},bu=async e=>{let{options:t,global:n,warnings:i,withResult:a}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new u('Action "install all" does not accept --ref.',h.USAGE);let r=[],o=new Map;for(let s of await Wt()){let d=await mt(s),c=ne.resolve(d),l=o.get(c);l===void 0&&(l=await si(s,{...t,install:!0},n),o.set(c,l)),r.push({alias:s,result:l})}return i.push(...r.flatMap(s=>s.result.warnings)),a(Qo(r,t.dryRun===!0),r.every(s=>s.result.ok))},ku=async(e,t,n)=>{let{resolvedRoots:i}=e,{bundledAliasName:a,bundledPackageName:r,installSource:o,sourceResolution:s}=await so(t,n,e.options.ref,(await pe(i.selected_root)).state.entries);if(s.ambiguous){let c=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${a}:npm:${c.package}`)}let d=await Cr(o);try{let c=await Ze(d.directory,{source_kind:o.kind,source_input:o.input,source_root:d.source_root}),l=Jt(c.manifest.name),p=e.options.dryRun===!0||o.kind==="local"&&a===null?await ro(d,ne.join(i.selected_root,l),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:c.manifest.name,version:c.manifest.version},source_resolution:s,install_plan:p}):await Xn(i.settings_root,l,()=>vu(e,{validated:c,destinationDirectoryName:l,bundledAliasName:a,bundledPackageName:r,sourceResolution:s,installSource:o,resolvedSource:d,installPlan:p}))}finally{d.cleanup&&await d.cleanup()}},Su=async e=>{let t=rn(e.options),n=t??on(e.normalizedTarget,e.action,e.options);return[t===void 0,yr(n)].every(Boolean)?bu(e):ku(e,n,t)},xu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:a,options:r,withResult:o}=e;if(t!==void 0)throw new u('Action "adopt-all" does not accept a target argument.',h.USAGE);if(rn(r)!==void 0||typeof r.ref=="string"&&r.ref.trim().length>0)throw new u('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let s=await I(i.settings_root),d=await pe(i.selected_root);a.push(...d.warnings);let c=await ue(i.selected_root,n,s,d.state);a.push(...c.warnings);let l=await oi(i.selected_root,n,c.extensions,d.state),p=await ue(i.selected_root,n,s,l.state);a.push(...p.warnings);let m=nn(n,a,p.extensions,r);a.push(...m.warnings);let y=new Map(p.extensions.map(f=>[`${b(f.name)}:${b(f.directory)}`,f])),g=new Map(p.extensions.map(f=>[b(f.directory),f])),_=l.adopted_entries.map(f=>{let w=b(f.directory),v=y.get(`${b(f.name)}:${w}`)??g.get(w);return{...f,..._s(v)}});return o({adopted_all:_.length>0,adopted_count:_.length,already_managed_count:l.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})},_s=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Eu=(e,t,n,i)=>{if(e===void 0)return{kind:"local",input:t,location:n};let a=ut(e,{forceGithub:!0,ref:i});if(a.kind!=="github")throw new u(`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}},$u=async e=>{let{action:t,normalizedTarget:n,scope:i,resolvedRoots:a,warnings:r,options:o,withResult:s}=e,d=on(n,t,o),c=rn(o),l=await I(a.settings_root),p=await pe(a.selected_root);r.push(...p.warnings);let m=await ue(a.selected_root,i,l,p.state);r.push(...m.warnings);let y=await ds(m.extensions,d);if(!y)throw new u(`Installed extension "${d}" was not found in ${i} scope.`,h.NOT_FOUND);if(y.managed)return s({adopted:!1,already_managed:!0,extension:{name:y.name,directory:y.directory}});let g=ne.join(a.selected_root,y.directory),_=await Ze(g),f=A(),w=Eu(c,d,g,o.ref),v=pt(p.state,{name:_.manifest.name,directory:y.directory,scope:i,manifest_version:_.manifest.version,manifest_entry:_.manifest.entry,capabilities:[..._.manifest.capabilities],contributions:_.manifest.contributions,installed_at:f,updated_at:f,source:w});await Qe(a.selected_root,v);let S=await ue(a.selected_root,i,l,v);r.push(...S.warnings);let x=S.extensions.find(C=>b(C.name)===b(_.manifest.name))??S.extensions.find(C=>b(C.directory)===b(y.directory));return s({adopted:!0,extension:{name:_.manifest.name,directory:y.directory,version:_.manifest.version,entry:_.manifest.entry},source:w,..._s(x)})},ws=async e=>{let{action:t,normalizedTarget:n,scope:i,resolvedRoots:a,warnings:r,options:o}=e,s=on(n,t,o),d=await I(a.settings_root),c=await pe(a.selected_root);r.push(...c.warnings);let l=await ue(a.selected_root,i,d,c.state);r.push(...l.warnings);let p=await ds(l.extensions,s);if(!p)throw new u(`Installed extension "${s}" was not found in ${i} scope.`,h.NOT_FOUND);return{settings:d,managedStateRead:c,candidate:p}},Iu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:i,managedStateRead:a,candidate:r}=await ws(e),o=ne.join(t.selected_root,r.directory);await it.rm(o,{recursive:!0,force:!0});let s={...a.state,updated_at:A(),entries:a.state.entries.filter(c=>b(c.name)!==b(r.name)&&b(c.directory)!==b(r.directory))};await Qe(t.selected_root,s);let d=Fm(i,r.name);return d&&await ge(t.settings_root,i,"settings:write"),n({removed:!0,extension:{name:r.name,directory:r.directory},destination_path:o,settings_changed:d})},is=async e=>{let{action:t,resolvedRoots:n,warnings:i,global:a,withResult:r}=e,{settings:o,candidate:s}=await ws(e),d=t==="activate"?ps(o,s.name):jm(o,s.name);d&&await ge(n.settings_root,o,"settings:write");let c=t==="activate"?await ys(n.pm_root,ne.dirname(n.selected_root),o,[s],a).then(l=>(i.push(...l.warnings),gs(s.name,l.activation_failures,e.scope))):void 0;return c&&i.push(`extension_activate_failed:${e.scope}:${s.name}`),r({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:d,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},c===void 0)},Tu=(e,t,n,i,a,r)=>{let o=i==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],d=a?.adopted_entries.length??0,c=[[r!==null,r??""],[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.`],[d>0,`Managed-state fix adopted ${d} extension(s).`]];return[...new Set([...e,...c.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},ri=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Au=(e,t,n,i)=>{if(e!=="project"||t||!ri(i))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.`},Ou=(e,t,n)=>{if(String(e??"").trim().length>0)throw new u('Action "doctor" does not accept a target argument.',h.USAGE);let i=[n.isolated,n.ignoreGlobal].includes(!0);if([i,t==="global"].every(Boolean))throw new u("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let a=Io(n.detail),r=n.trace===!0;if([r,a!=="deep"].every(Boolean))throw new u("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:i,detailMode:a,includeTrace:r}},Cu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let i=await oi(e.resolvedRoots.selected_root,e.scope,t,n);return{state:i.state,fix:i}},Pu=(e,t,n,i)=>{let a=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:ri(i),rerun_command:null,pm_global_path_recipe:null};let r=`pm ${a} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:ri(i),rerun_command:t?null:r,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${a} doctor --project --detail deep --trace`}},Ru=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:a,options:r,global:o,withResult:s}=e,{isolated:d,detailMode:c,includeTrace:l}=Ou(t,n,r),p=await I(i.settings_root),m=await pe(i.selected_root);a.push(...m.warnings);let y=await ue(i.selected_root,n,p,m.state);a.push(...y.warnings);let{state:g,fix:_}=await Cu(e,y.extensions,m.state),f=await ue(i.selected_root,n,p,g);a.push(...f.warnings);let w=await Se({pmRoot:i.pm_root,settings:p,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:d}),v=await xe({...w,loaded:w.loaded}),S=await es(i.pm_root);a.push(...S.warnings,...w.warnings),a.push(...xo(w.failed)),a.push(...v.warnings),a.push(...Eo(v.failed)),a.push(...$o(w,v)),a.push(...Ro(v,w)),a.push(...nu(w,v)),a.push(...No(v));let x=tn(f.extensions,w,v),C=Co(n,x,w.loaded.map(O=>({layer:O.layer,name:O.name})),w.failed.map(O=>({name:O.name})),w.disabled_by_flag);a.push(...C.warnings);let ie=x.filter(O=>O.update_check_status==="failed").map(O=>`extension_update_check_failed:${O.name}`);a.push(...ie);let L=nn(n,a,x,r);a.push(...L.warnings);let E=[...L.warnings],G={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},at=Ao(E),cn=Oo(),_i=L.warning_codes,ec=Au(n,d,r.vocabulary,w),tc=Tu(L.remediation,w.failed.length,v.failed.length,r.vocabulary,_,ec),wi=Pu(n,d,r.vocabulary,w),nc={status:L.status,scope:n,warning_count:L.warning_count,warning_codes:_i,total_extensions:x.length,managed_total:x.filter(O=>O.managed).length,enabled_total:x.filter(O=>O.enabled).length,active_total:x.filter(O=>O.active).length,unmanaged_loaded_extension_count:L.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:L.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:L.unmanaged_expected_extension_count,runtime_active_total:x.filter(O=>O.runtime_active===!0).length,activation_status_totals:{ok:x.filter(O=>O.activation_status==="ok").length,failed:x.filter(O=>O.activation_status==="failed").length,not_loaded:x.filter(O=>O.activation_status==="not_loaded").length,unknown:x.filter(O=>O.activation_status==="unknown").length},unknown_capability_count:at.length,capability_contract_version:cn.version,update_available_total:L.update_available_total,update_check_status_totals:L.update_check_status_totals,update_health_coverage:L.update_health_coverage,update_health_partial:L.update_health_partial,update_check_failed_total:x.filter(O=>O.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:ei(w.failed),activation_failures:ei(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:C.warnings.length,trace_enabled:l,isolation:wi,policy:G,remediation:tc},ic=_?{requested:!0,applied:_.adopted_entries.length>0,adopted_count:_.adopted_entries.length,already_managed_count:_.already_managed_count,adopted_extensions:_.adopted_entries.map(O=>O.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:f.extensions.filter(O=>O.managed).length,adopted_extensions:[]},dn={mode:c,summary:nc,triage:L,trace_enabled:l,capability_contract:cn,capability_guidance:at,managed_state_fix:ic,author_manifest:S,isolation:wi,policy:w.policy};if(c==="deep"){let O=l?v.failed:v.failed.map(N=>{let{trace:If,...ac}=N;return ac});dn.deep={warnings:E,warning_codes:_i,capability_contract:cn,capability_guidance:at,trace_enabled:l,managed_state:{path:m.path,count:g.entries.length,entries:g.entries},installed_extensions:x,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(N=>({layer:N.layer,directory:N.directory,name:N.name,version:N.version,entry:N.entry,priority:N.priority}))},activation:{failed:O,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:C.summary},l&&(dn.deep.trace={activation_failures:v.failed.filter(N=>N.trace!==void 0).map(N=>({layer:N.layer,name:N.name,entry_path:N.entry_path,error:N.error,method:N.trace.method,command:N.trace.command,capability:N.trace.capability,missing_capability:N.trace.missing_capability,registration_index:N.trace.registration_index,expected_schema:N.trace.expected_schema,hint:N.trace.hint,received:N.trace.received}))})}return s(dn)},Nu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:a,options:r,global:o,withResult:s}=e,d=await I(i.settings_root),c=await Se({pmRoot:i.pm_root,settings:d,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),l=await xe(c);a.push(...c.warnings),a.push(...l.warnings);let p=Hr(t,c,l);if(t!==void 0&&p.extensions.length===0){let m=r.vocabulary==="package"?"package":"extension",y=[...new Set(c.loaded.map(_=>r.vocabulary==="package"&&typeof _.source_package=="string"&&_.source_package.trim().length>0?_.source_package.trim():_.name))].sort((_,f)=>_.localeCompare(f)),g=y.length>0?` Loaded ${m} names: ${y.join(", ")}.`:"";throw new u(`No loaded ${m} named "${t}" was found in ${n} scope.${g} 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})},Du=async(e,t,n)=>{let i=n,a=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(a=await oi(e.resolvedRoots.selected_root,e.scope,t,n),i=a.state),e.action==="manage"){let r=e.options.fixManagedState===!0;i=await Zo(i,e.options.offline,r?ni:tt(),!r)}return{state:i,fix:a}},Lu=async(e,t,n)=>{let i=await Se({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),a=await xe({...i,loaded:i.loaded});return e.warnings.push(...i.warnings,...a.warnings),{installed:tn(n,i,a),failures:hs(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:i.failed.length,activation_failure_count:a.failed.length,warning_count:[...new Set([...i.warnings,...a.warnings])].length,policy:i.policy}}},ju=(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},as=async e=>{let{action:t,scope:n,resolvedRoots:i,warnings:a,options:r,withResult:o}=e,s=await I(i.settings_root),d=Lm(s.extensions.policy),c=await pe(i.selected_root);a.push(...c.warnings);let l=await ue(i.selected_root,n,s,c.state);a.push(...l.warnings);let{state:p,fix:m}=await Du(e,l.extensions,c.state),y=await ue(i.selected_root,n,s,p);if(a.push(...y.warnings),t==="manage"&&r.offline===!0)for(let v of y.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=y.extensions.filter(S=>S.update_check_status==="failed").map(S=>`extension_update_check_failed:${S.name}`);a.push(...v)}let g=await Lu(e,s,y.extensions),_=g.installed,f=nn(n,a,_,r);a.push(...f.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:f,policy:d};return g.failures!==void 0&&(w.activation_diagnostics={failed_count:g.failures.length,failed:g.failures}),t==="explore"&&(w.runtime_probe=g.summary),t==="manage"&&(w.runtime_probe=g.summary,w.managed_state_fix=ju(m,_)),o(w)},rs={init:cu,install:Su,uninstall:Iu,explore:as,manage:as,describe:Nu,reload:du,doctor:Ru,catalog:lu,adopt:$u,"adopt-all":xu,activate:is,deactivate:is,migrate:La},Fu=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),Mu=e=>Fu(e)?Xn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>rs[e.action](e)):rs[e.action](e);import li from"node:fs/promises";import z from"node:path";import vs from"node:readline/promises";import{stdin as bs,stdout as St}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]="bb8a4985-8bc0-5290-a6f9-310d940cf4d7")}catch{}})();var ks=["ask","add","skip","status"],Uu=["AGENTS.md","CLAUDE.md"],zu=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Gu=8,pi=1,Ju="<!-- pm-cli:agent-guidance:start:",qu=`<!-- pm-cli:agent-guidance:start:v${pi} -->`,ci="<!-- pm-cli:agent-guidance:end -->",Et="Add workflow guidance later: pm init --agent-guidance add",Hv={toPortableRelativePath:Ue,ensureTrailingNewline:di,detectLineEnding:xs,findGuidanceBlockRange:mi,buildAgentGuidanceBlock:Es,upsertAgentGuidanceBlock:ui,resolveProjectRoot:Is,resolveTargetGuidancePath:Ts,parsePromptChoice:As,pushUnique:Ce,promptForGuidanceWrite:Os,normalizeAgentGuidanceState:fi,applyAgentGuidanceState:Ps,writeGuidanceFile:hi,setAgentGuidanceReadlineFactoryForTests:Wu},Ss=()=>vs.createInterface({input:bs,output:St});function Wu(e){Ss=e??(()=>vs.createInterface({input:bs,output:St}))}function Ue(e,t){let n=z.relative(e,t);return n.length===0?z.basename(t):n.split(z.sep).join("/")}function di(e){return e.endsWith(`
41
+ `)?e:`${e}
42
+ `}function xs(e){return e.includes(`\r
43
+ `)?`\r
44
+ `:`
45
+ `}function mi(e){let t=e.indexOf(Ju);if(t===-1)return null;let n=e.indexOf(ci,t);return n===-1?null:{start_index:t,end_index:n+ci.length}}function Bu(e){return mi(e)!==null}function Es(e,t="<your project test command>"){return[qu,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --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: `pm claim <id> --start`, or `pm claim --next --start` to take the next available item in one write.",`- 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.","",ci,""].join(e)}function ui(e,t="<your project test command>"){let n=xs(e),i=Es(n,t),a=mi(e);if(a){let s=e.slice(a.end_index),d=s.startsWith(`\r
46
+ `)?s.slice(2):s.startsWith(`
47
+ `)?s.slice(1):s,c=di(`${e.slice(0,a.start_index)}${i}${d}`);return{next_content:c,changed:c!==e}}let r=e.length===0?"":e.endsWith(`
48
+ `)?`
49
+ `:`
50
+
51
+ `,o=di(`${e}${r}${i}`);return{next_content:o,changed:o!==e}}async function $s(e){if(await k(z.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await li.readFile(z.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=Hu(t);if(n===void 0)return"<your project test command>";let i=n.packageManager?.split("@")[0];return i==="pnpm"?"pnpm test":i==="bun"?"bun run test":i==="yarn"?"yarn test":i==="npm"?"npm test":await k(z.join(e,"pnpm-lock.yaml"))?"pnpm test":await k(z.join(e,"bun.lock"))||await k(z.join(e,"bun.lockb"))?"bun run test":await k(z.join(e,"yarn.lock"))?"yarn test":"npm test"}function Hu(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 Is(e,t){let n=z.dirname(e);return z.basename(e)==="pm"&&z.basename(n)===".agents"?z.dirname(n):z.resolve(t,e)}function Ts(e,t){let n=e.find(a=>z.basename(a.file_path)==="AGENTS.md"&&a.exists);if(n)return n.file_path;let i=e.find(a=>a.exists);return i?i.file_path:z.join(t,"AGENTS.md")}function As(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 Os(e){let t=Ss();try{St.write(`
52
+ Agent guidance check
53
+ `),St.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
54
+ `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return St.write(`
55
+ `),As(n,!0)}finally{t.close()}}function fi(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:pi,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,i)=>n.localeCompare(i)):[]}}async function Cs(e){let t=[],n=await $s(e);for(let i of Uu){let a=z.join(e,i),r=await k(a);if(!r){t.push({file_path:a,exists:r,has_guidance:!1,has_marker:!1});continue}let o=await li.readFile(a,"utf8"),s=o.toLowerCase(),d=zu.filter(l=>s.includes(l)),c=Bu(o);t.push({file_path:a,exists:r,has_guidance:c||d.length>=Gu,has_marker:c,outdated:c&&ui(o,n).changed})}return t}function Ce(e,t){e.includes(t)||e.push(t)}function Ps(e,t){let n=fi(e),i=JSON.stringify(n)!==JSON.stringify(t);return i&&(e.agent_guidance=t),{changed:i,state:t}}async function hi(e,t=z.dirname(e)){let n=await k(e)?await li.readFile(e,"utf8"):"",i=ui(n,await $s(t));return i.changed?(await fe(e,i.next_content),{changed:!0,warnings:await B({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function Ku(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=>Ue(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Ue(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Ue(e.projectRoot,t.file_path))}}async function Vu(e,t,n){return e?await Cs(n):t}function xt(e,t,n){e.state={...e.state,...n,template_version:pi,last_checked_files:t}}async function Rs(e,t){if(t.presentBefore)return;let n=await hi(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Yu(e,t){t||(e.warnings.push("agent_guidance:missing"),Ce(e.nextSteps,Et))}function Xu(e,t){e.skipped=!0,xt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Ce(e.nextSteps,Et)}async function Zu(e,t){await Rs(e,t),xt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Qu(e,t){e.state.declined&&xt(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function ef(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ce(e.nextSteps,Et)}async function tf(e,t){if(e.prompted=!0,await Os(t.targetRelativePath)){await Rs(e,t),xt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,xt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ce(e.nextSteps,Et)}function nf(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ce(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Ce(e.nextSteps,Et)}async function af(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Yu(n,t.presentBefore),n):t.mode==="skip"?(Xu(n,t.checkedFiles),n):t.mode==="add"?(await Zu(n,t),n):t.presentBefore?(Qu(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(ef(n),n):t.interactive?(await tf(n,t),n):(nf(n),n)}async function Ns(e){let t=Is(e.pm_root,e.cwd),n=await Cs(t),i=Ts(n,t),a=Ue(t,i),r=n.map(l=>Ue(t,l.file_path)),o=n.some(l=>l.has_guidance),s=await af(fi(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:i,targetRelativePath:a,checkedFiles:r,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let l of n.filter(p=>p.outdated)){let p=await hi(l.file_path,t);s.applied||=p.changed,s.warnings.push(...p.warnings)}let d=Ps(e.settings,s.state);n=await Vu(s.applied,n,t);let c=n.filter(l=>l.outdated).map(l=>Ue(t,l.file_path));return c.length>0&&(s.warnings.push(`agent_guidance_outdated:${c.join(",")}`),Ce(s.nextSteps,"pm init --agent-guidance add")),{summary:Ku({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:d.changed}}import rf from"node:fs/promises";import R from"node:path";import Ls from"node:readline/promises";import{stdin as js,stdout as X}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]="0bfdfae5-a153-5cc1-9946-aa2ef215aa85")}catch{}})();var of=Symbol.for("pm.sdk.init-invocation-cwd");function _b(e,t=!1){if(t){let n=e.warnings.filter(a=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(a)),i=n.includes("agent_guidance:missing_non_interactive")?e.next_steps.filter(a=>a.includes("--agent-guidance")):[];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:[...i,...e.next_steps.filter(a=>!i.includes(a))].slice(0,3),...n.length>0?{warnings:n.join("; ")}:{},details:`${se(["--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 wb={normalizeInitGovernancePreset:gi,normalizeInitTypePreset:Ms,normalizeOptionalInitAuthor:Us,normalizeInitAgentGuidanceMode:Js,isPathLikeInitTarget:sn,resolveInitInvocation:zs,resolveInitPrefixInput:Gs,parseYesNoChoice:qs,applyGovernancePreset:yi,runInitWizard:Ys,setInitReadlineFactoryForTests:sf,summarizeInstalledPackages:Ws,buildInitNextSteps:Zs,registerInitTypePreset:Bs,assertExplicitTrackerPathIsNotWorkspaceRoot:Ks,isLikelyWorkspaceRoot:Hs,installInitMergeFence:Qs},Fs=()=>Ls.createInterface({input:js,output:X});function sf(e){Fs=e??(()=>Ls.createInterface({input:js,output:X}))}function cf(){return structuredClone(Si)}var df=["minimal","default","strict"];function gi(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new u("--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 u(`Invalid --preset value "${e}". Allowed: ${df.join(", ")}`,h.USAGE)}function Ms(e){if(e!==void 0){if(e.trim().length===0)throw new u("--type-preset must not be empty",h.USAGE);try{return Xt(e)}catch{throw new u(`Invalid --type-preset value "${e}". Allowed: ${_t.join(", ")}`,h.USAGE)}}}function Us(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new u("--author must not be empty",h.USAGE);return t}function sn(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:R.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function zs(e,t,n,i){let a=i?.trim();if(i!==void 0&&a?.length===0)throw new u("--workspace must not be empty",h.USAGE);if(a!==void 0){if(t.path!==void 0||sn(n))throw new u("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",h.USAGE);let c=R.resolve(e,a),l=R.join(c,".agents","pm");return{pmRoot:l,prefixArg:n,target:{mode:"workspace-path",tracker_root:l,workspace_root:c}}}if(t.path===void 0&&sn(n)){let c=R.resolve(e,n.trim());return{pmRoot:c,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:c}}}let r=F(e,t.path),o=R.join(R.resolve(e),".agents","pm"),s=R.dirname(R.dirname(r)),d=R.resolve(r)===o?"current":"ancestor";return{pmRoot:r,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:r,workspace_root:s,discovery:d,requested_cwd:R.resolve(e),...d==="ancestor"?{suggested_current_tracker_root:o}:{}}:{mode:"tracker-path",tracker_root:r}}}function Gs(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new u("--id-prefix must not be empty",h.USAGE);if(sn(t))throw new u(`--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 u(`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 Js(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new u("--agent-guidance must not be empty",h.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new u(`Invalid --agent-guidance value "${e}". Allowed: ${ks.join(", ")}`,h.USAGE)}function qs(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function yi(e,t){let n=ki[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function lf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ws(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(lf).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Bs(e,t,n){let i=K(t.schema),a=Q(e,i.files.types,V.types),r=ae(await M(a)),o=[],s=[];for(let d of wt(n)){let c=ze(r,d);r=c.file,(c.replaced?s:o).push(c.definition.name)}return await Ee({pmRoot:e,filePath:a,raw:ce(r),op:"init:type-preset",author:J(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 Hs(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",R.join(".agents","pm")];for(let n of t)if(await k(R.join(e,n)))return!0;return!1}async function Ks(e,t,n){if(!t||n||await k(R.join(e,"settings.json"))||!await Hs(e))return;let i=R.join(e,".agents","pm");throw new u(`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 ${i} 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 ${i} init --yes`}})}async function Vs(e,t){let n=[],i=[];for(let a of t){let r=a?R.join(e,a):e,o=await k(r);await rf.mkdir(r,{recursive:!0}),o?i.push(`already_exists:${r}`):n.push(r),i.push(...await B({path:r,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:i}}async function Ys(e,t){let n=Fs(),i=t===void 0?2:3;try{X.write(`pm init setup wizard (agent-optimized)
56
+ `),X.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
57
+
58
+ `),X.write(`1/${i} Item ID prefix
59
+ `),X.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
60
+ `);let a=await n.question(`Item ID prefix [${e}]: `),r=a.trim().length>0?$e(a):e;X.write(`
61
+ 2/${i} Governance preset
62
+ `),X.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
63
+ `),X.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
64
+ `),X.write(`strict: ownership blocking, strict create defaults, close validation strict.
65
+ `);let o=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),s=o.trim().length>0?o.trim():"minimal",d="minimal";try{d=gi(s)}catch{X.write(`Unrecognized governance preset "${s}"; using minimal.
66
+ `)}let c;if(t!==void 0){X.write(`
67
+ 3/3 Telemetry
68
+ `),X.write(`Telemetry helps improve reliability. The choice applies to this CLI install; change it with pm config global set telemetry-tracking.
69
+ `);let l=await n.question(`Enable telemetry for this CLI install? [${t?"Y/n":"y/N"}] `);c=qs(l,t)}return X.write(`
70
+ `),{prefix:r,preset:d,telemetry_enabled:c}}finally{n.close()}}function pf(e){return{presetFromOption:gi(e.preset),useDefaults:e.defaults===!0,authorFromOption:Us(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:Js(e.agentGuidance),typePreset:Ms(e.typePreset)}}function mf(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 uf(e,t,n,i){if(t.length===0||n)return;let a=i.discovery==="ancestor";throw new u(`${a?`No tracker exists in ${i.requested_cwd}; pm init found an ancestor tracker at ${i.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:i.tracker_root,requested_path:i.requested_cwd,suggested_path:i.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 ff(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&&(yi(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 hf(e){let t=await I(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=mf({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return uf(e.settingsPath,n,e.options.force===!0,e.target),ff({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await ge(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function gf(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,i,a=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await Ys(t,await yf());t=c.prefix,n=c.preset,i=c.telemetry_enabled,a=!0}let r=n??"minimal",o=cf();o.id_prefix=t,yi(o,r);let s=Ui()?.trim()||void 0;o.author_default=e.normalizedOptions.authorFromOption??s??"";let d=Xs(e.pmRoot);return i!==void 0&&(o.telemetry.enabled=i,o.telemetry.first_run_prompt_completed=!0),await ge(e.pmRoot,o,void 0,d),i!==void 0&&d.omitSections&&await _f(i,e.warnings),{settings:o,normalizedPrefix:t,chosenPreset:n,wizardUsed:a}}function Xs(e){return R.resolve(e)===R.resolve(Pe(process.cwd()))?{}:{omitSections:["telemetry"]}}async function yf(){let e=await I(Pe(process.cwd()));if(!(fa().telemetry_disabled||e.telemetry.first_run_prompt_completed||_n(e)))return e.telemetry.enabled}async function _f(e,t){let n=Pe(process.cwd()),i=await I(n);if(_n(i)){t.push("telemetry_consent_not_recorded:global_settings_unreadable");return}let a=!1;i.telemetry.enabled=e,i.telemetry.first_run_prompt_completed=!0,await ge(n,i,"telemetry:first_run_prompt",{skipIfStored:r=>a=r.telemetry?.first_run_prompt_completed===!0}),a&&t.push("telemetry_consent_kept:recorded_while_prompting")}async function wf(e){let{telemetry:t}=await I(Pe(process.cwd()));return{...e,telemetry:{...e.telemetry,enabled:t.enabled,first_run_prompt_completed:t.first_run_prompt_completed,capture_level:t.capture_level}}}async function Ds(e){return e.settingsExists?await hf(e):await gf({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions,warnings:e.warnings})}async function vf(e){let t=await Ns({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 ge(e.pmRoot,e.settings,void 0,Xs(e.pmRoot)),{...t.summary,next_steps:t.next_steps}}async function bf(e,t){let n=[],i=[],a=await Mi(e,t.schema);for(let r of a.created_paths)n.push(r),i.push(...await B({path:r,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:i}}async function kf(e){if(e.typePreset===void 0)return;let t=await Bs(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await B({path:t.file,scope:"project",op:"init:type_preset"})),t}async function Sf(e){let t=W(e.settings,q()).folders.filter(i=>!ln.includes(i)),n=await Vs(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function xf(e){let t=R.resolve(e.tracker_root),n=R.dirname(t);return R.basename(t)==="pm"&&R.basename(n)===".agents"?R.dirname(n):e.workspace_root}async function Ef(e,t,n,i){if(!e)return;let a=await si("all",{install:!0,project:!0},{...t,path:n});i.push(...a.warnings);let r=Ws(a),o=r.packages.filter(s=>!s.ok).map(s=>s.alias);if(!r.installed_all||o.length>0)throw new u(`pm init --with-packages did not install all bundled packages successfully${o.length>0?`: ${o.join(", ")}`:"."}`,h.GENERIC_FAILURE);return r}function Zs(e){let t=i=>se([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...i]),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 i of e.agentGuidanceNextSteps){let a=e.target.mode==="workspace-discovery"?i:i.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(a)||n.push(a)}return n}async function Qs(e,t,n,i=wa){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 i({pmRoot:e,workspaceRoot:t});a.gitattributes.changed&&n.push(`updated:merge_fence:${a.gitattributes.path}`)}catch(a){if(!(a instanceof u))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 $f(e,t,n,i){if(e==null||n==="status")return;let a=await ga(e,{pmRoot:t});a.changed&&i.push(`updated:gitignore:${a.path}`)}async function vb(e,t,n={}){let i=t[of],a=typeof i=="string"?i:process.cwd(),r=zs(a,t,e,n.workspace),o=r.pmRoot;e=Gs(r.prefixArg,n.idPrefix);let s=pf(n);await Ks(o,r.target.mode==="tracker-path",n.force===!0);let d=[],c=[],l=R.join(o,"settings.json"),p=await k(l),m;p&&(m=await Ds({pmRoot:o,settingsPath:l,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:r.target}));let y=await Vs(o,ln);d.push(...y.createdDirs),c.push(...y.warnings),m??=await Ds({pmRoot:o,settingsPath:l,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:r.target});let{settings:g}=m,_=xf(r.target),f=await ya(_??R.dirname(o)),w=_??f,v=await vf({pmRoot:o,cwd:w??a,agentGuidanceMode:s.agentGuidanceMode,settings:g,warnings:c}),S=await bf(o,g);d.push(...S.createdDirs),c.push(...S.warnings);let x=await kf({pmRoot:o,settings:g,typePreset:s.typePreset,warnings:c});x&&(g=await I(o)),await Sf({pmRoot:o,settings:g,createdDirs:d,warnings:c}),await $f(w,o,s.agentGuidanceMode,c),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await Qs(o,f,c);let C=await Ef(s.installBundledPackages,t,o,c),ie=Zs({installBundledPackages:s.installBundledPackages,registeredTypePreset:x,agentGuidanceNextSteps:v.next_steps,target:r.target});return{ok:!0,path:o,target:r.target,settings:await wf(g),created_dirs:d,warnings:c,governance_preset:g.governance.preset,wizard_used:m.wizardUsed,...x?{registered_type_preset:x}:{},...C?{installed_packages:C}:{},next_steps:ie,agent_guidance:v}}export{Of as a,bn as b,In as c,Pa as d,Jf as e,yc as f,qf as g,An as h,bc as i,kc as j,Sc as k,La as l,yp as m,Je as n,Xa as o,Be as p,He as q,Za as r,Ka as s,qe as t,We as u,Va as v,Ec as w,nh as x,oh as y,Ma as z,Tc as A,Sh as B,ar as C,cr as D,ud as E,fd as F,E_ as G,T_ as H,A_ as I,vt as J,O_ as K,C_ as L,P_ as M,R_ as N,N_ as O,D_ as P,L_ as Q,j_ as R,F_ as S,M_ as T,U_ as U,z_ as V,G_ as W,J_ as X,q_ as Y,W_ as Z,B_ as _,H_ as $,K_ as aa,V_ as ba,Y_ as ca,X_ as da,Z_ as ea,Q_ as fa,ew as ga,Z as ha,b as ia,Ln as ja,Nd as ka,pe as la,zt as ma,hd as na,ct as oa,Gt as pa,Er as qa,Nr as ra,Vn as sa,Hr as ta,yy as ua,_o as va,Mp as wa,Ao as xa,Oo as ya,Uo as za,ro as Aa,mp as Ba,Sm as Ca,so as Da,si as Ea,ks as Fa,Hv as Ga,Ns as Ha,of as Ia,_b as Ja,wb as Ka,vb as La};
71
+ //# sourceMappingURL=chunk-2UTJ5QIE.js.map