@unbrained/pm-cli 2026.11.25 → 2026.11.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/commander-usage.js +9 -9
- package/dist/cli/error-guidance.js +5 -5
- package/dist/cli/help-content.js +4 -4
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli/runtime/selection.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-LPW7S5KA.js → chunk-5AAIRHNE.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-5BPDT7G2.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-7EPYCU7U.js → chunk-5FY2VHRF.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-YIGBEY7K.js → chunk-7F3UFYZA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-B2GM6KOM.js +2 -0
- package/dist/cli-bundle/chunks/chunk-BITDGTAX.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-L6VS7F3R.js → chunk-CBBKXTJG.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-DUJSME77.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-OWK2JL4I.js → chunk-DYL2N3OC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GBVF2ZB3.js → chunk-FWBR3OW7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OS5W4ZG2.js → chunk-GQXK4KKH.js} +31 -31
- package/dist/cli-bundle/chunks/{chunk-FHLOGAGA.js → chunk-HOLQZ56F.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-HTGN24XM.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-K34FR5CO.js → chunk-IGW3RVJC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FVY7U3SU.js → chunk-KCRRTJ4X.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DF6A7C32.js → chunk-KES4VHU4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CZEMEPPQ.js → chunk-LNZKNVMT.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-MNFCJNQA.js +35 -0
- package/dist/cli-bundle/chunks/{chunk-CONBVY2O.js → chunk-NDS4MXZX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BVJMVU4Z.js → chunk-PQSEEVOA.js} +6 -6
- package/dist/cli-bundle/chunks/chunk-QMM46SJM.js +4 -0
- package/dist/cli-bundle/chunks/chunk-RFK3ERYX.js +2 -0
- package/dist/cli-bundle/chunks/chunk-T3GJPXIZ.js +69 -0
- package/dist/cli-bundle/chunks/{chunk-CNUFU454.js → chunk-WZOJSHJT.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-C4KIZQHW.js → chunk-XRCE4QNL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SCIPT7WF.js → chunk-ZDL45VTB.js} +2 -2
- package/dist/cli-bundle/chunks/{field-option-collisions-QE65APSD.js → field-option-collisions-CGRJEAPQ.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-INDHJV6X.js → item-revision-FGDR5NSF.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-C3KAMEYO.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-actor-KU7BMLUN.js → mutation-actor-HGG47KXV.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-3OMCTQD4.js → mutation-admission-LLHIRY6O.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-3GV3LBOT.js → register-list-query-EKSCZWEZ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-GZLF47SX.js → register-mutation-ZIAOKKUJ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-PBJZGCAL.js → register-operations-ECVBZ5FM.js} +2 -2
- package/dist/cli-bundle/chunks/register-setup-3QYD5H4H.js +2 -0
- package/dist/cli-bundle/chunks/{stage-3WIZBD4N.js → stage-RSCSUYEJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-VU2PH4PF.js → chunk-3BR5NWQI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BOIMP2AR.js → chunk-3GQRWIT5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-X4EWD6TL.js → chunk-AAB3ZR7Z.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-C3FEDTSD.js → chunk-AVLB4L7M.js} +26 -26
- package/dist/cli-bundle/focused-chunks/{chunk-5RBC4WSE.js → chunk-FQWKESMI.js} +58 -59
- package/dist/cli-bundle/focused-chunks/{chunk-BYQK5DGH.js → chunk-FW5Q26HA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GQBWI4KA.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-TQIKDFOD.js → chunk-IWEGGRRD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZLRRII55.js → chunk-JUG3BAZZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KEZ4VXYD.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-XKLBTDJ7.js → chunk-NSFS3VWP.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-TRL4JDWX.js → chunk-NXUFVQ33.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YYEWIKNI.js → chunk-QNWNUQSJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QSRXF6XS.js +15 -0
- package/dist/cli-bundle/focused-chunks/{chunk-WVA5KOXF.js → chunk-R6QFPHWW.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-PKX2EHE3.js → chunk-RDELKGLS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3Y5PTQ2F.js → chunk-RFJ3MEFP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SXC2EO3E.js → chunk-RMJKVQYE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UWWAVXG4.js → chunk-TNVLDU7Z.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-UA2JNKMY.js +4 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7SSGTGZO.js → chunk-VV2QF5IE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MB56Y4M6.js → chunk-WHHFPATO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JOKRDFMQ.js → chunk-YNRW2FWB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4LQL4EO6.js → chunk-YSZZSV6M.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{field-option-collisions-5ROXGUME.js → field-option-collisions-WV6GPYYP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-revision-KYMSQVZE.js → item-revision-RPTXN7WW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-I4HLVHEJ.js → item-transaction-A6MVNPT7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-actor-GGOQKAE6.js → mutation-actor-6ZVW6OME.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-OS36ZCMH.js → mutation-admission-2DA4CINP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-4ZFWJUKO.js → stage-RG3PKST7.js} +2 -2
- package/dist/cli-bundle/main.js +26 -26
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +63 -63
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/reproducibility/context.d.ts +2 -0
- package/dist/core/reproducibility/context.js +1 -1
- package/dist/sdk/cli-bootstrap.d.ts +17 -0
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/completion/shared.d.ts +1 -1
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/extension/bundled-catalog.js +1 -1
- package/dist/sdk/extension/install-sources.js +5 -5
- package/dist/sdk/extension/listing-fields.d.ts +15 -0
- package/dist/sdk/extension/listing-fields.js +2 -0
- package/dist/sdk/extension/managed-update-status.js +1 -1
- package/dist/sdk/extension/npm-spec.d.ts +18 -0
- package/dist/sdk/extension/npm-spec.js +2 -0
- package/dist/sdk/extension/static-inventory.d.ts +53 -1
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/extension/update-check.js +1 -1
- package/dist/sdk/extension/update-observations.js +3 -0
- package/dist/sdk/extension/upgrade-hints.js +2 -0
- package/dist/sdk/extension.d.ts +2 -0
- package/dist/sdk/extension.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/upgrade.d.ts +7 -2
- package/dist/sdk/governance/upgrade.js +2 -2
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.d.ts +20 -7
- package/dist/sdk/query/context.js +4 -2
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/testing.d.ts +20 -2
- package/docs/COMMANDS.md +19 -1
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +6 -0
- package/docs/EXTENSION_LIFECYCLE.md +72 -2
- package/docs/SDK.md +21 -2
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4FZH5BTV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-GZI7ZAB7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-LOX3VY4T.js +0 -2
- package/dist/cli-bundle/chunks/chunk-VA4T37Q4.js +0 -70
- package/dist/cli-bundle/chunks/chunk-WQOEVGLQ.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XHCIOLJP.js +0 -3
- package/dist/cli-bundle/chunks/chunk-XKWJONAO.js +0 -2
- package/dist/cli-bundle/chunks/chunk-ZBOQEZ2H.js +0 -33
- package/dist/cli-bundle/chunks/chunk-ZLICQPRG.js +0 -3
- package/dist/cli-bundle/chunks/item-transaction-LCKK4XXB.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-ZLJEF6NZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-A4R57E4K.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IAOKVKWW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VMYVN36N.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-WL2R7T5G.js +0 -2
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import{i as mi,n as fi,p as hi}from"./chunk-LNZKNVMT.js";import{f as ui}from"./chunk-KHFUHGL3.js";import{c as re,d as x,e as Pt,f as gi,g as qe,h as _n,i as _i,j as yi,l as ce,m as ot,n as Rt,o as wi,p as Nt,q as vi,u as ki}from"./chunk-QMM46SJM.js";import{_ as Ct}from"./chunk-5FY2VHRF.js";import{$a as ei,Ab as fn,Ca as Vr,Da as Pe,Ea as it,Fa as Xr,Ga as Yr,Ha as ne,Ia as Ue,Ja as Zr,Ka as se,R as Rr,Vc as hn,ab as ti,bb as Ee,cb as ni,db as ri,ec as si,hb as ii,ia as Se,nb as oi,qb as It,rb as Ot,ub as Re,zb as ai}from"./chunk-KCRRTJ4X.js";import{I as Ge,a as Wr,b as Br,d as un,e as Hr,f as Kr,g as be,m as Qr,p as fe,r as mn,v as A,w as he}from"./chunk-XRCE4QNL.js";import{Bg as Fr,Dh as W,Eg as Mr,Fa as Cr,Fg as Ur,Mb as Q,Oh as H,Pg as Gr,Qa as Pr,Sg as Ce,T as $r,U as Ar,V as B,a as bt,b as vr,ba as M,c as cn,ca as Tr,d as dn,da as Oe,e as ln,ea as Ir,g as kr,gc as jr,gh as pn,h as xr,ih as At,k as br,kh as ke,mh as xe,nc as q,ph as zr,r as Er,rh as Tt,sc as Dr,sh as Jr,ta as Y,th as qr,wg as ve}from"./chunk-WZOJSHJT.js";import{a as ci,b as ze,c as Je,d as di,e as li,m as pi,n as gn}from"./chunk-IGW3RVJC.js";import{Q as I,n as Sr,v as Or,x as ae}from"./chunk-DUJSME77.js";import{E as O,F as V,H as Nr,J as K,K as Z,M as Lr,O as rt,Q as $t,d as Et}from"./chunk-SX76UGEY.js";import{A as h,C as f,E as S,F as St,G as Me,H as U,K as me,a as _r,d as xt,t as sn,v as yr,y as wr}from"./chunk-6OIHST4I.js";import{AsyncLocalStorage as Ys}from"node:async_hooks";import xi from"node:path";var bi=new Ys;function Si(e,t){return bi.run({...e,pmRoot:xi.resolve(e.pmRoot)},t)}function af(e,t){let n=bi.getStore();return n!==void 0&&n.pmRoot===xi.resolve(e)&&n.transactionId===t?n.step:void 0}import{mkdir as Zs,readFile as Qs}from"node:fs/promises";import $i from"node:path";import{createHash as ec}from"node:crypto";var yn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Ai="sdk-workspace-transaction",Ti=/^[a-zA-Z0-9._-]+$/,Ii=30,Oi=3e3;function bn(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Ti.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function wn(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 Sn(e){return{pmRoot:wn(e.pmRoot,"Transaction pmRoot"),transactionId:bn(e.transactionId,"Transaction id"),author:wn(e.author,"Transaction author")}}function jt(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function Ci(e,t){return $i.join(e,"transactions","sdk",`${t}.json`)}async function de(e,t){t.updatedAt=I();let n=Ci(e,t.transactionId);await Zs($i.dirname(n),{recursive:!0}),await me(n,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`)}function tc(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"&&nc(e)}function nc(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"&&Ti.test(t.supersededBy)&&t.supersededBy!==e.transactionId)}function Ne(e){return Object.assign(Object.create(null),e)}function Pi(e,t){try{let n=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function vn(e,t){return e===void 0?void 0:Pi(e,t)}function kn(e,t,n,r){let i=vn(n,r);i===void 0?delete e[t]:e[t]=i}function Ei(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function xn(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function rc(e,t){if(!xn(e.startedStepIds,t)||!xn(e.completedStepIds,t)||!Ei(e.results)||!Ei(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,o=new Set(i);return Object.keys(e.compensationData).some(a=>!r.has(a))||Object.keys(e.results).some(a=>!o.has(a))?!1:e.status==="committed"?t.every(a=>o.has(a)):!["compensated","abandoned"].includes(e.status??"")||o.size===0&&r.size===0}function Lt(e,t){return new f(`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 Ri(e){return new f(`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 ic(e,t,n){return n===void 0||e.abandonment!==void 0||e.status==="compensated"||t.length===n.length&&t.every((r,i)=>r===n[i])}function oc(e,t,n){let r;try{r=JSON.parse(e)}catch{throw Lt(t,"invalid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw Lt(t,"expected an object");let i=r;if(!((i.schemaVersion===1||i.schemaVersion===2)&&i.transactionId===t))throw Lt(t,"schema version or transaction id does not match the journal file");let a=i.stepIds;if(!Array.isArray(a)||!xn(a,a)||!rc(i,a)||!tc(i)||typeof i.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(i.status))throw Lt(t,"invalid lifecycle, metadata, status or step ids");if(!ic(i,a,n))throw Ri(t);return{...i,results:Ne(i.results),compensationData:Ne(i.compensationData)}}async function ac(e,t,n,r,i){let o=i,a=o!==void 0;if(o?.status==="compensating"&&await En(e,o),o===void 0||o.status==="compensated"){let s=I();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:Ne(),compensationData:Ne(),...e.recoveryData===void 0?{}:{recoveryData:Pi(e.recoveryData,"Transaction recovery data")}},await de(e.pmRoot,o),await ge(e,o,"prepared")}return{journal:o,recovered:a}}async function sc(e,t,n){try{await cc(t,e.steps),await de(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let o of e.steps){if(r.has(o.id))continue;let a=await o.inspect(),s=vn(a.result,`Step ${o.id} result`);if(a.state!=="applied"){let c=await o.prepareCompensation?.();kn(t.compensationData,o.id,c,`Step ${o.id} compensation data`),i.add(o.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await de(e.pmRoot,t);let d=await o.apply();s=vn(d,`Step ${o.id} result`)}await ge(e,t,"step_applied",o.id),r.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),kn(t.results,o.id,s,`Step ${o.id} result`),await de(e.pmRoot,t),await ge(e,t,"step_recorded",o.id)}return await ge(e,t,"committing"),t.status="committed",await de(e.pmRoot,t),await ge(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Ne(t.results)}}catch(r){if(r instanceof yn||t.status==="committed")throw r;try{await En(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function Dt(e,t,n){try{return oc(await Qs(Ci(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&Me(r))return;throw r}}async function ge(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function cc(e,t){let n=new Set,r=Ne();for(let i of t){let o=await i.inspect();o.state==="applied"&&(n.add(i.id),kn(r,i.id,o.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function En(e,t){t.status="compensating",await de(e.pmRoot,t),await ge(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!r.has(i.id)&&!n.has(i.id))continue;let o;try{let a=(await i.inspect()).state;o=r.has(i.id)&&(a==="applied"||a==="pending"&&i.compensatePending===!0)}catch{o=r.has(i.id)}o&&(await ge(e,t,"step_compensating",i.id),await Si({pmRoot:e.pmRoot,transactionId:t.transactionId,step:i},()=>i.compensate(t.compensationData[i.id]))),n.delete(i.id),r.delete(i.id),t.completedStepIds=e.steps.map(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>r.has(a)),delete t.results[i.id],delete t.compensationData[i.id],await de(e.pmRoot,t),await ge(e,t,"step_compensated",i.id)}t.status="compensated",await de(e.pmRoot,t),await ge(e,t,"compensated")}async function Ni(e){let{pmRoot:t,transactionId:n,author:r}=Sn(e),i=jt(e.lockTtlSeconds,Ii,"Transaction lock TTL"),o=jt(e.lockWaitMs,Oi,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(l=>{let p=bn(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 c={...e,pmRoot:t,transactionId:n,author:r,steps:a,lockTtlSeconds:i,lockWaitMs:o},d=await Q(t,Ai,i,r,!1,!1,o);try{let l=await Dt(t,n,s);if(l?.status==="abandoned"||l?.abandonment!==void 0)throw Li(l);let p=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Ne(l.results)};let u=await ac(c,n,r,s,l);return await sc(c,u.journal,p||u.recovered)}finally{await d()}}function Li(e){let t=e.status!=="abandoned",n=e.abandonment.supersededBy,r=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 f(t?`Transaction ${e.transactionId} retirement is incomplete`:`Transaction ${e.transactionId} has been abandoned`,h.CONFLICT,{code:"transaction_abandoned",required:t?r:"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:[r]}:{}})}async function wf(e,t){let n=Sn({pmRoot:e,transactionId:t,author:"reader"});return Dt(n.pmRoot,n.transactionId)}function dc(e){return ec("sha256").update(JSON.stringify(e.stepIds)).digest("hex")}async function vf(e){let t=Sn(e),n=wn(e.reason,"Abandonment reason"),r=e.supersededBy===void 0?void 0:bn(e.supersededBy,"Replacement transaction id");if(r===t.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");let i=jt(e.lockTtlSeconds,Ii,"Transaction lock TTL"),o=jt(e.lockWaitMs,Oi,"Transaction lock wait"),a=await Q(t.pmRoot,Ai,i,t.author,!1,!1,o);try{let s=await Dt(t.pmRoot,t.transactionId);if(s===void 0)throw new f(`Transaction ${t.transactionId} was not found`,h.NOT_FOUND);if(s.status==="committed")throw new f(`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!==r)throw Li(s);if(s.status==="abandoned")return s;let c=e.resolveSteps(structuredClone(s));if(JSON.stringify(c.map(d=>d.id))!==JSON.stringify(s.stepIds))throw Ri(t.transactionId);if(s.abandonment===void 0){if(r!==void 0&&await Dt(t.pmRoot,r)!==void 0)throw new f(`Replacement transaction ${r} already exists`,h.CONFLICT);s.schemaVersion=2,s.abandonment={reason:n,author:t.author,...r===void 0?{}:{supersededBy:r}},await de(t.pmRoot,s)}return s.status!=="compensated"&&await En({...e,...t,steps:c},s),await lc(s,t.pmRoot,i,o),s.status="abandoned",await de(t.pmRoot,s),s}finally{await a()}}async function lc(e,t,n,r){let i=dc(e);if((await Dr(Br(t),Wr)).some(s=>s.op==="transaction_abandon"&&s.context?.transaction_id===e.transactionId&&s.context?.attempt===e.attempt&&s.context?.plan_digest===i))return;let a=e.abandonment;await Hr({pmRoot:t,author:a.author,lockTtlSeconds:n,lockWaitMs:r,op:"transaction_abandon",message:a.reason,context:{transaction_id:e.transactionId,attempt:e.attempt,plan_digest:i,...a.supersededBy===void 0?{}:{superseded_by:a.supersededBy}}})}import pc from"node:fs/promises";import uc from"node:path";function $n(e){return uc.join(e,"extension-migrations.json")}function ji(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 Di(e,t){return`${e.layer}:${e.name}:${t}`}async function mc(e){let t=$n(e);if(!await S(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await pc.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function fc(e,t){let n=await mc(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let a=ji(i,o),s=r.get(Di(i,a));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function hc(e){let t=await fc(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),r=[],i=!1,o=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 o){let u=ji(l,p),_=Di(l,u),g=n.get(_),w=String(l.definition.status??"pending").toLowerCase(),m=g?.status??(w==="applied"||w==="failed"?w:"pending");if(m==="applied"){r.push({key:_,layer:l.layer,extension:l.name,id:u,before:m,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:_,layer:l.layer,extension:l.name,id:u,before:m,outcome:"pending"});continue}let y=l.runtime_definition?.run??l.definition.run;if(typeof y!="function"){r.push({key:_,layer:l.layer,extension:l.name,id:u,before:m,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(y({id:u,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:m}));let k={key:_,layer:l.layer,extension:l.name,id:u,status:"applied",attempted_at:v};n.set(_,k),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:_,layer:l.layer,extension:l.name,id:u,before:m,outcome:"applied"}),i=!0}catch(k){let b=k instanceof Error?k.message:String(k),L={key:_,layer:l.layer,extension:l.name,id:u,status:"failed",attempted_at:v,error:b};n.set(_,L),l.definition.status="failed",l.definition.reason=b,r.push({key:_,layer:l.layer,extension:l.name,id:u,before:m,outcome:"failed",error:b}),i=!0}}if(i){let l=await A(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((u,_)=>u.key.localeCompare(_.key))};await be({pmRoot:e.pmRoot,filePath:$n(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 a=r.filter(l=>l.outcome==="pending").length,s=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:$n(e.pmRoot),total:r.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function Fi(e){let t=await A(e.resolvedRoots.settings_root),n=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await xe(n);e.warnings.push(...n.warnings,...r.warnings);let i=await hc({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}var gc=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function We(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Tt(t.extensionName));for(let m of t.extensionNames??[])n.add(Tt(m));let r=m=>n.size===0||n.has(Tt(m)),i=(m,y)=>Mi(m.filter(v=>r(v.name)).map(y)),o=(m,y)=>Mi(m.filter(v=>r(v.name)).flatMap(y)),{registrations:a,commands:s,parsers:c,preflight:d,services:l,renderers:p,hooks:u}=e,_=o(a.relationship_kinds??[],m=>m.definitions.map(y=>y.kind)),g=p.overrides.filter(m=>r(m.name)&&((m.commands?.length??0)>0||m.resultDiscriminator!==void 0)).map(m=>({format:m.format,commands:[...m.commands??[]],result_discriminator:m.resultDiscriminator!==void 0})).sort((m,y)=>m.format.localeCompare(y.format)),w=i(a.assurance_providers??[],m=>m.definition.id);return{capabilities:Jr(e,t),commands:i(a.commands,m=>m.command),command_overrides:i(s.overrides,m=>m.command),command_handlers:i(s.handlers,m=>m.command),hooks:gc.filter(([m])=>u[m].some(y=>r(y.name))).map(([,m])=>m),flag_commands:i(a.flags,m=>m.target_command),item_types:o(a.item_types,m=>m.types.map(y=>y.name)),item_fields:o(a.item_fields,m=>m.fields.map(y=>y.name)),..._.length>0?{relationship_kinds:_}:{},migrations:o(a.migrations,m=>typeof m.definition.id=="string"?[m.definition.id]:[]),profiles:i(a.profiles,m=>m.profile.name),importers:i(a.importers,m=>m.importer),exporters:i(a.exporters,m=>m.exporter),search_providers:i(a.search_providers,m=>m.definition.name),vector_store_adapters:i(a.vector_store_adapters,m=>m.definition.name),...w.length>0?{assurance_providers:w}:{},parser_overrides:i(c.overrides,m=>m.command),service_overrides:i(l.overrides,m=>m.service),renderer_overrides:i(p.overrides,m=>m.format),...g.length>0?{renderer_ownership:g}:{},preflight_overrides:d.overrides.filter(m=>r(m.name)).length,preflight_ownership:d.overrides.filter(m=>r(m.name)).map(m=>({commands:[...m.commands??[]]}))}}function Mi(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}var at={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Ft={type:"array",minItems:1,maxItems:cn,items:at},Ui={...Ft,items:{...at,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},_c={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,Ft])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:at,id:at}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Ui}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Ft}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Ui,authors:Ft}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:cn,items:{type:"array",minItems:2,maxItems:2,items:at}}}}]}}},Pf={$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:vr,items:_c}}};async function jf(e,t,n,r){let i=await Ee(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Gi(i,t,n,r)}function yc(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Gi(e,t,n=5,r=!1){let i=[],o=new Map,a=e.policies.filter(m=>m.rule.kind==="require_fields"),s=a.filter(m=>m.subject?.operations===void 0),c=new Set,d=0,l=0,p=0,u=0,_=0,g=br(e);for(let m of t){let y=g({operation:"",author:"",before:m,after:m,completeness_only:!0});d+=+(y.decisions.length>0),l+=y.decisions.length,y.decisions.forEach(b=>c.add(b.policy_id));let v=y.decisions.filter(b=>!b.satisfied);if(v.length===0)continue;u+=1;let k=o.get(m.type)??{items:0,violations:0,missing_fields:0};k.items+=1;for(let b of v)p+=1,k.violations+=1,k.missing_fields+=b.missing_fields.length,b.effect==="refuse"&&(_+=1),i.length<n&&i.push({id:m.id,type:m.type,status:m.status,decision:b});o.set(m.type,k)}let w=r||_>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:w,ok:w==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:a.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:l,governed_items:d,ungoverned_items:t.length-d,contract_status:yc(a.length,t.length,d),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:u,violation_count:p,refused_violations:_,missing_by_type:Object.fromEntries(o),violations:i,violations_truncated:i.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}import wc from"node:path";function vc(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([t,n])=>({id:`completeness-${t.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${t} work reaches completion.`,subject:{types:[t],statuses:["closed"]},rule:{kind:"require_fields",fields:[...n]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function qi(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new f("Policy definition must be valid JSON.",h.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new f("Policy definition must be an object.",h.USAGE);return t}async function kc(e,t){let n=M(process.cwd(),e.path);await Ge(n);let r=await A(n);return{pmRoot:n,settings:r,author:q(t,r.author_default)}}function zi(e,t,n,r){if(e==="policy-mode")return ln({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let o=dn(r.definition),a=ln({...n,policies:[...i,o].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(a,null,2)}
|
|
4
|
+
`)>ei)throw new f("Policy registry exceeds its byte ceiling.",h.USAGE);return a}async function Ji(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:zi(e,t,await Ee(r.pmRoot),n)};let i=await Kr({pmRoot:r.pmRoot,filePath:wc.join(r.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:r.author,message:n.message,lockTtlSeconds:r.settings.locks.ttl_seconds,lockWaitMs:r.settings.locks.wait_ms,mutate(o){let a=zi(e,t,ti(o),n);return{raw:`${JSON.stringify(a,null,2)}
|
|
5
|
+
`,result:a}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function xc(e,t,n){let r,i=await ai({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(o){let s=(await Ee(n.pmRoot)).policies.find(c=>c.id===t.policy);if(!s||s.rule.kind!=="approval")throw new f("--policy must name an approval rule.",h.USAGE);if(!s.rule.authors.includes(n.author))throw new f("This actor is not a declared approver.",h.CONFLICT);return await ni(n.pmRoot,o.metadata.id),r={policy_id:s.id,policy_fingerprint:kr(s),content_fingerprint:xr(s,{...o.metadata,body:o.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...r,warnings:i.warnings}}}function bc(e,t){let n=qi(t),r=dn({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==r.id)throw new f("Policy id operand does not match definition.id.",h.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return r}async function Yf(e,t,n={},r={}){if(!bt.includes(e))throw new f("Unknown workflow policy action.",h.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:vc()};let i=await kc(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Ee(i.pmRoot)};if(e==="policy-put"){let l=bc(t,n.definition);return Ji(e,l.id,{...n,definition:l},i)}if(!t?.trim())throw new f(`schema ${e} requires an operand.`,h.USAGE);if(["policy-remove","policy-mode"].includes(e))return Ji(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new f("Use policy-check to preview; policy-approve records an approval.",h.USAGE);return xc(t,n,i)}let o=B(i.settings,W()),a=await It(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,o.type_to_folder);if(!a)throw new f(`Item ${t} not found.`,h.NOT_FOUND);let{document:s}=await Ot(a,{schema:i.settings.schema}),c={...s.metadata,body:s.body},d=n.definition===void 0?c:{...c,...qi(n.definition)};if(d.id!==c.id)throw new f("Policy preview cannot change the item id.",h.USAGE);return{policy_result:!0,action:e,changed:!1,result:await ri(i.pmRoot,await Ee(i.pmRoot),{operation:"update",author:i.author,before:c,after:d,completeness_only:n.definition===void 0})}}import{createHash as Xi}from"node:crypto";import Ve from"node:fs/promises";import Xe from"node:path";var Sc=new Set(Et),Le=new Set(Nr.map(e=>O(e.id)).filter(e=>e.length>0));function Ec(e){let t=new Set;for(let n of e){let r=O(n);r.length>0&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function Wi(e){let t=O(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(Le.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...Le].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let a=new Set;for(let s of e.roles){let c=typeof s=="string"?s.trim().toLowerCase():"";if(c.length!==0){if(!Sc.has(c))throw new Error(`Invalid status role "${s}". Allowed roles: ${Et.join(", ")}.`);a.has(c)||(a.add(c),n.push(c))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${Et.join(", ")}.`)}let r=e.aliases===void 0?void 0:Ec(e.aliases).filter(a=>a!==t),i=e.description?.trim(),o=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:r,description:i&&i.length>0?i:void 0,order:o}}function $c(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 Ac(e){let t=$c(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let i=r;typeof i.id!="string"||i.id.trim().length===0||n.push(i)}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:Ac(t)}}function He(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
|
|
6
|
+
`}function Bi(e,t,n){let r=e.statuses.slice(),i=r.findIndex(s=>O(s.id)===t.id),o=i>=0?r[i]:n,a={...o,id:t.id};return t.roles!==void 0&&(t.roles.length>0?a.roles=[...t.roles]:a.roles!==void 0&&delete a.roles),t.aliases!==void 0&&(t.aliases.length>0?a.aliases=[...t.aliases]:a.aliases!==void 0&&delete a.aliases),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),i>=0?r[i]=a:r.push(a),{file:{statuses:r},definition:a,replaced:o!==void 0}}function Hi(e,t){let n=O(t);if(n.length===0)throw new Error("Status id must not be empty.");if(Le.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...Le].join(", ")}.`);let r=e.statuses.slice(),i=r.findIndex(a=>O(a.id)===n);if(i<0)return{file:{statuses:r},removed:!1};let[o]=r.splice(i,1);return{file:{statuses:r},removed:!0,definition:o}}function An(e,t){let n=[e.id,...e.aliases??[]];for(let r of n){let i=O(r);if(i.length===0)continue;let o=t.get(i);if(o!==void 0&&o!==e.id)throw new Error(`Status token "${i}" already belongs to status "${o}". Choose a different id/alias to avoid shadowing it.`)}}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 Yi(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 Zi(e,t){let n=In(e),r=_e(t,"migrationScope");return`auto-${Xi("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function In(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:O(_e(e.from,"source")),to:O(_e(e.to,"target")),...e.type===void 0?{}:{type:_e(e.type,"type")}}:{kind:e.kind,from:O(_e(e.from,"source")),to:O(_e(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Tc(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Ic(e,t,n){let r=K(t.schema),i=Tc(n);return Z(e,r.files[i],V[i])}function Qi(e,t){return Xe.join(e,"transactions","schema",`${t}-plan.json`)}function Mt(e){return e.length===0?null:JSON.parse(e)}async function Ke(e){let t=await U(e);return{exists:t!==null,raw:t??""}}async function eo(e,t){t.exists?await me(e,t.raw):await Ve.rm(e,{force:!0})}function Oc(e,t,n){let r=ne(e),i=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),o=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return se(r);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[i],name:t.to})}else i>=0&&r.definitions.splice(i,1);return se(r)}function to(e,t){return{...e,key:t,metadata_key:t,front_matter_key:t,cli_flag:t.replaceAll("_","-")}}function Cc(e,t,n){if(t.kind!=="rename-field"||n)return;let r=e.schema.fields.find(i=>O(i.key)===t.from);r!==void 0&&gn(to(r,t.to))}function Pc(e,t,n){let r=ze(e),i=r.fields.findIndex(a=>a.key===t.from),o=r.fields.findIndex(a=>a.key===t.to);if(n==="stage"){if(o>=0)return Je(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let a=to(r.fields[i],t.to);gn(a),r.fields.push(a)}else i>=0&&r.fields.splice(i,1);return Je(r)}function Rc(e,t,n){let r=Be(e),i=r.statuses.findIndex(a=>a.id===t.from),o=r.statuses.findIndex(a=>a.id===t.to);if(n==="stage"){if(o>=0)return He(r);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[i],id:t.to})}else i>=0&&r.statuses.splice(i,1);return He(r)}function Nc(e,t,n){return t.kind==="rename-type"?Oc(e,t,n):t.kind==="rename-field"?Pc(e,t,n):Rc(e,t,n)}function $e(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function On(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Ye(e){return Array.isArray(e)?e.map(t=>On(t)).filter(t=>t!==void 0):[]}function Lc(e,t){for(let n of Ye(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>$e(r,t)));for(let n of Ye(e.type_workflows))n.type=$e(n.type,t)}function jc(e,t){for(let r of Ye(e.definitions))r.default_status=$e(r.default_status,t);let n=On(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=$e(i,t);for(let r of Ye(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(o=>$e(o,t)):i))}function Dc(e,t){for(let n of Ye(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>$e(i,t)));for(let r of["options","command_option_policies"])for(let i of Ye(n[r])){let o=r==="options"?"key":"option";i[o]=$e(i[o],t)}}}function Fc(e,t){let n=On(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=$e(n[r],t)}function Tn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?Lc(r,t):t.kind==="rename-field"?Dc(r,t):jc(r,t),Fc(r,t),`${JSON.stringify(r,null,2)}
|
|
7
|
+
`}function no(e,t){if(t.kind==="rename-type"){let r=ne(e).definitions;return{source:r.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=ze(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=Be(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function Mc(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 Uc(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 ro(e,t){let n=In(t.request),r=t.migrationId===void 0?Zi(n,t.migrationScope??"plan"):Yi(t.migrationId),i=e.map(c=>Uc(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),o=Xi("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),a=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!a.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:o,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function Gc(e){let t=B(e.settings,W()),n=[...new Set(Object.values(t.type_to_folder))],r=await oi(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},o=r?await ii({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:i}):null;return o?{items:o.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Re(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function zc(e,t){let n=await U(Qi(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new f(`Stored schema migration plan "${t}" is invalid: ${Cr(r)}`,h.GENERIC_FAILURE)}}async function Jc(e,t){let n=Qi(e,t.migration_id);await Ve.mkdir(Xe.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await me(n,`${JSON.stringify(r,null,2)}
|
|
8
|
+
`)}function qc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Wc(e){let t=await It(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new f(`Schema migration item "${e.id}" no longer exists.`,h.NOT_FOUND);return(await Ot(t,{schema:e.settings.schema})).document.metadata}function Ki(e,t,n){let r=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let o=e.metadata;if(Object.prototype.hasOwnProperty.call(o,i)&&!Object.prototype.hasOwnProperty.call(o,r))return[];if(!Object.prototype.hasOwnProperty.call(o,r)||Object.prototype.hasOwnProperty.call(o,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return o[i]=o[r],delete o[r],[r,i]}function Vi(e){return{id:e.id,inspect:async()=>{let t=await Ke(e.filePath),n=no(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Ke(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ke(e.filePath);return await me(e.filePath,Nc(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 eo(e.filePath,{exists:t.exists,raw:t.raw})}}}function Bc(e){return{id:e.stepId,inspect:async()=>{let t=await Ke(e.filePath);return{state:Tn(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 me(e.filePath,Tn(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 eo(e.filePath,{exists:t.exists,raw:t.raw})}}}function Hc(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await A(e.pmRoot),n=B(t,W()).type_to_folder,r=await Wc({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=Mc(r,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await A(e.pmRoot),n=B(t,W()).type_to_folder,r=await fn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:Ki(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await A(e.pmRoot),n=B(t,W()).type_to_folder;await fn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:Ki(r,e.request,"reverse")}}})}}}async function Kc(e){let t=await zc(e.pmRoot,e.migrationId);if(t){if(!qc(t.request,e.request))throw new f(`Schema migration id "${e.migrationId}" already belongs to a different request.`,h.CONFLICT);return{plan:t,stored:!0}}let n=await Gc({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...ro(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Vc(e){let t=no(await U(e.schemaPath)??"",e.request);if(!t.source)throw new f(`Schema migration source "${e.request.from}" is not a custom definition.`,h.NOT_FOUND);if(t.target)throw new f(`Schema migration target "${e.request.to}" already exists.`,h.CONFLICT);await Jc(e.pmRoot,e.plan)}async function Xc(e){let t=K(e.settings.schema),n=[...new Set([["types",V.types],["fields",V.fields],["workflows",V.workflows]].map(([i,o])=>Z(e.pmRoot,t.files[i],o)).filter(i=>i!==e.schemaPath))];try{let i=Xe.join(e.pmRoot,"templates"),o=await Ve.readdir(i,{withFileTypes:!0});n.push(...o.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>Xe.join(i,a.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!Me(i))throw i}n.sort((i,o)=>i.localeCompare(o));let r=[];for(let i of n){let o=await U(i);o!==null&&Tn(o,e.request)!==o&&r.push({filePath:i,beforeRaw:o})}return{paths:n,snapshots:r}}async function Yc(e){for(let t of e.snapshots){let n=await Ve.readFile(t.filePath,"utf8"),r=Xe.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await un({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Mt(t.beforeRaw),after:Mt(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function Zc(e,t,n){let r=In(e),i=M(process.cwd(),n.path);await Ge(i);let o=t.migrationId===void 0?Zi(r,await Ve.realpath(i)):Yi(t.migrationId),a=await A(i),s=q(t.author,a.author_default),c=await Kc({pmRoot:i,settings:a,migrationId:o,request:r});Cc(a,r,c.stored);let d=c.plan;if(t.dryRun===!0)return{...d,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Ic(i,a,r),p=await U(l)??"";c.stored||await Vc({pmRoot:i,schemaPath:l,request:r,plan:d});let u=await Xc({pmRoot:i,schemaPath:l,settings:a,request:r}),_=[Vi({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...u.paths.map((y,v)=>Bc({filePath:y,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(y=>Hc({pmRoot:i,id:y.id,request:r,author:s,force:t.force===!0})),Vi({id:"retire-source",filePath:l,request:r,phase:"retire"})],g=await Ni({pmRoot:i,transactionId:`schema-${o}`,author:s,steps:_,lockTtlSeconds:Math.max(a.locks.ttl_seconds,300),lockWaitMs:a.locks.wait_ms}),w=await Ve.readFile(l,"utf8"),{historyPath:m}=await un({pmRoot:i,author:s,documentPath:Xe.relative(i,l).replaceAll("\\","/"),before:Mt(p),after:Mt(w),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await Yc({pmRoot:i,author:s,settings:a,request:r,plan:d,snapshots:u.snapshots}),{...d,action:r.kind,applied:!0,recovered:g.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:m}}function Qc(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(`
|
|
9
|
+
`)}import ao from"node:fs/promises";import je from"node:path";var Ut=["extensions","docs","examples","assets","prompts"],ed=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 td(e){return Ut.includes(e)}function nd(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],r=[];for(let i of n){if(typeof i!="string"||i.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);r.push(i.trim())}return[...new Set(r)].sort((i,o)=>i.localeCompare(o))}function rd(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new f("Package manifest field pm must be an object.",h.USAGE);let t={},n=e;for(let[r,i]of Object.entries(n)){if(!td(r))continue;let o=nd(r,i);o.length>0&&(t[r]=o)}return t}function le(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function Cn(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,r)=>n.localeCompare(r)):void 0}function io(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 id(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(r=>typeof r=="string")?n:void 0}function od(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(r=>typeof r=="string")?n:void 0}function ad(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:id(t.links),media:od(t.media),tags:Cn(t.tags)};return Object.values(n).some(r=>r!==void 0)?n:void 0}async function st(e){let t=je.join(e,"package.json");if(!await S(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await ao.readFile(t,"utf8"))}catch(s){throw new f(`Failed to parse package manifest at "${t}": ${String(s)}`,h.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new f(`Package manifest at "${t}" must be a JSON object.`,h.USAGE);let r=n,i=r.pm,o=i!=null,a=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};return{source:o?"pm":"convention",package_json_path:t,package_name:typeof r.name=="string"?r.name:void 0,package_version:typeof r.version=="string"?r.version:void 0,package_private:r.private===!0,package_description:typeof r.description=="string"?r.description:void 0,package_keywords:Cn(r.keywords),package_homepage:typeof r.homepage=="string"?r.homepage:void 0,package_repository_url:io(r.repository),package_bugs_url:io(r.bugs),aliases:Cn(a.aliases),resources:rd(i),catalog:ad(a.catalog)}}async function oo(e){if(!await S(e))return[];let t=await ao.readdir(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let i=je.join(e,r.name);await S(je.join(i,"manifest.json"))&&n.push(i)}return n.sort((r,i)=>r.localeCompare(i))}async function Gt(e){if(await S(je.join(e,"manifest.json")))return[e];let n=(await st(e)).resources.extensions??[],r=new Set;for(let i of n){if(i.includes("*")||i.startsWith("!"))throw new f(`Package extension entry "${i}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let o=je.resolve(e,i);if(!Y(e,o))throw new f(`Package extension entry "${i}" resolves outside package root.`,h.USAGE);if(await S(je.join(o,"manifest.json"))){r.add(o);continue}for(let a of await oo(o))r.add(a)}if(n.length===0)for(let i of ed.extensions)for(let o of await oo(je.join(e,i)))r.add(o);return[...r].sort((i,o)=>i.localeCompare(o))}function Pn(e,t,n,r){if(e==null||e===!1)return;let i=[...new Set(String(e).split(",").map(a=>a.trim()).filter(a=>a.length>0))];if(i.length===0)throw new f(`Package ${n} --fields requires a comma-separated list of field names`,h.USAGE);let o=i.filter(a=>!t.includes(a));if(o.length>0)throw new f(`Package ${n} --fields has unknown field(s): ${o.join(", ")}`,h.USAGE,{code:"invalid_argument_value",examples:[r??`pm package ${n} --fields ${t.slice(0,3).join(",")}`],recovery:{allowed_values:[...t],provided_fields:["--fields"]}});return i}function sd(e,t){return e.map(n=>Object.fromEntries(t.map(r=>[r,n[r]??null])))}var cd=["name","directory","version","entry","scope","active","enabled","runtime_active","activation_status","managed","source","update_available","last_update_check_at","last_update_remote_version","last_update_remote_commit","update_error","update_check_timeout_ms","update_check_status","update_check_reason","command_paths","action_paths","contributions"];function Rn(e,t){return Pn(e,cd,t)}function so(e,t){return t!==void 0?sd(e,t):e.map(n=>{let{contributions:r,...i}=n;return i})}import{execFile as wd}from"node:child_process";import C from"node:fs/promises";import Mn from"node:os";import $ from"node:path";import{fileURLToPath as vd}from"node:url";import{promisify as kd}from"node:util";import Un from"npm-package-arg";import{extract as xd,list as bd}from"tar";import dd from"node:fs/promises";import ie from"node:path";var ld="PM_CLI_PACKAGE_ROOT",co={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},pd=new Set(["*","all"]);function Nn(){let e=[],t=process.env[ld];return typeof t=="string"&&t.trim().length>0&&e.push(ie.resolve(t.trim())),e.push(ve(import.meta.url,["../../.."])),[...new Set(e)]}async function ct(e){let t=e.trim().toLowerCase(),n=await po(t);if(n)return n;let r=co[t];if(!r)return null;for(let i of Nn()){let o=ie.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await S(ie.join(o,"manifest.json")))return o}return null}function lo(e){return pd.has(e.trim().toLowerCase())}function ud(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function md(e,t){let n=await dd.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=ie.join(e,r.name);if(!await S(ie.join(i,"package.json")))continue;let o=await st(i),a=o.aliases&&o.aliases.length>0?o.aliases:[ud(r.name)];for(let s of a){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:i,package_name:o.package_name??null})}}}async function Ln(){let e=new Map;for(let t of Nn()){let n=ie.join(t,"packages");await S(n)&&await md(n,e)}for(let[t,n]of Object.entries(co))if(!e.has(t))for(let r of Nn()){let i=ie.join(r,"packages",n.package_directory);if(await S(ie.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function zt(){return(await Ln()).map(e=>e.alias)}async function po(e){let t=e.trim().toLowerCase();return(await Ln()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function uo(e){let t=await po(e);return t?(await st(t)).package_name??null:null}async function mo(e){let t=await ct(e);if(!t)return null;try{let n=await Gt(t);return n.length!==1?null:(await qe(n[0])).manifest.name}catch{return null}}function fd(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 hd(e,t,n,r,i,o){let a=r==="global"?"--global":"--project",s=Object.fromEntries(Ut.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||o.has(ie.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${a}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:fd(e),media:e.catalog?.media}}}async function fo(e,t,n={}){let r=At(M(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,o=await ce(i),a=new Set(o.state.entries.filter(u=>u.scope===e).filter(u=>u.source.kind!=="builtin").map(u=>ie.resolve(u.source.location))),s=new Set(o.state.entries.filter(u=>u.scope===e&&u.source.kind==="builtin").flatMap(u=>[u.source.name,u.source.input,u.source.location]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toLowerCase())),c=[],d=new Map;for(let u of await Ln()){let _=ie.resolve(u.package_root),g=d.get(_)??[];g.push(u),d.set(_,g)}for(let u of d.values()){let _=u[0],g=u.map(m=>m.alias).sort((m,y)=>m.localeCompare(y)),w=await st(_.package_root);c.push(hd(w,_,g,e,s,a))}let l=_d(n.fields),p=l?c.map(u=>yd(u,l)):c;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Ut.filter(u=>u!=="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 _d(e){return Pn(e,[...gd],"catalog","pm package catalog --project --fields alias,package_name,category")}function yd(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;return n}var _o=kd(wd),Jt="@unbrained/pm-cli",Sd={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},jn;async function yo(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=$.resolve(t);for(;;){let i=$.join(r,"node_modules",...n.split("/")),o=$.join(i,"package.json");if(await S(o))try{let s=JSON.parse(await C.readFile(o,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let a=$.dirname(r);if(a===r)return null;r=a}}function Dn(e,t,n){let r=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(r.length<2)return null;let i=r[0],o=r[1].replace(/\.git$/i,"");if(i.length===0||o.length===0)return null;let a=r.slice(2),s,c;return a[0]==="tree"&&a.length>=2?(s=a[1],c=a.slice(2).join("/")):a.length>0&&(c=a.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:o,repository:`https://github.com/${i}/${o}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function Ed(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new f('npm package source must include a package spec after "npm:".',h.USAGE);if(t)throw new f('Options "--gh/--github" cannot be combined with npm: package sources.',h.USAGE);if(n)throw new f('Option "--ref" cannot be combined with npm: package sources.',h.USAGE);return{kind:"npm",input:e,spec:r}}function dt(e,t={}){let n=e.trim();if(n.length===0)throw new f("Extension source is required for --install.",h.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Ed(n,t.forceGithub===!0,r);let i=(()=>{try{let a=new URL(n);if(a.hostname!=="github.com")return null;let s=a.pathname.replace(/^\/+/,"");return Dn(s,n,r)}catch{return null}})();if(i)return i;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let a=Dn(o,n,r);if(!a)throw new f(`Invalid GitHub source "${n}".`,h.USAGE);return a}if(t.forceGithub){let a=Dn(n,n,r);if(!a)throw new f(`Invalid GitHub shorthand "${n}".`,h.USAGE);return a}if(/^https?:\/\//i.test(n))throw new f(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,h.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function ho(e,t=_o,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new f(`Git command failed: git ${e.join(" ")}
|
|
10
|
+
${o}`,h.GENERIC_FAILURE)}}function Gn(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function zn(e=process.platform){return e==="win32"}async function wo(e,t,n=_o,r=process.platform,i=process.env){let o=Gn(r),a=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(o,e,{cwd:t,encoding:"utf8",env:a,shell:zn(r)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",d=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new f(`npm command failed: ${o} ${e.join(" ")}
|
|
11
|
+
${d}`,h.GENERIC_FAILURE)}}function vo(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}var $d=/^(?:(?:github|gitlab|bitbucket|gist):|git(?:\+[a-z]+)?:|[a-z][a-z0-9+.-]*:\/\/|[\w.-]+@[\w.-]+:)/iu;function Ad(e){if(!ko(e)){try{let t=Un(e.trim());if((t.type==="git"||t.type==="remote")&&!t.name)return}catch{}return vo(e)}}function Td(e){let t=e.trim(),n;try{n=Un(t)}catch{return}if(!(n.type!=="git"||n.name||$d.test(t)))throw new f(`npm:${t} names no local directory here, and npm would read it as a git repository.`,h.USAGE,{code:"npm_source_shorthand_ambiguous",required:"Spell the source explicitly: npm:./<path> for a local directory, or npm:github:<owner>/<repo> for a repository.",why:"A bare owner/repo npm spec means a local directory when one exists and a git host otherwise, so pm refuses to guess which code to install."})}function ko(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 Id(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("npm err! code e404")||n.includes("404 not found")||n.includes("is not in this registry")}function Od(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return Id(e)||n.includes("not found")}function Cd(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Pd(e){let t=vo(e),n=Cd(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,o=i?`pm package install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:o?[o,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:o?[`Try ${o} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&o?{fallback_candidates:[{source:i,command:o,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:o}:{}}}}}function Rd(e,t){if(!Od(t))return null;let n=Pd(e);return new f(n.message,h.NOT_FOUND,n.context)}async function xo(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await S(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=vd(t);return await S(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await S(t))return t}return null}async function Nd(e){let t=await xo(e);if(t)return t;let n=Ld(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Ld(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!ko(e))return e;let i=e.slice(0,r),o=e.slice(r+n.length);if(o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${i}@${$.resolve(t,o)}`;let a;try{a=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(a)?a.slice(1):a;return`${i}@${s}`}function go(e,t){let n=$.resolve(e,t),r=$.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${$.sep}`)||$.isAbsolute(r))throw new f("npm pack reported a package archive outside its isolated destination.",h.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function jd(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function Dd(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]).flatMap(({key:n,value:r})=>{let i=jd(r,n);return i?[i]:[]})}function Fd(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(a=>{let s=a.name?.trim().toLowerCase();return s!==void 0?s===n:a.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let i=e[0],o=i.name??i.key;return n&&o!==void 0&&o.trim().toLowerCase()!==n?void 0:i}function Md(e,t,n){let r;try{r=JSON.parse(e)}catch{let a=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!a)throw new f("npm pack did not report a tarball filename.",h.GENERIC_FAILURE);return{tarball:go(t,a)}}let i=Dd(r),o=Fd(i,n);if(!o)throw new f("npm pack --json returned an unsupported or ambiguous package receipt.",h.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:go(t,o.filename),package:o.name??o.key,version:o.version}}async function Ud(e){return Gd(e,wo)}async function Gd(e,t){let n=await xo(e.spec);if(n){if((await C.stat(n)).isFile()&&bo(n))return Fn(n);let a=$.join(n,"package.json"),s=await S(a)?JSON.parse(await C.readFile(a,"utf8")):{};return{directory:await qt(n,e.input),package:typeof s.name=="string"?s.name:void 0,version:typeof s.version=="string"?s.version:void 0,cleanup:async()=>{}}}Td(e.spec);let r=await C.mkdtemp($.join(Mn.tmpdir(),"pm-npm-package-source-")),i=$.join(r,"pack");await C.mkdir(i,{recursive:!0});try{let o=await Nd(e.spec),a=await t(["pack",o,"--json","--pack-destination",i]),s=Md(a,i,Ad(e.spec));if(!await S(s.tarball))throw new f("npm pack did not create its reported package archive.",h.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await Fn(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await C.rm(r,{recursive:!0,force:!0})}}}}catch(o){await C.rm(r,{recursive:!0,force:!0});let a=Rd(e.spec,o);throw a||o}}function bo(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ye(e){throw new f(e,h.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function zd(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&ye(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,i=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||i.some(o=>o===".."))&&ye(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&ye(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ye(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ye(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ye(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&ye(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function Fn(e,t=Sd){(await C.stat(e)).size>t.maxArchiveBytes&&ye(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await C.mkdtemp($.join(Mn.tmpdir(),"pm-local-package-archive-")),i=$.join(r,"extract");await C.mkdir(i,{recursive:!0});let o={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await bd({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(a===void 0)try{zd(l,t,o)}catch(p){a=p}}}),a!==void 0)throw a;o.packageJsonEntries!==1&&ye(`Local package archive must contain exactly one package/package.json entry; found ${o.packageJsonEntries}.`),await xd({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=$.join(i,"package"),c=$.join(s,"package.json"),d=JSON.parse(await C.readFile(c,"utf8"));return await Jd(s),{directory:await qt(s,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await C.rm(r,{recursive:!0,force:!0})}}}catch(s){throw await C.rm(r,{recursive:!0,force:!0}),s}}async function Jd(e,t=wo){let n=$.join(e,"package.json");if(!await S(n))return;let r;try{r=JSON.parse(await C.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,o=Vd(i),a=qd(i);if(o.length===0&&!a)return;let s={...r};delete s.devDependencies;let c={...s};Wd(c),await C.writeFile(n,`${JSON.stringify(c,null,2)}
|
|
12
|
+
`,"utf8");try{await Promise.all([C.rm($.join(e,"package-lock.json"),{force:!0}),C.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),o.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),a&&await Bd(e)}finally{await C.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
13
|
+
`,"utf8")}}function qd(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Jt in t)return!0;return!1}function Wd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Jt],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function Bd(e){let t=ve(import.meta.url,["../../.."]),[n,r]=Jt.split("/"),i=$.join(e,"node_modules",n),o=$.join(i,r);await C.mkdir(i,{recursive:!0}),await C.rm(o,{recursive:!0,force:!0}),await C.symlink(t,o,Hd(process.platform))}function Hd(e){return e==="win32"?"junction":"dir"}function Kd(e,t){if(e.startsWith("-"))throw new f(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,h.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(r=>{let i=r.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(r)}))throw new f(`Extension runtime dependency "${e}" has an unsafe version specifier.`,h.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Un.resolve(e,t)}catch{throw new f(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,h.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function Vd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===Jt||typeof i!="string"||i.trim().length===0||t.has(r))continue;let o=i.trim();t.set(r,Kd(r,o))}return[...t.values()]}async function qt(e,t){let n=await Gt(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>$.relative(e,i).replaceAll($.sep,"/")).sort((i,o)=>i.localeCompare(o));throw new f(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,h.USAGE)}throw new f(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,h.USAGE)}async function Xd(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push($.posix.join(".agents/pm/extensions",t.subpath)),n.push($.posix.join(".custom/pm-extensions",t.subpath)),n.push($.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let o=$.resolve(e,i);if(Y(e,o)&&await S($.join(o,"manifest.json")))return{directory:o,resolved_subpath:i}}if(await S($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await qt(e,t.input);return{directory:r,resolved_subpath:$.relative(e,r).replaceAll($.sep,"/")}}function Yd(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function Zd(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Yd(n))return new f(t,h.NOT_FOUND);let r=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,a=typeof o=="string"&&o.trim().length>0?$.resolve(o.trim()):"";jn?.key!==a&&(jn={key:a,aliases:await zt()}),r=jn.aliases}catch{}let i=[`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): ${r.join(", ")}`];return new f(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,h.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm package install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm package install npm:${n}`}})}async function So(e){if(e.kind==="local"){let r;try{r=await C.stat(e.absolute_path)}catch{throw await Zd(e)}if(r.isFile()&&bo(e.absolute_path)){let o=await Fn(e.absolute_path);return{source:e,directory:o.directory,source_root:$.dirname(o.directory),resolved_subpath:$.relative($.dirname(o.directory),o.directory).replaceAll($.sep,"/"),npm_package:o.package,npm_version:o.version,cleanup:o.cleanup}}if(!r.isDirectory())throw new f(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let i=await qt(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await Ud(e);return{source:e,directory:r.directory,source_root:$.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:$.relative($.dirname(r.directory),r.directory).replaceAll($.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await C.mkdtemp($.join(Mn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await ho(n);let r=await ho(["-C",t,"rev-parse","HEAD"]),i=await Xd(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await C.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await C.rm(t,{recursive:!0,force:!0}),r}}async function Ze(e,t){if(!await S(e)||!await S(t))return!1;let[n,r]=await Promise.all([C.realpath(e),C.realpath(t)]);return n===r}import lt from"node:fs/promises";import pt from"node:path";var Jn=1,De="2026.6.24",Qd=">=22.18.0",el={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Eo=new Set([...Er.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Sr).map(e=>e.toLowerCase()),"scaffold"]),tl="^6.0.0",nl="^22.0.0",To=["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."," }"," }","}",""],pe=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function $o(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Io(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 Oo(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 rl={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Ao=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Co={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"]},il={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"]'},ol={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."},al={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."},Po="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",sl={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."]},cl={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."]},dl={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`."]},ll={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 Ro(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 No(e,t){return e==="schema"?dl[t]:e==="profile"?ll[t]:cl[t]}function pl(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),o=r>0&&(r===t.length||i!==void 0&&Eo.has(i));return`${(Eo.has(n)||o?["starter",...t]:t).join(" ")} ping`}function Lo(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],o=`${e.replace(/-/g,"_")}_owner`,a="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(a)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(o)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(a)}],`,` [${JSON.stringify(a)}, "in_progress"],`,` [${JSON.stringify(a)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function ul(e,t,n){let r=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,a=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return a;if(n==="search")return[...a,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],p=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`;return[...a,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(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(u)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...a,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...Lo(e).map(s=>` ${s}`)," });"]:n==="importers"?[...a,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(o)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(o)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...a,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...a,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...a,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...a,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function ml(e,t,n){let r=n==="hooks",i=n==="search",o=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",p=n==="services",u=il[n],_=e,g=`${e}s`,w=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`,y=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],k=i?qn(e,t,"search",u):[],b=o?qn(e,t,"importers",u):[],L=a?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...$o(Io({extensionName:e,itemTypeName:_,itemTypeFolder:g,fieldName:w,migrationId:m,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],F=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...$o(Oo(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],j=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],E=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],J=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],nt=p?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...y,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...To,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});","",...v,...k,...b,...L,...F,...j,...E,...J,...nt,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
14
|
+
`)}function fl(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var hl={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"},gl={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 _l(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function yl(e,t,n){let r=[],i=[..._l(e,t,n)],o=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,p=e.replace(/-/g,""),u=p===d?[]:[p],_=`${e.replace(/-/g,"_")}_note`,g=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),o.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(a)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),o.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),o.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(_)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(u)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(g)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),o.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...Lo(e),"});"),o.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),o.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),o.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),o.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),o.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:o}}function wl(e,t,n){let r=yl(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((o,a)=>o.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
|
|
15
|
+
`)}function qn(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,o=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],u=_=>[...p," let deactivated = false;"," try {",..._.map(g=>g===""?g:` ${g}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...u([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...u([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(o)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...u([` ext.assertImporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(a)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...u(Io({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(Oo(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...u([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...u([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...u([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...u([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function vl(e,t,n){let r=n==="parser",i=JSON.stringify([...Co[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" };',"",...To,`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(De)},`," },",` target: { pmVersion: ${JSON.stringify(De)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});","",...qn(e,t,n,i)].join(`
|
|
16
|
+
`)}function kl(e,t,n){let r=Ro(n,"package"),i=No(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${hl[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`.",Po,"- `.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 ${gl[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Jn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${De}\`. 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(`
|
|
17
|
+
`)}function xl(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 bl(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 Sl(e,t,n,r){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function El(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function $l(e,t,n,r="commands",i=!1){let o=`pm-${e}`,a=Co[r],s=fl(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Jn,pm_min_version:De,trusted:!0,sandbox_profile:"strict",permissions:{...el},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
|
|
18
|
+
`,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...ul(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
|
|
19
|
+
`),l=`${JSON.stringify(rl,null,2)}
|
|
20
|
+
`,p=ol[r],u=Ro(r,"package"),_=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Qd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${De}`},devDependencies:{"@types/node":nl,typescript:tl},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)}
|
|
21
|
+
`,g=ml(e,t,r),w=al[r],m=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
22
|
+
`),y=xl(e),k=["```ts",`import { ${bl(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Sl(e,t,r,y),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...El(t,r,y),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],b=[`# ${o}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",u,p,w,Po,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...k,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...sl[r],...No(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${De}\`. 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 \`${Jn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${De}\`. 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(`
|
|
23
|
+
`);return{"package.json":_,"manifest.json":c,"index.ts":i?wl(e,t,r):d,"index.test.ts":i?vl(e,t,r):g,"tsconfig.json":l,".gitignore":m,"README.md":i?kl(o,t,r):b}}async function jo(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!Ao.includes(i))throw new f(`Unknown scaffold capability "${n}". Supported capabilities: ${Ao.join(", ")}.`,h.USAGE);let o=i;if(r&&t!=="package")throw new f("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",h.USAGE);let a=r?"declarative":"imperative",s=e.trim(),c=pt.resolve(process.cwd(),s),d=Pt(pt.basename(c)).replace(/^(?:pm-)+/u,""),l=pl(d),p=$l(d,l,t,o,r),u=!1;if(await S(c)){if(!(await lt.stat(c)).isDirectory())throw new f(`Scaffold target "${c}" exists and is not a directory.`,h.CONFLICT)}else await lt.mkdir(c,{recursive:!0}),u=!0;for(let[g,w]of Object.entries(p)){let m=pt.join(c,g);if(!await S(m))continue;if(await lt.readFile(m,"utf8")!==w)throw new f(`Scaffold file "${g}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,h.CONFLICT)}let _=[];for(let[g,w]of Object.entries(p)){let m=pt.join(c,g);if(await S(m)){_.push({path:g,status:"unchanged"});continue}await lt.mkdir(pt.dirname(m),{recursive:!0}),await lt.writeFile(m,w,"utf8"),_.push({path:g,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:o,style:a,target_path:c,created_directory:u,files:_}}var Do=[["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 Wn(e){return"#".repeat(e)}function Fo(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let o of e)n=o==="`"?n+1:0,t=Math.max(t,n);let r="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${r}${i}${e}${i}${r}`}function Al(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(Fo).join(", ")}`}function Tl(e,t,n){let r=[`${Wn(t)} ${e}`,""];return n.length===0?(r.push("_None._",""),r):(r.push(...n.map(i=>`- ${Fo(i)}`),""),r)}function Il(e,t,n){return e===0&&!n?[]:[`${Wn(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function Bn(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<1||n>6)throw new RangeError(`headingLevel must be an integer in [1, 6], received ${String(t.headingLevel)}`);let r=Math.min(n+1,6),i=t.includeEmpty===!0,o=t.title??"Extension surfaces",a=[`${Wn(n)} ${o}`,""];(i||e.capabilities.length>0)&&a.push(Al(e.capabilities),"");for(let[c,d]of Do){let l=e[c]??[];l.length===0&&!i||a.push(...Tl(d,r,l))}return a.push(...Il(e.preflight_overrides,r,i)),!(e.preflight_overrides>0||Do.some(([c])=>(e[c]?.length??0)>0))&&!i&&a.push("_This extension registers no surfaces._",""),`${a.join(`
|
|
24
|
+
`).trimEnd()}
|
|
25
|
+
`}function Mo(e,t){return`${e}:${x(t)}`}function Ol(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let a of i){let s=o.get(a.command)??[];o.set(a.command,[...s,a])}for(let[a,s]of o){if(t!==null&&!s.some(d=>t.has(x(d.name))))continue;let c=s.at(-1);n.push({command:a,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function Uo(e,t,n){let r=new Set(n.failed.map(d=>Mo(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(Mo(d.layer,d.name))?"failed":"ok",surfaces:We(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:We(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),o=typeof e=="string"?x(e):null,a=o===null?null:new Set(t.loaded.filter(d=>x(d.name)===o||typeof d.source_package=="string"&&x(d.source_package)===o||(d.source_aliases??[]).some(l=>x(l)===o)).map(d=>x(d.name)).concat(o)),s=a===null?i:i.filter(d=>a.has(x(d.name))),c=a===null?{}:{extensionNames:[...a]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:We(n,c),command_ownership:Ol(n,a)}}var Cl={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function Ag(e,t){let r=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(r.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),r.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){r.push("## Command ownership","");for(let i of e.command_ownership){let o=i.claimants.find(s=>s.winner),a=i.claimants.map(s=>`${s.layer}:${s.name}`).join(", ");r.push(`- \`${i.command}\` (${i.surface}): ${o.layer}:${o.name}; policy=${i.policy}; collision=${String(i.collision)}; claimants=${a}`)}r.push("")}if(e.extensions.length===0)return r.push(`_No ${t}s are loaded._`,""),`${r.join(`
|
|
26
|
+
`).trimEnd()}
|
|
27
|
+
`;for(let i of e.extensions){let o=`${i.name} (${i.layer} v${i.version}, ${Cl[i.activation_status]})`;r.push(Bn(i.surfaces,{title:o,headingLevel:2}))}return e.extensions.length>1&&r.push(Bn(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${r.join(`
|
|
28
|
+
`).trimEnd()}
|
|
29
|
+
`}import Ht from"node:fs/promises";import Bt from"node:path";import Go from"node:path";function ut(e,t,n,r){let i=Go.relative(e,n);if(i!==""&&!Y(e,n)||n===t||Y(t,n))return!1;let o=i.split(Go.sep);return o.includes(".git")?!1:r?!o.some(a=>a===".agents"||a==="node_modules"||a.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as Pl}from"node:crypto";import D from"node:fs/promises";import Rl from"node:os";import N from"node:path";var zo=3,Nl=120,Jo=250,Ll=12e4,jl=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),qo=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Wo=e=>jl.has(String(qo(e))),Wt=(e,t)=>qo(e)===t,Bo=e=>new Promise(t=>{setTimeout(t,e)}),Ho=async e=>{let t=N.join(e,"package.json");await S(t)||await D.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
30
|
+
`,"utf8")},Ko=async e=>{let t=ve(import.meta.url,["../../.."]),n=N.join(e,"node_modules","@unbrained"),r=N.join(n,"pm-cli");await D.mkdir(n,{recursive:!0}),await D.rm(r,{recursive:!0,force:!0}),await D.symlink(t,r,process.platform==="win32"?"junction":"dir")},mt=async e=>{let t=N.resolve(e),n=N.dirname(t),r=N.parse(n).root,i=await D.realpath(r).catch(()=>r),o=N.relative(r,n),a=o===""?[]:o.split(N.sep);for(let[s,c]of a.entries()){let d=N.join(i,c);try{i=await D.realpath(d)}catch{i=N.join(i,...a.slice(s));break}}return N.join(i,N.basename(t))},Vo=async(e,t,n,r=Rl.tmpdir())=>Ce("extension_install_copy",async()=>{let i=N.resolve(e),o=await D.realpath(i).catch(()=>i),a=await mt(t);if(o===a)return;if(!Y(o,a)){await n(o,t,{recursive:!0,force:!0,filter:p=>ut(o,a,N.resolve(p),!1)});return}let s=await D.realpath(N.resolve(r)).catch(()=>mt(r)),c=Y(o,s)?N.dirname(o):s;if(Y(o,c))throw new f(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,h.USAGE,{code:"extension_install_source_contains_destination"});let d=await D.mkdtemp(N.join(c,"pm-extension-copy-")),l=N.join(d,"extension");try{await n(o,l,{recursive:!0,force:!0,filter:p=>ut(o,a,N.resolve(p),!0)}),await n(l,t,{recursive:!0,force:!0})}finally{await D.rm(d,{recursive:!0,force:!0})}}),Xo=async(e,t,n=D.cp)=>{for(let r=1;r<=zo;r+=1)try{await Ce("extension_install_copy",async()=>{await D.rm(t,{recursive:!0,force:!0}),await Vo(e,t,n)});return}catch(i){if(!Wo(i)||r===zo)throw i;await Bo(Jo)}},Hn=async e=>{let t;try{t=await D.readFile(N.join(e,"owner.json"),"utf8")}catch(i){if(!St(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},Yo=async(e,t)=>await Hn(e)!==t?!1:(await D.rm(e,{recursive:!0,force:!0}),!0),Dl=async(e,t)=>{let n;try{n=await D.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await Hn(e);return r===null?(await D.rm(e,{recursive:!0,force:!0}),!0):Yo(e,r)},Fl=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await Hn(e)!==t)return;let o=new Date;await D.utimes(e,o,o)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},Ml=async(e,t)=>{await D.mkdir(e);try{await D.writeFile(N.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
31
|
+
`,"utf8")}catch(n){throw await D.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Ul=async(e,t,n,r,i)=>{for(let o=1;o<=n;o+=1)try{return await Ml(e,t),!0}catch(a){if(!Wt(a,"EEXIST"))throw a;await Dl(e,i)?o-=1:await Bo(r)}return!1},Kn=async(e,t,n,r)=>Ce("extension_install",async()=>{let i=N.join(e,"runtime","extension-install-locks"),o=N.join(i,"scope.lock");await D.mkdir(i,{recursive:!0});let{attempts:a=Nl,delay_ms:s=Jo,stale_ms:c=Ll,heartbeat_ms:d}=r??{};if(![a,s,c,d].filter(v=>v!==void 0).every(Number.isFinite))throw new f("Extension install lock timings must be finite numbers.",h.USAGE);let l=Math.max(1,Math.floor(a)),p=Math.max(0,Math.floor(s)),u=Math.floor(c),_=Math.floor(d??u/3);if(u<=0||_<=0||_>=u)throw new f("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",h.USAGE);let g={pid:process.pid,token:Pl(),created_at:I(),destination:t};if(!await Ul(o,g,l,p,u))throw new f(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let m=Fl(o,g.token,_),y=!1;try{let v=await n();return y=!0,v}finally{await m(),await Yo(o,g.token).catch(v=>{if(y)throw v})}});var Gl=new Set(["node_modules",".git","dist","build","coverage"]);async function Zo(e,t,n,r){let i=e.source.kind==="local"?await Ht.stat(e.source.absolute_path):void 0,o=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,a=await zl(e.directory,t,r),s={source_mode:o,...o==="archive"?{archive_bytes:i.size}:{},copy:a},c=e.source_root??e.directory;if(o==="directory"&&(!a.complete||a.development_entries>0||a.bytes>=16*1024*1024)&&await S(Bt.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),o==="directory"&&!a.complete){let d=a.stop_reason==="entry_limit"?`${a.max_entries} entries`:`${a.max_depth} directory levels`;throw new f(`Local extension source scan stopped at ${d}; 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:a.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 zl(e,t,n={}){let{maxEntries:r=1e4,maxDepth:i=64,signal:o}=n;if(![r,i].every(p=>Number.isSafeInteger(p)&&p>0))throw new f("maxEntries and maxDepth must be positive safe integers.",h.USAGE);o?.throwIfAborted();let a=await Ht.realpath(e),s=await mt(t),c=await Ze(a,s);o?.throwIfAborted();let d=c?"in_place":Y(a,s)?"nested_filtered_snapshot":"directory_snapshot",l={copy_scope:d,source_directory:a,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:r,max_depth:i};return d==="in_place"||await Qo(a,0,l,o),l}async function Qo(e,t,n,r){r?.throwIfAborted();let i=await Ht.opendir(e);for await(let o of i){if(r?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let a=Bt.join(e,o.name);if(!ut(n.source_directory,n.destination_directory,a,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(Bt.relative(n.source_directory,a).split(Bt.sep).some(s=>Gl.has(s))&&(n.development_entries+=1),await Jl(a,t,n,r),!n.complete)return}}async function Jl(e,t,n,r){let i=await Ht.lstat(e);if(r?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await Qo(e,t+1,n,r)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import ql from"node:fs/promises";import Wl from"npm-package-arg";async function Bl(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 ql.lstat(e.absolute_path),e}catch(a){if(!Me(a))throw a}let n=e.input.trim(),r=t.filter(a=>a.source.kind==="npm"),o=(r.find(a=>a.name===n)??r.find(a=>a.directory===n)??r.find(a=>a.source.package===n))?.source.package;if(o===void 0)return e;try{let a=Wl(o);if(!a.registry||a.name!==o)return e}catch{return e}return dt(`npm:${o}`,{})}async function ea(e,t,n,r=[]){let i=typeof t=="string"?null:await ct(e),o=i===null?null:e.trim().toLowerCase(),a=o===null?null:await uo(o),s=await Bl(dt(i??e,{forceGithub:typeof t=="string",ref:n}),r),c=o===null?null:await yo(e);return{bundledAliasName:o,bundledPackageName:a,installSource:s,sourceResolution:{requested:e,selected:{kind:o===null?s.kind:"builtin",input:o??s.input,...a===null?{}:{package:a}},ambiguous:c!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...o===null?[]:[{kind:"builtin",input:o,...a===null?{}:{package:a},command:`pm install ${o}`}],...c===null?[]:[{kind:"npm",input:`npm:${c.package}`,package:c.package,...c.version===void 0?{}:{version:c.version},directory:c.directory,command:`pm install npm:${c.package}`}]]}}}import tt from"node:fs/promises";import te from"node:path";import Yl from"node:path";import{mkdir as Zl}from"node:fs/promises";var ft=["agile","ops","research"],Hl={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 Kt(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: ${ft.join(", ")}.`)}function ht(e){return Hl[e].map(t=>it(t))}var Kl=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Vl(e){let t=Kl.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Xl(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function ta(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=Vl(s);if(c===void 0)continue;let d=i.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(s),i.set(c,d)}let o=[];for(let[a,s]of i.entries()){if(s.count<n)continue;let c=Xl(a);o.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:Vr(c)!==void 0})}return o.sort((a,s)=>s.count-a.count||a.name.localeCompare(s.name)),o}var j_=[...bt,"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"],Vt="schema-types",na="schema-statuses",ra="schema-fields";function Ae(e){return be({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function D_(e,t,n){let r=M(process.cwd(),n.path);await we(r);let i;try{i=it({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let o=await A(r),a=K(o.schema),s=Z(r,a.files.types,V.types),c=[],d=q(t.author,o.author_default),l=fe(o),p=await Q(r,Vt,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms),u;try{let _=await U(s),g;try{g=ne(_)}catch(w){throw new f(w instanceof Error?w.message:String(w),h.GENERIC_FAILURE)}try{Xr(i,g);let w=new Map,m=B(o,W());for(let[y,v]of Object.entries(m.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!w.has(k)&&w.set(k,y)}Yr(i,g,w)}catch(w){throw new f(w instanceof Error?w.message:String(w),h.USAGE)}u=Ue(g,i),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await Ae({pmRoot:r,filePath:s,raw:se(u.file),op:"schema:add-type",author:d,settings:o}),await gt(r,[u.definition],c,"schema:add-type-folder"),c.push(...await H({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await ia(r,c),{action:"add-type",registered:!0,replaced:u.replaced,type:u.definition,file:{path:s,definitions:u.file.definitions.length},warnings:Te(c),generated_at:I()}}async function we(e){await Ge(e)}async function ia(e,t){try{let n=await fi(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Te(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Ql(e,t,n,r){let i=B(t,W()),o=r.trim().toLowerCase();return(await Re(e,t.item_format,i.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===o).length}async function ep(e,t,n,r){let i=B(t,W()),o=rt(n),a=O(r);return(await Re(e,t.item_format,i.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(o.alias_to_id.get(O(d))??O(d))===a}).length}async function tp(e,t,n,r,i){if(i.length===0||Le.has(i))return;let o=await ep(t,n,r,i);o>0&&e.push(`items_using_status:${o}`);let a=oa(r.workflow,i);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function oa(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,r])=>r!==void 0&&O(r)===t).map(([r])=>r)}async function F_(e,t,n){let r=M(process.cwd(),n.path);await we(r);let i=await A(r),o=K(i.schema),a=Z(r,o.files.types,V.types),s=[],c=q(t.author,i.author_default),d=fe(i),l=await Q(r,Vt,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await U(a),_;try{_=ne(u)}catch(g){throw new f(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=Zr(_,e)}catch(g){throw new f(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=(p.definition?.name??e??"").trim();if(g.length>0){let w=await Ql(r,i,o,g);w>0&&s.push(`items_using_type:${w}`)}await Ae({pmRoot:r,filePath:a,raw:se(p.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await H({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return p.removed&&await ia(r,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:a,definitions:p.file.definitions.length},warnings:Te(s),generated_at:I()}}function Vn(e,t){return Z(e,t.files.statuses,V.statuses)}function Xt(e,t){return Z(e,t.files.fields,V.fields)}function aa(e,t){return Z(e,t.files.types,V.types)}async function gt(e,t,n,r){for(let i of t){let o=Ar(i.folder??$r(i.name)),a=Yl.join(e,o);await S(a)||(await Zl(a,{recursive:!0}),n.push(...await H({path:a,scope:"project",op:r})))}}function Xn(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 np(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 rp(e){let t=new Map;for(let n of e){let r=O(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let o=O(i);o.length>0&&!t.has(o)&&t.set(o,r)}}}return t}async function M_(e,t,n){let r=M(process.cwd(),n.path);await we(r);let i;try{i=Wi({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(m){throw new f(m instanceof Error?m.message:String(m),h.USAGE)}let o=await A(r),a=K(o.schema),s=Vn(r,a),c=rt(a);try{An(i,c.alias_to_id)}catch(m){throw new f(m instanceof Error?m.message:String(m),h.USAGE)}let d=np(c.by_id.get(i.id));if((i.roles??d?.roles??[]).length===0)throw new f(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,h.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Pe(i.id)}" --role active`,`pm schema add-status "${Pe(i.id)}" --role blocked`]});let p=[],u=q(t.author,o.author_default),_=fe(o),g=await Q(r,na,o.locks.ttl_seconds,u,!!t.force,_.force_required_for_stale_lock,o.locks.wait_ms),w;try{let m=await U(s),y;try{y=Be(m)}catch(k){throw new f(k instanceof Error?k.message:String(k),h.GENERIC_FAILURE)}let v=rp(y.statuses);try{An(i,v)}catch(k){throw new f(k instanceof Error?k.message:String(k),h.USAGE)}w=Bi(y,i,d),await Ae({pmRoot:r,filePath:s,raw:He(w.file),op:"schema:add-status",author:u,settings:o}),p.push(...await H({path:s,scope:"project",op:"schema:add-status"}))}finally{await g()}return{action:"add-status",registered:!0,replaced:w.replaced,status:w.definition,file:{path:s,statuses:w.file.statuses.length},warnings:Te(p),generated_at:I()}}async function U_(e,t,n){let r=M(process.cwd(),n.path);await we(r);let i=await A(r),o=K(i.schema),a=Vn(r,o),s=[],c=q(t.author,i.author_default),d=fe(i),l=await Q(r,na,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await U(a),_;try{_=Be(u)}catch(g){throw new f(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=Hi(_,e)}catch(g){throw new f(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=O(p.definition?.id??e);await tp(s,r,i,o,g),await Ae({pmRoot:r,filePath:a,raw:He(p.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await H({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:a,statuses:p.file.statuses.length},warnings:Te(s),generated_at:I()}}function sa(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 ip(e,t,n){return{...sa(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 ca(e){return{id:e.id,source:Le.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 da(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function op(){let e=new Map,t=W();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let i of r){if(typeof i!="object"||i===null||Array.isArray(i))continue;let o=i.name;typeof o=="string"&&o.trim().length>0&&e.set(o.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function ap(e){let t=rt(e),n=[],r=[];for(let i of t.definitions){let o=ca(i);o.source==="builtin"?n.push(o):r.push(o)}return{builtin:n,custom:r}}async function _t(e){let t=M(process.cwd(),e.path);await we(t);let n=await A(t),r=K(n.schema),i=Z(t,r.files.types,V.types),o=Vn(t,r),a=B(n,W()),s=op(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:i,statusesPath:o,byType:a.by_type,customNames:c,extensionProvenance:s,schema:r}}async function G_(e){let t=await _t(e),n=[],r=[],i=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=da(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=sa(s);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let o=ap(t.schema),a=$t(t.schema).definitions.map(Xn);return{action:"list",builtin:n,custom:r,extension:i,counts:{builtin:n.length,custom:r.length,extension:i.length,total:n.length+r.length+i.length},statuses:{builtin:o.builtin,custom:o.custom,counts:{builtin:o.builtin.length,custom:o.custom.length,total:o.builtin.length+o.custom.length}},fields:{custom:a,counts:{total:a.length}},file:{path:t.typesPath},generated_at:I()}}async function z_(e,t){let n=(e??"").trim();if(n.length===0)throw new f("Type name must not be empty.",h.USAGE);let r=await _t(t),i=Object.values(r.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!i)throw new f(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Pe(n)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:ip(i,da(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:I()}}async function J_(e,t){let n=O(e);if(n.length===0)throw new f("Status id must not be empty.",h.USAGE);let r=await _t(t),i=rt(r.schema),o=i.alias_to_id.get(n)??n,a=i.by_id.get(o);if(!a)throw new f(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Pe(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:ca(a),file:{path:r.statusesPath},generated_at:I()}}async function q_(e,t,n){let r=M(process.cwd(),n.path);await we(r);let i;try{i=ci({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 f(g instanceof Error?g.message:String(g),h.USAGE)}pi(i);let o=await A(r),a=K(o.schema),s=Xt(r,a),c=[],d=Ct(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=q(t.author,o.author_default),p=fe(o),u=await Q(r,ra,o.locks.ttl_seconds,l,!!t.force,p.force_required_for_stale_lock,o.locks.wait_ms),_;try{let g=await U(s),w;try{w=ze(g)}catch(m){throw new f(m instanceof Error?m.message:String(m),h.GENERIC_FAILURE)}_=di(w,i),await Ae({pmRoot:r,filePath:s,raw:Je(_.file),op:"schema:add-field",author:l,settings:o}),c.push(...await H({path:s,scope:"project",op:"schema:add-field"}))}finally{await u()}return{action:"add-field",registered:!0,replaced:_.replaced,field:_.definition,file:{path:s,fields:_.file.fields.length},warnings:Te(c),generated_at:I()}}async function sp(e,t,n,r){let i=B(t,W());return(await Re(e,t.item_format,i.type_to_folder,[],n)).filter(a=>{let s=a[r];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function W_(e,t,n){let r=M(process.cwd(),n.path);await we(r);let i=await A(r),o=K(i.schema),a=Xt(r,o),s=[],c=q(t.author,i.author_default),d=fe(i),l=await Q(r,ra,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await U(a),_;try{_=ze(u)}catch(g){throw new f(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=li(_,e)}catch(g){throw new f(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=O(p.definition?.key??e),w=O(p.definition?.metadata_key??p.definition?.front_matter_key??g);if(w.length>0){let m=await sp(r,i,o,w);m>0&&s.push(`items_using_field:${m}`)}await Ae({pmRoot:r,filePath:a,raw:Je(p.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await H({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:a,fields:p.file.fields.length},warnings:Te(s),generated_at:I()}}async function B_(e){let t=await _t(e),n=$t(t.schema).definitions.map(Xn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Xt(t.pmRoot,t.schema)},generated_at:I()}}async function H_(e,t){let n=O(e);if(n.length===0)throw new f("Field key must not be empty.",h.USAGE);let r=await _t(t),i=$t(r.schema).by_key.get(n);if(!i)throw new f(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Pe(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Xn(i),file:{path:Xt(r.pmRoot,r.schema)},generated_at:I()}}async function K_(e,t,n){let r=M(process.cwd(),n.path);await we(r);let i;try{let w=Kt(e);if(w===void 0)throw new Error(`Type preset name is required. Allowed: ${ft.join(", ")}.`);i=w}catch(w){throw new f(w instanceof Error?w.message:String(w),h.USAGE)}let o=await A(r),a=K(o.schema),s=aa(r,a),c=[],d=q(t.author,o.author_default),l=fe(o),p=[],u=[],_,g=await Q(r,Vt,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms);try{let w=await U(s),m;try{m=ne(w)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let y=m;for(let v of ht(i)){let k=Ue(y,v);y=k.file,(k.replaced?u:p).push(k.definition.name)}_=y.definitions.length,await Ae({pmRoot:r,filePath:s,raw:se(y),op:"schema:apply-preset",author:d,settings:o}),await gt(r,ht(i),c,"schema:apply-preset-folder"),c.push(...await H({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await g()}return{action:"apply-preset",preset:i,registered:p,replaced:u,file:{path:s,definitions:_},warnings:Te(c),generated_at:I()}}function cp(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new f("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function V_(e,t){let n=M(process.cwd(),t.path);await we(n);let r=await A(n),i=K(r.schema),o=aa(n,i),a=cp(e.minCount),s=B(r,W()),d=(await Re(n,r.item_format,s.type_to_folder,[],i)).map(k=>typeof k.title=="string"?k.title:""),l=ta(d,{minCount:a}),p=[],u=[],_=[],g=[],w;if(!e.apply){let k;try{k=ne(await U(o))}catch(b){throw new f(b instanceof Error?b.message:String(b),h.GENERIC_FAILURE)}return w=k.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:l,registered:u,replaced:_,skipped:g,file:{path:o,definitions:w},warnings:p,generated_at:I()}}let m=q(e.author,r.author_default),y=fe(r),v=await Q(n,Vt,r.locks.ttl_seconds,m,!!e.force,y.force_required_for_stale_lock,r.locks.wait_ms);try{let k=await U(o),b;try{b=ne(k)}catch(F){throw new f(F instanceof Error?F.message:String(F),h.GENERIC_FAILURE)}let L=b;for(let F of l){if(F.shadows_builtin){g.push({name:F.name,reason:"shadows_builtin"});continue}let j;try{j=it({name:F.name})}catch{g.push({name:F.name,reason:"invalid_type_token"});continue}let E=Ue(L,j);L=E.file,(E.replaced?_:u).push(E.definition.name)}w=L.definitions.length,await Ae({pmRoot:n,filePath:o,raw:se(L),op:"schema:infer-types",author:m,settings:r}),await gt(n,L.definitions.filter(F=>u.includes(F.name)||_.includes(F.name)),p,"schema:infer-types-folder"),p.push(...await H({path:o,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:l,registered:u,replaced:_,skipped:g,file:{path:o,definitions:w},warnings:Te(p),generated_at:I()}}function X_(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 "${Pe(e.type.name)}" "<title>"`}function Y_(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 Z_(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",r=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${r} in ${e.file.path}.`}function 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 ey(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,r]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])r.length!==0&&t.push(`${n}: ${r.map(i=>i.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,r]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])r.length!==0&&t.push(`${n}: ${r.map(i=>i.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(n=>`${n.key} (${n.type}, ${n.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
|
|
32
|
+
`)}function ty(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(`
|
|
33
|
+
`)}function ny(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(`
|
|
34
|
+
`)}function dp(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 ry(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 iy(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 oy(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${dp(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
|
|
35
|
+
`)}function ay(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(`
|
|
36
|
+
`)}function sy(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",r=[t,n].filter(i=>i.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${r.length>0?` (${r})`:""}.`}function cy(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;let t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(let n of e.candidates){let r=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${r}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
|
|
37
|
+
`)}var dy={workflowSlotsReferencing:oa};function la(e){let t=/^extension_(disabled_)?pm_(min|max)_version_([a-z_]+):(project|global):([^:]+):(.+)$/u.exec(e);if(!t)return;let[,n,r,i,o,a,s]=t,c=s.split(":")[0].replace(r==="min"?"required=":"allowed=",""),d=i==="invalid"?`a valid pm_${r}_version instead of ${c}`:`pm ${r==="min"?">=":"<="} ${c}`;return n?`Package ${a} is disabled and requires ${d} before activation. After satisfying the bound, run ${ae(["package","activate",a,`--${o}`])}.`:`Package ${a} requires ${d}. Use a compatible host or package version, or keep it disabled with ${ae(["package","deactivate",a,`--${o}`])}.`}function Yn(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function Yt(e,t,n){let r=x(t),i=n.trim();if(r.length===0||i.length===0)return;let o=e.get(r)??new Set;o.add(i),e.set(r,o)}function lp(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)Yt(t,r.name,r.command),Yt(n,r.name,r.action);for(let r of e.commands.handlers)Yt(t,r.name,r.command);for(let r of e.commands.overrides)Yt(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function pa(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function pp(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:o}=e;return t?i.has(n)||o.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function Zt(e,t,n){let r=new Set(t.loaded.map(c=>x(c.name))),i=new Set(t.failed.map(c=>x(c.name))),o=new Set(n.failed.map(c=>x(c.name))),{commandPathsByExtension:a,actionPathsByExtension:s}=lp(n);return e.map(c=>{let d=x(c.name),l=pa(a.get(d)),p=pa(s.get(d)),u={...l?{command_paths:l}:{},...p?{action_paths:p}:{}},_=pp({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:i,activationFailedNames:o});return{...c,..._,...u}})}function up(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function G(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var fa=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 mp(e){return fa.has(va(e))}function ua(e){return e==="project"||e==="global"}function ha(e){let t=e.split(":"),n=t[0];if(!n||!fa.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),o=t.at(-2),a=t.at(-1)?.trim();return!ua(r)||!ua(o)||!i||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:o,name:a}}}function fp(e){let t=new Set;for(let n of e){let r=ha(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function hp(e,t){let n=e.filter(mp);if(n.length===0)return null;let r=fp(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function gp(e,t,n,r){let i=t.map(p=>ha(p)).filter(p=>p!==null).sort((p,u)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`));if(i.length===0)return;let o=e==="global"?"--global":"--project",a=G(r,"deactivate"),s=`${G(r,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(p=>[x(p.name),p])),d=new Map;for(let p of i)for(let u of[p.winner.name,p.displaced.name]){let _=x(u);d.set(_,(d.get(_)??0)+1)}let l=[...d.entries()].map(([p,u])=>{let _=c.get(p),g=_?.name??p,w=_?.command_paths??[],m=_?.action_paths??[];return{action:"deactivate",extension:g,command:`${a} ${g} ${o}`,affected_collisions:u,feature_loss:{command_paths:[...w].sort((y,v)=>y.localeCompare(v)),action_paths:[...m].sort((y,v)=>y.localeCompare(v))}}}).sort((p,u)=>{let _=u.affected_collisions-p.affected_collisions;if(_!==0)return _;let g=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,w=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length;return g!==w?g-w:p.extension.localeCompare(u.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:d.size,next_best_command:s,collisions:i,remediation_candidates:l}}function ga(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function _a(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function ya(e,t){let n=[];for(let r of qr(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var _p=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${G(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: ${_r.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 ${G(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 ${G(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 ${G(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 ${G(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 ${G(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${G(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 yp(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:a,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,p=t.map(la).filter(_=>_!==void 0),u={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:a};if(t.length>0){let _=hp(t,{deactivate:`${G(n,"deactivate")} <name> ${i}`,doctor:`${G(n,"doctor")} ${i} --detail deep --trace`});_&&p.push(_);for(let g of _p)g.matches(t,u)&&p.push(g.build(u))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${G(n,"manage")} ${i} --fix-managed-state (or ${G(n,"adopt-all")} ${i}, ${G(n,"adopt")} <name> ${i}, or reinstall via ${G(n,"install")} ${i} <source>).`),d>0&&p.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${G(n,"manage")} ${i} to request update checks.`),l>0&&p.push(`Update available managed extensions via ${G(n,"install")} ${i} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${G(n,"manage")} ${i} after extension changes.`),p}function Qt(e,t,n,r={}){let i=[...new Set(t)].sort((E,J)=>E.localeCompare(J)),o=n.filter(E=>E.managed).length,a=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,c=n.filter(E=>E.update_check_status==="checked"&&E.update_available===!0).length,d=n.filter(E=>E.managed===!1),l=d.filter(E=>ma(E)).map(E=>E.name).sort((E,J)=>E.localeCompare(J)),p=d.filter(E=>!ma(E)).map(E=>E.name).sort((E,J)=>E.localeCompare(J)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)u[E.update_check_status]+=1;let _=u.failed,g=n.filter(E=>E.update_check_status==="skipped_non_github"&&E.source?.kind!=="builtin").length,w=Object.entries({skipped_unmanaged:p.length,skipped_non_github:g,failed:_,not_checked:u.not_checked}).filter(([,E])=>E>0).map(([E,J])=>`extension_update_health_partial_coverage:${E}:${J}`),m=w.length>0,y=m?"partial":"full",v=[...new Set([...i,...w])].sort((E,J)=>E.localeCompare(J)),k=[...new Set(v.map(E=>va(E)))].sort((E,J)=>E.localeCompare(J)),b=up(v),L=e==="global"?"--global":"--project",F=gp(e,i,n,r),j=yp({normalizedWarnings:v,options:r,scope:e,scopeFlag:L,updateCheckFailedTotal:_,policyWarningCount:b.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:u.not_checked,skippedNonGithubTotal:g,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:k,warnings:v,policy_warning_count:b.warning_count,policy_violation_count:b.violation_count,policy_blocked_count:b.blocked_count,total_extensions:n.length,managed_total:o,enabled_total:a,active_total:s,update_available_total:c,update_health_coverage:y,update_health_partial:m,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(E=>E.name).sort((E,J)=>E.localeCompare(J)),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:u,update_check_failed_total:_,top_warnings:v.slice(0,8),remediation:j,...F?{collision_plan:F}:{}}}function wa(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new f(`Invalid --detail value "${e}". Expected summary or deep.`,h.USAGE)}function va(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function ka(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let o=Mr(r);return o?[o]:Ur(r)})();for(let o of i){let a=`${o.layer}:${o.name}:${o.capability}`;t.has(a)||(t.add(a),n.push(o))}}return n}function xa(){return{version:xt.version,capabilities:[...xt.capabilities],legacy_aliases:{...xt.legacy_aliases}}}function ma(e){let t=x(e.name),n=x(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function ba(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let o=[...new Set(t.filter(l=>l.active).map(l=>x(l.name)))].sort((l,p)=>l.localeCompare(p)),a=[...new Set(n.filter(l=>l.layer==="project").map(l=>x(l.name)))].sort((l,p)=>l.localeCompare(p)),s=new Set(r.map(l=>x(l.name))),c=o.filter(l=>!a.includes(l)&&!s.has(l)).sort((l,p)=>l.localeCompare(p));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:o.length,loaded_project_count:a.length,active_project_names:o,loaded_project_names:a,missing_active_project_names:c}}}function Sa(e,t){let n=x(e),r=t.find(i=>x(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,o)=>i.localeCompare(o)),action_paths:[...r?.action_paths??[]].sort((i,o)=>i.localeCompare(o))}}function Ea(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${x(o.name)}`]:[])),r=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>o.passThrough!==!0).filter(o=>!n.has(`${o.layer}:${x(o.name)}`)).map(o=>`extension_output_service_override_global:${o.service}:${o.layer}:${o.name}`),i=e.renderers.overrides.filter(o=>(o.commands?.length??0)===0&&o.resultDiscriminator===void 0).map(o=>`extension_output_renderer_override_global:${o.format}:${o.layer}:${o.name}`);return[...new Set([...r,...i])].sort((o,a)=>o.localeCompare(a))}var $a=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Ct(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{spawn as Cp}from"node:child_process";import{AsyncLocalStorage as Pp}from"node:async_hooks";import{isMainThread as Rp}from"node:worker_threads";import Np from"npm-package-arg";import{spawn as wp}from"node:child_process";import{existsSync as en,readFileSync as vp}from"node:fs";import Aa from"node:path";var Ta=2e3;function kp(e,t){let n=new Map;for(let a of e.split(`
|
|
38
|
+
`)){let s=a.trim().split(/\s+/u);if(s.length!==2)continue;let[c,d]=s.map(Number);if(!Number.isSafeInteger(c)||!Number.isSafeInteger(d)||c<=0)continue;let l=n.get(d);l?l.push(c):n.set(d,[c])}let r=new Set([t]),i=[],o=(n.get(t)??[]).map(a=>({pid:a,parent:t}));for(let a=0;a<o.length;a+=1){let s=o[a];if(!r.has(s.pid)){r.add(s.pid),i.push(s);for(let c of n.get(s.pid)??[])o.push({pid:c,parent:s.pid})}}return i.reverse()}function Zn(e,t=Ia){let n=t(`/proc/${e.pid}/stat`);if(n===void 0)return!en("/proc/self/stat");let r=n.slice(n.lastIndexOf(")")+1).trim().split(/\s+/u);return Number(r[1])===e.parent}function xp(e=Ia,t=process.platform){let n=e("/proc/self/status");if(n===void 0)return t!=="linux"&&!en("/proc/self/status");let r=/^NSpid:\s*(.*)$/mu.exec(n)?.[1]?.trim().split(/\s+/u);return r?.length===1&&Number(r[0])===process.pid}function bp(e,t,n,r=Zn,i=new Map){let o=[],a=!0;for(let s=e;s!==t;){let c=i.get(s);if(c!==void 0){a=c;break}o.push(s);let d=n.get(s);if(d===void 0||!r({pid:s,parent:d})){a=!1;break}s=d}for(let s of o)i.set(s,a);return a}function Ia(e){try{return vp(e,"utf8")}catch{return}}var Sp=["/bin/ps","/usr/bin/ps"],Ep={PATH:"/usr/bin:/bin",LC_ALL:"C"};function $p(e=en){return Sp.find(t=>e(t))}var Ap="C:\\Windows";function Tp(e=process.env,t=en){let n=r=>Object.entries(e).find(([i])=>i.toLowerCase()===r)?.[1];return[n("systemroot"),n("windir"),Ap].find(r=>typeof r=="string"&&/^[A-Za-z]:[\\/]/u.test(r)&&t(Aa.win32.join(r,"System32","taskkill.exe")))}function Oa(e){try{process.kill(e,"SIGKILL")}catch{}}function Ca(e,t,n,r=Ta){return new Promise(i=>{let o=!1,a="",s;try{s=wp(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0,...n===void 0?{}:{env:n}})}catch{i(void 0);return}let c=r===null?void 0:setTimeout(()=>{d(void 0),s.stdout?.destroy(),s.kill("SIGKILL"),s.unref()},r);function d(l){o||(o=!0,clearTimeout(c),i(l))}if(s.on("error",()=>d(void 0)),!s.stdout){d(void 0);return}s.stdout.setEncoding("utf8"),s.stdout.on("data",l=>{a+=l}),s.on("close",l=>d({code:l,stdout:a}))})}async function Pa(e,t={kill:()=>Oa(e),alive:()=>!0},n={}){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await Ip(e,t,n.taskkillTimeoutMs===void 0?Ta:n.taskkillTimeoutMs);return}try{process.kill(-e,"SIGKILL");return}catch{}await Op(e,t),t.kill()}}async function Ip(e,t,n){let r=Tp();if(r===void 0){t.alive()&&t.kill();return}let i=Aa.win32.join(r,"System32","taskkill.exe");(await Ca(i,["/pid",String(e),"/T","/F"],void 0,n))?.code!==0&&t.alive()&&t.kill()}async function Op(e,t){let n=$p();if(n===void 0||!xp())return;let r=await Ca(n,["-A","-o","pid=","-o","ppid="],Ep);if(r?.code!==0||!t.alive())return;let i=kp(r.stdout,e),o=new Map(i.map(s=>[s.pid,s.parent])),a=new Map;for(let s of i)Zn(s)&&bp(s.parent,e,o,Zn,a)&&Oa(s.pid)}var Lp="PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS",Qn=1e4,jp=1e3,Dp=25e3,Fp=2e3,Mp="npm_registry_lookup_failed",Up="npm_registry_lookup_timed_out",Gp="github_remote_lookup_failed",zp="github_remote_lookup_timed_out";function Qe(e=process.env){let t=e[Lp]?.trim(),n=t?Number(t):Number.NaN;return Number.isFinite(n)?Math.min(Dp,Math.max(jp,Math.trunc(n))):Qn}var ee=class extends Error{timeout_ms;teardown;constructor(t,n,r){super(t),this.name="UpdateQueryError",this.timeout_ms=n,this.teardown=r}},La=new WeakMap;function ja(e){return La.get(e)??Promise.resolve()}function Da(e,t){let n={checked_at:e,available:null,error:t instanceof Error?t.message:String(t)};return t instanceof ee&&t.timeout_ms!==void 0&&(n.timeout_ms=t.timeout_ms),t instanceof ee&&t.teardown!==void 0&&La.set(n,t.teardown),n}var yt=new Set;function Ra(){for(let e of yt)e()}var Fa=new Pp;async function Ma(e){let t=new Set;try{return await Fa.run(t,e)}finally{Rp||await Promise.all(t)}}function Jp(e){return yt.size===0&&process.on("exit",Ra),yt.add(e),()=>{yt.delete(e),yt.size===0&&process.off("exit",Ra)}}function qp(e){let t=()=>e.exitCode!==null||e.signalCode!==null,n=()=>{t()||e.kill("SIGKILL")},r=()=>t()||e.pid===void 0?Promise.resolve():new Promise(o=>{let a=setTimeout(()=>{e.unref(),o()},Fp);e.once("exit",()=>{clearTimeout(a),o()})}),i=()=>(n(),e.stdout?.destroy(),r());return{stop:()=>t()||e.pid===void 0?Promise.resolve().then(i):Pa(e.pid,{kill:n,alive:()=>!t()}).then(i,i),killNow:n}}function Ua(e,t,n,r){return new Promise((i,o)=>{let a;try{a=Cp(e,t,{env:r.env,shell:r.shell,stdio:["ignore","pipe","ignore"]})}catch{o(new ee(r.failed));return}let s=a,c=performance.now()+n,d=!1,l="",p=0,u=qp(s),_=Fa.getStore(),g,w=()=>{let v=Jp(u.killNow),k=new Promise(b=>{setTimeout(()=>{u.stop().then(b,b)},0)}).finally(v);return _?.add(k),g=k,k},m=setTimeout(()=>{y(new ee(r.timedOut,n,w()))},n);function y(v){d||(d=!0,clearTimeout(m),performance.now()>=c?o(new ee(r.timedOut,n,g)):v?o(v):i(l.trim()))}if(s.on("error",()=>y(new ee(r.failed))),!s.stdout){y(new ee(r.failed,void 0,w()));return}s.stdout.setEncoding("utf8"),s.stdout.on("data",v=>{if(!d){if(p+=Buffer.byteLength(v),p>r.maxBuffer){y(new ee(r.failed,void 0,w()));return}l+=v}}),s.on("exit",(v,k)=>{v===0&&k===null||(y(new ee(r.failed)),s.stdout.destroy())}),s.on("close",(v,k)=>y(v===0&&k===null?void 0:new ee(r.failed)))})}function Na(e,t,n){if(typeof t=="string")try{let r=Np.resolve(e,t);if(r.type==="version")return r.fetchSpec}catch{}throw new Error(n)}var Wp=(e,t)=>Ua(Gn(),e,t,{env:{...process.env,npm_config_ignore_scripts:"true"},shell:zn(),maxBuffer:64*1024,timedOut:Up,failed:Mp}),Bp=(e,t)=>Ua("git",e,t,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never"},maxBuffer:1024*1024,timedOut:zp,failed:Gp});async function Ga(e,t=Wp,n=Qe()){try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let r=Na(e.package,e.version,"missing_or_invalid_installed_npm_version"),i=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],n),o;try{o=JSON.parse(i)}catch{throw new Error("invalid_npm_registry_metadata")}let a=Array.isArray(o)&&o.length===1?o[0]:o,s=Na(e.package,a,"invalid_npm_registry_version");return{checked_at:I(),available:vi(s,r),remote_version:s}}catch(r){return Da(I(),r)}}var Hp=(e,t,n)=>{let r=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),i=r.find(a=>a.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let o=t?.trim();return o?{checked_at:n,remote_commit:i.commit,available:i.commit!==o}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},er=async(e,t=Bp,n=Qe())=>{if(e.kind!=="github"||!e.repository)return{checked_at:I(),available:null,error:"not_a_github_managed_source"};try{let r=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,r,`${r}^{}`],n);return Hp(i,e.commit,I())}catch(r){return Da(I(),r)}};var za=4;function Kp(e){let t=e,n=[];return{acquire:()=>t>0?(t-=1,Promise.resolve()):new Promise(r=>n.push(r)),release:()=>{let r=n.shift();r?r():t+=1}}}function Ja(e,t){let{update_check_timeout_ms:n,...r}=e;return t===void 0?r:{...r,update_check_timeout_ms:t}}async function qa(e,t=!1,n=Qe(),r=!0){let i=Kp(za),o=await hn(e.entries,za,async a=>{if(!["github","npm"].includes(a.source.kind))return a;if(t||a.source.kind==="npm"&&!Nt(a.source))return Ja({...a,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 i.acquire();let s=a.source.kind==="github"?await er(a.source,void 0,n):await Ga(a.source,void 0,n);return r?ja(s).then(i.release):i.release(),Ja({...a,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:_i(o)}}function Wa(e,t){let n=e.filter(r=>r.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:r,result:i})=>{let o=i.details;return{alias:r,ok:i.ok,extension:o.extension,source:o.source,source_resolution:o.source_resolution,install_plan:o.install_plan,dry_run:o.dry_run,destination_path:o.destination_path,activated:o.activated,settings_changed:o.settings_changed,previous_state_preserved:o.previous_state_preserved,rollback:o.rollback,command_paths:o.command_paths,action_paths:o.action_paths,command_discovery:o.command_discovery,verification:o.verification,runtime_activation_status:o.runtime_activation_status,activation_diagnostics:o.activation_diagnostics,warnings:i.warnings}})}}import Vp from"node:fs/promises";import Xp from"node:path";function Yp(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Zp(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 Qp(e){let t=Xp.join(e,"manifest.json"),n;try{n=await Vp.readFile(t,"utf8")}catch(s){if(St(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=r,o=Gr(i),a=Yp(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:o.findings,warnings:o.findings.map(s=>Zp(a,s)),remediation:o.findings.map(s=>s.message)}}function Ba(e){return Qp(Tr(e))}import oe from"node:fs/promises";import et from"node:path";var tr=async e=>oe.readFile(e).catch(t=>{if(Wt(t,"ENOENT"))return null;throw t}),eu=async(e,t,n,r,i)=>Ce("extension_install_backup",async()=>{let o=_n(e),a=Ir(t),[s,c]=await Promise.all([tr(o),tr(a)]);return r&&await oe.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:o,managedStateContents:s,settingsPath:a,settingsContents:c}}),Ha=async e=>Ce("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 r=et.dirname(e.settingsPath),i=await A(r);try{await be({pmRoot:r,filePath:t,raw:n.toString("utf8"),op:"extension:install:rollback",author:q(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms})}finally{Qr(r)}}else await oe.mkdir(et.dirname(t),{recursive:!0}),await oe.writeFile(t,n)});async function Ka(e,t){let n=await S(e.destinationDirectory),r=await Ze(e.sourceDirectory,e.destinationDirectory);await oe.mkdir(e.selectedRoot,{recursive:!0});let i=et.join(et.dirname(e.selectedRoot),"runtime","extension-installs");await oe.mkdir(i,{recursive:!0});let o=await oe.mkdtemp(et.join(i,".pm-extension-install-backup-")),a=et.join(o,"destination"),s=["package","install",a,`--${e.scope}`],c=ae(s),d=!1;try{let l=await eu(e.selectedRoot,e.settingsRoot,e.destinationDirectory,n,a),p;try{p=await t()}catch(u){try{await Ha(l)}catch(_){d=!0;let g=new f(`Extension install failed: ${String(u)}; rollback failed: ${String(_)}`,h.GENERIC_FAILURE,{code:"extension_install_rollback_failed",original_code:u instanceof f?u.code:void 0,required:"Restore the previous package before retrying the replacement. Previous state was not preserved.",nextSteps:[n?c:"Repair the reported metadata write failure, then retry the original install."],...n?{recovery:{suggested_retry:c,suggested_retry_args:s}}:{}});throw Object.defineProperty(g,"cause",{value:u,configurable:!0,writable:!0}),g}throw u}if(p.ok)return p;if(!n||r)return{...p,details:{...p.details,previous_state_preserved:!1}};try{await Ha(l)}catch(u){return d=!0,{...p,details:{...p.details,previous_state_preserved:!1,rollback:{status:"failed",error:String(u),backup_directory:a,recovery_command:c,recovery_args:s}}}}return{...p,details:{...p.details,overwritten:!1,settings_changed:!1,previous_state_preserved:!0,rollback:{status:"restored"}}}}finally{d||await oe.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}var Za=[["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"]],tu=Za.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),nu={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"},ru="__pm_native_output",iu=["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"],Qa=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],ou=["disabled","require_trusted","require_provenance"],es={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:[]},au=e=>{let t=e??es,n={};for(let r of iu)n[r]=re(t[r]??[]);return n},su=(e,t)=>{for(let n of Qa)t[n].length>0&&(e[n]=t[n]);return e},cu=(e,t)=>{for(let n of ou)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},du=e=>{let t={};for(let n of Qa)t[n]=re(e[n]??[]);return t},lu=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:su(cu({name:t},e),du(e))},pu=e=>(e??[]).map(t=>lu(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),uu=e=>{let t=Object.assign({},es,e??{}),n=au(e),r=pu(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},ts=async(e,t)=>{let n=[t],r=await mo(t);r&&n.push(r);let i=[...new Set(n.map(o=>x(o)).filter(o=>o.length>0))];for(let o of i){let a=e.find(c=>x(c.name)===o);if(a)return a;let s=e.find(c=>x(c.directory)===o);if(s)return s}},ns=(e,t)=>{let n=t.trim(),r=new Set(re(e.extensions.enabled));return new Set(re(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},rs=(e,t)=>{let n=t.trim(),r=new Set(re(e.extensions.enabled)),i=new Set(re(e.extensions.disabled)),o=[...r],a=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},mu=(e,t)=>{let n=t.trim(),r=new Set(re(e.extensions.enabled)),i=new Set(re(e.extensions.disabled)),o=[...r],a=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},fu=(e,t)=>{let n=t.trim(),r=new Set(re(e.extensions.enabled)),i=new Set(re(e.extensions.disabled)),o=[...r],a=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},hu=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=Za.map(([i,o,a])=>({action:o,flag:a,distance:Pr(t,i,n)})).filter(i=>i.distance!==null).sort((i,o)=>i.distance-o.distance)[0];return r?{action:r.action,flag:r.flag}:null},gu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=hu(e);if(!r)return new f(`One action flag is required. Use one of: ${tu}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let i=`pm ${n} ${r.flag}`;return Rr({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(is),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},_u=[["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"]],is={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},yu=e=>is[e]??null,wu=(e,t)=>{let n=[...new Set(_u.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=yu(e.trim().toLowerCase());if(r)return r;throw gu(e,t)}if(n.length>1)throw new f("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},vu=e=>{let t=e.scope,n=e.project===!0||e.local===!0||t==="project"||t==="local",r=e.global===!0||t==="global";if(n&&r)throw new f('Options "--project/--local" and "--global" are mutually exclusive.',h.USAGE);return r?"global":"project"},ku=[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=>e?.source.kind==="npm"&&!Nt(e.source)?{status:"skipped_non_github",reason:"managed_npm_source_not_registry"}: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"}}],os=e=>{for(let t of ku){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},as=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,last_update_remote_version:i.last_update_remote_version,update_error:i.update_error,...r.status==="failed"&&i.update_check_timeout_ms!==void 0?{update_check_timeout_ms:i.update_check_timeout_ms}:{},update_check_status:r.status,update_check_reason:r.reason}},xu=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),o=r?ns(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:as({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:o},t,r,os(r))}},bu=async(e,t,n,r,i,o)=>{let a=te.join(e,t),s=te.join(a,"manifest.json"),c=o.get(x(t));if(!await S(s))return xu(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await tt.readFile(s,"utf8").then(_=>JSON.parse(_)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=gi(l);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=i.get(x(p.name))??o.get(x(t));return{summary:as({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:ns(r,p.name)},n,u,os(u))}},ue=async(e,t,n,r)=>{if(!await S(e))return{extensions:[],warnings:[]};let o=(await tt.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,p)=>l.localeCompare(p)),a=new Map(r.entries.map(l=>[x(l.name),l])),s=new Map(r.entries.map(l=>[x(l.directory),l])),c=[],d=[];for(let l of o){let p=await bu(e,l,t,n,a,s);p.warning&&c.push(p.warning),p.summary&&d.push(p.summary)}return{extensions:d.sort((l,p)=>l.name.localeCompare(p.name)),warnings:c.sort((l,p)=>l.localeCompare(p))}},Su=zr(),Eu=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,$u=(e,t,n,r)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),o=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&a.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Eu(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:a,...o?{sdk_dependency_status:"missing"}:{}}},Au=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},ss=e=>e.map(t=>Au(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),cs=(e,t,n)=>{let r=x(e);return t.find(i=>(n===void 0||i.layer===n)&&x(i.name)===r)},Tu=(e,t,n,r)=>n.find(o=>o.scope===t&&x(o.name)===x(e))?.activation_status??(r?"failed":"unknown"),ds=(e,t,n,r,i)=>Su.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,a=await tt.mkdtemp(te.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=ve(import.meta.url,["../.."]);try{let s=await ke({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:pn(),cache_bust:!0,module_graph_snapshot_root:a}),c=await xe({...s}),d=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...ss(c.failed)],l=Object.fromEntries(s.loaded.map(p=>[x(p.name),Fr(We(c,{extensionName:p.name}))]));return{installed:Zt(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await tt.rm(a,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),rr=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),o=[...i].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),a=r,s=[];for(let c of o){let d=te.join(e,c.directory),l=await qe(d),p=I(),u={kind:"local",input:c.name,location:d};a=Rt(a,{name:l.manifest.name,directory:c.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:u}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:u})}return s.length>0&&await ot(e,a),{state:a,adopted_entries:s,unmanaged_candidates:o,already_managed_count:n.length-i.length}},Iu=(e,t)=>{let n=M(process.cwd(),t.path),r=At(n,process.cwd()),i=e==="global"?Oe(process.cwd()):n,o=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:o,roots:r}},tn=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new f('Options "--gh" and "--github" must match when both are provided.',h.USAGE);return n[0]},Ou=e=>nu[e],Cu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,o=Ou(e),a=`<${r}>`,s=`pm ${n} ${o} ${a}`;throw new f(`Action "${e}" requires ${i} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},nn=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new f('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',h.USAGE);return Cu(t,n)},Pu=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${x(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${x(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,i,o)=>o.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},Ru=(e,t)=>{let r=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."},{triggered:t.fields!==void 0,allowed:e==="explore"||e==="manage"||e==="catalog",message:"--fields is only valid on the package listings: pm package list, pm package explore, pm package manage and pm package catalog."}].find(i=>i.triggered&&!i.allowed);if(r)throw new f(r.message,h.USAGE)},Nu=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},Lu=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},ju=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:Lu(e),warnings:[...new Set(e.warnings)].sort((i,o)=>i.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(r,ru,{value:!0,enumerable:!1,configurable:!1}),r},ir=async(e,t,n)=>{let r=wu(e,t);Ru(r,t),(r==="explore"||r==="manage")&&Rn(t.fields,r);let i=Nu(e,r,t),o=vu(t),a=Iu(o,n),c={action:r,normalizedTarget:i,scope:o,resolvedRoots:a,warnings:[],options:t,global:n},l={...c,withResult:(p,u=!0)=>ju(c,p,u)};return await Ma(()=>hm(l))},Du=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=Or(r),o={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},a={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[o[n],...s,`Install the scaffold: ${ae(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},Fu=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([tn(r),r.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new f('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let s=nn(n,t,r),c=await jo(s,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:c.created_directory||c.files.some(d=>d.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:Du(c,r)})},Mu=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:o,withResult:a}=e;if(t!==void 0)throw new f('Action "reload" does not accept a target argument.',h.USAGE);let s=await A(n.settings_root),c=pn(),d=await ke({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await xe(d);r.push(...l.warnings);let p={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(u=>({name:u.name,layer:u.layer,version:u.version})),failed_extensions:d.failed.map(u=>({name:u.name,layer:u.layer,error:u.error})),activation_failures:l.failed.map(u=>({name:u.name,layer:u.layer,error:u.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},Uu=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:o}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new f('Action "catalog" does not accept a package target.',h.USAGE);return o(await fo(n,i,r))},Gu=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),zu=e=>({kind:"local",input:e.input,location:e.absolute_path}),Ju=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),qu=(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}),Wu=(e,t,n,r)=>e?Gu(e,t):n.kind==="local"?zu(n):n.kind==="npm"?Ju(n,r):qu(n,r),Bu=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:yi(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},Hu=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:o,destinationDirectoryName:a}=t,s=await A(r.settings_root),c=await ce(r.selected_root);i.push(...c.warnings);let d=te.join(r.selected_root,a),l=await S(d),p=await Ze(o.directory,d);await tt.mkdir(r.selected_root,{recursive:!0});let u=Wu(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),_=c.state.entries.find(y=>x(y.name)===x(o.manifest.name)),g=Bu(_,o.manifest.version,u,I()),w=Rt(c.state,{name:o.manifest.name,directory:a,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,...g,source:u}),m=rs(s,o.manifest.name);return p||await Xo(o.directory,d),await Ho(d),await Ko(d),await ot(r.selected_root,w),m&&await he(r.settings_root,s,"settings:write"),{settings:s,managedState:w,sourceRecord:u,destinationDirectory:d,destinationExists:l,installInPlace:p,activationChanged:m}},Ku=async(e,t,n)=>{let r=n.filter(i=>x(i.name)===x(t)).flatMap(i=>i.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&r.length>0&&await gt(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},Vu=(e,t,n,r,i)=>{let o=cs(t,n.activation_failures,e.scope),a=Tu(t,e.scope,n.installed,o),s=[!n.extensions_disabled,a==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${a}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:a,failure:o,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:a,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},Xu=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:o,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t;return Ka({selectedRoot:r.selected_root,settingsRoot:r.settings_root,destinationDirectory:te.join(r.selected_root,c),sourceDirectory:s.directory,scope:n},async()=>{let d=await Hu(e,t),l=await ue(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let p=await ds(r.pm_root,te.dirname(r.selected_root),d.settings,l.extensions,o);i.push(...p.warnings);let u=await Ku(e,s.manifest.name,p.item_type_registrations),_=Sa(s.manifest.name,p.installed),g=Vu(e,s.manifest.name,p,_,u),w=p.contribution_inventories[x(s.manifest.name)];return w&&(d.managedState=await wi(r.selected_root,d.managedState,s.manifest.name,w)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:g.activated,settings_changed:d.activationChanged,runtime_activation_status:g.status,command_paths:_.command_paths,action_paths:_.action_paths,contributions:w,command_discovery:$u(s.manifest.name,d.sourceRecord,_,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)})},Yu=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new f('Action "install all" does not accept --ref.',h.USAGE);let o=[],a=new Map;for(let s of await zt()){let c=await ct(s),d=te.resolve(c),l=a.get(d);l===void 0&&(l=await ir(s,{...t,install:!0},n),a.set(d,l)),o.push({alias:s,result:l})}return r.push(...o.flatMap(s=>s.result.warnings)),i(Wa(o,t.dryRun===!0),o.every(s=>s.result.ok))},Zu=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:o,installSource:a,sourceResolution:s}=await ea(t,n,e.options.ref,(await ce(r.selected_root)).state.entries);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${d.package}`)}let c=await So(a);try{let d=await qe(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),l=Pt(d.manifest.name),p=e.options.dryRun===!0||a.kind==="local"&&i===null?await Zo(c,te.join(r.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:d.manifest.name,version:d.manifest.version},source_resolution:s,install_plan:p}):await Kn(r.settings_root,l,()=>Xu(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:o,sourceResolution:s,installSource:a,resolvedSource:c,installPlan:p}))}finally{c.cleanup&&await c.cleanup()}},Qu=async e=>{let t=tn(e.options),n=t??nn(e.normalizedTarget,e.action,e.options);return[t===void 0,lo(n)].every(Boolean)?Yu(e):Zu(e,n,t)},em=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:a}=e;if(t!==void 0)throw new f('Action "adopt-all" does not accept a target argument.',h.USAGE);if(tn(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new f('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let c=await A(r.settings_root),d=await ce(r.selected_root);i.push(...d.warnings);let l=await ue(r.selected_root,n,c,d.state);i.push(...l.warnings);let p=await rr(r.selected_root,n,l.extensions,d.state),u=await ue(r.selected_root,n,c,p.state);i.push(...u.warnings);let _=Qt(n,i,u.extensions,o);i.push(..._.warnings);let g=new Map(u.extensions.map(y=>[`${x(y.name)}:${x(y.directory)}`,y])),w=new Map(u.extensions.map(y=>[x(y.directory),y])),m=p.adopted_entries.map(y=>{let v=x(y.directory),k=g.get(`${x(y.name)}:${v}`)??w.get(v);return{...y,...ls(k)}});return a({adopted_all:m.length>0,adopted_count:m.length,already_managed_count:p.already_managed_count,extensions:m,triage:_,warning_codes:_.warning_codes,update_health_partial:_.update_health_partial,update_health_coverage:_.update_health_coverage})},ls=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),tm=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=dt(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new f(`Invalid GitHub shorthand "${e}".`,h.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},nm=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:a,withResult:s}=e,c=nn(n,t,a),d=tn(a),l=await A(i.settings_root),p=await ce(i.selected_root);o.push(...p.warnings);let u=await ue(i.selected_root,r,l,p.state);o.push(...u.warnings);let _=await ts(u.extensions,c);if(!_)throw new f(`Installed extension "${c}" was not found in ${r} scope.`,h.NOT_FOUND);if(_.managed)return s({adopted:!1,already_managed:!0,extension:{name:_.name,directory:_.directory}});let g=te.join(i.selected_root,_.directory),w=await qe(g),m=I(),y=tm(d,c,g,a.ref),v=Rt(p.state,{name:w.manifest.name,directory:_.directory,scope:r,manifest_version:w.manifest.version,manifest_entry:w.manifest.entry,capabilities:[...w.manifest.capabilities],contributions:w.manifest.contributions,installed_at:m,updated_at:m,source:y});await ot(i.selected_root,v);let k=await ue(i.selected_root,r,l,v);o.push(...k.warnings);let b=k.extensions.find(L=>x(L.name)===x(w.manifest.name))??k.extensions.find(L=>x(L.directory)===x(_.directory));return s({adopted:!0,extension:{name:w.manifest.name,directory:_.directory,version:w.manifest.version,entry:w.manifest.entry},source:y,...ls(b)})},ps=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:a}=e,s=nn(n,t,a),c=await A(i.settings_root),d=await ce(i.selected_root);o.push(...d.warnings);let l=await ue(i.selected_root,r,c,d.state);o.push(...l.warnings);let p=await ts(l.extensions,s);if(!p)throw new f(`Installed extension "${s}" was not found in ${r} scope.`,h.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:p}},rm=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:o}=await ps(e),a=te.join(t.selected_root,o.directory);await tt.rm(a,{recursive:!0,force:!0});let s={...i.state,updated_at:I(),entries:i.state.entries.filter(d=>x(d.name)!==x(o.name)&&x(d.directory)!==x(o.directory))};await ot(t.selected_root,s);let c=fu(r,o.name);return c&&await he(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:a,settings_changed:c})},Va=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:o}=e,{settings:a,candidate:s}=await ps(e),c=t==="activate"?rs(a,s.name):mu(a,s.name);c&&await he(n.settings_root,a,"settings:write");let d=t==="activate"?await ds(n.pm_root,te.dirname(n.selected_root),a,[s],i).then(l=>(r.push(...l.warnings),cs(s.name,l.activation_failures,e.scope))):void 0;return d&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),o({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},d===void 0)},im=(e,t,n,r,i,o)=>{let a=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=i?.adopted_entries.length??0,d=[[o!==null,o??""],[t>0,`Run pm ${a} explore --project and pm ${a} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${a} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},nr=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),om=(e,t,n,r)=>{if(e!=="project"||t||!nr(r))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},am=(e,t,n)=>{if(String(e??"").trim().length>0)throw new f('Action "doctor" does not accept a target argument.',h.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new f("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let i=wa(n.detail),o=n.trace===!0;if([o,i!=="deep"].every(Boolean))throw new f("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:r,detailMode:i,includeTrace:o}},sm=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await rr(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},cm=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:nr(r),rerun_command:null,pm_global_path_recipe:null};let o=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:nr(r),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},dm=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:a,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=am(t,n,o),p=await A(r.settings_root),u=await ce(r.selected_root);i.push(...u.warnings);let _=await ue(r.selected_root,n,p,u.state);i.push(..._.warnings);let{state:g,fix:w}=await sm(e,_.extensions,u.state),m=await ue(r.selected_root,n,p,g);i.push(...m.warnings);let y=await ke({pmRoot:r.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await xe({...y,loaded:y.loaded}),k=await Ba(r.pm_root);i.push(...k.warnings,...y.warnings),i.push(...ga(y.failed)),i.push(...v.warnings),i.push(..._a(v.failed)),i.push(...ya(y,v)),i.push(...Ea(v,y)),i.push(...Pu(y,v)),i.push(...$a(v));let b=Zt(m.extensions,y,v),L=ba(n,b,y.loaded.map(T=>({layer:T.layer,name:T.name})),y.failed.map(T=>({name:T.name})),y.disabled_by_flag);i.push(...L.warnings);let F=b.filter(T=>T.update_check_status==="failed").map(T=>`extension_update_check_failed:${T.name}`);i.push(...F);let j=Qt(n,i,b,o);i.push(...j.warnings);let E=[...j.warnings],J={mode:y.policy.mode,trust_mode:y.policy.trust_mode,require_provenance:y.policy.require_provenance,default_sandbox_profile:y.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:y.policy.trusted_extensions.length,allowed_extensions_count:y.policy.allowed_extensions.length,blocked_extensions_count:y.policy.blocked_extensions.length,allowed_capabilities_count:y.policy.allowed_capabilities.length,blocked_capabilities_count:y.policy.blocked_capabilities.length,allowed_surfaces_count:y.policy.allowed_surfaces.length,blocked_surfaces_count:y.policy.blocked_surfaces.length,allowed_commands_count:y.policy.allowed_commands.length,blocked_commands_count:y.policy.blocked_commands.length,allowed_actions_count:y.policy.allowed_actions.length,blocked_actions_count:y.policy.blocked_actions.length,allowed_services_count:y.policy.allowed_services.length,blocked_services_count:y.policy.blocked_services.length,extension_override_count:y.policy.extension_overrides.length},nt=ka(E),on=xa(),hr=j.warning_codes,Bs=om(n,c,o.vocabulary,y),Hs=im(j.remediation,y.failed.length,v.failed.length,o.vocabulary,w,Bs),gr=cm(n,c,o.vocabulary,y),Ks={status:j.status,scope:n,warning_count:j.warning_count,warning_codes:hr,total_extensions:b.length,managed_total:b.filter(T=>T.managed).length,enabled_total:b.filter(T=>T.enabled).length,active_total:b.filter(T=>T.active).length,unmanaged_loaded_extension_count:j.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:j.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:j.unmanaged_expected_extension_count,runtime_active_total:b.filter(T=>T.runtime_active===!0).length,activation_status_totals:{ok:b.filter(T=>T.activation_status==="ok").length,failed:b.filter(T=>T.activation_status==="failed").length,not_loaded:b.filter(T=>T.activation_status==="not_loaded").length,unknown:b.filter(T=>T.activation_status==="unknown").length},unknown_capability_count:nt.length,capability_contract_version:on.version,update_available_total:j.update_available_total,update_check_status_totals:j.update_check_status_totals,update_health_coverage:j.update_health_coverage,update_health_partial:j.update_health_partial,update_check_failed_total:b.filter(T=>T.update_check_status==="failed").length,load_failure_count:y.failed.length,activation_failure_count:v.failed.length,load_failures:Yn(y.failed),activation_failures:Yn(v.failed),blocking_failure_count:y.failed.length+v.failed.length,has_blocking_failures:y.failed.length+v.failed.length>0,consistency_warning_count:L.warnings.length,trace_enabled:l,isolation:gr,policy:J,remediation:Hs},Vs=w?{requested:!0,applied:w.adopted_entries.length>0,adopted_count:w.adopted_entries.length,already_managed_count:w.already_managed_count,adopted_extensions:w.adopted_entries.map(T=>T.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:m.extensions.filter(T=>T.managed).length,adopted_extensions:[]},an={mode:d,summary:Ks,triage:j,trace_enabled:l,capability_contract:on,capability_guidance:nt,managed_state_fix:Vs,author_manifest:k,isolation:gr,policy:y.policy};if(d==="deep"){let T=l?v.failed:v.failed.map(R=>{let{trace:nf,...Xs}=R;return Xs});an.deep={warnings:E,warning_codes:hr,capability_contract:on,capability_guidance:nt,trace_enabled:l,managed_state:{path:u.path,count:g.entries.length,entries:g.entries},installed_extensions:b,load:{roots:y.roots,policy:y.policy,warnings:y.warnings,failed:y.failed,loaded:y.loaded.map(R=>({layer:R.layer,directory:R.directory,name:R.name,version:R.version,entry:R.entry,priority:R.priority}))},activation:{failed:T,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:L.summary},l&&(an.deep.trace={activation_failures:v.failed.filter(R=>R.trace!==void 0).map(R=>({layer:R.layer,name:R.name,entry_path:R.entry_path,error:R.error,method:R.trace.method,command:R.trace.command,capability:R.trace.capability,missing_capability:R.trace.missing_capability,registration_index:R.trace.registration_index,expected_schema:R.trace.expected_schema,hint:R.trace.hint,received:R.trace.received}))})}return s(an)},lm=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:a,withResult:s}=e,c=await A(r.settings_root),d=await ke({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),l=await xe(d);i.push(...d.warnings),i.push(...l.warnings);let p=Uo(t,d,l);if(t!==void 0&&p.extensions.length===0){let u=o.vocabulary==="package"?"package":"extension",_=[...new Set(d.loaded.map(w=>o.vocabulary==="package"&&typeof w.source_package=="string"&&w.source_package.trim().length>0?w.source_package.trim():w.name))].sort((w,m)=>w.localeCompare(m)),g=_.length>0?` Loaded ${u} names: ${_.join(", ")}.`:"";throw new f(`No loaded ${u} named "${t}" was found in ${n} scope.${g} Run pm ${u} explore to list discovered ${u}s.`,h.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},pm=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await rr(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let o=e.options.fixManagedState===!0;r=await qa(r,e.options.offline,o?Qn:Qe(),!o);let a=await ki(e.resolvedRoots.settings_root,e.resolvedRoots.selected_root,r.entries,e.options.offline===!0);a&&e.warnings.push(a)}return{state:r,fix:i}},um=async(e,t,n)=>{let r=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await xe({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:Zt(n,r,i),failures:ss(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...r.warnings,...i.warnings])].length,policy:r.policy}}},mm=(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},Xa=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:a}=e,s=Rn(o.fields,t),c=await A(r.settings_root),d=uu(c.extensions.policy),l=await ce(r.selected_root);i.push(...l.warnings);let p=await ue(r.selected_root,n,c,l.state);i.push(...p.warnings);let{state:u,fix:_}=await pm(e,p.extensions,l.state),g=await ue(r.selected_root,n,c,u);if(i.push(...g.warnings),t==="manage"&&o.offline===!0)for(let k of g.extensions)k.managed&&["npm","github"].includes(k.source.kind)&&(k.update_check_reason="offline_requested");if(t==="manage"){let k=g.extensions.filter(b=>b.update_check_status==="failed").map(b=>`extension_update_check_failed:${b.name}`);i.push(...k)}let w=await um(e,c,g.extensions),m=w.installed,y=Qt(n,i,m,o);i.push(...y.warnings);let v={total:m.length,managed_total:m.filter(k=>k.managed).length,enabled_total:m.filter(k=>k.enabled).length,active_total:m.filter(k=>k.active).length,extensions:so(m,s),triage:y,policy:d};return w.failures!==void 0&&(v.activation_diagnostics={failed_count:w.failures.length,failed:w.failures}),t==="explore"&&(v.runtime_probe=w.summary),t==="manage"&&(v.runtime_probe=w.summary,v.managed_state_fix=mm(_,m)),a(v)},Ya={init:Fu,install:Qu,uninstall:rm,explore:Xa,manage:Xa,describe:lm,reload:Mu,doctor:dm,catalog:Uu,adopt:nm,"adopt-all":em,activate:Va,deactivate:Va,migrate:Fi},fm=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),hm=e=>fm(e)?Kn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Ya[e.action](e)):Ya[e.action](e);import sr from"node:fs/promises";import z from"node:path";import us from"node:readline/promises";import{stdin as ms,stdout as wt}from"node:process";var fs=["ask","add","skip","status"],gm=["AGENTS.md","CLAUDE.md"],_m=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],ym=8,cr=1,wm="<!-- pm-cli:agent-guidance:start:",vm=`<!-- pm-cli:agent-guidance:start:v${cr} -->`,or="<!-- pm-cli:agent-guidance:end -->",kt="Add workflow guidance later: pm init --agent-guidance add",dv={toPortableRelativePath:Fe,ensureTrailingNewline:ar,detectLineEnding:gs,findGuidanceBlockRange:dr,buildAgentGuidanceBlock:_s,upsertAgentGuidanceBlock:lr,resolveProjectRoot:ws,resolveTargetGuidancePath:vs,parsePromptChoice:ks,pushUnique:Ie,promptForGuidanceWrite:xs,normalizeAgentGuidanceState:pr,applyAgentGuidanceState:Ss,writeGuidanceFile:ur,setAgentGuidanceReadlineFactoryForTests:km},hs=()=>us.createInterface({input:ms,output:wt});function km(e){hs=e??(()=>us.createInterface({input:ms,output:wt}))}function Fe(e,t){let n=z.relative(e,t);return n.length===0?z.basename(t):n.split(z.sep).join("/")}function ar(e){return e.endsWith(`
|
|
39
|
+
`)?e:`${e}
|
|
40
|
+
`}function gs(e){return e.includes(`\r
|
|
41
|
+
`)?`\r
|
|
42
|
+
`:`
|
|
43
|
+
`}function dr(e){let t=e.indexOf(wm);if(t===-1)return null;let n=e.indexOf(or,t);return n===-1?null:{start_index:t,end_index:n+or.length}}function xm(e){return dr(e)!==null}function _s(e,t="<your project test command>"){return[vm,"## 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.","",or,""].join(e)}function lr(e,t="<your project test command>"){let n=gs(e),r=_s(n,t),i=dr(e);if(i){let s=e.slice(i.end_index),c=s.startsWith(`\r
|
|
44
|
+
`)?s.slice(2):s.startsWith(`
|
|
45
|
+
`)?s.slice(1):s,d=ar(`${e.slice(0,i.start_index)}${r}${c}`);return{next_content:d,changed:d!==e}}let o=e.length===0?"":e.endsWith(`
|
|
46
|
+
`)?`
|
|
47
|
+
`:`
|
|
48
|
+
|
|
49
|
+
`,a=ar(`${e}${o}${r}`);return{next_content:a,changed:a!==e}}async function ys(e){if(await S(z.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await sr.readFile(z.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=bm(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await S(z.join(e,"pnpm-lock.yaml"))?"pnpm test":await S(z.join(e,"bun.lock"))||await S(z.join(e,"bun.lockb"))?"bun run test":await S(z.join(e,"yarn.lock"))?"yarn test":"npm test"}function bm(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 ws(e,t){let n=z.dirname(e);return z.basename(e)==="pm"&&z.basename(n)===".agents"?z.dirname(n):z.resolve(t,e)}function vs(e,t){let n=e.find(i=>z.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let r=e.find(i=>i.exists);return r?r.file_path:z.join(t,"AGENTS.md")}function ks(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 xs(e){let t=hs();try{wt.write(`
|
|
50
|
+
Agent guidance check
|
|
51
|
+
`),wt.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
52
|
+
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return wt.write(`
|
|
53
|
+
`),ks(n,!0)}finally{t.close()}}function pr(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:cr,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function bs(e){let t=[],n=await ys(e);for(let r of gm){let i=z.join(e,r),o=await S(i);if(!o){t.push({file_path:i,exists:o,has_guidance:!1,has_marker:!1});continue}let a=await sr.readFile(i,"utf8"),s=a.toLowerCase(),c=_m.filter(l=>s.includes(l)),d=xm(a);t.push({file_path:i,exists:o,has_guidance:d||c.length>=ym,has_marker:d,outdated:d&&lr(a,n).changed})}return t}function Ie(e,t){e.includes(t)||e.push(t)}function Ss(e,t){let n=pr(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function ur(e,t=z.dirname(e)){let r=await S(e)?await sr.readFile(e,"utf8"):"",i=lr(r,await ys(t));return i.changed?(await me(e,i.next_content),{changed:!0,warnings:await H({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function Sm(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=>Fe(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Fe(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Fe(e.projectRoot,t.file_path))}}async function Em(e,t,n){return e?await bs(n):t}function vt(e,t,n){e.state={...e.state,...n,template_version:cr,last_checked_files:t}}async function Es(e,t){if(t.presentBefore)return;let n=await ur(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function $m(e,t){t||(e.warnings.push("agent_guidance:missing"),Ie(e.nextSteps,kt))}function Am(e,t){e.skipped=!0,vt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Ie(e.nextSteps,kt)}async function Tm(e,t){await Es(e,t),vt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Im(e,t){e.state.declined&&vt(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Om(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ie(e.nextSteps,kt)}async function Cm(e,t){if(e.prompted=!0,await xs(t.targetRelativePath)){await Es(e,t),vt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,vt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ie(e.nextSteps,kt)}function Pm(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ie(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Ie(e.nextSteps,kt)}async function Rm(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?($m(n,t.presentBefore),n):t.mode==="skip"?(Am(n,t.checkedFiles),n):t.mode==="add"?(await Tm(n,t),n):t.presentBefore?(Im(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Om(n),n):t.interactive?(await Cm(n,t),n):(Pm(n),n)}async function $s(e){let t=ws(e.pm_root,e.cwd),n=await bs(t),r=vs(n,t),i=Fe(t,r),o=n.map(p=>Fe(t,p.file_path)),a=n.some(p=>p.has_guidance),s=await Rm(pr(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:i,checkedFiles:o,presentBefore:a,projectRoot:t});if(e.mode==="add")for(let p of n.filter(u=>u.outdated)){let u=await ur(p.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=Ss(e.settings,s.state);n=await Em(s.applied,n,t);let d=n.filter(p=>p.outdated).map(p=>Fe(t,p.file_path));return d.length>0&&(s.warnings.push(`agent_guidance_outdated:${d.join(",")}`),Ie(s.nextSteps,"pm init --agent-guidance add")),{summary:Sm({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import Nm from"node:fs/promises";import P from"node:path";import Ts from"node:readline/promises";import{stdin as Is,stdout as X}from"node:process";var Lm=Symbol.for("pm.sdk.init-invocation-cwd");function Nv(e,t=!1){if(t){let n=e.warnings.filter(i=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(i)),r=n.includes("agent_guidance:missing_non_interactive")?e.next_steps.filter(i=>i.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:[...r,...e.next_steps.filter(i=>!r.includes(i))].slice(0,3),...n.length>0?{warnings:n.join("; ")}:{},details:`${ae(["--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 Lv={normalizeInitGovernancePreset:mr,normalizeInitTypePreset:Cs,normalizeOptionalInitAuthor:Ps,normalizeInitAgentGuidanceMode:Ls,isPathLikeInitTarget:rn,resolveInitInvocation:Rs,resolveInitPrefixInput:Ns,parseYesNoChoice:js,applyGovernancePreset:fr,runInitWizard:zs,setInitReadlineFactoryForTests:jm,summarizeInstalledPackages:Ds,buildInitNextSteps:qs,registerInitTypePreset:Fs,assertExplicitTrackerPathIsNotWorkspaceRoot:Us,isLikelyWorkspaceRoot:Ms,installInitMergeFence:Ws},Os=()=>Ts.createInterface({input:Is,output:X});function jm(e){Os=e??(()=>Ts.createInterface({input:Is,output:X}))}function Dm(){return structuredClone(wr)}var Fm=["minimal","default","strict"];function mr(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new f("--preset must not be empty",h.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new f(`Invalid --preset value "${e}". Allowed: ${Fm.join(", ")}`,h.USAGE)}function Cs(e){if(e!==void 0){if(e.trim().length===0)throw new f("--type-preset must not be empty",h.USAGE);try{return Kt(e)}catch{throw new f(`Invalid --type-preset value "${e}". Allowed: ${ft.join(", ")}`,h.USAGE)}}}function Ps(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new f("--author must not be empty",h.USAGE);return t}function rn(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:P.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function Rs(e,t,n,r){let i=r?.trim();if(r!==void 0&&i?.length===0)throw new f("--workspace must not be empty",h.USAGE);if(i!==void 0){if(t.path!==void 0||rn(n))throw new f("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",h.USAGE);let d=P.resolve(e,i),l=P.join(d,".agents","pm");return{pmRoot:l,prefixArg:n,target:{mode:"workspace-path",tracker_root:l,workspace_root:d}}}if(t.path===void 0&&rn(n)){let d=P.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let o=M(e,t.path),a=P.join(P.resolve(e),".agents","pm"),s=P.dirname(P.dirname(o)),c=P.resolve(o)===a?"current":"ancestor";return{pmRoot:o,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:o,workspace_root:s,discovery:c,requested_cwd:P.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:o}}}function Ns(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new f("--id-prefix must not be empty",h.USAGE);if(rn(t))throw new f(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,h.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&Se(e)!==Se(t))throw new f(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,h.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Se(e)}`,`pm init --id-prefix ${Se(t)}`]});return t}function Ls(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new f("--agent-guidance must not be empty",h.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new f(`Invalid --agent-guidance value "${e}". Allowed: ${fs.join(", ")}`,h.USAGE)}function js(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function fr(e,t){let n=yr[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function Mm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ds(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(Mm).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Fs(e,t,n){let r=K(t.schema),i=Z(e,r.files.types,V.types),a=ne(await U(i)),s=[],c=[];for(let d of ht(n)){let l=Ue(a,d);a=l.file,(l.replaced?c:s).push(l.definition.name)}return await be({pmRoot:e,filePath:i,raw:se(a),op:"init:type-preset",author:q(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:s,updated:c,file:i}}async function Ms(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",P.join(".agents","pm")];for(let n of t)if(await S(P.join(e,n)))return!0;return!1}async function Us(e,t,n){if(!t||n||await S(P.join(e,"settings.json"))||!await Ms(e))return;let r=P.join(e,".agents","pm");throw new f(`Refusing to initialize tracker files directly in workspace root "${e}".`,h.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function Gs(e,t){let n=[],r=[];for(let i of t){let o=i?P.join(e,i):e,a=await S(o);await Nm.mkdir(o,{recursive:!0}),a?r.push(`already_exists:${o}`):n.push(o),r.push(...await H({path:o,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function zs(e,t){let n=Os(),r=t===void 0?2:3;try{X.write(`pm init setup wizard (agent-optimized)
|
|
54
|
+
`),X.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
55
|
+
|
|
56
|
+
`),X.write(`1/${r} Item ID prefix
|
|
57
|
+
`),X.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
|
|
58
|
+
`);let i=await n.question(`Item ID prefix [${e}]: `),o=i.trim().length>0?Se(i):e;X.write(`
|
|
59
|
+
2/${r} Governance preset
|
|
60
|
+
`),X.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
61
|
+
`),X.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
62
|
+
`),X.write(`strict: ownership blocking, strict create defaults, close validation strict.
|
|
63
|
+
`);let a=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),s=a.trim().length>0?a.trim():"minimal",c="minimal";try{c=mr(s)}catch{X.write(`Unrecognized governance preset "${s}"; using minimal.
|
|
64
|
+
`)}let d;if(t!==void 0){X.write(`
|
|
65
|
+
3/3 Telemetry
|
|
66
|
+
`),X.write(`Telemetry helps improve reliability. The choice applies to this CLI install; change it with pm config global set telemetry-tracking.
|
|
67
|
+
`);let l=await n.question(`Enable telemetry for this CLI install? [${t?"Y/n":"y/N"}] `);d=js(l,t)}return X.write(`
|
|
68
|
+
`),{prefix:o,preset:c,telemetry_enabled:d}}finally{n.close()}}function Um(e){return{presetFromOption:mr(e.preset),useDefaults:e.defaults===!0,authorFromOption:Ps(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:Ls(e.agentGuidance),typePreset:Cs(e.typePreset)}}function Gm(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 zm(e,t,n,r){if(t.length===0||n)return;let i=r.discovery==="ancestor";throw new f(`${i?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,h.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:i?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...i?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...i?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function Jm(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&&(fr(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 qm(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=Gm({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return zm(e.settingsPath,n,e.options.force===!0,e.target),Jm({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await he(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function Wm(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,i=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let d=await zs(t,await Bm());t=d.prefix,n=d.preset,r=d.telemetry_enabled,i=!0}let o=n??"minimal",a=Dm();a.id_prefix=t,fr(a,o);let s=jr()?.trim()||void 0;a.author_default=e.normalizedOptions.authorFromOption??s??"";let c=Js(e.pmRoot);return r!==void 0&&(a.telemetry.enabled=r,a.telemetry.first_run_prompt_completed=!0),await he(e.pmRoot,a,void 0,c),r!==void 0&&c.omitSections&&await Hm(r,e.warnings),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:i}}function Js(e){return P.resolve(e)===P.resolve(Oe(process.cwd()))?{}:{omitSections:["telemetry"]}}async function Bm(){let e=await A(Oe(process.cwd()));if(!(si().telemetry_disabled||e.telemetry.first_run_prompt_completed||mn(e)))return e.telemetry.enabled}async function Hm(e,t){let n=Oe(process.cwd()),r=await A(n);if(mn(r)){t.push("telemetry_consent_not_recorded:global_settings_unreadable");return}let i=!1;r.telemetry.enabled=e,r.telemetry.first_run_prompt_completed=!0,await he(n,r,"telemetry:first_run_prompt",{skipIfStored:o=>i=o.telemetry?.first_run_prompt_completed===!0}),i&&t.push("telemetry_consent_kept:recorded_while_prompting")}async function Km(e){let{telemetry:t}=await A(Oe(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 As(e){return e.settingsExists?await qm(e):await Wm({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions,warnings:e.warnings})}async function Vm(e){let t=await $s({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 he(e.pmRoot,e.settings,void 0,Js(e.pmRoot)),{...t.summary,next_steps:t.next_steps}}async function Xm(e,t){let n=[],r=[],i=await Lr(e,t.schema);for(let o of i.created_paths)n.push(o),r.push(...await H({path:o,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function Ym(e){if(e.typePreset===void 0)return;let t=await Fs(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await H({path:t.file,scope:"project",op:"init:type_preset"})),t}async function Zm(e){let n=B(e.settings,W()).folders.filter(i=>!sn.includes(i)),r=await Gs(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function Qm(e){let t=P.resolve(e.tracker_root),n=P.dirname(t);return P.basename(t)==="pm"&&P.basename(n)===".agents"?P.dirname(n):e.workspace_root}async function ef(e,t,n,r){if(!e)return;let i=await ir("all",{install:!0,project:!0},{...t,path:n});r.push(...i.warnings);let o=Ds(i),a=o.packages.filter(s=>!s.ok).map(s=>s.alias);if(!o.installed_all||a.length>0)throw new f(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,h.GENERIC_FAILURE);return o}function qs(e){let t=r=>ae([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let i=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(i)||n.push(i)}return n}async function Ws(e,t,n,r=hi){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let i=await r({pmRoot:e,workspaceRoot:t});i.gitattributes.changed&&n.push(`updated:merge_fence:${i.gitattributes.path}`)}catch(i){if(!(i instanceof f))throw i;n.push(`merge_fence_skipped:install_failed:${i.context.code??"pm_error"}:${i.message}:run pm merge install after resolving the Git repository error`)}}async function tf(e,t,n,r){if(e==null||n==="status")return;let i=await ui(e,{pmRoot:t});i.changed&&r.push(`updated:gitignore:${i.path}`)}async function jv(e,t,n={}){let r=t[Lm],i=typeof r=="string"?r:process.cwd(),o=Rs(i,t,e,n.workspace),a=o.pmRoot;e=Ns(o.prefixArg,n.idPrefix);let s=Um(n);await Us(a,o.target.mode==="tracker-path",n.force===!0);let c=[],d=[],l=P.join(a,"settings.json"),p=await S(l),u;p&&(u=await As({pmRoot:a,settingsPath:l,settingsExists:p,normalizedPrefix:Se(e),prefixArg:e,options:n,normalizedOptions:s,warnings:d,target:o.target}));let _=await Gs(a,sn);c.push(..._.createdDirs),d.push(..._.warnings),u??=await As({pmRoot:a,settingsPath:l,settingsExists:p,normalizedPrefix:Se(e),prefixArg:e,options:n,normalizedOptions:s,warnings:d,target:o.target});let{settings:g}=u,w=Qm(o.target),m=await mi(w??P.dirname(a)),y=w??m,v=await Vm({pmRoot:a,cwd:y??i,agentGuidanceMode:s.agentGuidanceMode,settings:g,warnings:d}),k=await Xm(a,g);c.push(...k.createdDirs),d.push(...k.warnings);let b=await Ym({pmRoot:a,settings:g,typePreset:s.typePreset,warnings:d});b&&(g=await A(a)),await Zm({pmRoot:a,settings:g,createdDirs:c,warnings:d}),await tf(y,a,s.agentGuidanceMode,d),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await Ws(a,m,d);let L=await ef(s.installBundledPackages,t,a,d),F=qs({installBundledPackages:s.installBundledPackages,registeredTypePreset:b,agentGuidanceNextSteps:v.next_steps,target:o.target});return{ok:!0,path:a,target:o.target,settings:await Km(g),created_dirs:c,warnings:d,governance_preset:g.governance.preset,wizard_used:u.wizardUsed,...b?{registered_type_preset:b}:{},...L?{installed_packages:L}:{},next_steps:F,agent_guidance:v}}export{af as a,yn as b,Sn as c,Ni as d,wf as e,dc as f,vf as g,$n as h,mc as i,fc as j,hc as k,Fi as l,Hl as m,We as n,Wi as o,Be as p,He as q,Bi as r,_c as s,Pf as t,jf as u,Gi as v,vc as w,Yf as x,Zi as y,ro as z,Zc as A,Qc as B,j_ as C,D_ as D,F_ as E,gt as F,M_ as G,U_ as H,G_ as I,z_ as J,J_ as K,q_ as L,W_ as M,B_ as N,H_ as O,K_ as P,V_ as Q,X_ as R,Y_ as S,Z_ as T,Q_ as U,ey as V,ty as W,ny as X,ry as Y,iy as Z,oy as _,ay as $,sy as aa,cy as ba,dy as ca,Ut as da,ed as ea,st as fa,Gt as ga,Pn as ha,sd as ia,yo as ja,Ao as ka,Bn as la,Uo as ma,Ag as na,la as oa,hp as pa,ka as qa,xa as ra,Pa as sa,Zo as ta,zl as ua,Qp as va,ea as wa,ir as xa,fs as ya,dv as za,$s as Aa,Lm as Ba,Nv as Ca,Lv as Da,jv as Ea};
|
|
69
|
+
//# sourceMappingURL=chunk-T3GJPXIZ.js.map
|