@unbrained/pm-cli 2026.10.7 → 2026.10.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +32 -0
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +154 -154
- package/dist/cli-bundle/chunks/{chunk-DWH555SN.js → chunk-55MK3QQM.js} +30 -30
- package/dist/cli-bundle/chunks/chunk-5MOFELIF.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-TON7H63A.js → chunk-5NR6TDYB.js} +53 -52
- package/dist/cli-bundle/chunks/chunk-5TCQ5J3V.js +234 -0
- package/dist/cli-bundle/chunks/{chunk-TG3IOQUG.js → chunk-CPZOW6L2.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-E4XR5LKU.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-MOXX7D3F.js → chunk-KOGF6O6W.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-N7GKWO4G.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-VU77O6HC.js → chunk-NIF7JOPW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-N2PFAWVV.js → chunk-P5NS7EFC.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-A4QWRU7D.js → chunk-QQHNXCO3.js} +5 -5
- package/dist/cli-bundle/chunks/chunk-XW3BLWFF.js +20 -0
- package/dist/cli-bundle/chunks/chunk-ZNXRGATT.js +2 -0
- package/dist/cli-bundle/chunks/register-list-query-2YOWMNWY.js +11 -0
- package/dist/cli-bundle/chunks/{register-mutation-JRH6EGSE.js → register-mutation-ILOWFMTV.js} +2 -2
- package/dist/cli-bundle/chunks/register-operations-BMK65YM3.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-24TFFK6N.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7X3QD5V4.js → chunk-2ATAD56F.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PBNQZV33.js → chunk-2CJWTLQG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XIGFEA3W.js → chunk-362645PL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4FKCHJGV.js → chunk-AU6VJGTY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QY4Z23QC.js → chunk-B3YW6H2I.js} +17 -21
- package/dist/cli-bundle/focused-chunks/{chunk-3NSZ5C4A.js → chunk-DMSADMEU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-DSLNUL2Q.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-EPOCI7ZX.js → chunk-EZ4367G4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FWWFCLDM.js → chunk-IARAEFMA.js} +60 -59
- package/dist/cli-bundle/focused-chunks/{chunk-SIR5RFJX.js → chunk-MCVWZUGK.js} +27 -27
- package/dist/cli-bundle/focused-chunks/chunk-PBCYGO7X.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NRSA5ZB2.js → chunk-PLTTMQAW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HMG5F5EC.js → chunk-SAN3KPX4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3BKRCR57.js → chunk-W5AE7GKZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QEYEDXRI.js → chunk-WAOXID5J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2YICTWWA.js → chunk-WOEZJUA2.js} +2 -2
- package/dist/cli-bundle/main.js +2 -2
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +22 -22
- 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 +51 -50
- 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 +7 -7
- package/dist/core/extensions/item-fields.d.ts +6 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/fs/fs-utils.d.ts +19 -4
- package/dist/core/fs/fs-utils.js +2 -2
- package/dist/core/history/event-index.d.ts +1 -2
- package/dist/core/history/event-index.js +2 -2
- package/dist/core/lock/lock.d.ts +9 -2
- package/dist/core/lock/lock.js +2 -2
- package/dist/core/output/output.d.ts +16 -14
- package/dist/core/output/output.js +6 -10
- package/dist/core/store/item-metadata-query-index.d.ts +1 -2
- package/dist/core/store/item-metadata-query-index.js +1 -1
- package/dist/core/store/settings.js +2 -2
- package/dist/core/store/sqlite-runtime.d.ts +15 -0
- package/dist/core/store/sqlite-runtime.js +2 -0
- package/dist/core/telemetry/runtime.d.ts +1 -1
- package/dist/core/telemetry/runtime.js +4 -4
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/merge/abandoned-receipts.js +1 -1
- package/dist/sdk/merge/driver.js +1 -1
- package/dist/sdk/merge/install.js +3 -2
- package/dist/sdk/merge/receipt-operation.d.ts +5 -5
- package/dist/sdk/merge/receipt-operation.js +1 -1
- package/dist/sdk/merge/receipts.d.ts +1 -1
- package/dist/sdk/merge/receipts.js +3 -3
- package/dist/sdk/merge/worktree-config.d.ts +2 -0
- package/dist/sdk/merge/worktree-config.js +1 -1
- package/dist/sdk/output/table-rows.d.ts +37 -0
- package/dist/sdk/output/table-rows.js +2 -0
- package/dist/sdk/output.d.ts +1 -0
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output-contracts.d.ts +3 -3
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/test/workspace-snapshot.d.ts +1 -1
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/docs/AGENT_OUTPUT_ENCODINGS.md +119 -0
- package/docs/BUILD_AND_RELEASE_ACCEPTANCE.md +36 -100
- package/docs/MERGE_SAFETY.md +61 -6
- package/docs/PACKAGE_GATE_ACCEPTANCE.md +56 -0
- package/docs/PACKED_FIRST_RUN.md +26 -42
- package/docs/README.md +3 -0
- package/docs/SDK_AUDITED_MUTATIONS.md +18 -0
- package/docs/SDK_STORAGE_LIFECYCLE.md +35 -0
- package/docs/TESTING.md +11 -3
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
- package/marketplace.json +2 -2
- 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 +2 -2
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +2 -2
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +2 -2
- package/dist/cli-bundle/chunks/chunk-754AV3DC.js +0 -8
- package/dist/cli-bundle/chunks/chunk-CEM35QB2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-CMIU2NDK.js +0 -20
- package/dist/cli-bundle/chunks/chunk-GJ2OJKRM.js +0 -238
- package/dist/cli-bundle/chunks/chunk-GSQK3VUT.js +0 -2
- package/dist/cli-bundle/chunks/chunk-WUOFG4JY.js +0 -3
- package/dist/cli-bundle/chunks/register-list-query-CBJELTDX.js +0 -11
- package/dist/cli-bundle/chunks/register-operations-FYV7CUBF.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-M5VO6JUH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3RJ4VK7U.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-H5VREEUE.js +0 -20
|
@@ -1,67 +1,68 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)}function
|
|
3
|
-
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let o=i.filter(d=>d.outcome==="pending").length,s=i.filter(d=>d.outcome==="applied").length,l=i.filter(d=>d.outcome==="skipped").length,c=i.filter(d=>d.outcome==="failed").length;return{ok:c===0,dry_run:e.dryRun===!0,state_path:Pn(e.pmRoot),total:i.length,pending_count:o,applied_count:s,skipped_count:l,failed_count:c,migrations:i}}async function
|
|
4
|
-
`)}async function
|
|
1
|
+
import{$ as oe,$i as Ft,Ab as Ki,Am as me,Bi as $e,Bl as _r,Ec as W,Fi as pr,G as ji,Gi as mr,Hi as Ie,Ib as Vi,Ii as ur,Ji as fr,Kb as Yi,Kn as xr,L as wn,Md as jt,N as Li,Nb as De,Nc as H,Nd as nr,Od as Sn,Pd as En,Q as vn,Qd as $n,R as h,Sd as ir,Si as hr,T as f,Ta as Mi,Td as rr,Tf as Se,Ua as Gi,V as k,Va as U,W as Pt,Wd as ar,X as ie,Y as G,Yi as gr,aj as Mt,ba as K,bb as N,be as or,cb as Ui,cd as tr,db as zi,dd as st,dj as je,eb as Ji,ei as In,fa as pe,fg as I,gf as T,gg as Z,gh as lr,gi as dr,hc as xn,hg as sr,hi as He,ic as Xi,ig as Y,ij as yr,jc as Nt,jg as re,jj as An,k as Ni,ka as Fi,lc as ke,lg as cr,lh as B,nc as xe,nf as V,ng as ct,oi as se,pg as Lt,qc as Zi,sc as Dt,sm as wr,tc as Qi,ti as A,tm as Le,ua as Rt,ub as qi,uc as er,ui as Ee,um as lt,va as bn,vb as Wi,vm as vr,w as Di,wa as kn,wb as Bi,wm as br,xm as ce,ym as Ke,z as Ct,zb as Hi,zm as kr,zo as Gt}from"./chunk-5TCQ5J3V.js";import{mkdir as oc,readFile as sc}from"node:fs/promises";import Ar from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0bd9a904-c076-5c2a-a9d8-42a543625e33")}catch{}})();var Tn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},cc="sdk-workspace-transaction",lc=/^[a-zA-Z0-9._-]+$/,dc=30,pc=3e3;function Tr(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!lc.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Sr(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 mc(e){return{pmRoot:Sr(e.pmRoot,"Transaction pmRoot"),transactionId:Tr(e.transactionId,"Transaction id"),author:Sr(e.author,"Transaction author")}}function Er(e,t,n){let i=e??t;if(!Number.isInteger(i)||i<=0)throw new TypeError(`${n} must be a positive integer`);return i}function Or(e,t){return Ar.join(e,"transactions","sdk",`${t}.json`)}async function Ae(e,t){t.updatedAt=T();let n=Or(e,t.transactionId);await oc(Ar.dirname(n),{recursive:!0}),await oe(n,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`)}function uc(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Fe(e){return Object.assign(Object.create(null),e)}function fc(e,t){try{let n=JSON.stringify(e,(i,r)=>{if(typeof r=="number"&&!Number.isFinite(r))throw new TypeError(`${t} contains a non-finite number`);if(r===void 0||typeof r=="function"||typeof r=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return r});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function On(e,t){return e===void 0?void 0:fc(e,t)}function Cn(e,t,n,i){let r=On(n,i);r===void 0?delete e[t]:e[t]=r}function $r(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ir(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function hc(e,t){if(!Ir(e.startedStepIds,t)||!Ir(e.completedStepIds,t)||!$r(e.results)||!$r(e.compensationData))return!1;let n=e.startedStepIds,i=new Set(n),r=e.completedStepIds,a=new Set(r);return Object.keys(e.compensationData).some(o=>!i.has(o))||Object.keys(e.results).some(o=>!a.has(o))?!1:e.status==="committed"?t.every(o=>a.has(o)):e.status!=="compensated"||a.size===0&&i.size===0}function gc(e,t,n){let i;try{i=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!i||typeof i!="object"||Array.isArray(i))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let r=i,a=r.schemaVersion===1&&r.transactionId===t,o=Array.isArray(r.stepIds)&&r.stepIds.length===n.length&&r.stepIds.every((d,p)=>d===n[p]),s=hc(r,n),l=uc(r),c=["applying","compensating","compensated","committed"].includes(String(r.status));if(!a||!o||!s||!l||!c)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...r,results:Fe(r.results),compensationData:Fe(r.compensationData)}}async function yc(e,t,n,i,r){let a=r,o=a!==void 0;if(a?.status==="compensating"&&await Cr(e,a),a===void 0||a.status==="compensated"){let s=T();a={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(a?.attempt??0)+1,createdAt:a?.createdAt??s,updatedAt:s,stepIds:i,startedStepIds:[],completedStepIds:[],results:Fe(),compensationData:Fe()},await Ae(e.pmRoot,a),await _e(e,a,"prepared")}return{journal:a,recovered:o}}async function _c(e,t,n){try{await vc(t,e.steps),await Ae(e.pmRoot,t);let i=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let a of e.steps){if(i.has(a.id))continue;let o=await a.inspect(),s=On(o.result,`Step ${a.id} result`);if(o.state!=="applied"){let l=await a.prepareCompensation?.();Cn(t.compensationData,a.id,l,`Step ${a.id} compensation data`),r.add(a.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>r.has(d)),await Ae(e.pmRoot,t);let c=await a.apply();s=On(c,`Step ${a.id} result`)}await _e(e,t,"step_applied",a.id),i.add(a.id),t.completedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),Cn(t.results,a.id,s,`Step ${a.id} result`),await Ae(e.pmRoot,t),await _e(e,t,"step_recorded",a.id)}return await _e(e,t,"committing"),t.status="committed",await Ae(e.pmRoot,t),await _e(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Fe(t.results)}}catch(i){if(i instanceof Tn||t.status==="committed")throw i;try{await Cr(e,t)}catch(r){throw new AggregateError([i,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw i}}async function wc(e,t,n){try{return gc(await sc(Or(e,t),"utf8"),t,n)}catch(i){if(i!==null&&typeof i=="object"&&"code"in i&&ie(i))return;throw i}}async function _e(e,t,n,i){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...i===void 0?{}:{stepId:i}})}async function vc(e,t){let n=new Set,i=Fe();for(let r of t){let a=await r.inspect();a.state==="applied"&&(n.add(r.id),Cn(i,r.id,a.result,`Step ${r.id} result`))}e.results=i,e.completedStepIds=t.map(r=>r.id).filter(r=>n.has(r))}async function Cr(e,t){t.status="compensating",await Ae(e.pmRoot,t),await _e(e,t,"compensating");let n=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let r of[...e.steps].reverse()){if(!i.has(r.id)&&!n.has(r.id))continue;let a;try{a=i.has(r.id)&&(await r.inspect()).state==="applied"}catch{a=i.has(r.id)}a&&(await _e(e,t,"step_compensating",r.id),await r.compensate(t.compensationData[r.id])),n.delete(r.id),i.delete(r.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>i.has(o)),delete t.results[r.id],delete t.compensationData[r.id],await Ae(e.pmRoot,t),await _e(e,t,"step_compensated",r.id)}t.status="compensated",await Ae(e.pmRoot,t),await _e(e,t,"compensated")}async function Pr(e){let{pmRoot:t,transactionId:n,author:i}=mc(e),r=Er(e.lockTtlSeconds,dc,"Transaction lock TTL"),a=Er(e.lockWaitMs,pc,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(d=>{let p=Tr(d.id,"Transaction step id");if(p!==d.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return p});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let l={...e,pmRoot:t,transactionId:n,author:i,steps:o,lockTtlSeconds:r,lockWaitMs:a},c=await V(t,cc,r,i,!1,!1,a);try{let d=await wc(t,n,s),p=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Fe(d.results)};let m=await yc(l,n,i,s,d);return await _c(l,m.journal,p||m.recovered)}finally{await c()}}import bc from"node:fs/promises";import kc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function Pn(e){return kc.join(e,"extension-migrations.json")}function Rr(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 Nr(e,t){return`${e.layer}:${e.name}:${t}`}async function xc(e){let t=Pn(e);if(!await k(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await bc.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(i=>typeof i?.key=="string"&&(i.status==="applied"||i.status==="failed")):[]}}async function Sc(e,t){let n=await xc(e),i=new Map(n.entries.map(r=>[r.key,r]));return t.forEach((r,a)=>{let o=Rr(r,a),s=i.get(Nr(r,o));s&&(r.definition.status=s.status,s.status==="failed"?r.definition.reason=s.error:(delete r.definition.reason,delete r.definition.error,delete r.definition.message))}),n}async function Ec(e){let t=await Sc(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),i=[],r=!1,a=e.migrations.map((d,p)=>({migration:d,index:p})).filter(({migration:d})=>e.scope===void 0||d.layer===e.scope);for(let{migration:d,index:p}of a){let m=Rr(d,p),g=Nr(d,m),y=n.get(g),_=String(d.definition.status??"pending").toLowerCase(),u=y?.status??(_==="applied"||_==="failed"?_:"pending");if(u==="applied"){i.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"skipped"});continue}if(e.dryRun===!0){i.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"pending"});continue}let w=d.runtime_definition?.run??d.definition.run;if(typeof w!="function"){i.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:u}));let x={key:g,layer:d.layer,extension:d.name,id:m,status:"applied",attempted_at:v};n.set(g,x),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,i.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"applied"}),r=!0}catch(x){let S=x instanceof Error?x.message:String(x),O={key:g,layer:d.layer,extension:d.name,id:m,status:"failed",attempted_at:v,error:S};n.set(g,O),d.definition.status="failed",d.definition.reason=S,i.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"failed",error:S}),r=!0}}if(r){let d=await A(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,g)=>m.key.localeCompare(g.key))};await He({pmRoot:e.pmRoot,filePath:Pn(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
|
|
3
|
+
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let o=i.filter(d=>d.outcome==="pending").length,s=i.filter(d=>d.outcome==="applied").length,l=i.filter(d=>d.outcome==="skipped").length,c=i.filter(d=>d.outcome==="failed").length;return{ok:c===0,dry_run:e.dryRun===!0,state_path:Pn(e.pmRoot),total:i.length,pending_count:o,applied_count:s,skipped_count:l,failed_count:c,migrations:i}}async function Dr(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}),i=await xe(n);e.warnings.push(...n.warnings,...i.warnings);let r=await Ec({pmRoot:e.resolvedRoots.pm_root,migrations:i.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:r,load_failure_count:n.failed.length,activation_failure_count:i.failed.length},r.ok)}import{readFile as $c,writeFile as Ic}from"node:fs/promises";import dt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1de99e25-e132-5071-833e-37361b4cc7e6")}catch{}})();var Lr="# pm-cli:runtime-cache:start",Rn="# pm-cli:runtime-cache:end",Fr=".agents/pm",Ac=["runtime/","search/","locks/","transactions/","checkpoints/"],Tc=["search/eval-queries.json"];async function jr(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new f("The workspace .gitignore is not writable.",h.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function Mr(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function Nn(e){let t=e.replaceAll("\\","/");return dt.isAbsolute(e)||t===".."||t.startsWith("../")}function Oc(e=Fr){let t=Mr(e);return[Lr,...Ac.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Tc.map(n=>`!${t}/${n}`),Rn].join(`
|
|
4
|
+
`)}async function Gr(e,t={}){let n=dt.join(e,".gitignore"),i=Fr;if(t.pmRoot!==void 0){let c=Mr(dt.relative(dt.resolve(e),dt.resolve(t.pmRoot)));if(Nn(c))return{path:n,changed:!1};c.length>0&&(i=c)}let r="";try{r=await jr(()=>$c(n,"utf8"))}catch(c){if(!(c instanceof Error&&"code"in c&&ie(c)))throw c}let a=r.indexOf(Lr),o=r.indexOf(Rn),s=(a>=0&&o>=a?`${r.slice(0,a)}${r.slice(o+Rn.length)}`:r).trimEnd(),l=`${s.length>0?`${s}
|
|
5
5
|
|
|
6
|
-
`:""}${
|
|
7
|
-
`;return l===r?{path:n,changed:!1}:(await
|
|
8
|
-
`).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??a[0].match(Ln)?.[0]}catch{return}}function Fn(e){let t=[],n=jn(zt.join(e,"package.json"));n&&t.push(...Fc(n).map(a=>({...a,source:"package.json"})));let i=jn(zt.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof i=="string"&&Jt(i)&&t.push({version:i,source:"installed-package",constraint:"exact",history_epoch_compatible:Ut(i)===3});let r=Mc(e);r&&Jt(r)&&t.push({version:r,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Ut(r)===3});for(let a of["pnpm-lock.yaml","yarn.lock"]){let o=Gc(e,a);o&&t.push({version:o,source:a,constraint:"exact",history_epoch_compatible:Ut(o)===3})}return t}function qr(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Jr.has(n)){t+=1;continue}if(!n.startsWith("-"))return{command:n.toLowerCase(),index:t}}}function Uc(e){let t=qr(e);if(!t||Y(e,["--help","-h","--dry-run"]))return!1;let{command:n,index:i}=t,r=[];for(let o=i+1;o<e.length;o+=1){let s=e[o];if(Jr.has(s)){o+=1;continue}s.startsWith("-")||r.push(s.toLowerCase())}let a=Nc[n];return a?a(e,r):Rc.has(n)}function zc(e){let t=qr(e.argv)?.command,n=Uc(e.argv),i=Fn(e.projectRoot).filter(d=>Me(d.version,e.executingVersion)!==null).sort((d,p)=>Me(p.version,d.version)),r=i[0],a=r!==void 0&&Me(e.executingVersion,r.version)===-1,o=Ut(e.executingVersion),s=Dc(i,o),l=n&&s!==void 0,c=a&&!n?{code:"project_runtime_stale_read",executing_version:e.executingVersion,project_version:r.version,source:r.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${pt} ${r.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!n||!a&&!l||e.allowStale===!0,executing_version:e.executingVersion,...r?{project_version:r.version,source:r.source}:{},...t?{command:t}:{},mutating:n,stale:a,history_epoch_incompatible:l,writer_item_hash_version:o,...s?{incompatible_project_version:s.declaration,incompatible_source:s.source}:{},...c?{warning:c}:{},override_applied:n&&(a||l)&&e.allowStale===!0}}function rh(e){let t=zc(e);if(t.compatible)return t;throw t.history_epoch_incompatible?new f(`pm ${t.executing_version} cannot write item-hash epoch ${t.writer_item_hash_version} into a project pinned to pm ${t.incompatible_project_version}.`,h.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:t.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${t.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${pt} pin to ${qt} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new f(`pm ${t.executing_version} cannot mutate a project pinned to newer pm ${t.project_version}.`,h.CONFLICT,{code:"project_runtime_stale_mutation",reason:t.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${pt} ${t.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}import{access as Bc,readFile as Gn,realpath as Te}from"node:fs/promises";import{constants as Hc}from"node:fs";import{execFile as Kc}from"node:child_process";import P from"node:path";import{promisify as Vc}from"node:util";import{execFile as Jc}from"node:child_process";import qc from"node:path";import{promisify as Wc}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed89ee24-d57b-5964-a95b-742c4f4f28a8")}catch{}})();var Ve=Wc(Jc);function ae(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"])delete e[t];return e}async function Mn(e,t){try{return(await Ve("git",["config","--local",...t==="core.bare"||t==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",t],{cwd:e,env:ae(),timeout:1e4})).stdout.trim()}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code===1)return;throw n}}async function Wr(e){if(await Mn(e,"extensions.worktreeConfig")==="true")return"--worktree";let{stdout:t}=await Ve("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"],{cwd:e,env:ae(),timeout:1e4}),[n,i]=t.trim().split(/\r?\n/);if(n===i)return"--local";let r=qc.join(i,"config.worktree");for(let a of["core.bare","core.worktree"]){let o=await Mn(e,a);o===void 0||a==="core.bare"&&o!=="true"||(await Ve("git",["config","--file",r,a,o],{cwd:e,env:ae(),timeout:1e4}),await Ve("git",["config","--local","--unset-all",a],{cwd:e,env:ae(),timeout:1e4}))}for(let a of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(let o of["name","driver"]){let s=`merge.${a}.${o}`,l=await Mn(e,s);l!==void 0&&await Ve("git",["config","--file",r,s,l],{cwd:e,env:ae(),timeout:1e4})}return await Ve("git",["config","--local","extensions.worktreeConfig","true"],{cwd:e,env:ae(),timeout:1e4}),"--worktree"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5bcde7f0-1785-530a-91bb-80f2793fb8cf")}catch{}})();var Ye=Vc(Kc),Wt="# pm-cli:merge-drivers:start",Yc="# pm-cli:merge-drivers:end",mt="# pm-cli:merge-drivers:v2:start",Kr="# pm-cli:merge-drivers:v2:end",Xc="merge-fence",Zc="merge-attributes";function Br(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function Qc(e,t){let n=await Te(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(n))return;let{stdout:i}=await Ye(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return i.trim()===t?n:void 0}async function el(){let e=me(import.meta.url,["../../.."]),t=process.execPath,n=!1,i=await Te(process.execPath),r=process.versions.bun,a=(process.env.PATH??"").split(P.delimiter).filter(s=>P.isAbsolute(s)).map(s=>P.join(s,r===void 0?P.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),o=r===void 0?a:[process.env.npm_execpath??"",...a,i].filter(s=>P.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(P.basename(s)));for(let s of o)try{if(await Bc(s,Hc.X_OK),r!==void 0){let l=await Qc(s,r);if(l!==void 0){t=l,n=!0;break}continue}if(s!==i&&await Te(s)===i){t=s;break}}catch{}if(r!==void 0&&!n)throw new f("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",h.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${Br(t)} ${Br(P.join(e,"dist","cli.js"))}`}var Vr=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function tl(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),i=e.environment.PM_SOURCE_PM_PATH?.trim(),r=Ur(e.environment),a=!!(n&&i),o=t===void 0&&a&&(e.dryRun||r.source_writes_allowed);if(t!==void 0){let s=N(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:a,source_context_selected:!1,source_policy:r}}return o?{pm_root:P.resolve(i),workspace_start:P.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:r}:{pm_root:a?N(e.cwd,".agents/pm"):N(e.cwd),workspace_start:e.cwd,source_coordinates_available:a,source_context_selected:!1,source_policy:r}}async function Bt(e){try{let{stdout:t}=await Ye("git",["rev-parse","--show-toplevel"],{cwd:e,env:ae(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await Te(t.trim())}catch{return null}}async function Yr(e){let t=await Bt(e);if(t===null)throw new f("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function Un(e,t){return P.relative(e,t).replaceAll("\\","/")}function de(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Hr(e,t){if(e[t]!=="'")return null;let n="";for(let i=t+1;i<e.length;i+=1){if(e.startsWith(`'"'"'`,i)){n+="'",i+=4;continue}if(e[i]==="'")return{value:n,nextOffset:i+1};n+=e[i]}return null}async function nl(e,t,n){if(Fn(t).filter(r=>r.constraint==="exact").some(r=>r.version!==n))return!1;let i=await Bt(e);if(i!==null&&i!==await Te(t)){let r=await Promise.all([i,t].map(async a=>{let o=await Ye("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:a,env:ae(),timeout:1e4});return Te(o.stdout.trim())}));if(r[0]===r[1])return!1}return!0}async function il(e,t,n){let i=Hr(e,0);if(i===null||e[i.nextOffset]!==" ")return!1;let r=Hr(e,i.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^(?:node|bun)(?:\.exe)?$/iu.test(P.basename(i.value))||P.basename(r.value)!=="cli.js"||P.basename(P.dirname(r.value))!=="dist"||!await k(i.value)||!await k(r.value))return!1;try{let a=P.dirname(P.dirname(r.value)),o=JSON.parse(await Gn(P.join(a,"package.json"),"utf8")),s=typeof o.bin=="string"?o.bin:o.bin?.pm;return await nl(a,n,o.version)?o.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function zn(e,t){let n=e.length>0?`${e}/`:"",i=[`${de(`${n}**/*.toon`)} merge=pm-item-toon`,`${de(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)i.push(`${de(`${n}${r}/*.toon`)} merge=pm-item-toon`),i.push(`${de(`${n}${r}/*.md`)} merge=pm-item-markdown`);return i.push(`${de(`${n}**/*.jsonl`)} merge=pm-relationship`),i.push(`${de(`${n}history/*.jsonl`)} merge=pm-history`),i.push(`${de(`${n}settings.json`)} merge=pm-json`),i.push(`${de(`${n}**/*.json`)} merge=pm-json`),i.push(`${de(`${n}extensions/**`)} -merge`),i.push(`${de(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),i}function Xr(e){let t=[],n=0;for(;n<e.length;){let i=e.indexOf(Wt,n),r=e.indexOf(mt,n),a=i===-1?r:r===-1?i:Math.min(i,r);if(a===-1)break;let o=a===r,s=o?mt:Wt,l=o?Kr:Yc,c=e.indexOf(l,a+s.length),d=c===-1?e.length:c+l.length;t.push({start:a,end:d,closed:c!==-1,lines:e.slice(a+s.length,c===-1?d:c).split(`
|
|
9
|
-
`).map(p=>p.trim()).filter(Boolean)}),n=d}return t}function
|
|
10
|
-
`),c=
|
|
6
|
+
`:""}${Oc(i)}
|
|
7
|
+
`;return l===r?{path:n,changed:!1}:(await jr(()=>Ic(n,l,"utf8")),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var Cc=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Ve(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Dt(t.extensionName));for(let u of t.extensionNames??[])n.add(Dt(u));let i=u=>n.size===0||n.has(Dt(u)),r=(u,w)=>Ur(u.filter(v=>i(v.name)).map(w)),a=(u,w)=>Ur(u.filter(v=>i(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:l,preflight:c,services:d,renderers:p,hooks:m}=e,g=a(o.relationship_kinds??[],u=>u.definitions.map(w=>w.kind)),y=p.overrides.filter(u=>i(u.name)&&((u.commands?.length??0)>0||u.resultDiscriminator!==void 0)).map(u=>({format:u.format,commands:[...u.commands??[]],result_discriminator:u.resultDiscriminator!==void 0})).sort((u,w)=>u.format.localeCompare(w.format)),_=r(o.assurance_providers??[],u=>u.definition.id);return{capabilities:Qi(e,t),commands:r(o.commands,u=>u.command),command_overrides:r(s.overrides,u=>u.command),command_handlers:r(s.handlers,u=>u.command),hooks:Cc.filter(([u])=>m[u].some(w=>i(w.name))).map(([,u])=>u),flag_commands:r(o.flags,u=>u.target_command),item_types:a(o.item_types,u=>u.types.map(w=>w.name)),item_fields:a(o.item_fields,u=>u.fields.map(w=>w.name)),...g.length>0?{relationship_kinds:g}:{},migrations:a(o.migrations,u=>typeof u.definition.id=="string"?[u.definition.id]:[]),profiles:r(o.profiles,u=>u.profile.name),importers:r(o.importers,u=>u.importer),exporters:r(o.exporters,u=>u.exporter),search_providers:r(o.search_providers,u=>u.definition.name),vector_store_adapters:r(o.vector_store_adapters,u=>u.definition.name),..._.length>0?{assurance_providers:_}:{},parser_overrides:r(l.overrides,u=>u.command),service_overrides:r(d.overrides,u=>u.service),renderer_overrides:r(p.overrides,u=>u.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:c.overrides.filter(u=>i(u.name)).length,preflight_ownership:c.overrides.filter(u=>i(u.name)).map(u=>({commands:[...u.commands??[]]}))}}function Ur(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d1f8e03-97b4-5d83-b85c-e47f39c07d48")}catch{}})();var Pc="PM_SOURCE_CONTEXT_ACCESS",Rc="PM_ALLOW_SOURCE_CONTEXT_WRITES";function zr(e){let t=e[Pc],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",i=n==="read_only"&&e[Rc]?.trim()==="1";return{access:n,write_override_applied:i,source_writes_allowed:n==="write"||i}}import Jr from"node:fs";import zt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2d40ac36-0627-5636-9679-5669dbacf06b")}catch{}})();var pt="@unbrained/pm-cli",Nc=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]),qr=new Set(["--author","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),Ln=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,qt="2026.8.31";function X(e,t){return e.some(n=>t.includes(n.split("=",1)[0]))}function Dn(e,t){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(t[0]??"")||X(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var Dc={changelog:(e,t)=>{if(t[0]==="generate")return!X(e,["--check"]);let n=e.indexOf("export");return t[0]==="export"&&(X(e,["--output"])||n>=0&&e[n+1]!==void 0&&!e[n+1].startsWith("-"))},comments:e=>X(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>X(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:Dn,files:(e,t)=>X(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&X(e,["--apply"]),health:e=>!X(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>X(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>X(e,["--add","--delete","--edit","--file","--stdin"]),package:Dn,packages:Dn,profile:(e,t)=>t[0]==="apply",schema:(e,t)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(t[0]??"")&&!(X(e,["--infer"])&&!X(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(n=>["clear","flush"].includes(n)),templates:(e,t)=>t[0]==="save",test:e=>X(e,["--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>X(e,["--auto-fix","--prune-missing"]),vcs:(e,t)=>["abandon","create","merge","propose","ref-create"].includes(t[0]??""),workspace:(e,t)=>t[0]==="snapshot"&&["create","delete","restore"].includes(t[1]??"")};function Jt(e){let t=e.match(Ln);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function Me(e,t){let n=Jt(e),i=Jt(t);if(!n||!i)return null;for(let r=0;r<n.length;r+=1){let a=n[r]-i[r];if(a!==0)return Math.sign(a)}return 0}function Ut(e){return Me(e,qt)!==-1?3:2}function jc(e,t){if(t===3)return e.filter(n=>n.history_epoch_compatible===!1).map(n=>({...n,declaration:n.declaration??n.version})).sort((n,i)=>Me(n.version,i.version))[0]}function jn(e){try{let t=JSON.parse(Jr.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Lc(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(i=>({inclusive:i[1]==="<=",version:i[2]})),n=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...t,{inclusive:!0,version:n[1]}]:t}function Fc(e){let t=e.split("||").map(n=>Lc(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(i=>{let r=Me(qt,i.version);return r!==null&&(i.inclusive?r!==1:r===-1)}))}}function Mc(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let i=n[pt],r=typeof i=="string"?i.trim():"",a=/^[<!]/u.test(r)?void 0:r.match(Ln)?.[0];if(!a)return[];let o=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(r),s=Fc(r);return[{version:a,constraint:o?"exact":s.bounded?"range":"minimum",...o?{}:{declaration:r},history_epoch_compatible:o?Me(a,qt)!==-1:s.compatible}]})}function Gc(e){let t=jn(zt.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let n=t["node_modules/@unbrained/pm-cli"];if(typeof n!="object"||n===null)return;let i=n.version;return typeof i=="string"?i:void 0}function Uc(e,t){try{let n=Jr.readFileSync(zt.join(e,t),"utf8").split(/\r?\n/u),i=n.findIndex(o=>o.includes(pt));if(i<0)return;let r=n[i].match(/^\s*/u)[0].length,a=[n[i]];for(let o=i+1;o<n.length;o+=1){let s=n[o],l=s.trim(),c=s.match(/^\s*/u)[0].length;if(l.length>0&&c<=r)break;a.push(s)}return a.join(`
|
|
8
|
+
`).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??a[0].match(Ln)?.[0]}catch{return}}function Fn(e){let t=[],n=jn(zt.join(e,"package.json"));n&&t.push(...Mc(n).map(a=>({...a,source:"package.json"})));let i=jn(zt.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof i=="string"&&Jt(i)&&t.push({version:i,source:"installed-package",constraint:"exact",history_epoch_compatible:Ut(i)===3});let r=Gc(e);r&&Jt(r)&&t.push({version:r,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Ut(r)===3});for(let a of["pnpm-lock.yaml","yarn.lock"]){let o=Uc(e,a);o&&t.push({version:o,source:a,constraint:"exact",history_epoch_compatible:Ut(o)===3})}return t}function Wr(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(qr.has(n)){t+=1;continue}if(!n.startsWith("-"))return{command:n.toLowerCase(),index:t}}}function zc(e){let t=Wr(e);if(!t||X(e,["--help","-h","--dry-run"]))return!1;let{command:n,index:i}=t,r=[];for(let o=i+1;o<e.length;o+=1){let s=e[o];if(qr.has(s)){o+=1;continue}s.startsWith("-")||r.push(s.toLowerCase())}let a=Dc[n];return a?a(e,r):Nc.has(n)}function Jc(e){let t=Wr(e.argv)?.command,n=zc(e.argv),i=Fn(e.projectRoot).filter(d=>Me(d.version,e.executingVersion)!==null).sort((d,p)=>Me(p.version,d.version)),r=i[0],a=r!==void 0&&Me(e.executingVersion,r.version)===-1,o=Ut(e.executingVersion),s=jc(i,o),l=n&&s!==void 0,c=a&&!n?{code:"project_runtime_stale_read",executing_version:e.executingVersion,project_version:r.version,source:r.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${pt} ${r.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!n||!a&&!l||e.allowStale===!0,executing_version:e.executingVersion,...r?{project_version:r.version,source:r.source}:{},...t?{command:t}:{},mutating:n,stale:a,history_epoch_incompatible:l,writer_item_hash_version:o,...s?{incompatible_project_version:s.declaration,incompatible_source:s.source}:{},...c?{warning:c}:{},override_applied:n&&(a||l)&&e.allowStale===!0}}function sh(e){let t=Jc(e);if(t.compatible)return t;throw t.history_epoch_incompatible?new f(`pm ${t.executing_version} cannot write item-hash epoch ${t.writer_item_hash_version} into a project pinned to pm ${t.incompatible_project_version}.`,h.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:t.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${t.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${pt} pin to ${qt} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new f(`pm ${t.executing_version} cannot mutate a project pinned to newer pm ${t.project_version}.`,h.CONFLICT,{code:"project_runtime_stale_mutation",reason:t.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${pt} ${t.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}import{access as Kc,readFile as Un,realpath as Te}from"node:fs/promises";import{constants as Vc}from"node:fs";import{execFile as Yc}from"node:child_process";import P from"node:path";import{promisify as Xc}from"node:util";import{execFile as qc}from"node:child_process";import Wc from"node:path";import{promisify as Bc}from"node:util";import{setTimeout as Hc}from"node:timers/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f8f33f3d-854e-5cb4-b0bf-8d2d89da27e8")}catch{}})();var Gn=Bc(qc);async function Ye(e,t){let n=performance.now()+5e3,i=25;for(;;)try{await Gn("git",["config",...t],{cwd:e,env:{...ue(),LC_ALL:"C"},timeout:1e4});return}catch(r){let a=n-performance.now();if(typeof r!="object"||r===null||!("stderr"in r)||typeof r.stderr!="string"||!/could not lock config file [^\r\n]+: File exists/u.test(r.stderr)||a<=0)throw r;await Hc(Math.min(i,a)),i=Math.min(i*2,200)}}function ue(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"])delete e[t];return e}async function Mn(e,t){try{return(await Gn("git",["config","--local",...t==="core.bare"||t==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",t],{cwd:e,env:ue(),timeout:1e4})).stdout.trim()}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code===1)return;throw n}}async function Br(e){if(await Mn(e,"extensions.worktreeConfig")==="true")return"--worktree";let{stdout:t}=await Gn("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"],{cwd:e,env:ue(),timeout:1e4}),[n,i]=t.trim().split(/\r?\n/);if(n===i)return"--local";let r=Wc.join(i,"config.worktree");for(let a of["core.bare","core.worktree"]){let o=await Mn(e,a);o===void 0||a==="core.bare"&&o!=="true"||(await Ye(e,["--file",r,a,o]),await Ye(e,["--local","--unset-all",a]))}for(let a of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(let o of["name","driver"]){let s=`merge.${a}.${o}`,l=await Mn(e,s);l!==void 0&&await Ye(e,["--file",r,s,l])}return await Ye(e,["--local","extensions.worktreeConfig","true"]),"--worktree"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36ccb98d-6645-52fe-aac2-be11f3a63c25")}catch{}})();var Ge=Xc(Yc),Wt="# pm-cli:merge-drivers:start",Zc="# pm-cli:merge-drivers:end",mt="# pm-cli:merge-drivers:v2:start",Vr="# pm-cli:merge-drivers:v2:end",Qc="merge-fence",el="merge-attributes";function Hr(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function tl(e,t){let n=await Te(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(n))return;let{stdout:i}=await Ge(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return i.trim()===t?n:void 0}async function nl(){let e=pe(import.meta.url,["../../.."]),t=process.execPath,n=!1,i=await Te(process.execPath),r=process.versions.bun,a=(process.env.PATH??"").split(P.delimiter).filter(s=>P.isAbsolute(s)).map(s=>P.join(s,r===void 0?P.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),o=r===void 0?a:[process.env.npm_execpath??"",...a,i].filter(s=>P.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(P.basename(s)));for(let s of o)try{if(await Kc(s,Vc.X_OK),r!==void 0){let l=await tl(s,r);if(l!==void 0){t=l,n=!0;break}continue}if(s!==i&&await Te(s)===i){t=s;break}}catch{}if(r!==void 0&&!n)throw new f("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",h.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${Hr(t)} ${Hr(P.join(e,"dist","cli.js"))}`}var Yr=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function il(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),i=e.environment.PM_SOURCE_PM_PATH?.trim(),r=zr(e.environment),a=!!(n&&i),o=t===void 0&&a&&(e.dryRun||r.source_writes_allowed);if(t!==void 0){let s=N(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:a,source_context_selected:!1,source_policy:r}}return o?{pm_root:P.resolve(i),workspace_start:P.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:r}:{pm_root:a?N(e.cwd,".agents/pm"):N(e.cwd),workspace_start:e.cwd,source_coordinates_available:a,source_context_selected:!1,source_policy:r}}async function Bt(e){try{let{stdout:t}=await Ge("git",["rev-parse","--show-toplevel"],{cwd:e,env:ue(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await Te(t.trim())}catch{return null}}async function Xr(e){let t=await Bt(e);if(t===null)throw new f("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function zn(e,t){return P.relative(e,t).replaceAll("\\","/")}function le(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Kr(e,t){if(e[t]!=="'")return null;let n="";for(let i=t+1;i<e.length;i+=1){if(e.startsWith(`'"'"'`,i)){n+="'",i+=4;continue}if(e[i]==="'")return{value:n,nextOffset:i+1};n+=e[i]}return null}async function rl(e,t,n){if(Fn(t).filter(r=>r.constraint==="exact").some(r=>r.version!==n))return!1;let i=await Bt(e);if(i!==null&&i!==await Te(t)){let r=await Promise.all([i,t].map(async a=>{let o=await Ge("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:a,env:ue(),timeout:1e4});return Te(o.stdout.trim())}));if(r[0]===r[1])return!1}return!0}async function al(e,t,n){let i=Kr(e,0);if(i===null||e[i.nextOffset]!==" ")return!1;let r=Kr(e,i.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^(?:node|bun)(?:\.exe)?$/iu.test(P.basename(i.value))||P.basename(r.value)!=="cli.js"||P.basename(P.dirname(r.value))!=="dist"||!await k(i.value)||!await k(r.value))return!1;try{let a=P.dirname(P.dirname(r.value)),o=JSON.parse(await Un(P.join(a,"package.json"),"utf8")),s=typeof o.bin=="string"?o.bin:o.bin?.pm;return await rl(a,n,o.version)?o.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function Jn(e,t){let n=e.length>0?`${e}/`:"",i=[`${le(`${n}**/*.toon`)} merge=pm-item-toon`,`${le(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)i.push(`${le(`${n}${r}/*.toon`)} merge=pm-item-toon`),i.push(`${le(`${n}${r}/*.md`)} merge=pm-item-markdown`);return i.push(`${le(`${n}**/*.jsonl`)} merge=pm-relationship`),i.push(`${le(`${n}history/*.jsonl`)} merge=pm-history`),i.push(`${le(`${n}settings.json`)} merge=pm-json`),i.push(`${le(`${n}**/*.json`)} merge=pm-json`),i.push(`${le(`${n}extensions/**`)} -merge`),i.push(`${le(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),i}function Zr(e){let t=[],n=0;for(;n<e.length;){let i=e.indexOf(Wt,n),r=e.indexOf(mt,n),a=i===-1?r:r===-1?i:Math.min(i,r);if(a===-1)break;let o=a===r,s=o?mt:Wt,l=o?Vr:Zc,c=e.indexOf(l,a+s.length),d=c===-1?e.length:c+l.length;t.push({start:a,end:d,closed:c!==-1,lines:e.slice(a+s.length,c===-1?d:c).split(`
|
|
9
|
+
`).map(p=>p.trim()).filter(Boolean)}),n=d}return t}function Qr(e,t,n){let i=new Set(t),r=le(n.length>0?`${n}/`:"").slice(0,-1);return e.some(a=>i.has(a)||a.startsWith(r)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(a.slice(r.length)))}async function ea(e,t,n,i){let r=P.join(e,".gitattributes"),a=i?null:(await Ge("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:ue(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),o=a===null?null:await V(a,el,120,"merge-fence",!1,!0,5e3);try{let s=await G(r)??"",l=[mt,...n,Vr].join(`
|
|
10
|
+
`),c=Zr(s),d=c.filter(m=>Qr(m.lines,n,t));d.length===0&&t===".agents/pm"&&c.length===1&&c[0].lines.every(m=>!m.includes(".agents/pm/"))&&d.push(c[0]);let p;if(d.length>0){let m=d[0];p=s;for(let g of d.slice(1).reverse())p=`${p.slice(0,g.start)}${p.slice(g.end)}`;p=`${p.slice(0,m.start)}${l}${p.slice(m.end)}`}else{let m=s.trimEnd();p=`${m.length>0?`${m}
|
|
11
11
|
|
|
12
12
|
`:""}${l}
|
|
13
|
-
`}return p===s?{path:r,changed:!1}:(i||await se(r,p),{path:r,changed:!0})}finally{await o?.()}}function ea(e){let t=U(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,i)=>n.localeCompare(i))}async function Ch(e,t){let n=P.resolve(e),i=null,r="",a=n;for(let u=0;u<8;u+=1){let w=P.join(a,".gitattributes");try{let x=await Gn(w,"utf8");if(x.includes(mt)||x.includes(Wt)){i=a,r=x;break}}catch{}let v=P.dirname(a);if(v===a)break;a=v}if(i===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=P.join(i,".gitattributes"),s=Un(i,n),l=Xr(r),c=zn(s,t),d=l.filter(u=>Zr(u.lines,c,s)),p=d.flatMap(u=>u.closed?u.lines:[]),m=new Set(p),g=new Set(c),y=c.filter(u=>!m.has(u)),_=p.filter(u=>!g.has(u));return{status:d.length!==1||!d[0].closed||y.length>0||_.length>0?"drift":"ok",path:o,missing_patterns:y,stale_patterns:_,schema_scope:"project"}}async function Ph(e){let t=[],n=[];for(let i of Vr){let r=`merge.${i.key}.driver`,a=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`;try{let{stdout:o}=await Ye("git",["config","--get",r],{cwd:e,env:ae(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=o.trim();await il(s,a,e)||n.push(r)}catch{t.push(r)}}return{status:t.length>0?"missing":n.length>0?"drift":"ok",missing_keys:t,drifted_keys:n}}async function ta(e){let t;try{t=await Yr(P.resolve(e))}catch{return{status:"no_git"}}let n=Un(t,P.resolve(e)),i=await A(e),r=B(void 0,i.author_default),a=await X(e,Xc,i.locks.ttl_seconds,r,!1,ce(i).force_required_for_stale_lock,i.locks.wait_ms);try{let o=P.join(t,".gitattributes"),s;try{s=await Gn(o,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&ie(p))return{status:"not_installed",path:o};throw p}if(!s.includes(mt)&&!s.includes(Wt))return{status:"not_installed",path:o};let l=await A(e),c=ea(l),d=await Qr(t,n,zn(n,c),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await a()}}async function Rh(e,t){let n=tl({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),i=n.pm_root;await Se(i);let r=await Yr(n.workspace_start);return Jn({pmRoot:i,workspaceRoot:r,dryRun:e.dryRun===!0})}async function Jn(e){let t=P.resolve(e.pmRoot),n=P.resolve(e.workspaceRoot),i=e.dryRun===!0,r,a;try{[r,a]=await Promise.all([Te(t),Te(n)])}catch(g){throw new f(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(g)}`,h.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let o=Un(a,r);if(Nn(o))throw new f(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,h.USAGE);let s=await A(r),l=ea(s),c=zn(o,l),d=[],p=await el();for(let g of Vr)d.push({key:`merge.${g.key}.name`,value:g.name}),d.push({key:`merge.${g.key}.driver`,value:`${p} merge driver ${g.artifact} "%O" "%A" "%B"${g.itemPath===void 0?"":` --item-path ${g.itemPath}`}`});if(!i)try{let g=await Wr(a);for(let y of d)await Ye("git",["config",g,y.key,y.value],{cwd:a,env:ae(),encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new f(`Cannot install repository-local merge drivers in ${a}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,h.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await Qr(a,o,c,i);return{ok:!0,dry_run:i,workspace_root:a,pm_root:r,gitattributes:{path:m.path,changed:m.changed,patterns:c,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var ut={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Ht={type:"array",minItems:1,maxItems:Sn,items:ut},na={...Ht,items:{...ut,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},rl={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Ht])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:ut,id:ut}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:na}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Ht}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:na,authors:Ht}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Sn,items:{type:"array",minItems:2,maxItems:2,items:ut}}}}]}}},jh={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:tr,items:rl}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function Gh(e,t,n,i){let r=await Ie(e).catch(()=>null);return r===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"]}:ia(r,t,n,i)}function al(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function ia(e,t,n=5,i=!1){let r=[],a=new Map,o=e.policies.filter(u=>u.rule.kind==="require_fields"),s=o.filter(u=>u.subject?.operations===void 0),l=new Set,c=0,d=0,p=0,m=0,g=0,y=rr(e);for(let u of t){let w=y({operation:"",author:"",before:u,after:u,completeness_only:!0});c+=+(w.decisions.length>0),d+=w.decisions.length,w.decisions.forEach(S=>l.add(S.policy_id));let v=w.decisions.filter(S=>!S.satisfied);if(v.length===0)continue;m+=1;let x=a.get(u.type)??{items:0,violations:0,missing_fields:0};x.items+=1;for(let S of v)p+=1,x.violations+=1,x.missing_fields+=S.missing_fields.length,S.effect==="refuse"&&(g+=1),r.length<n&&r.push({id:u.id,type:u.type,status:u.status,decision:S});a.set(u.type,x)}let _=i||g>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:_,ok:_==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:l.size,requirement_application_count:d,governed_items:c,ungoverned_items:t.length-c,contract_status:al(o.length,t.length,c),applied_policy_ids:[...l].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:l.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:p,refused_violations:g,missing_by_type:Object.fromEntries(a),violations:r,violations_truncated:r.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...i?["validate_completeness_source_incomplete"]:[]]}}import ol from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function sl(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function oa(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new f("Policy definition must be valid JSON.",h.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new f("Policy definition must be an object.",h.USAGE);return t}async function cl(e,t){let n=N(process.cwd(),e.path);await Se(n);let i=await A(n);return{pmRoot:n,settings:i,author:B(t,i.author_default)}}function ra(e,t,n,i){if(e==="policy-mode")return $n({...n,enforcement:t});let r=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:r};let a=En(i.definition),o=$n({...n,policies:[...r,a].sort((s,l)=>s.id.localeCompare(l.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
|
|
14
|
-
`)
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
`}function
|
|
18
|
-
`}function
|
|
19
|
-
`
|
|
20
|
-
`)}import Ta from"node:fs/promises";import ze from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="74b72dd8-0877-55a4-9c80-d043f19e1f96")}catch{}})();var Vt=["extensions","docs","examples","assets","prompts"],Kl=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});function Vl(e){return Vt.includes(e)}function Yl(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],i=[];for(let r of n){if(typeof r!="string"||r.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);i.push(r.trim())}return[...new Set(i)].sort((r,a)=>r.localeCompare(a))}function Xl(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new f("Package manifest field pm must be an object.",h.USAGE);let t={},n=e;for(let[i,r]of Object.entries(n)){if(!Vl(i))continue;let a=Yl(i,r);a.length>0&&(t[i]=a)}return t}function fe(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function Kn(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,i)=>n.localeCompare(i)):void 0}function Ia(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=e.url;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}}function Zl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:fe(t,"docs"),npm:fe(t,"npm"),repository:fe(t,"repository"),report:fe(t,"report")};return Object.values(n).some(i=>typeof i=="string")?n:void 0}function Ql(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:fe(t,"image"),video:fe(t,"video")};return Object.values(n).some(i=>typeof i=="string")?n:void 0}function ed(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:fe(t,"display_name")??fe(t,"displayName"),category:fe(t,"category"),summary:fe(t,"summary"),links:Zl(t.links),media:Ql(t.media),tags:Kn(t.tags)};return Object.values(n).some(i=>i!==void 0)?n:void 0}async function ft(e){let t=ze.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await Ta.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 i=n,r=i.pm,a=r!=null,o=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{};return{source:a?"pm":"convention",package_json_path:t,package_name:typeof i.name=="string"?i.name:void 0,package_version:typeof i.version=="string"?i.version:void 0,package_private:i.private===!0,package_description:typeof i.description=="string"?i.description:void 0,package_keywords:Kn(i.keywords),package_homepage:typeof i.homepage=="string"?i.homepage:void 0,package_repository_url:Ia(i.repository),package_bugs_url:Ia(i.bugs),aliases:Kn(o.aliases),resources:Xl(r),catalog:ed(o.catalog)}}async function Aa(e){if(!await k(e))return[];let t=await Ta.readdir(e,{withFileTypes:!0}),n=[];for(let i of t){if(!i.isDirectory())continue;let r=ze.join(e,i.name);await k(ze.join(r,"manifest.json"))&&n.push(r)}return n.sort((i,r)=>i.localeCompare(r))}async function Yt(e){if(await k(ze.join(e,"manifest.json")))return[e];let t=(await ft(e)).resources.extensions??[],n=new Set;for(let i of t){if(i.includes("*")||i.startsWith("!"))throw new f(`Package extension entry "${i}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let r=ze.resolve(e,i);if(!K(e,r))throw new f(`Package extension entry "${i}" resolves outside package root.`,h.USAGE);if(await k(ze.join(r,"manifest.json"))){n.add(r);continue}for(let a of await Aa(r))n.add(a)}if(t.length===0)for(let i of Kl.extensions)for(let r of await Aa(ze.join(e,i)))n.add(r);return[...n].sort((i,r)=>i.localeCompare(r))}import{execFile as bd}from"node:child_process";import R from"node:fs/promises";import ii from"node:os";import $ from"node:path";import{fileURLToPath as kd}from"node:url";import{promisify as xd}from"node:util";import Sd from"npm-package-arg";import{extract as Ed,list as $d}from"tar";import pd from"node:fs/promises";import pe from"node:path";import Oa from"node:fs/promises";import Vn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cf1403b0-7b07-5f00-9523-87bc727dd7fa")}catch{}})();function te(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function b(e){return e.trim().toLowerCase()}function Xt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let i=t.length;for(;i>n&&t[i-1]==="-";)i-=1;let r=t.slice(n,i);if(r.length===0)throw new f("Extension manifest name must resolve to a non-empty directory name.",h.USAGE);if(r==="."||r==="..")throw new f('Extension manifest name must not resolve to "." or "..".',h.USAGE);return r}function Yn(e){return Ki(e)}async function td(e){try{let t=JSON.parse(await Oa.readFile(Vn.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(i=>typeof t.scripts?.[i]=="string")}}catch{return{has_build_script:!1}}}async function nd(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new f(`Extension entry file is missing at "${t}".`,h.USAGE);let i=await td(n.source_root),r=i.package_name?`pm install npm:${i.package_name}`:void 0,a=n.source_input??n.source_root;return new f(`Extension entry "${e.entry}" is absent from GitHub source "${a}". pm install copies GitHub repositories without running package scripts${i.has_build_script?", and this package declares a build or publish script":""}. ${r?`Try "${r}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,h.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:r?[r,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:r?[`Retry with ${r}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${a}`,normalized_args:["install",a],...r?{next_best_command:r}:{}}})}async function rt(e,t={}){let n=Vn.join(e,"manifest.json");if(!await k(n))throw new f(`Extension manifest is missing at "${n}".`,h.USAGE);let i;try{i=JSON.parse(await Oa.readFile(n,"utf8"))}catch(o){throw new f(`Failed to parse extension manifest at "${n}": ${id(o)}`,h.USAGE)}let r=Yn(i);if(!r)throw new f(`Extension manifest at "${n}" is invalid.`,h.USAGE);let a=Vn.resolve(e,r.entry);if(!K(e,a))throw new f(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,h.USAGE);if(!await k(a))throw await nd(r,a,t);if(!await Yi(e,a))throw new f(`Extension entry "${r.entry}" resolves outside extension directory after symlink resolution.`,h.USAGE);return{directory:e,manifest_path:n,entry_path:a,manifest:r}}function id(e){return e instanceof Error?e.message:String(e)}import Xn from"node:fs/promises";import rd from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5181479f-469f-525b-add2-914a9934afbd")}catch{}})();var ad=".managed-extensions.json",Zt=1;function ht(e){return rd.join(e,ad)}function od(){return{version:Zt,updated_at:T(),entries:[]}}function gt(e){return[...e].sort((t,n)=>{let i=t.scope.localeCompare(n.scope);if(i!==0)return i;let r=t.name.localeCompare(n.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function Ca(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function Q(e){return typeof e=="string"?e:void 0}function sd(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function cd(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:Q(t.name),package:Q(t.package),version:Q(t.version),repository:Q(t.repository),owner:Q(t.owner),repo:Q(t.repo),ref:Q(t.ref),subpath:Q(t.subpath),commit:Q(t.commit)}}function ld(e){if(typeof e!="object"||e===null)return null;let t=e;if(!sd(t))return null;let n=cd(t.source);if(!n)return null;let i=Ji(t.contributions);return i===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:te(t.capabilities),contributions:i,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Q(t.last_update_check_at),last_update_remote_commit:Q(t.last_update_remote_commit),last_update_remote_version:Q(t.last_update_remote_version),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Q(t.update_error)}}function dd(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Zt||!Array.isArray(t.entries))return null;let n=[];for(let i of t.entries){let r=ld(i);r&&n.push(r)}return{version:Zt,updated_at:Q(t.updated_at)??T(),entries:gt(n)}}async function he(e){let t=ht(e),n=od();try{let i=await Xn.readFile(t,"utf8"),r=JSON.parse(i),a=dd(r);if(!a)throw new f(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:a,warnings:[]}}catch(i){if(i instanceof f)throw i;if(typeof i=="object"&&i!==null&&"code"in i&&ie(i))return{path:t,state:n,warnings:[]};throw new f(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}async function at(e,t){let n=ht(e),i={version:Zt,updated_at:T(),entries:gt(t.entries)};await Xn.mkdir(e,{recursive:!0}),await Xn.writeFile(n,`${JSON.stringify(i,null,2)}
|
|
21
|
-
`,"utf8")}function yt(e,t){let n=e.entries.filter(i=>b(i.name)!==b(t.name)&&b(i.directory)!==b(t.directory));return n.push(t),{...e,updated_at:T(),entries:gt(n)}}async function Pa(e,t,n,i){let r=t.entries.find(o=>b(o.name)===b(n));if(!r)return t;let a=yt(t,{...r,contributions:i});return await at(e,a),a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var md="PM_CLI_PACKAGE_ROOT",Ra={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},ud=new Set(["*","all"]);function Zn(){let e=[],t=process.env[md];return typeof t=="string"&&t.trim().length>0&&e.push(pe.resolve(t.trim())),e.push(me(import.meta.url,["../../.."])),[...new Set(e)]}async function _t(e){let t=e.trim().toLowerCase(),n=await Da(t);if(n)return n;let i=Ra[t];if(!i)return null;for(let r of Zn()){let a=pe.join(r,".agents","pm","extensions",i.legacy_extension_directory);if(await k(pe.join(a,"manifest.json")))return a}return null}function Na(e){return ud.has(e.trim().toLowerCase())}function fd(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function hd(e,t){let n=await pd.readdir(e,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||!i.name.startsWith("pm-"))continue;let r=pe.join(e,i.name);if(!await k(pe.join(r,"package.json")))continue;let a=await ft(r),o=a.aliases&&a.aliases.length>0?a.aliases:[fd(i.name)];for(let s of o){let l=s.trim().toLowerCase();l.length===0||t.has(l)||t.set(l,{alias:l,package_directory:i.name,package_root:r,package_name:a.package_name??null})}}}async function Qn(){let e=new Map;for(let t of Zn()){let n=pe.join(t,"packages");await k(n)&&await hd(n,e)}for(let[t,n]of Object.entries(Ra))if(!e.has(t))for(let i of Zn()){let r=pe.join(i,"packages",n.package_directory);if(await k(pe.join(r,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:r,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Qt(){return(await Qn()).map(e=>e.alias)}async function Da(e){let t=e.trim().toLowerCase();return(await Qn()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function ja(e){let t=await Da(e);return t?(await ft(t)).package_name??null:null}async function La(e){let t=await _t(e);if(!t)return null;try{let n=await Yt(t);return n.length!==1?null:(await rt(n[0])).manifest.name}catch{return null}}function gd(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function yd(e,t,n,i,r,a){let o=i==="global"?"--global":"--project",s=Object.fromEntries(Vt.filter(l=>l!=="extensions").map(l=>[l,e.resources[l]??[]]).filter(([,l])=>Array.isArray(l)&&l.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(l=>r.has(l))||a.has(pe.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:gd(e),media:e.catalog?.media}}}async function Fa(e,t,n={}){let i=Nt(N(process.cwd(),t.path),process.cwd()),r=e==="global"?i.global:i.project,a=await he(r),o=new Set(a.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>pe.resolve(m.source.location))),s=new Set(a.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),l=[],c=new Map;for(let m of await Qn()){let g=pe.resolve(m.package_root),y=c.get(g)??[];y.push(m),c.set(g,y)}for(let m of c.values()){let g=m[0],y=m.map(u=>u.alias).sort((u,w)=>u.localeCompare(w)),_=await ft(g.package_root);l.push(yd(_,g,y,e,s,o))}let d=wd(n.fields),p=d?l.map(m=>vd(m,d)):l;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Vt.filter(m=>m!=="extensions"),packages:p}}var _d=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function wd(e){if(e===void 0)return;let t=kr(e);if(t.length===0)throw new f("Package catalog --fields requires a comma-separated list of field names",h.USAGE);let n=t.filter(i=>!_d.has(i));if(n.length>0)throw new f(`Unknown package catalog --fields value(s): ${n.join(", ")}`,h.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function vd(e,t){let n={};for(let i of t)i==="category"?n[i]=e.catalog?.category??null:i==="display_name"?n[i]=e.catalog?.display_name??null:n[i]=e[i]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="db10bb85-f21c-58b1-8b78-8ce1024b3e08")}catch{}})();var Ga=xd(bd),tn="@unbrained/pm-cli",Id={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},ei;async function Ua(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let i=$.resolve(t);for(;;){let r=$.join(i,"node_modules",...n.split("/")),a=$.join(r,"package.json");if(await k(a))try{let s=JSON.parse(await R.readFile(a,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:r}}catch{return null}let o=$.dirname(i);if(o===i)return null;i=o}}function ti(e,t,n){let i=e.split("/").map(c=>c.trim()).filter(c=>c.length>0);if(i.length<2)return null;let r=i[0],a=i[1].replace(/\.git$/i,"");if(r.length===0||a.length===0)return null;let o=i.slice(2),s,l;return o[0]==="tree"&&o.length>=2?(s=o[1],l=o.slice(2).join("/")):o.length>0&&(l=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:r,repo:a,repository:`https://github.com/${r}/${a}.git`,ref:s,subpath:l&&l.length>0?l:void 0}}function Ad(e,t,n){let i=e.slice(4).trim();if(i.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:i}}function wt(e,t={}){let n=e.trim();if(n.length===0)throw new f("Extension source is required for --install.",h.USAGE);let i=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Ad(n,t.forceGithub===!0,i);let r=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return ti(s,n,i)}catch{return null}})();if(r)return r;let a=n.startsWith("github.com/")?n.slice(11):null;if(a){let o=ti(a,n,i);if(!o)throw new f(`Invalid GitHub source "${n}".`,h.USAGE);return o}if(t.forceGithub){let o=ti(n,n,i);if(!o)throw new f(`Invalid GitHub shorthand "${n}".`,h.USAGE);return o}if(/^https?:\/\//i.test(n))throw new f(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,h.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function en(e,t=Ga,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(i){let r=typeof i=="object"&&i!==null&&"stderr"in i?String(i.stderr):"",a=r.trim().length>0?r.trim():i instanceof Error?i.message:String(i);throw new f(`Git command failed: git ${e.join(" ")}
|
|
22
|
-
|
|
23
|
-
${
|
|
24
|
-
`,"
|
|
25
|
-
`,"utf8")}}function qd(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&tn in t)return!0;return!1}function Wd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let i={...n};delete i[tn],Object.keys(i).length===0?delete e[t]:e[t]=i}}async function Bd(e){let t=me(import.meta.url,["../../.."]),[n,i]=tn.split("/"),r=$.join(e,"node_modules",n),a=$.join(r,i);await R.mkdir(r,{recursive:!0}),await R.rm(a,{recursive:!0,force:!0}),await R.symlink(t,a,Hd(process.platform))}function Hd(e){return e==="win32"?"junction":"dir"}function Kd(e,t){if(e.startsWith("-"))throw new f(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,h.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(n=>{let i=n.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(n)}))throw new f(`Extension runtime dependency "${e}" has an unsafe version specifier.`,h.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Sd.resolve(e,t)}catch{throw new f(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,h.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function Vd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[i,r]of Object.entries(n)){if(i===tn||typeof r!="string"||r.trim().length===0||t.has(i))continue;let a=r.trim();t.set(i,Kd(i,a))}return[...t.values()]}async function nn(e,t){let n=await Yt(e);if(n.length===1)return n[0];if(n.length>1){let i=n.map(r=>$.relative(e,r).replaceAll($.sep,"/")).sort((r,a)=>r.localeCompare(a));throw new f(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${i.join(", ")}`,h.USAGE)}throw new f(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,h.USAGE)}async function Yd(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push($.posix.join(".agents/pm/extensions",t.subpath)),n.push($.posix.join(".custom/pm-extensions",t.subpath)),n.push($.posix.join(".custom/pm-extension",t.subpath)));for(let r of n){let a=$.resolve(e,r);if(K(e,a)&&await k($.join(a,"manifest.json")))return{directory:a,resolved_subpath:r}}if(await k($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let i=await nn(e,t.input);return{directory:i,resolved_subpath:$.relative(e,i).replaceAll($.sep,"/")}}function Xd(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function Zd(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Xd(n))return new f(t,h.NOT_FOUND);let i=[];try{let a=process.env.PM_CLI_PACKAGE_ROOT,o=typeof a=="string"&&a.trim().length>0?$.resolve(a.trim()):"";ei?.key!==o&&(ei={key:o,aliases:await Qt()}),i=ei.aliases}catch{}let r=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${i.join(", ")}`];return new f(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,h.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:r,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Ha(e){if(e.kind==="local"){let i;try{i=await R.stat(e.absolute_path)}catch{throw await Zd(e)}if(i.isFile()&&Ba(e.absolute_path)){let a=await ni(e.absolute_path);return{source:e,directory:a.directory,source_root:$.dirname(a.directory),resolved_subpath:$.relative($.dirname(a.directory),a.directory).replaceAll($.sep,"/"),npm_package:a.package,npm_version:a.version,cleanup:a.cleanup}}if(!i.isDirectory())throw new f(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let r=await nn(e.absolute_path,e.input);return{source:e,directory:r,source_root:e.absolute_path}}if(e.kind==="npm"){let i=await Gd(e);return{source:e,directory:i.directory,source_root:$.dirname(i.directory),cleanup:i.cleanup,resolved_subpath:$.relative($.dirname(i.directory),i.directory).replaceAll($.sep,"/"),npm_package:i.package,npm_version:i.version}}let t=await R.mkdtemp($.join(ii.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await en(n);let i=await en(["-C",t,"rev-parse","HEAD"]),r=await Yd(t,e);return{source:e,directory:r.directory,source_root:t,resolved_subpath:r.resolved_subpath,commit:i,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(i){throw await R.rm(t,{recursive:!0,force:!0}),i}}async function rn(e,t){if(!await k(e)||!await k(t))return!1;let[n,i]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===i}import vt from"node:fs/promises";import bt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var oi=1,Je="2026.6.24",Qd=">=22.18.0",ep={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Ka=new Set([...ar.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Ri).map(e=>e.toLowerCase()),"scaffold"]),tp="^6.0.0",np="^22.0.0",Xa=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],ge=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Va(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Za(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 Qa(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 ip={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Ya=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],eo={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},rp={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},ap={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},op={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},to="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",sp={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},cp={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},lp={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},dp={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function no(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function io(e,t){return e==="schema"?lp[t]:e==="profile"?dp[t]:cp[t]}function pp(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(o=>o.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),i=0;for(;t[i]?.toLowerCase()==="starter";)i+=1;let r=t[i]?.toLowerCase(),a=i>0&&(i===t.length||r!==void 0&&Ka.has(r));return`${(Ka.has(n)||a?["starter",...t]:t).join(" ")} ping`}function ro(e){let t=e,n=`${e}s`,i=e.replace(/-/g,""),r=i===t?[]:[i],a=`${e.replace(/-/g,"_")}_owner`,o="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(r)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(a)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function mp(e,t,n){let i=`${e}-search`,r=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,o=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(i)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(r)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,l=`${e}s`,c=e.replace(/-/g,""),d=c===s?[]:[c],p=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...ro(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(a)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} 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(a)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...o,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...o,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function up(e,t,n){let i=n==="hooks",r=n==="search",a=n==="importers",o=n==="schema",s=n==="profile",l=n==="renderers",c=n==="parser",d=n==="preflight",p=n==="services",m=rp[n],g=e,y=`${e}s`,_=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=i?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],x=r?si(e,t,"search",m):[],S=a?si(e,t,"importers",m):[],O=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Va(Za({extensionName:e,itemTypeName:g,itemTypeFolder:y,fieldName:_,migrationId:u,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],oe=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Va(Qa(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],L=l?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],E=c?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],q=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],ot=p?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...r?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Xa,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...c?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});","",...v,...x,...S,...O,...oe,...L,...E,...q,...ot,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
26
|
-
`)}function fp(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let i=`${e.replace(/-/g," ")} items`;return[t,`${i} import`,`${i} export`]}return[t]}var hp={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},gp={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function yp(e,t,n){let i=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...i?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...i?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function _p(e,t,n){let i=[],r=[...yp(e,t,n)],a=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,l=`${e.replace(/-/g," ")} items`,c=e,d=`${e}s`,p=e.replace(/-/g,""),m=p===c?[]:[p],g=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":i.push("defineAfterCommandHook"),r.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... */ }","});"),a.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":i.push("defineSearchProvider","defineVectorStoreAdapter"),r.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),a.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":i.push("defineExporter","defineImporter"),r.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,","}));"),a.push(" importers: ["," {",` name: ${JSON.stringify(l)},`," importer,"," options: {",` action: ${JSON.stringify(`${l} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(l)},`," exporter,"," options: {",` action: ${JSON.stringify(`${l} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":i.push("defineItemField","defineItemType","defineMigration"),r.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(g)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(c)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(y)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),a.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":i.push("defineProjectProfile"),r.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({",...ro(e),"});"),a.push(" profiles: [starterProfile],");break;case"renderers":i.push("defineRendererOverride"),r.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);`," },","});"),a.push(" renderers: { toon: toonRenderer },");break;case"parser":i.push("defineParserOverride"),r.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 };","});"),a.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":i.push("definePreflightOverride"),r.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,","});"),a.push(" preflights: [preflightOverride],");break;case"services":i.push("defineServiceOverride"),r.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 };`,"});"),a.push(" services: { output_format: outputService },");break}return{builderImports:i,definitions:r,blueprintFields:a}}function wp(e,t,n){let i=_p(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...i.builderImports].sort((r,a)=>r.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...i.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...i.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
|
|
27
|
-
`)}function si(e,t,n,i){if(n==="commands")return[];let r=`${e}-search`,a=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,l=`${e}s`,c=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"],m=g=>[...p," let deactivated = false;"," try {",...g.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(r)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(a)}, 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(r)},`,' 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(r)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(a)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(Za({extensionName:e,itemTypeName:s,itemTypeFolder:l,fieldName:c,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Qa(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function vp(e,t,n){let i=n==="parser",r=JSON.stringify([...eo[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...Xa,`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(Je)},`," },",` target: { pmVersion: ${JSON.stringify(Je)} },`," });"," // 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, ${r});`,` assert.deepEqual(report.manifest?.capabilities, ${r});`,"});","",`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: ${r},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...i?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});","",...si(e,t,n,r)].join(`
|
|
28
|
-
`)}function bp(e,t,n){let i=no(n,"package"),r=io(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",i,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${hp[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",to,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${gp[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...r,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${oi}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Je}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
|
|
29
|
-
`)}function
|
|
30
|
-
`,
|
|
31
|
-
`),
|
|
32
|
-
|
|
33
|
-
`,
|
|
34
|
-
|
|
35
|
-
`)
|
|
13
|
+
`}return p===s?{path:r,changed:!1}:(i||await oe(r,p),{path:r,changed:!0})}finally{await o?.()}}function ta(e){let t=U(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,i)=>n.localeCompare(i))}async function Dh(e,t){let n=P.resolve(e),i=null,r="",a=n;for(let u=0;u<8;u+=1){let w=P.join(a,".gitattributes");try{let x=await Un(w,"utf8");if(x.includes(mt)||x.includes(Wt)){i=a,r=x;break}}catch{}let v=P.dirname(a);if(v===a)break;a=v}if(i===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=P.join(i,".gitattributes"),s=zn(i,n),l=Zr(r),c=Jn(s,t),d=l.filter(u=>Qr(u.lines,c,s)),p=d.flatMap(u=>u.closed?u.lines:[]),m=new Set(p),g=new Set(c),y=c.filter(u=>!m.has(u)),_=p.filter(u=>!g.has(u));return{status:d.length!==1||!d[0].closed||y.length>0||_.length>0?"drift":"ok",path:o,missing_patterns:y,stale_patterns:_,schema_scope:"project"}}async function jh(e){let t=[],n=[];for(let i of Yr){let r=`merge.${i.key}.driver`,a=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`;try{let{stdout:o}=await Ge("git",["config","--get",r],{cwd:e,env:ue(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=o.trim();await al(s,a,e)||n.push(r)}catch{t.push(r)}}return{status:t.length>0?"missing":n.length>0?"drift":"ok",missing_keys:t,drifted_keys:n}}async function na(e){let t;try{t=await Xr(P.resolve(e))}catch{return{status:"no_git"}}let n=zn(t,P.resolve(e)),i=await A(e),r=B(void 0,i.author_default),a=await V(e,Qc,i.locks.ttl_seconds,r,!1,se(i).force_required_for_stale_lock,i.locks.wait_ms);try{let o=P.join(t,".gitattributes"),s;try{s=await Un(o,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&ie(p))return{status:"not_installed",path:o};throw p}if(!s.includes(mt)&&!s.includes(Wt))return{status:"not_installed",path:o};let l=await A(e),c=ta(l),d=await ea(t,n,Jn(n,c),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await a()}}async function Lh(e,t){let n=il({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),i=n.pm_root;await Se(i);let r=await Xr(n.workspace_start);return qn({pmRoot:i,workspaceRoot:r,dryRun:e.dryRun===!0})}async function ol(e,t){let n=(await Ge("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:e,env:ue(),timeout:1e4})).stdout.trim(),i=await V(n,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{let r=await Br(e),a;try{a=(await Ge("git",["config",r,"--null","--get-regexp","."],{cwd:e,env:ue(),timeout:1e4})).stdout}catch(s){if(typeof s!="object"||s===null||!("code"in s)||s.code!==1)throw s;a=""}let o=new Map(a.split("\0").filter(Boolean).map(s=>{let l=s.indexOf(`
|
|
14
|
+
`);return[s.slice(0,l),s.slice(l+1)]}));for(let s of t)o.get(s.key)!==s.value&&await Ye(e,[r,s.key,s.value])}finally{await i()}}async function qn(e){let t=P.resolve(e.pmRoot),n=P.resolve(e.workspaceRoot),i=e.dryRun===!0,r,a;try{[r,a]=await Promise.all([Te(t),Te(n)])}catch(g){throw new f(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(g)}`,h.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let o=zn(a,r);if(Nn(o))throw new f(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,h.USAGE);let s=await A(r),l=ta(s),c=Jn(o,l),d=[],p=await nl();for(let g of Yr)d.push({key:`merge.${g.key}.name`,value:g.name}),d.push({key:`merge.${g.key}.driver`,value:`${p} merge driver ${g.artifact} "%O" "%A" "%B"${g.itemPath===void 0?"":` --item-path ${g.itemPath}`}`});if(!i)try{await ol(a,d)}catch{throw new f(`Cannot install repository-local merge drivers in ${a}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,h.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await ea(a,o,c,i);return{ok:!0,dry_run:i,workspace_root:a,pm_root:r,gitattributes:{path:m.path,changed:m.changed,patterns:c,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var ut={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Ht={type:"array",minItems:1,maxItems:Sn,items:ut},ia={...Ht,items:{...ut,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},sl={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Ht])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:ut,id:ut}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:ia}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Ht}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:ia,authors:Ht}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Sn,items:{type:"array",minItems:2,maxItems:2,items:ut}}}}]}}},Gh={$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:nr,items:sl}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function qh(e,t,n,i){let r=await Ie(e).catch(()=>null);return r===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"]}:ra(r,t,n,i)}function cl(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function ra(e,t,n=5,i=!1){let r=[],a=new Map,o=e.policies.filter(u=>u.rule.kind==="require_fields"),s=o.filter(u=>u.subject?.operations===void 0),l=new Set,c=0,d=0,p=0,m=0,g=0,y=ar(e);for(let u of t){let w=y({operation:"",author:"",before:u,after:u,completeness_only:!0});c+=+(w.decisions.length>0),d+=w.decisions.length,w.decisions.forEach(S=>l.add(S.policy_id));let v=w.decisions.filter(S=>!S.satisfied);if(v.length===0)continue;m+=1;let x=a.get(u.type)??{items:0,violations:0,missing_fields:0};x.items+=1;for(let S of v)p+=1,x.violations+=1,x.missing_fields+=S.missing_fields.length,S.effect==="refuse"&&(g+=1),r.length<n&&r.push({id:u.id,type:u.type,status:u.status,decision:S});a.set(u.type,x)}let _=i||g>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:_,ok:_==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:l.size,requirement_application_count:d,governed_items:c,ungoverned_items:t.length-c,contract_status:cl(o.length,t.length,c),applied_policy_ids:[...l].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:l.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:p,refused_violations:g,missing_by_type:Object.fromEntries(a),violations:r,violations_truncated:r.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...i?["validate_completeness_source_incomplete"]:[]]}}import ll from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function dl(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function sa(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 pl(e,t){let n=N(process.cwd(),e.path);await Se(n);let i=await A(n);return{pmRoot:n,settings:i,author:B(t,i.author_default)}}function aa(e,t,n,i){if(e==="policy-mode")return $n({...n,enforcement:t});let r=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:r};let a=En(i.definition),o=$n({...n,policies:[...r,a].sort((s,l)=>s.id.localeCompare(l.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
|
|
15
|
+
`)>pr)throw new f("Policy registry exceeds its byte ceiling.",h.USAGE);return o}async function oa(e,t,n,i){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:aa(e,t,await Ie(i.pmRoot),n)};let r=await dr({pmRoot:i.pmRoot,filePath:ll.join(i.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:i.author,message:n.message,lockTtlSeconds:i.settings.locks.ttl_seconds,lockWaitMs:i.settings.locks.wait_ms,mutate(a){let o=aa(e,t,mr(a),n);return{raw:`${JSON.stringify(o,null,2)}
|
|
16
|
+
`,result:o}}});return{policy_result:!0,action:e,changed:r.changed,result:r.result}}async function ml(e,t,n){let i,r=await yr({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:i}),async mutate(a){let o=(await Ie(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!o||o.rule.kind!=="approval")throw new f("--policy must name an approval rule.",h.USAGE);if(!o.rule.authors.includes(n.author))throw new f("This actor is not a declared approver.",h.CONFLICT);return await ur(n.pmRoot,a.metadata.id),i={policy_id:o.id,policy_fingerprint:ir(o),content_fingerprint:rr(o,{...a.metadata,body:a.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:r.item.id,...i,warnings:r.warnings}}}function ul(e,t){let n=sa(t),i=En({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==i.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 i}async function sg(e,t,n={},i={}){if(!jt.includes(e))throw new f("Unknown workflow policy action.",h.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:dl()};let r=await pl(i,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Ie(r.pmRoot)};if(e==="policy-put"){let d=ul(t,n.definition);return oa(e,d.id,{...n,definition:d},r)}if(!t?.trim())throw new f(`schema ${e} requires an operand.`,h.USAGE);if(["policy-remove","policy-mode"].includes(e))return oa(e,t,n,r);if(e==="policy-approve"){if(n.dryRun)throw new f("Use policy-check to preview; policy-approve records an approval.",h.USAGE);return ml(t,n,r)}let a=U(r.settings,W()),o=await Ft(r.pmRoot,t,r.settings.id_prefix,r.settings.item_format,a.type_to_folder);if(!o)throw new f(`Item ${t} not found.`,h.NOT_FOUND);let{document:s}=await Mt(o,{schema:r.settings.schema}),l={...s.metadata,body:s.body},c=n.definition===void 0?l:{...l,...sa(n.definition)};if(c.id!==l.id)throw new f("Policy preview cannot change the item id.",h.USAGE);return{policy_result:!0,action:e,changed:!1,result:await fr(r.pmRoot,await Ie(r.pmRoot),{operation:"update",author:r.author,before:l,after:c,completeness_only:n.definition===void 0})}}import{createHash as ba}from"node:crypto";import ze from"node:fs/promises";import nt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="68be16cc-4cb4-5df6-90f0-897d4fe82339")}catch{}})();var fl=new Set(bn),hl=new Set(kn),ca=new Set([...ji.filter(e=>e!=="severity"),"id","title","type","status","priority","tags","assignee","parent","description","body","created_at","updated_at","closed_at","completed_at","author","deadline","estimate","sprint","release","risk","confidence","reviewer","resolution","expected","actual"]),gl=["create","update"];function ma(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function la(e){return e.replaceAll("_","-")}function yl(e,t){let n=new Set;for(let i of e){let r=ma(i);r.length>0&&r!==t&&n.add(r)}return[...n].sort((i,r)=>i.localeCompare(r))}function _l(e){let t=new Set;for(let n of e??[]){let i=n.trim();i.length>0&&t.add(i)}return[...t].sort((n,i)=>n.localeCompare(i))}function wl(e){let t=new Set,n=[];for(let i of e??[]){let r=i.trim().toLowerCase();if(r.length!==0){if(!hl.has(r))throw new Error(`Invalid field command "${i}". Allowed: ${kn.join(", ")}.`);t.has(r)||(t.add(r),n.push(r))}}return e===void 0||n.length===0?[...gl]:n}function ua(e){let t=I(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(ca.has(t))throw new Error(`Cannot define custom field "${t}": custom schema field "${t}" collides with built-in item metadata "${t}". Rename the custom field with a project-specific prefix. Reserved fields: ${[...ca].sort((d,p)=>d.localeCompare(p)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!fl.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${bn.join(", ")}.`);let i=n,r=wl(e.commands),a=ma(e.cliFlag),o=a.length>0&&a!==la(t)?a:void 0,s=o??la(t),l=yl(e.aliases??[],s),c=e.description?.trim();return{key:t,type:i,commands:r,description:c&&c.length>0?c:void 0,cliFlag:o,cliAliases:l,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:_l(e.requiredTypes)}}function vl(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function bl(e){let t=vl(e);if(!t)return[];let n=[];for(let i of t){if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i;typeof r.key!="string"||r.key.trim().length===0||n.push(r)}return n}function Xe(e){if(e==null||e.trim().length===0)return{fields:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/fields.json contains invalid JSON.")}return{fields:bl(t)}}function Ze(e){return`${JSON.stringify({fields:e.fields},null,2)}
|
|
17
|
+
`}function fa(e,t){let n=e.fields.find(o=>I(o.key)===t.key),i=n!==void 0,r=e.fields.filter(o=>I(o.key)!==t.key),a={...n,key:t.key,type:t.type,commands:[...t.commands]};return da(a,"description",t.description),da(a,"cli_flag",t.cliFlag),t.cliAliases.length>0?a.cli_aliases=[...t.cliAliases]:delete a.cli_aliases,pa(a,"required",t.required),pa(a,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?a.allow_unset=!1:delete a.allow_unset,t.requiredTypes.length>0?a.required_types=[...t.requiredTypes]:delete a.required_types,r.push(a),r.sort((o,s)=>I(o.key).localeCompare(I(s.key))),{file:{fields:r},definition:a,replaced:i}}function ha(e,t){let n=I(t);if(n.length===0)throw new Error("Field key must not be empty.");let i=[],r=e.fields.filter(a=>I(a.key)===n?(i.push(a),!1):!0);return i.length===0?{file:{fields:r},removed:!1}:{file:{fields:r},removed:!0,definition:i[0]}}function da(e,t,n){let i=e;n!==void 0&&n.length>0?i[t]=n:delete i[t]}function pa(e,t,n){let i=e;n?i[t]=!0:delete i[t]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1e4c04e-0ade-5d24-95e3-b8dca3832c5a")}catch{}})();var kl=new Set(Rt),Ue=new Set(sr.map(e=>I(e.id)).filter(e=>e.length>0));function xl(e){let t=new Set;for(let n of e){let i=I(n);i.length>0&&t.add(i)}return[...t].sort((n,i)=>n.localeCompare(i))}function ga(e){let t=I(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(Ue.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...Ue].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let o=new Set;for(let s of e.roles){let l=typeof s=="string"?s.trim().toLowerCase():"";if(l.length!==0){if(!kl.has(l))throw new Error(`Invalid status role "${s}". Allowed roles: ${Rt.join(", ")}.`);o.has(l)||(o.add(l),n.push(l))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${Rt.join(", ")}.`)}let i=e.aliases===void 0?void 0:xl(e.aliases).filter(o=>o!==t),r=e.description?.trim(),a=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:i,description:r&&r.length>0?r:void 0,order:a}}function Sl(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 El(e){let t=Sl(e);if(!t)return[];let n=[];for(let i of t){if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i;typeof r.id!="string"||r.id.trim().length===0||n.push(r)}return n}function Qe(e){if(e==null||e.trim().length===0)return{statuses:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/statuses.json contains invalid JSON.")}return{statuses:El(t)}}function et(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
|
|
18
|
+
`}function ya(e,t,n){let i=e.statuses.slice(),r=i.findIndex(s=>I(s.id)===t.id),a=r>=0?i[r]:n,o={...a,id:t.id};return t.roles!==void 0&&(t.roles.length>0?o.roles=[...t.roles]:o.roles!==void 0&&delete o.roles),t.aliases!==void 0&&(t.aliases.length>0?o.aliases=[...t.aliases]:o.aliases!==void 0&&delete o.aliases),t.description!==void 0&&(o.description=t.description),t.order!==void 0&&(o.order=t.order),r>=0?i[r]=o:i.push(o),{file:{statuses:i},definition:o,replaced:a!==void 0}}function _a(e,t){let n=I(t);if(n.length===0)throw new Error("Status id must not be empty.");if(Ue.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...Ue].join(", ")}.`);let i=e.statuses.slice(),r=i.findIndex(o=>I(o.id)===n);if(r<0)return{file:{statuses:i},removed:!1};let[a]=i.splice(r,1);return{file:{statuses:i},removed:!0,definition:a}}function Wn(e,t){let n=[e.id,...e.aliases??[]];for(let i of n){let r=I(i);if(r.length===0)continue;let a=t.get(r);if(a!==void 0&&a!==e.id)throw new Error(`Status token "${r}" already belongs to status "${a}". Choose a different id/alias to avoid shadowing it.`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d04c087-62e4-51d3-8832-6cbcfd3ed993")}catch{}})();function we(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function ka(e){let t=we(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function xa(e,t){let n=Hn(e),i=we(t,"migrationScope");return`auto-${ba("sha256").update(JSON.stringify({scope:i,request:n})).digest("hex").slice(0,20)}`}function Hn(e){let t=e.kind==="rename-type"?{kind:e.kind,from:we(e.from,"source"),to:we(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:I(we(e.from,"source")),to:I(we(e.to,"target")),...e.type===void 0?{}:{type:we(e.type,"type")}}:{kind:e.kind,from:I(we(e.from,"source")),to:I(we(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function $l(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Il(e,t,n){let i=Y(t.schema),r=$l(n);return re(e,i.files[r],Z[r])}function Sa(e,t){return nt.join(e,"transactions","schema",`${t}-plan.json`)}function Kt(e){return e.length===0?null:JSON.parse(e)}async function tt(e){let t=await G(e);return{exists:t!==null,raw:t??""}}async function Ea(e,t){t.exists?await oe(e,t.raw):await ze.rm(e,{force:!0})}function Al(e,t,n){let i=ce(e),r=i.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),a=i.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(a>=0)return me(i);if(r<0)throw new TypeError(`Unknown custom type "${t.from}".`);i.definitions.push({...i.definitions[r],name:t.to})}else r>=0&&i.definitions.splice(r,1);return me(i)}function Tl(e,t,n){let i=Xe(e),r=i.fields.findIndex(o=>o.key===t.from),a=i.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(a>=0)return Ze(i);if(r<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=i.fields[r];i.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else r>=0&&i.fields.splice(r,1);return Ze(i)}function Ol(e,t,n){let i=Qe(e),r=i.statuses.findIndex(o=>o.id===t.from),a=i.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(a>=0)return et(i);if(r<0)throw new TypeError(`Unknown custom status "${t.from}".`);i.statuses.push({...i.statuses[r],id:t.to})}else r>=0&&i.statuses.splice(r,1);return et(i)}function Cl(e,t,n){return t.kind==="rename-type"?Al(e,t,n):t.kind==="rename-field"?Tl(e,t,n):Ol(e,t,n)}function Oe(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Kn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function it(e){return Array.isArray(e)?e.map(t=>Kn(t)).filter(t=>t!==void 0):[]}function Pl(e,t){for(let n of it(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(i=>Oe(i,t)));for(let n of it(e.type_workflows))n.type=Oe(n.type,t)}function Rl(e,t){for(let i of it(e.definitions))i.default_status=Oe(i.default_status,t);let n=Kn(e.workflow);if(n)for(let[i,r]of Object.entries(n))n[i]=Oe(r,t);for(let i of it(e.type_workflows))Array.isArray(i.allowed_transitions)&&(i.allowed_transitions=i.allowed_transitions.map(r=>Array.isArray(r)?r.map(a=>Oe(a,t)):r))}function Nl(e,t){for(let n of it(e.definitions)){for(let i of["required_create_fields","required_create_repeatables"])Array.isArray(n[i])&&(n[i]=n[i].map(r=>Oe(r,t)));for(let i of["options","command_option_policies"])for(let r of it(n[i])){let a=i==="options"?"key":"option";r[a]=Oe(r[a],t)}}}function Dl(e,t){let n=Kn(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let i=t.kind==="rename-type"?"type":"status";n[i]=Oe(n[i],t)}function Bn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let i=n;return t.kind==="rename-type"?Pl(i,t):t.kind==="rename-field"?Nl(i,t):Rl(i,t),Dl(i,t),`${JSON.stringify(i,null,2)}
|
|
19
|
+
`}function $a(e,t){if(t.kind==="rename-type"){let i=ce(e).definitions;return{source:i.some(r=>r.name.trim().toLowerCase()===t.from.toLowerCase()),target:i.some(r=>r.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let i=Xe(e).fields;return{source:i.some(r=>r.key===t.from),target:i.some(r=>r.key===t.to)}}let n=Qe(e).statuses;return{source:n.some(i=>i.id===t.from),target:n.some(i=>i.id===t.to)}}function jl(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 Ll(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 Ia(e,t){let n=Hn(t.request),i=t.migrationId===void 0?xa(n,t.migrationScope??"plan"):ka(t.migrationId),r=e.map(l=>Ll(l,n)).filter(l=>l!==null).sort((l,c)=>l.id.localeCompare(c.id)),a=ba("sha256").update(JSON.stringify({migrationId:i,request:n,items:r})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(l=>l.trim()).filter(l=>l.length>0)),s=r.filter(l=>!o.has(l.id));return Object.freeze({migration_id:i,request:n,fingerprint:a,affected_item_count:r.length,pending_item_count:s.length,skipped_completed_count:r.length-s.length,items:Object.freeze(s)})}async function Fl(e){let t=U(e.settings,W()),n=[...new Set(Object.values(t.type_to_folder))],i=await gr(e.pmRoot,n),r=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]}},a=i?await hr({pmRoot:e.pmRoot,expectedSourceCursor:i.source_cursor,query:r}):null;return a?{items:a.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await je(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Ml(e,t){let n=await G(Sa(e,t));if(n===null)return null;try{let i=JSON.parse(n);if(i.schema_version!==1||i.plan.migration_id!==t||!Array.isArray(i.plan.items))throw new TypeError("invalid plan envelope");return i.plan}catch(i){throw new f(`Stored schema migration plan "${t}" is invalid: ${Fi(i)}`,h.GENERIC_FAILURE)}}async function Gl(e,t){let n=Sa(e,t.migration_id);await ze.mkdir(nt.dirname(n),{recursive:!0});let i={schema_version:1,plan:t,created_at:new Date().toISOString()};await oe(n,`${JSON.stringify(i,null,2)}
|
|
20
|
+
`)}function Ul(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function zl(e){let t=await Ft(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new f(`Schema migration item "${e.id}" no longer exists.`,h.NOT_FOUND);return(await Mt(t,{schema:e.settings.schema})).document.metadata}function wa(e,t,n){let i=n==="forward"?t.from:t.to,r=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===r.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==i.toLowerCase())throw new TypeError(`Schema migration expected type "${i}" on item "${e.metadata.id}".`);return e.metadata.type=r,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===r.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==i.toLowerCase())throw new TypeError(`Schema migration expected status "${i}" on item "${e.metadata.id}".`);return e.metadata.status=r,["status"]}let a=e.metadata;if(Object.prototype.hasOwnProperty.call(a,r)&&!Object.prototype.hasOwnProperty.call(a,i))return[];if(!Object.prototype.hasOwnProperty.call(a,i)||Object.prototype.hasOwnProperty.call(a,r))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return a[r]=a[i],delete a[i],[i,r]}function va(e){return{id:e.id,inspect:async()=>{let t=await tt(e.filePath),n=$a(t.raw,e.request),i=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:i?"applied":"pending",...i?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await tt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await tt(e.filePath);return await oe(e.filePath,Cl(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 Ea(e.filePath,{exists:t.exists,raw:t.raw})}}}function Jl(e){return{id:e.stepId,inspect:async()=>{let t=await tt(e.filePath);return{state:Bn(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await tt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await tt(e.filePath);return await oe(e.filePath,Bn(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 Ea(e.filePath,{exists:t.exists,raw:t.raw})}}}function ql(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await A(e.pmRoot),n=U(t,W()).type_to_folder,i=await zl({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),r=jl(i,e.request).length===0;return{state:r?"applied":"pending",...r?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await A(e.pmRoot),n=U(t,W()).type_to_folder,i=await An({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(r){return{changedFields:wa(r,e.request,"forward")}}});return{item_id:e.id,changed_fields:i.changedFields}},compensate:async()=>{let t=await A(e.pmRoot),n=U(t,W()).type_to_folder;await An({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(i){return{changedFields:wa(i,e.request,"reverse")}}})}}}async function Wl(e){let t=await Ml(e.pmRoot,e.migrationId);if(t){if(!Ul(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 Fl({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Ia(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Bl(e){let t=$a(await G(e.schemaPath)??"",e.request);if(!t.source)throw new f(`Schema migration source "${e.request.from}" is not a custom definition.`,h.NOT_FOUND);if(t.target)throw new f(`Schema migration target "${e.request.to}" already exists.`,h.CONFLICT);await Gl(e.pmRoot,e.plan)}async function Hl(e){let t=Y(e.settings.schema),n=[...new Set([["types",Z.types],["fields",Z.fields],["workflows",Z.workflows]].map(([r,a])=>re(e.pmRoot,t.files[r],a)).filter(r=>r!==e.schemaPath))];try{let r=nt.join(e.pmRoot,"templates"),a=await ze.readdir(r,{withFileTypes:!0});n.push(...a.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>nt.join(r,o.name)))}catch(r){if(typeof r!="object"||r===null||!("code"in r)||!ie(r))throw r}n.sort((r,a)=>r.localeCompare(a));let i=[];for(let r of n){let a=await G(r);a!==null&&Bn(a,e.request)!==a&&i.push({filePath:r,beforeRaw:a})}return{paths:n,snapshots:i}}async function Kl(e){for(let t of e.snapshots){let n=await ze.readFile(t.filePath,"utf8"),i=nt.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await In({pmRoot:e.pmRoot,author:e.author,documentPath:i,before:Kt(t.beforeRaw),after:Kt(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${i}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function Vl(e,t,n){let i=Hn(e),r=N(process.cwd(),n.path);await Se(r);let a=t.migrationId===void 0?xa(i,await ze.realpath(r)):ka(t.migrationId),o=await A(r),s=B(t.author,o.author_default),l=await Wl({pmRoot:r,settings:o,migrationId:a,request:i}),c=l.plan;if(t.dryRun===!0)return{...c,action:i.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=Il(r,o,i),p=await ze.readFile(d,"utf8");l.stored||await Bl({pmRoot:r,schemaPath:d,request:i,plan:c});let m=await Hl({pmRoot:r,schemaPath:d,settings:o,request:i}),g=[va({id:"stage-schema",filePath:d,request:i,phase:"stage"}),...m.paths.map((w,v)=>Jl({filePath:w,request:i,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...c.items.map(w=>ql({pmRoot:r,id:w.id,request:i,author:s,force:t.force===!0})),va({id:"retire-source",filePath:d,request:i,phase:"retire"})],y=await Pr({pmRoot:r,transactionId:`schema-${a}`,author:s,steps:g,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),_=await ze.readFile(d,"utf8"),{historyPath:u}=await In({pmRoot:r,author:s,documentPath:nt.relative(r,d).replaceAll("\\","/"),before:Kt(p),after:Kt(_),op:"schema_migration",idempotencyKey:`${c.migration_id}:${c.fingerprint}`,message:`${i.kind}: ${i.from} -> ${i.to}; affected=${c.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await Kl({pmRoot:r,author:s,settings:o,request:i,plan:c,snapshots:m.snapshots}),{...c,action:i.kind,applied:!0,recovered:y.recovered,migrated_item_count:c.affected_item_count,workspace_history_path:u}}function Yl(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(`
|
|
21
|
+
`)}import Oa from"node:fs/promises";import Je from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="74b72dd8-0877-55a4-9c80-d043f19e1f96")}catch{}})();var Vt=["extensions","docs","examples","assets","prompts"],Xl=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 Zl(e){return Vt.includes(e)}function Ql(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],i=[];for(let r of n){if(typeof r!="string"||r.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);i.push(r.trim())}return[...new Set(i)].sort((r,a)=>r.localeCompare(a))}function ed(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[i,r]of Object.entries(n)){if(!Zl(i))continue;let a=Ql(i,r);a.length>0&&(t[i]=a)}return t}function fe(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function Vn(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,i)=>n.localeCompare(i)):void 0}function Aa(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 td(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:fe(t,"docs"),npm:fe(t,"npm"),repository:fe(t,"repository"),report:fe(t,"report")};return Object.values(n).some(i=>typeof i=="string")?n:void 0}function nd(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:fe(t,"image"),video:fe(t,"video")};return Object.values(n).some(i=>typeof i=="string")?n:void 0}function id(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:fe(t,"display_name")??fe(t,"displayName"),category:fe(t,"category"),summary:fe(t,"summary"),links:td(t.links),media:nd(t.media),tags:Vn(t.tags)};return Object.values(n).some(i=>i!==void 0)?n:void 0}async function ft(e){let t=Je.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await Oa.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 i=n,r=i.pm,a=r!=null,o=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{};return{source:a?"pm":"convention",package_json_path:t,package_name:typeof i.name=="string"?i.name:void 0,package_version:typeof i.version=="string"?i.version:void 0,package_private:i.private===!0,package_description:typeof i.description=="string"?i.description:void 0,package_keywords:Vn(i.keywords),package_homepage:typeof i.homepage=="string"?i.homepage:void 0,package_repository_url:Aa(i.repository),package_bugs_url:Aa(i.bugs),aliases:Vn(o.aliases),resources:ed(r),catalog:id(o.catalog)}}async function Ta(e){if(!await k(e))return[];let t=await Oa.readdir(e,{withFileTypes:!0}),n=[];for(let i of t){if(!i.isDirectory())continue;let r=Je.join(e,i.name);await k(Je.join(r,"manifest.json"))&&n.push(r)}return n.sort((i,r)=>i.localeCompare(r))}async function Yt(e){if(await k(Je.join(e,"manifest.json")))return[e];let t=(await ft(e)).resources.extensions??[],n=new Set;for(let i of t){if(i.includes("*")||i.startsWith("!"))throw new f(`Package extension entry "${i}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let r=Je.resolve(e,i);if(!K(e,r))throw new f(`Package extension entry "${i}" resolves outside package root.`,h.USAGE);if(await k(Je.join(r,"manifest.json"))){n.add(r);continue}for(let a of await Ta(r))n.add(a)}if(t.length===0)for(let i of Xl.extensions)for(let r of await Ta(Je.join(e,i)))n.add(r);return[...n].sort((i,r)=>i.localeCompare(r))}import{execFile as Sd}from"node:child_process";import R from"node:fs/promises";import ri from"node:os";import $ from"node:path";import{fileURLToPath as Ed}from"node:url";import{promisify as $d}from"node:util";import Id from"npm-package-arg";import{extract as Ad,list as Td}from"tar";import fd from"node:fs/promises";import de from"node:path";import Ca from"node:fs/promises";import Yn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cf1403b0-7b07-5f00-9523-87bc727dd7fa")}catch{}})();function te(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function b(e){return e.trim().toLowerCase()}function Xt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let i=t.length;for(;i>n&&t[i-1]==="-";)i-=1;let r=t.slice(n,i);if(r.length===0)throw new f("Extension manifest name must resolve to a non-empty directory name.",h.USAGE);if(r==="."||r==="..")throw new f('Extension manifest name must not resolve to "." or "..".',h.USAGE);return r}function Xn(e){return Vi(e)}async function rd(e){try{let t=JSON.parse(await Ca.readFile(Yn.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(i=>typeof t.scripts?.[i]=="string")}}catch{return{has_build_script:!1}}}async function ad(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new f(`Extension entry file is missing at "${t}".`,h.USAGE);let i=await rd(n.source_root),r=i.package_name?`pm install npm:${i.package_name}`:void 0,a=n.source_input??n.source_root;return new f(`Extension entry "${e.entry}" is absent from GitHub source "${a}". pm install copies GitHub repositories without running package scripts${i.has_build_script?", and this package declares a build or publish script":""}. ${r?`Try "${r}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,h.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:r?[r,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:r?[`Retry with ${r}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${a}`,normalized_args:["install",a],...r?{next_best_command:r}:{}}})}async function rt(e,t={}){let n=Yn.join(e,"manifest.json");if(!await k(n))throw new f(`Extension manifest is missing at "${n}".`,h.USAGE);let i;try{i=JSON.parse(await Ca.readFile(n,"utf8"))}catch(o){throw new f(`Failed to parse extension manifest at "${n}": ${od(o)}`,h.USAGE)}let r=Xn(i);if(!r)throw new f(`Extension manifest at "${n}" is invalid.`,h.USAGE);let a=Yn.resolve(e,r.entry);if(!K(e,a))throw new f(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,h.USAGE);if(!await k(a))throw await ad(r,a,t);if(!await Xi(e,a))throw new f(`Extension entry "${r.entry}" resolves outside extension directory after symlink resolution.`,h.USAGE);return{directory:e,manifest_path:n,entry_path:a,manifest:r}}function od(e){return e instanceof Error?e.message:String(e)}import Zn from"node:fs/promises";import sd from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5181479f-469f-525b-add2-914a9934afbd")}catch{}})();var cd=".managed-extensions.json",Zt=1;function ht(e){return sd.join(e,cd)}function ld(){return{version:Zt,updated_at:T(),entries:[]}}function gt(e){return[...e].sort((t,n)=>{let i=t.scope.localeCompare(n.scope);if(i!==0)return i;let r=t.name.localeCompare(n.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function Pa(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function Q(e){return typeof e=="string"?e:void 0}function dd(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function pd(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:Q(t.name),package:Q(t.package),version:Q(t.version),repository:Q(t.repository),owner:Q(t.owner),repo:Q(t.repo),ref:Q(t.ref),subpath:Q(t.subpath),commit:Q(t.commit)}}function md(e){if(typeof e!="object"||e===null)return null;let t=e;if(!dd(t))return null;let n=pd(t.source);if(!n)return null;let i=qi(t.contributions);return i===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:te(t.capabilities),contributions:i,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Q(t.last_update_check_at),last_update_remote_commit:Q(t.last_update_remote_commit),last_update_remote_version:Q(t.last_update_remote_version),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Q(t.update_error)}}function ud(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Zt||!Array.isArray(t.entries))return null;let n=[];for(let i of t.entries){let r=md(i);r&&n.push(r)}return{version:Zt,updated_at:Q(t.updated_at)??T(),entries:gt(n)}}async function he(e){let t=ht(e),n=ld();try{let i=await Zn.readFile(t,"utf8"),r=JSON.parse(i),a=ud(r);if(!a)throw new f(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:a,warnings:[]}}catch(i){if(i instanceof f)throw i;if(typeof i=="object"&&i!==null&&"code"in i&&ie(i))return{path:t,state:n,warnings:[]};throw new f(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}async function at(e,t){let n=ht(e),i={version:Zt,updated_at:T(),entries:gt(t.entries)};await Zn.mkdir(e,{recursive:!0}),await Zn.writeFile(n,`${JSON.stringify(i,null,2)}
|
|
22
|
+
`,"utf8")}function yt(e,t){let n=e.entries.filter(i=>b(i.name)!==b(t.name)&&b(i.directory)!==b(t.directory));return n.push(t),{...e,updated_at:T(),entries:gt(n)}}async function Ra(e,t,n,i){let r=t.entries.find(o=>b(o.name)===b(n));if(!r)return t;let a=yt(t,{...r,contributions:i});return await at(e,a),a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var hd="PM_CLI_PACKAGE_ROOT",Na={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},gd=new Set(["*","all"]);function Qn(){let e=[],t=process.env[hd];return typeof t=="string"&&t.trim().length>0&&e.push(de.resolve(t.trim())),e.push(pe(import.meta.url,["../../.."])),[...new Set(e)]}async function _t(e){let t=e.trim().toLowerCase(),n=await ja(t);if(n)return n;let i=Na[t];if(!i)return null;for(let r of Qn()){let a=de.join(r,".agents","pm","extensions",i.legacy_extension_directory);if(await k(de.join(a,"manifest.json")))return a}return null}function Da(e){return gd.has(e.trim().toLowerCase())}function yd(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function _d(e,t){let n=await fd.readdir(e,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||!i.name.startsWith("pm-"))continue;let r=de.join(e,i.name);if(!await k(de.join(r,"package.json")))continue;let a=await ft(r),o=a.aliases&&a.aliases.length>0?a.aliases:[yd(i.name)];for(let s of o){let l=s.trim().toLowerCase();l.length===0||t.has(l)||t.set(l,{alias:l,package_directory:i.name,package_root:r,package_name:a.package_name??null})}}}async function ei(){let e=new Map;for(let t of Qn()){let n=de.join(t,"packages");await k(n)&&await _d(n,e)}for(let[t,n]of Object.entries(Na))if(!e.has(t))for(let i of Qn()){let r=de.join(i,"packages",n.package_directory);if(await k(de.join(r,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:r,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Qt(){return(await ei()).map(e=>e.alias)}async function ja(e){let t=e.trim().toLowerCase();return(await ei()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function La(e){let t=await ja(e);return t?(await ft(t)).package_name??null:null}async function Fa(e){let t=await _t(e);if(!t)return null;try{let n=await Yt(t);return n.length!==1?null:(await rt(n[0])).manifest.name}catch{return null}}function wd(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 vd(e,t,n,i,r,a){let o=i==="global"?"--global":"--project",s=Object.fromEntries(Vt.filter(l=>l!=="extensions").map(l=>[l,e.resources[l]??[]]).filter(([,l])=>Array.isArray(l)&&l.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(l=>r.has(l))||a.has(de.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:wd(e),media:e.catalog?.media}}}async function Ma(e,t,n={}){let i=Nt(N(process.cwd(),t.path),process.cwd()),r=e==="global"?i.global:i.project,a=await he(r),o=new Set(a.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>de.resolve(m.source.location))),s=new Set(a.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),l=[],c=new Map;for(let m of await ei()){let g=de.resolve(m.package_root),y=c.get(g)??[];y.push(m),c.set(g,y)}for(let m of c.values()){let g=m[0],y=m.map(u=>u.alias).sort((u,w)=>u.localeCompare(w)),_=await ft(g.package_root);l.push(vd(_,g,y,e,s,o))}let d=kd(n.fields),p=d?l.map(m=>xd(m,d)):l;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Vt.filter(m=>m!=="extensions"),packages:p}}var bd=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 kd(e){if(e===void 0)return;let t=xr(e);if(t.length===0)throw new f("Package catalog --fields requires a comma-separated list of field names",h.USAGE);let n=t.filter(i=>!bd.has(i));if(n.length>0)throw new f(`Unknown package catalog --fields value(s): ${n.join(", ")}`,h.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function xd(e,t){let n={};for(let i of t)i==="category"?n[i]=e.catalog?.category??null:i==="display_name"?n[i]=e.catalog?.display_name??null:n[i]=e[i]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="db10bb85-f21c-58b1-8b78-8ce1024b3e08")}catch{}})();var Ua=$d(Sd),tn="@unbrained/pm-cli",Od={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},ti;async function za(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let i=$.resolve(t);for(;;){let r=$.join(i,"node_modules",...n.split("/")),a=$.join(r,"package.json");if(await k(a))try{let s=JSON.parse(await R.readFile(a,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:r}}catch{return null}let o=$.dirname(i);if(o===i)return null;i=o}}function ni(e,t,n){let i=e.split("/").map(c=>c.trim()).filter(c=>c.length>0);if(i.length<2)return null;let r=i[0],a=i[1].replace(/\.git$/i,"");if(r.length===0||a.length===0)return null;let o=i.slice(2),s,l;return o[0]==="tree"&&o.length>=2?(s=o[1],l=o.slice(2).join("/")):o.length>0&&(l=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:r,repo:a,repository:`https://github.com/${r}/${a}.git`,ref:s,subpath:l&&l.length>0?l:void 0}}function Cd(e,t,n){let i=e.slice(4).trim();if(i.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:i}}function wt(e,t={}){let n=e.trim();if(n.length===0)throw new f("Extension source is required for --install.",h.USAGE);let i=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Cd(n,t.forceGithub===!0,i);let r=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return ni(s,n,i)}catch{return null}})();if(r)return r;let a=n.startsWith("github.com/")?n.slice(11):null;if(a){let o=ni(a,n,i);if(!o)throw new f(`Invalid GitHub source "${n}".`,h.USAGE);return o}if(t.forceGithub){let o=ni(n,n,i);if(!o)throw new f(`Invalid GitHub shorthand "${n}".`,h.USAGE);return o}if(/^https?:\/\//i.test(n))throw new f(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,h.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function en(e,t=Ua,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(i){let r=typeof i=="object"&&i!==null&&"stderr"in i?String(i.stderr):"",a=r.trim().length>0?r.trim():i instanceof Error?i.message:String(i);throw new f(`Git command failed: git ${e.join(" ")}
|
|
23
|
+
${a}`,h.GENERIC_FAILURE)}}function ai(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function oi(e=process.platform){return e==="win32"}async function Ja(e,t,n=Ua,i=process.platform,r=process.env){let a=ai(i),o=Object.fromEntries(Object.entries(r).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));o.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(a,e,{cwd:t,encoding:"utf8",env:o,shell:oi(i)})).stdout??"").trim()}catch(s){let l=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",c=l.trim().length>0?l.trim():s instanceof Error?s.message:String(s);throw new f(`npm command failed: ${a} ${e.join(" ")}
|
|
24
|
+
${c}`,h.GENERIC_FAILURE)}}function qa(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function Wa(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 Pd(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("npm err! code e404")||t.includes("404 not found")||t.includes("is not in this registry")}function Rd(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return Pd(e)||t.includes("not found")}function Nd(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Dd(e){let t=qa(e),n=Nd(t),i=t.replace(/^.*\//,""),r=n?`github.com/unbraind/${i}`:void 0,a=r?`pm install --project ${r}`: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:a?[a,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:a?[`Try ${a} 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}`],...r&&a?{fallback_candidates:[{source:r,command:a,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:a}:{}}}}}function jd(e,t){if(!Rd(t))return null;let n=Dd(e);return new f(n.message,h.NOT_FOUND,n.context)}async function Ba(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await k(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=Ed(t);return await k(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await k(t))return t}return null}async function Ld(e){let t=await Ba(e);if(t)return t;let n=Fd(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Fd(e,t=process.cwd()){let n="@file:",i=e.lastIndexOf(n);if(!Wa(e))return e;let r=e.slice(0,i),a=e.slice(i+n.length);if(a.startsWith("//")&&!a.startsWith("///"))return e;if(!a.startsWith("/"))return`${r}@${$.resolve(t,a)}`;let o;try{o=decodeURIComponent(new URL(`file:${a}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${r}@${s}`}function Ga(e,t){let n=$.resolve(e,t),i=$.relative(e,n);if(i.length===0||i===".."||i.startsWith(`..${$.sep}`)||$.isAbsolute(i))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 Md(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 Gd(e){return(Array.isArray(e)?e.map(t=>({value:t})):typeof e=="object"&&e!==null?Object.entries(e).map(([t,n])=>({key:t,value:n})):[]).flatMap(({key:t,value:n})=>{let i=Md(n,t);return i?[i]:[]})}function Ud(e,t){let n=t?.trim().toLowerCase(),i=n?e.filter(o=>{let s=o.name?.trim().toLowerCase();return s!==void 0?s===n:o.key?.trim().toLowerCase()===n}):[];if(i.length===1)return i[0];if(e.length!==1)return;let r=e[0],a=r.name??r.key;return n&&a!==void 0&&a.trim().toLowerCase()!==n?void 0:r}function zd(e,t,n){let i;try{i=JSON.parse(e)}catch{let o=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!o)throw new f("npm pack did not report a tarball filename.",h.GENERIC_FAILURE);return{tarball:Ga(t,o)}}let r=Gd(i),a=Ud(r,n);if(!a)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 ${r.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Ga(t,a.filename),package:a.name??a.key,version:a.version}}async function Jd(e){return qd(e,Ja)}async function qd(e,t){let n=await Ba(e.spec);if(n){if((await R.stat(n)).isFile()&&Ha(n))return ii(n);let a=$.join(n,"package.json"),o=await k(a)?JSON.parse(await R.readFile(a,"utf8")):{};return{directory:await nn(n,e.input),package:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,cleanup:async()=>{}}}let i=await R.mkdtemp($.join(ri.tmpdir(),"pm-npm-package-source-")),r=$.join(i,"pack");await R.mkdir(r,{recursive:!0});try{let a=await Ld(e.spec),o=await t(["pack",a,"--json","--pack-destination",r]),s=zd(o,r,Wa(e.spec)?void 0:qa(e.spec));if(!await k(s.tarball))throw new f("npm pack did not create its reported package archive.",h.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let l=await ii(s.tarball);return{directory:l.directory,package:s.package??l.package,version:s.version??l.version,cleanup:async()=>{try{await l.cleanup()}finally{await R.rm(i,{recursive:!0,force:!0})}}}}catch(a){throw await R.rm(i,{recursive:!0,force:!0}),jd(e.spec,a)||a}}function Ha(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ve(e){throw new f(e,h.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function Wd(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&ve(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let i=e.path,r=i.split("/");(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||r.some(a=>a===".."))&&ve(`Local package archive contains an escaping path: "${i}".`),r[0]!=="package"&&ve(`Local package archive entry "${i}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ve(`Local package archive link "${i}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ve(`Local package archive entry "${i}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ve(`Local package archive entry "${i}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&ve(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),i==="package/package.json"&&(n.packageJsonEntries+=1)}async function ii(e,t=Od){(await R.stat(e)).size>t.maxArchiveBytes&&ve(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await R.mkdtemp($.join(ri.tmpdir(),"pm-local-package-archive-")),i=$.join(n,"extract");await R.mkdir(i,{recursive:!0});let r={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await Td({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:c=>{if(a===void 0)try{Wd(c,t,r)}catch(d){a=d}}}),a!==void 0)throw a;r.packageJsonEntries!==1&&ve(`Local package archive must contain exactly one package/package.json entry; found ${r.packageJsonEntries}.`),await Ad({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let o=$.join(i,"package"),s=$.join(o,"package.json"),l=JSON.parse(await R.readFile(s,"utf8"));return await Bd(o),{directory:await nn(o,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.version:void 0,cleanup:async()=>{await R.rm(n,{recursive:!0,force:!0})}}}catch(o){throw await R.rm(n,{recursive:!0,force:!0}),o}}async function Bd(e,t=Ja){let n=$.join(e,"package.json");if(!await k(n))return;let i;try{i=JSON.parse(await R.readFile(n,"utf8"))}catch{return}if(typeof i!="object"||i===null)return;let r=i,a=Zd(r),o=Hd(r);if(a.length===0&&!o)return;let s={...i};delete s.devDependencies;let l={...s};Kd(l),await R.writeFile(n,`${JSON.stringify(l,null,2)}
|
|
25
|
+
`,"utf8");try{await Promise.all([R.rm($.join(e,"package-lock.json"),{force:!0}),R.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),a.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await Vd(e)}finally{await R.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
26
|
+
`,"utf8")}}function Hd(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&tn in t)return!0;return!1}function Kd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let i={...n};delete i[tn],Object.keys(i).length===0?delete e[t]:e[t]=i}}async function Vd(e){let t=pe(import.meta.url,["../../.."]),[n,i]=tn.split("/"),r=$.join(e,"node_modules",n),a=$.join(r,i);await R.mkdir(r,{recursive:!0}),await R.rm(a,{recursive:!0,force:!0}),await R.symlink(t,a,Yd(process.platform))}function Yd(e){return e==="win32"?"junction":"dir"}function Xd(e,t){if(e.startsWith("-"))throw new f(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,h.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(n=>{let i=n.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(n)}))throw new f(`Extension runtime dependency "${e}" has an unsafe version specifier.`,h.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Id.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 Zd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[i,r]of Object.entries(n)){if(i===tn||typeof r!="string"||r.trim().length===0||t.has(i))continue;let a=r.trim();t.set(i,Xd(i,a))}return[...t.values()]}async function nn(e,t){let n=await Yt(e);if(n.length===1)return n[0];if(n.length>1){let i=n.map(r=>$.relative(e,r).replaceAll($.sep,"/")).sort((r,a)=>r.localeCompare(a));throw new f(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${i.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 Qd(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 r of n){let a=$.resolve(e,r);if(K(e,a)&&await k($.join(a,"manifest.json")))return{directory:a,resolved_subpath:r}}if(await k($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let i=await nn(e,t.input);return{directory:i,resolved_subpath:$.relative(e,i).replaceAll($.sep,"/")}}function ep(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 tp(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!ep(n))return new f(t,h.NOT_FOUND);let i=[];try{let a=process.env.PM_CLI_PACKAGE_ROOT,o=typeof a=="string"&&a.trim().length>0?$.resolve(a.trim()):"";ti?.key!==o&&(ti={key:o,aliases:await Qt()}),i=ti.aliases}catch{}let r=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${i.join(", ")}`];return new f(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,h.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:r,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Ka(e){if(e.kind==="local"){let i;try{i=await R.stat(e.absolute_path)}catch{throw await tp(e)}if(i.isFile()&&Ha(e.absolute_path)){let a=await ii(e.absolute_path);return{source:e,directory:a.directory,source_root:$.dirname(a.directory),resolved_subpath:$.relative($.dirname(a.directory),a.directory).replaceAll($.sep,"/"),npm_package:a.package,npm_version:a.version,cleanup:a.cleanup}}if(!i.isDirectory())throw new f(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let r=await nn(e.absolute_path,e.input);return{source:e,directory:r,source_root:e.absolute_path}}if(e.kind==="npm"){let i=await Jd(e);return{source:e,directory:i.directory,source_root:$.dirname(i.directory),cleanup:i.cleanup,resolved_subpath:$.relative($.dirname(i.directory),i.directory).replaceAll($.sep,"/"),npm_package:i.package,npm_version:i.version}}let t=await R.mkdtemp($.join(ri.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await en(n);let i=await en(["-C",t,"rev-parse","HEAD"]),r=await Qd(t,e);return{source:e,directory:r.directory,source_root:t,resolved_subpath:r.resolved_subpath,commit:i,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(i){throw await R.rm(t,{recursive:!0,force:!0}),i}}async function rn(e,t){if(!await k(e)||!await k(t))return!1;let[n,i]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===i}import vt from"node:fs/promises";import bt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var si=1,qe="2026.6.24",np=">=22.18.0",ip={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Va=new Set([...or.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Ni).map(e=>e.toLowerCase()),"scaffold"]),rp="^6.0.0",ap="^22.0.0",Za=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],ge=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Ya(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Qa(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 eo(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 op={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Xa=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],to={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"]},sp={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"]'},cp={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."},lp={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."},no="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",dp={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."]},pp={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."]},mp={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`."]},up={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 io(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function ro(e,t){return e==="schema"?mp[t]:e==="profile"?up[t]:pp[t]}function fp(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(o=>o.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),i=0;for(;t[i]?.toLowerCase()==="starter";)i+=1;let r=t[i]?.toLowerCase(),a=i>0&&(i===t.length||r!==void 0&&Va.has(r));return`${(Va.has(n)||a?["starter",...t]:t).join(" ")} ping`}function ao(e){let t=e,n=`${e}s`,i=e.replace(/-/g,""),r=i===t?[]:[i],a=`${e.replace(/-/g,"_")}_owner`,o="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(r)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(a)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function hp(e,t,n){let i=`${e}-search`,r=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,o=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(i)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(r)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,l=`${e}s`,c=e.replace(/-/g,""),d=c===s?[]:[c],p=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...ao(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(a)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} 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(a)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...o,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...o,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function gp(e,t,n){let i=n==="hooks",r=n==="search",a=n==="importers",o=n==="schema",s=n==="profile",l=n==="renderers",c=n==="parser",d=n==="preflight",p=n==="services",m=sp[n],g=e,y=`${e}s`,_=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=i?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],x=r?ci(e,t,"search",m):[],S=a?ci(e,t,"importers",m):[],O=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Ya(Qa({extensionName:e,itemTypeName:g,itemTypeFolder:y,fieldName:_,migrationId:u,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],ae=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Ya(eo(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],L=l?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],E=c?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],q=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[],ot=p?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...r?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Za,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...c?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});","",...v,...x,...S,...O,...ae,...L,...E,...q,...ot,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
27
|
+
`)}function yp(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let i=`${e.replace(/-/g," ")} items`;return[t,`${i} import`,`${i} export`]}return[t]}var _p={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"},wp={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 vp(e,t,n){let i=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...i?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...i?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function bp(e,t,n){let i=[],r=[...vp(e,t,n)],a=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,l=`${e.replace(/-/g," ")} items`,c=e,d=`${e}s`,p=e.replace(/-/g,""),m=p===c?[]:[p],g=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":i.push("defineAfterCommandHook"),r.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... */ }","});"),a.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":i.push("defineSearchProvider","defineVectorStoreAdapter"),r.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),a.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":i.push("defineExporter","defineImporter"),r.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,","}));"),a.push(" importers: ["," {",` name: ${JSON.stringify(l)},`," importer,"," options: {",` action: ${JSON.stringify(`${l} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(l)},`," exporter,"," options: {",` action: ${JSON.stringify(`${l} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":i.push("defineItemField","defineItemType","defineMigration"),r.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(g)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(c)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(y)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),a.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":i.push("defineProjectProfile"),r.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...ao(e),"});"),a.push(" profiles: [starterProfile],");break;case"renderers":i.push("defineRendererOverride"),r.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);`," },","});"),a.push(" renderers: { toon: toonRenderer },");break;case"parser":i.push("defineParserOverride"),r.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 };","});"),a.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":i.push("definePreflightOverride"),r.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,","});"),a.push(" preflights: [preflightOverride],");break;case"services":i.push("defineServiceOverride"),r.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 };`,"});"),a.push(" services: { output_format: outputService },");break}return{builderImports:i,definitions:r,blueprintFields:a}}function kp(e,t,n){let i=bp(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...i.builderImports].sort((r,a)=>r.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...i.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...i.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
|
|
28
|
+
`)}function ci(e,t,n,i){if(n==="commands")return[];let r=`${e}-search`,a=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,l=`${e}s`,c=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"],m=g=>[...p," let deactivated = false;"," try {",...g.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(r)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(a)}, 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(r)},`,' 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(r)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(a)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(Qa({extensionName:e,itemTypeName:s,itemTypeFolder:l,fieldName:c,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(eo(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function xp(e,t,n){let i=n==="parser",r=JSON.stringify([...to[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" };',"",...Za,`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(qe)},`," },",` target: { pmVersion: ${JSON.stringify(qe)} },`," });"," // 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, ${r});`,` assert.deepEqual(report.manifest?.capabilities, ${r});`,"});","",`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: ${r},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...i?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ge,"});","",...ci(e,t,n,r)].join(`
|
|
29
|
+
`)}function Sp(e,t,n){let i=io(n,"package"),r=ro(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",i,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${_p[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`.",no,"- `.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 ${wp[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.",...r,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${si}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${qe}\`. 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(`
|
|
30
|
+
`)}function Ep(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 $p(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 Ip(e,t,n,i){let r=["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"&&r.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&r.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(i.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(i.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&r.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"&&r.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(i.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(i.itemTypeName)},`,` folder: ${JSON.stringify(i.itemTypeFolder)},`,` aliases: ${JSON.stringify(i.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(i.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&r.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(i.itemTypeName)}, folder: ${JSON.stringify(i.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&r.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&r.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&r.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"&&r.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),r}function Ap(e,t,n){let i=[];return t==="renderers"&&i.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&i.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&i.push(" api.registerPreflight(preflightOverride);"),t==="services"&&i.push(' api.registerService("output_format", outputService);'),t==="hooks"&&i.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&i.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&i.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&i.push(" api.registerProfile(starterProfile);"),t==="importers"&&i.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),i}function Tp(e,t,n,i="commands",r=!1){let a=`pm-${e}`,o=to[i],s=yp(e,t,i),l=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:si,pm_min_version:qe,trusted:!0,sandbox_profile:"strict",permissions:{...ip},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
|
|
31
|
+
`,c=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...hp(e,t,i),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
|
|
32
|
+
`),d=`${JSON.stringify(op,null,2)}
|
|
33
|
+
`,p=cp[i],m=io(i,"package"),g=`${JSON.stringify({name:a,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:np},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${qe}`},devDependencies:{"@types/node":ap,typescript:rp},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)}
|
|
34
|
+
`,y=gp(e,t,i),_=lp[i],u=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
35
|
+
`),w=Ep(e),v=["```ts",`import { ${$p(i)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Ip(e,t,i,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Ap(t,i,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],x=[`# ${a}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,p,_,no,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...v,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...dp[i],...ro(i,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${qe}\`. 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 \`${si}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${qe}\`. 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(`
|
|
36
|
+
`);return{"package.json":g,"manifest.json":l,"index.ts":r?kp(e,t,i):c,"index.test.ts":r?xp(e,t,i):y,"tsconfig.json":d,".gitignore":u,"README.md":r?Sp(a,t,i):x}}async function oo(e,t="extension",n="commands",i=!1){let r=n.trim().toLowerCase();if(!Xa.includes(r))throw new f(`Unknown scaffold capability "${n}". Supported capabilities: ${Xa.join(", ")}.`,h.USAGE);let a=r;if(i&&t!=="package")throw new f("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",h.USAGE);let o=i?"declarative":"imperative",s=e.trim(),l=bt.resolve(process.cwd(),s),c=Xt(bt.basename(l)).replace(/^(?:pm-)+/u,""),d=fp(c),p=Tp(c,d,t,a,i),m=!1;if(await k(l)){if(!(await vt.stat(l)).isDirectory())throw new f(`Scaffold target "${l}" exists and is not a directory.`,h.CONFLICT)}else await vt.mkdir(l,{recursive:!0}),m=!0;for(let[y,_]of Object.entries(p)){let u=bt.join(l,y);if(await k(u)&&await vt.readFile(u,"utf8")!==_)throw new f(`Scaffold file "${y}" already exists with different content in "${l}". Choose a new target path or remove conflicting files.`,h.CONFLICT)}let g=[];for(let[y,_]of Object.entries(p)){let u=bt.join(l,y);if(await k(u)){g.push({path:y,status:"unchanged"});continue}await vt.mkdir(bt.dirname(u),{recursive:!0}),await vt.writeFile(u,_,"utf8"),g.push({path:y,status:"created"})}return{extension_name:c,package_name:`pm-${c}`,command_name:d,invocation_command:`pm ${d}`,capability:a,style:o,target_path:l,created_directory:m,files:g}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3984f1ef-1703-5a83-a4fa-ec1cdc738572")}catch{}})();var so=[["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 li(e){return"#".repeat(e)}function co(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let a of e)n=a==="`"?n+1:0,t=Math.max(t,n);let i="`".repeat(t+1),r=e.startsWith("`")||e.endsWith("`")?" ":"";return`${i}${r}${e}${r}${i}`}function Op(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(co).join(", ")}`}function Cp(e,t,n){let i=[`${li(t)} ${e}`,""];return n.length===0?(i.push("_None._",""),i):(i.push(...n.map(r=>`- ${co(r)}`),""),i)}function Pp(e,t,n){return e===0&&!n?[]:[`${li(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function di(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<1||n>6)throw new RangeError(`headingLevel must be an integer in [1, 6], received ${String(t.headingLevel)}`);let i=Math.min(n+1,6),r=t.includeEmpty===!0,a=t.title??"Extension surfaces",o=[`${li(n)} ${a}`,""];(r||e.capabilities.length>0)&&o.push(Op(e.capabilities),"");for(let[s,l]of so){let c=e[s]??[];c.length===0&&!r||o.push(...Cp(l,i,c))}return o.push(...Pp(e.preflight_overrides,i,r)),!(e.preflight_overrides>0||so.some(([s])=>(e[s]?.length??0)>0))&&!r&&o.push("_This extension registers no surfaces._",""),`${o.join(`
|
|
36
37
|
`).trimEnd()}
|
|
37
|
-
`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function
|
|
38
|
+
`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function lo(e,t){return`${e}:${b(t)}`}function Rp(e,t){let n=[];for(let[i,r]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let a=new Map;for(let o of r){let s=a.get(o.command)??[];a.set(o.command,[...s,o])}for(let[o,s]of a){if(t!==null&&!s.some(c=>t.has(b(c.name))))continue;let l=s.at(-1);n.push({command:o,surface:i,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(c=>({name:c.name,layer:c.layer,winner:c===l}))})}}return n.sort((i,r)=>i.command.localeCompare(r.command)||i.surface.localeCompare(r.surface))}function po(e,t,n){let i=new Set(n.failed.map(c=>lo(c.layer,c.name))),r=[...t.loaded.map(c=>({name:c.name,layer:c.layer,version:c.version,activation_status:i.has(lo(c.layer,c.name))?"failed":"ok",surfaces:Ve(n,{extensionName:c.name})})),...t.failed.map(c=>({name:c.name,layer:c.layer,version:"unknown",activation_status:"not_loaded",surfaces:Ve(n,{extensionName:c.name})}))].sort((c,d)=>c.name.localeCompare(d.name)||c.layer.localeCompare(d.layer)),a=typeof e=="string"?b(e):null,o=a===null?null:new Set(t.loaded.filter(c=>b(c.name)===a||typeof c.source_package=="string"&&b(c.source_package)===a||(c.source_aliases??[]).some(d=>b(d)===a)).map(c=>b(c.name)).concat(a)),s=o===null?r:r.filter(c=>o.has(b(c.name))),l=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Ve(n,l),command_ownership:Rp(n,o)}}var Np={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function t_(e,t){let n=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(n.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),n.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){n.push("## Command ownership","");for(let i of e.command_ownership){let r=i.claimants.find(o=>o.winner),a=i.claimants.map(o=>`${o.layer}:${o.name}`).join(", ");n.push(`- \`${i.command}\` (${i.surface}): ${r.layer}:${r.name}; policy=${i.policy}; collision=${String(i.collision)}; claimants=${a}`)}n.push("")}if(e.extensions.length===0)return n.push(`_No ${t}s are loaded._`,""),`${n.join(`
|
|
38
39
|
`).trimEnd()}
|
|
39
|
-
`;for(let i of e.extensions){let r=`${i.name} (${i.layer} v${i.version}, ${
|
|
40
|
+
`;for(let i of e.extensions){let r=`${i.name} (${i.layer} v${i.version}, ${Np[i.activation_status]})`;n.push(di(i.surfaces,{title:r,headingLevel:2}))}return e.extensions.length>1&&n.push(di(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${n.join(`
|
|
40
41
|
`).trimEnd()}
|
|
41
|
-
`}import sn from"node:fs/promises";import on from"node:path";import
|
|
42
|
-
`,"utf8")},
|
|
43
|
-
`,"utf8")}catch(n){throw await M.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Gp=async(e,t,n,i,r)=>{for(let a=1;a<=n;a+=1)try{return await Mp(e,t),!0}catch(o){if(!an(o,"EEXIST"))throw o;await Lp(e,r)?a-=1:await go(i)}return!1},pi=async(e,t,n,i)=>De("extension_install",async()=>{let r=j.join(e,"runtime","extension-install-locks"),a=j.join(r,"scope.lock");await M.mkdir(r,{recursive:!0});let{attempts:o=Np,delay_ms:s=uo,stale_ms:l=Dp,heartbeat_ms:c}=i??{};if(![o,s,l,c].filter(w=>w!==void 0).every(Number.isFinite))throw new f("Extension install lock timings must be finite numbers.",h.USAGE);let d=Math.max(1,Math.floor(o)),p=Math.max(0,Math.floor(s)),m=Math.floor(l),g=Math.floor(c??m/3);if(m<=0||g<=0||g>=m)throw new f("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",h.USAGE);let y={pid:process.pid,token:Pp(),created_at:T(),destination:t};if(!await Gp(a,y,d,p,m))throw new f(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let _=Fp(a,y.token,g),u=!1;try{let w=await n();return u=!0,w}finally{await _(),await bo(a,y.token).catch(w=>{if(u)throw w})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var Up=new Set(["node_modules",".git","dist","build","coverage"]);async function ko(e,t,n,i){let r=e.source.kind==="local"?await sn.stat(e.source.absolute_path):void 0,a=e.source.kind==="local"?r.isDirectory()?"directory":"archive":e.source.kind,o=await zp(e.directory,t,i),s={source_mode:a,...a==="archive"?{archive_bytes:r.size}:{},copy:o},l=e.source_root??e.directory;if(a==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await k(on.join(l,"package.json"))&&(s.packed_alternative={cwd:l,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),a==="directory"&&!o.complete){let c=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new f(`Local extension source scan stopped at ${c}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,h.USAGE,{code:"extension_install_incomplete_source_scan",reason:o.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function zp(e,t,n={}){let{maxEntries:i=1e4,maxDepth:r=64,signal:a}=n;if(![i,r].every(p=>Number.isSafeInteger(p)&&p>0))throw new f("maxEntries and maxDepth must be positive safe integers.",h.USAGE);a?.throwIfAborted();let o=await sn.realpath(e),s=await xt(t),l=await rn(o,s);a?.throwIfAborted();let c=l?"in_place":K(o,s)?"nested_filtered_snapshot":"directory_snapshot",d={copy_scope:c,source_directory:o,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:i,max_depth:r};return c==="in_place"||await xo(o,0,d,a),d}async function xo(e,t,n,i){i?.throwIfAborted();let r=await sn.opendir(e);for await(let a of r){if(i?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=on.join(e,a.name);if(!kt(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(on.relative(n.source_directory,o).split(on.sep).some(s=>Up.has(s))&&(n.development_entries+=1),await Jp(o,t,n,i),!n.complete)return}}async function Jp(e,t,n,i){let r=await sn.lstat(e);if(i?.throwIfAborted(),r.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await xo(e,t+1,n,i)}else r.isFile()?(n.files+=1,n.bytes+=r.size):r.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import qp from"node:fs/promises";import Wp from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bef4424-f5b8-511b-91f7-0b39cf11f515")}catch{}})();async function Bp(e,t){if(e.kind!=="local"||e.input.startsWith(".")||e.input.includes("\\")||e.input.includes("/")&&!/^@[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/u.test(e.input))return e;try{return await qp.lstat(e.absolute_path),e}catch(a){if(!ie(a))throw a}let n=e.input.trim(),i=t.filter(a=>a.source.kind==="npm"),r=(i.find(a=>a.name===n)??i.find(a=>a.directory===n)??i.find(a=>a.source.package===n))?.source.package;if(r===void 0)return e;try{let a=Wp(r);if(!a.registry||a.name!==r)return e}catch{return e}return wt(`npm:${r}`,{})}async function So(e,t,n,i=[]){let r=typeof t=="string"?null:await _t(e),a=r===null?null:e.trim().toLowerCase(),o=a===null?null:await ja(a),s=await Bp(wt(r??e,{forceGithub:typeof t=="string",ref:n}),i),l=a===null?null:await Ua(e);return{bundledAliasName:a,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:a===null?s.kind:"builtin",input:a??s.input,...o===null?{}:{package:o}},ambiguous:l!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...a===null?[]:[{kind:"builtin",input:a,...o===null?{}:{package:o},command:`pm install ${a}`}],...l===null?[]:[{kind:"npm",input:`npm:${l.package}`,package:l.package,...l.version===void 0?{}:{version:l.version},directory:l.directory,command:`pm install npm:${l.package}`}]]}}}import Re from"node:fs/promises";import ne from"node:path";import Xp from"node:path";import{mkdir as Zp}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="abb182c9-6d6c-5be4-a2ad-c91b00a098d0")}catch{}})();var St=["agile","ops","research"],Hp={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function cn(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${St.join(", ")}.`)}function Et(e){return Hp[e].map(t=>lt(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var Kp=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Vp(e){let t=Kp.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Yp(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Eo(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,i=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,r=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let l=Vp(s);if(l===void 0)continue;let c=r.get(l)??{count:0,examples:[]};c.count+=1,c.examples.length<i&&c.examples.push(s),r.set(l,c)}let a=[];for(let[o,s]of r.entries()){if(s.count<n)continue;let l=Yp(o);a.push({name:l,prefix:o,count:s.count,examples:s.examples,shadows_builtin:_r(l)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var aw=[...jt,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],ln="schema-types",$o="schema-statuses",Io="schema-fields";function Ce(e){return Be({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function cw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r;try{r=lt({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(g){throw new f(g instanceof Error?g.message:String(g),h.USAGE)}let a=await A(i),o=V(a.schema),s=re(i,o.files.types,Z.types),l=[],c=B(t.author,a.author_default),d=ce(a),p=await X(i,ln,a.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,a.locks.wait_ms),m;try{let g=await G(s),y;try{y=le(g)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}try{wr(r,y);let _=new Map,u=U(a,W());for(let[w,v]of Object.entries(u.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!_.has(x)&&_.set(x,w)}vr(r,y,_)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}m=He(y,r),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&l.push(`type_recased:${m.previousName}->${m.definition.name}`),await Ce({pmRoot:i,filePath:s,raw:ue(m.file),op:"schema:add-type",author:c,settings:a}),await $t(i,[m.definition],l,"schema:add-type-folder"),l.push(...await H({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await Ao(i,l),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Pe(l),generated_at:T()}}async function be(e){await Se(e)}async function Ao(e,t){try{let n=await ta(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Pe(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Qp(e,t,n,i){let r=U(t,W()),a=i.trim().toLowerCase();return(await je(e,t.item_format,r.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===a).length}async function em(e,t,n,i){let r=U(t,W()),a=ct(n),o=I(i);return(await je(e,t.item_format,r.type_to_folder,[],n)).filter(s=>{let l=typeof s.status=="string"?s.status:"";return(a.alias_to_id.get(I(l))??I(l))===o}).length}async function tm(e,t,n,i,r){if(r.length===0||Ge.has(r))return;let a=await em(t,n,i,r);a>0&&e.push(`items_using_status:${a}`);let o=To(i.workflow,r);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function To(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&I(n)===t).map(([n])=>n)}async function lw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r=await A(i),a=V(r.schema),o=re(i,a.files.types,Z.types),s=[],l=B(t.author,r.author_default),c=ce(r),d=await X(i,ln,r.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,r.locks.wait_ms),p;try{let m=await G(o),g;try{g=le(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=br(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=(p.definition?.name??e??"").trim();if(y.length>0){let _=await Qp(i,r,a,y);_>0&&s.push(`items_using_type:${_}`)}await Ce({pmRoot:i,filePath:o,raw:ue(p.file),op:"schema:remove-type",author:l,settings:r}),s.push(...await H({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return p.removed&&await Ao(i,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:o,definitions:p.file.definitions.length},warnings:Pe(s),generated_at:T()}}function mi(e,t){return re(e,t.files.statuses,Z.statuses)}function dn(e,t){return re(e,t.files.fields,Z.fields)}function Oo(e,t){return re(e,t.files.types,Z.types)}async function $t(e,t,n,i){for(let r of t){let a=Mi(r.folder??Fi(r.name)),o=Xp.join(e,a);await k(o)||(await Zp(o,{recursive:!0}),n.push(...await H({path:o,scope:"project",op:i})))}}function ui(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function nm(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function im(e){let t=new Map;for(let n of e){let i=I(n.id);if(i.length!==0){t.set(i,i);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let a=I(r);a.length>0&&!t.has(a)&&t.set(a,i)}}}return t}async function dw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r;try{r=ha({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let a=await A(i),o=V(a.schema),s=mi(i,o),l=ct(o);try{qn(r,l.alias_to_id)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let c=nm(l.by_id.get(r.id));if((r.roles??c?.roles??[]).length===0)throw new f(`Status "${r.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 "${Le(r.id)}" --role active`,`pm schema add-status "${Le(r.id)}" --role blocked`]});let d=[],p=B(t.author,a.author_default),m=ce(a),g=await X(i,$o,a.locks.ttl_seconds,p,!!t.force,m.force_required_for_stale_lock,a.locks.wait_ms),y;try{let _=await G(s),u;try{u=Qe(_)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=im(u.statuses);try{qn(r,w)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.USAGE)}y=ga(u,r,c),await Ce({pmRoot:i,filePath:s,raw:et(y.file),op:"schema:add-status",author:p,settings:a}),d.push(...await H({path:s,scope:"project",op:"schema:add-status"}))}finally{await g()}return{action:"add-status",registered:!0,replaced:y.replaced,status:y.definition,file:{path:s,statuses:y.file.statuses.length},warnings:Pe(d),generated_at:T()}}async function pw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r=await A(i),a=V(r.schema),o=mi(i,a),s=[],l=B(t.author,r.author_default),c=ce(r),d=await X(i,$o,r.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,r.locks.wait_ms),p;try{let m=await G(o),g;try{g=Qe(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=ya(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=I(p.definition?.id??e);await tm(s,i,r,a,y),await Ce({pmRoot:i,filePath:o,raw:et(p.file),op:"schema:remove-status",author:l,settings:r}),s.push(...await H({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:o,statuses:p.file.statuses.length},warnings:Pe(s),generated_at:T()}}function Co(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function rm(e,t,n){return{...Co(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function Po(e){return{id:e.id,source:Ge.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Ro(e,t,n){let i=e.toLowerCase();return n.has(i)?"extension":t.has(i)?"custom":"builtin"}function am(){let e=new Map,t=W();for(let n of t?.item_types??[]){let i=n.types;if(Array.isArray(i))for(let r of i){if(typeof r!="object"||r===null||Array.isArray(r))continue;let a=r.name;typeof a=="string"&&a.trim().length>0&&e.set(a.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function om(e){let t=ct(e),n=[],i=[];for(let r of t.definitions){let a=Po(r);a.source==="builtin"?n.push(a):i.push(a)}return{builtin:n,custom:i}}async function It(e){let t=N(process.cwd(),e.path);await be(t);let n=await A(t),i=V(n.schema),r=re(t,i.files.types,Z.types),a=mi(t,i),o=U(n,W()),s=am(),l=new Set((n.item_types?.definitions??[]).map(c=>c.name.trim().toLowerCase()).filter(c=>c.length>0&&!s.has(c)));return{pmRoot:t,typesPath:r,statusesPath:a,byType:o.by_type,customNames:l,extensionProvenance:s,schema:i}}async function mw(e){let t=await It(e),n=[],i=[],r=[];for(let s of Object.values(t.byType).sort((l,c)=>l.name.localeCompare(c.name))){let l=Ro(s.name,t.customNames,new Set(t.extensionProvenance.keys())),c=Co(s);l==="extension"?r.push(c):l==="custom"?i.push(c):n.push(c)}let a=om(t.schema),o=Lt(t.schema).definitions.map(ui);return{action:"list",builtin:n,custom:i,extension:r,counts:{builtin:n.length,custom:i.length,extension:r.length,total:n.length+i.length+r.length},statuses:{builtin:a.builtin,custom:a.custom,counts:{builtin:a.builtin.length,custom:a.custom.length,total:a.builtin.length+a.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:T()}}async function uw(e,t){let n=(e??"").trim();if(n.length===0)throw new f("Type name must not be empty.",h.USAGE);let i=await It(t),r=Object.values(i.byType).find(a=>a.name.toLowerCase()===n.toLowerCase()||a.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!r)throw new f(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Le(n)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:rm(r,Ro(r.name,i.customNames,new Set(i.extensionProvenance.keys())),i.extensionProvenance.get(r.name.toLowerCase())),file:{path:i.typesPath},generated_at:T()}}async function fw(e,t){let n=I(e);if(n.length===0)throw new f("Status id must not be empty.",h.USAGE);let i=await It(t),r=ct(i.schema),a=r.alias_to_id.get(n)??n,o=r.by_id.get(a);if(!o)throw new f(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Le(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Po(o),file:{path:i.statusesPath},generated_at:T()}}async function hw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r;try{r=ma({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}let a=await A(i),o=V(a.schema),s=dn(i,o),l=[],c=Gt(r.key);c&&l.push(`custom_field_mcp_input_collision:${c.field}:${c.property}:${c.owner}:use=${c.nested_path}`);let d=B(t.author,a.author_default),p=ce(a),m=await X(i,Io,a.locks.ttl_seconds,d,!!t.force,p.force_required_for_stale_lock,a.locks.wait_ms),g;try{let y=await G(s),_;try{_=Xe(y)}catch(u){throw new f(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}g=ua(_,r),await Ce({pmRoot:i,filePath:s,raw:Ze(g.file),op:"schema:add-field",author:d,settings:a}),l.push(...await H({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:g.replaced,field:g.definition,file:{path:s,fields:g.file.fields.length},warnings:Pe(l),generated_at:T()}}async function sm(e,t,n,i){let r=U(t,W());return(await je(e,t.item_format,r.type_to_folder,[],n)).filter(a=>{let o=a[i];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function gw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r=await A(i),a=V(r.schema),o=dn(i,a),s=[],l=B(t.author,r.author_default),c=ce(r),d=await X(i,Io,r.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,r.locks.wait_ms),p;try{let m=await G(o),g;try{g=Xe(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=fa(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=I(p.definition?.key??e),_=I(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(_.length>0){let u=await sm(i,r,a,_);u>0&&s.push(`items_using_field:${u}`)}await Ce({pmRoot:i,filePath:o,raw:Ze(p.file),op:"schema:remove-field",author:l,settings:r}),s.push(...await H({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:o,fields:p.file.fields.length},warnings:Pe(s),generated_at:T()}}async function yw(e){let t=await It(e),n=Lt(t.schema).definitions.map(ui);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:dn(t.pmRoot,t.schema)},generated_at:T()}}async function _w(e,t){let n=I(e);if(n.length===0)throw new f("Field key must not be empty.",h.USAGE);let i=await It(t),r=Lt(i.schema).by_key.get(n);if(!r)throw new f(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Le(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:ui(r),file:{path:dn(i.pmRoot,i.schema)},generated_at:T()}}async function ww(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r;try{let _=cn(e);if(_===void 0)throw new Error(`Type preset name is required. Allowed: ${St.join(", ")}.`);r=_}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let a=await A(i),o=V(a.schema),s=Oo(i,o),l=[],c=B(t.author,a.author_default),d=ce(a),p=[],m=[],g,y=await X(i,ln,a.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,a.locks.wait_ms);try{let _=await G(s),u;try{u=le(_)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=u;for(let v of Et(r)){let x=He(w,v);w=x.file,(x.replaced?m:p).push(x.definition.name)}g=w.definitions.length,await Ce({pmRoot:i,filePath:s,raw:ue(w),op:"schema:apply-preset",author:c,settings:a}),await $t(i,Et(r),l,"schema:apply-preset-folder"),l.push(...await H({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:r,registered:p,replaced:m,file:{path:s,definitions:g},warnings:Pe(l),generated_at:T()}}function cm(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new f("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function vw(e,t){let n=N(process.cwd(),t.path);await be(n);let i=await A(n),r=V(i.schema),a=Oo(n,r),o=cm(e.minCount),s=U(i,W()),l=(await je(n,i.item_format,s.type_to_folder,[],r)).map(v=>typeof v.title=="string"?v.title:""),c=Eo(l,{minCount:o}),d=[],p=[],m=[],g=[],y;if(!e.apply){let v;try{v=le(await G(a))}catch(x){throw new f(x instanceof Error?x.message:String(x),h.GENERIC_FAILURE)}return y=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:c,registered:p,replaced:m,skipped:g,file:{path:a,definitions:y},warnings:d,generated_at:T()}}let _=B(e.author,i.author_default),u=ce(i),w=await X(n,ln,i.locks.ttl_seconds,_,!!e.force,u.force_required_for_stale_lock,i.locks.wait_ms);try{let v=await G(a),x;try{x=le(v)}catch(O){throw new f(O instanceof Error?O.message:String(O),h.GENERIC_FAILURE)}let S=x;for(let O of c){if(O.shadows_builtin){g.push({name:O.name,reason:"shadows_builtin"});continue}let oe;try{oe=lt({name:O.name})}catch{g.push({name:O.name,reason:"invalid_type_token"});continue}let L=He(S,oe);S=L.file,(L.replaced?m:p).push(L.definition.name)}y=S.definitions.length,await Ce({pmRoot:n,filePath:a,raw:ue(S),op:"schema:infer-types",author:_,settings:i}),await $t(n,S.definitions.filter(O=>p.includes(O.name)||m.includes(O.name)),d,"schema:infer-types-folder"),d.push(...await H({path:a,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:o,candidates:c,registered:p,replaced:m,skipped:g,file:{path:a,definitions:y},warnings:Pe(d),generated_at:T()}}function bw(e){let t=e.replaced?"Updated":"Registered",n=e.type.aliases&&e.type.aliases.length>0?` (aliases: ${e.type.aliases.join(", ")})`:"";return`${t} custom item type "${e.type.name}"${n} in ${e.file.path}. Run: pm create "${Le(e.type.name)}" "<title>"`}function kw(e){return e.removed?`Removed custom item type "${e.type?.name??"(unknown)"}" from ${e.file.path}.`:`No custom item type matched; nothing removed from ${e.file.path}.`}function xw(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",i=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${i} in ${e.file.path}.`}function Sw(e){return e.removed?`Removed custom status "${e.status?.id??"(unknown)"}" from ${e.file.path}.`:`No custom status matched; nothing removed from ${e.file.path}.`}function Ew(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,i]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])i.length!==0&&t.push(`${n}: ${i.map(r=>r.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,i]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])i.length!==0&&t.push(`${n}: ${i.map(r=>r.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(n=>`${n.key} (${n.type}, ${n.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
|
|
44
|
-
`)}function
|
|
45
|
-
`)}function
|
|
46
|
-
`)}function
|
|
47
|
-
`)}function
|
|
48
|
-
`)}function
|
|
49
|
-
`)}var Nw={workflowSlotsReferencing:To};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e6087f2-01b5-59c3-a471-433c722316b0")}catch{}})();function fi(e){return e.map(({layer:t,name:n,error:i})=>({layer:t,name:n,error:i}))}function pn(e,t,n){let i=b(t),r=n.trim();if(i.length===0||r.length===0)return;let a=e.get(i)??new Set;a.add(r),e.set(i,a)}function dm(e){let t=new Map,n=new Map;for(let i of e.registrations.commands)pn(t,i.name,i.command),pn(n,i.name,i.action);for(let i of e.commands.handlers)pn(t,i.name,i.command);for(let i of e.commands.overrides)pn(t,i.name,i.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function No(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function pm(e){let{enabled:t,normalizedName:n,loadedNames:i,loadFailedNames:r,activationFailedNames:a}=e;return t?r.has(n)||a.has(n)?{runtime_active:!1,activation_status:"failed"}:i.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function mn(e,t,n){let i=new Set(t.loaded.map(l=>b(l.name))),r=new Set(t.failed.map(l=>b(l.name))),a=new Set(n.failed.map(l=>b(l.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=dm(n);return e.map(l=>{let c=b(l.name),d=No(o.get(c)),p=No(s.get(c)),m={...d?{command_paths:d}:{},...p?{action_paths:p}:{}},g=pm({enabled:l.enabled,normalizedName:c,loadedNames:i,loadFailedNames:r,activationFailedNames:a});return{...l,...g,...m}})}function mm(e){let t=0,n=0,i=0;for(let r of e)if(r.startsWith("extension_policy_")){if(t+=1,r.startsWith("extension_policy_violation_")){n+=1;continue}r.startsWith("extension_policy_blocked_")&&(i+=1)}return{warning_count:t,violation_count:n,blocked_count:i}}function z(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Lo=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function um(e){return Lo.has(Jo(e))}function Do(e){return e==="project"||e==="global"}function Fo(e){let t=e.split(":"),n=t[0];if(!n||!Lo.has(n))return null;let i=t.at(-4),r=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!Do(i)||!Do(a)||!r||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:i,name:r},displaced:{layer:a,name:o}}}function fm(e){let t=new Set;for(let n of e){let i=Fo(n);i&&(t.add(i.winner.name),t.add(i.displaced.name))}return[...t].sort((n,i)=>n.localeCompare(i))}function hm(e,t){let n=e.filter(um);if(n.length===0)return null;let i=fm(n);return`Extension registration collisions or handler/override overlaps detected.${i.length>0?` Conflicting extensions: ${i.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function gm(e,t,n,i){let r=t.map(p=>Fo(p)).filter(p=>p!==null).sort((p,m)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(r.length===0)return;let a=e==="global"?"--global":"--project",o=z(i,"deactivate"),s=`${z(i,"doctor")} ${a} --detail deep --trace`,l=new Map(n.map(p=>[b(p.name),p])),c=new Map;for(let p of r)for(let m of[p.winner.name,p.displaced.name]){let g=b(m);c.set(g,(c.get(g)??0)+1)}let d=[...c.entries()].map(([p,m])=>{let g=l.get(p),y=g?.name??p,_=g?.command_paths??[],u=g?.action_paths??[];return{action:"deactivate",extension:y,command:`${o} ${y} ${a}`,affected_collisions:m,feature_loss:{command_paths:[..._].sort((w,v)=>w.localeCompare(v)),action_paths:[...u].sort((w,v)=>w.localeCompare(v))}}}).sort((p,m)=>{let g=m.affected_collisions-p.affected_collisions;if(g!==0)return g;let y=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,_=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return y!==_?y-_:p.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:r.length,extension_count:c.size,next_best_command:s,collisions:r,remediation_candidates:d}}function Mo(e){let t=[];for(let n of e){let i=n.error.toLowerCase();(i.includes("cannot find package '@unbrained/pm-cli'")||i.includes('cannot find module "@unbrained/pm-cli"')||i.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(i.includes("cannot use import statement outside a module")||i.includes("to load an es module")||i.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}function Go(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let i of t){if(!i||typeof i.name!="string")continue;let r=i.trace?.missing_capability??i.trace?.capability;typeof r=="string"&&r.trim().length>0&&n.push(`extension_capability_missing:${i.name}:${r.trim().toLowerCase()}`)}return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}function Uo(e,t){let n=[];for(let i of Qi(e.loaded,t))for(let r of i.unused)n.push(`extension_capability_unused:${i.layer}:${i.name}:${r}`);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}var ym=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${z(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${Di.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${z(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${z(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${z(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function _m(e){let{normalizedWarnings:t,options:n,scope:i,scopeFlag:r,updateCheckFailedTotal:a,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:l,skippedNonGithubTotal:c,updateAvailableTotal:d}=e,p=[],m={options:n,scope:i,scopeFlag:r,updateCheckFailedTotal:a,policyWarningCount:o};if(t.length>0){let g=hm(t,{deactivate:`${z(n,"deactivate")} <name> ${r}`,doctor:`${z(n,"doctor")} ${r} --detail deep --trace`});g&&p.push(g);for(let y of ym)y.matches(t,m)&&p.push(y.build(m))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${z(n,"manage")} ${r} --fix-managed-state (or ${z(n,"adopt-all")} ${r}, ${z(n,"adopt")} <name> ${r}, or reinstall via ${z(n,"install")} ${r} <source>).`),c>0&&p.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),l>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${z(n,"manage")} ${r} to request update checks.`),d>0&&p.push(`Update available managed extensions via ${z(n,"install")} ${r} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${z(n,"manage")} ${r} after extension changes.`),p}function un(e,t,n,i={}){let r=[...new Set(t)].sort((E,q)=>E.localeCompare(q)),a=n.filter(E=>E.managed).length,o=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,l=n.filter(E=>E.update_check_status==="checked"&&E.update_available===!0).length,c=n.filter(E=>E.managed===!1),d=c.filter(E=>jo(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),p=c.filter(E=>!jo(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)m[E.update_check_status]+=1;let g=m.failed,y=n.filter(E=>E.update_check_status==="skipped_non_github"&&E.source?.kind!=="builtin").length,_=Object.entries({skipped_unmanaged:p.length,skipped_non_github:y,failed:g,not_checked:m.not_checked}).filter(([,E])=>E>0).map(([E,q])=>`extension_update_health_partial_coverage:${E}:${q}`),u=_.length>0,w=u?"partial":"full",v=[...new Set([...r,..._])].sort((E,q)=>E.localeCompare(q)),x=[...new Set(v.map(E=>Jo(E)))].sort((E,q)=>E.localeCompare(q)),S=mm(v),O=e==="global"?"--global":"--project",oe=gm(e,r,n,i),L=_m({normalizedWarnings:v,options:i,scope:e,scopeFlag:O,updateCheckFailedTotal:g,policyWarningCount:S.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:y,updateAvailableTotal:l});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:x,warnings:v,policy_warning_count:S.warning_count,policy_violation_count:S.violation_count,policy_blocked_count:S.blocked_count,total_extensions:n.length,managed_total:a,enabled_total:o,active_total:s,update_available_total:l,update_health_coverage:w,update_health_partial:u,unmanaged_loaded_extension_count:c.length,unmanaged_loaded_extensions:c.map(E=>E.name).sort((E,q)=>E.localeCompare(q)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:m,update_check_failed_total:g,top_warnings:v.slice(0,8),remediation:L,...oe?{collision_plan:oe}:{}}}function zo(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new f(`Invalid --detail value "${e}". Expected summary or deep.`,h.USAGE)}function Jo(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function qo(e){let t=new Set,n=[];for(let i of e){let r=(()=>{let a=Bi(i);return a?[a]:Hi(i)})();for(let a of r){let o=`${a.layer}:${a.name}:${a.capability}`;t.has(o)||(t.add(o),n.push(a))}}return n}function Wo(){return{version:Pt.version,capabilities:[...Pt.capabilities],legacy_aliases:{...Pt.legacy_aliases}}}function jo(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Bo(e,t,n,i,r){if(e!=="project"||r)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let a=[...new Set(t.filter(c=>c.active).map(c=>b(c.name)))].sort((c,d)=>c.localeCompare(d)),o=[...new Set(n.filter(c=>c.layer==="project").map(c=>b(c.name)))].sort((c,d)=>c.localeCompare(d)),s=new Set(i.map(c=>b(c.name))),l=a.filter(c=>!o.includes(c)&&!s.has(c)).sort((c,d)=>c.localeCompare(d));return{warnings:l.length>0?[`extension_doctor_consistency_active_not_loaded:${l.join(",")}`]:[],summary:{active_project_count:a.length,loaded_project_count:o.length,active_project_names:a,loaded_project_names:o,missing_active_project_names:l}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var hi=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let i=new Array(e.length),r=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let o=r;r+=1,i[o]=await n(e[o])}});return await Promise.all(a),i};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function Ho(e,t){let n=b(e),i=t.find(r=>b(r.name)===n);return{command_paths:[...i?.command_paths??[]].sort((r,a)=>r.localeCompare(a)),action_paths:[...i?.action_paths??[]].sort((r,a)=>r.localeCompare(a))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function Ko(e,t){let n=new Set((t?.loaded??[]).flatMap(a=>(a.activation?.commands?.length??0)>0?[`${a.layer}:${b(a.name)}`]:[])),i=e.services.overrides.filter(a=>a.service==="output_format").filter(a=>a.passThrough!==!0).filter(a=>!n.has(`${a.layer}:${b(a.name)}`)).map(a=>`extension_output_service_override_global:${a.service}:${a.layer}:${a.name}`),r=e.renderers.overrides.filter(a=>(a.commands?.length??0)===0&&a.resultDiscriminator===void 0).map(a=>`extension_output_renderer_override_global:${a.format}:${a.layer}:${a.name}`);return[...new Set([...i,...r])].sort((a,o)=>a.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var Vo=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Gt(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,i)=>i.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{execFile as wm}from"node:child_process";import{promisify as vm}from"node:util";import bm from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b67e46f9-51ff-501b-98da-74353b4c66d9")}catch{}})();var km=vm(wm),Xo=1e4;function Yo(e,t,n){if(typeof t=="string")try{let i=bm.resolve(e,t);if(i.type==="version")return i.fetchSpec}catch{}throw new Error(n)}async function xm(e,t){try{return(await km(ri(),e,{encoding:"utf8",timeout:t,maxBuffer:65536,shell:ai(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function Zo(e,t=xm){let n=T();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let i=Yo(e.package,e.version,"missing_or_invalid_installed_npm_version"),r=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],Xo),a;try{a=JSON.parse(r)}catch{throw new Error("invalid_npm_registry_metadata")}let o=Array.isArray(a)&&a.length===1?a[0]:a,s=Yo(e.package,o,"invalid_npm_registry_version");return{checked_at:n,available:s!==i,remote_version:s}}catch(i){return{checked_at:n,available:null,error:i instanceof Error?i.message:String(i)}}}var Sm=(e,t,n)=>{let i=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,l=""]=o.split(/\s+/);return{commit:s,ref:l}}),r=i.find(o=>o.ref.endsWith("^{}"))??i[0];if(!r)return{checked_at:n,available:null,error:"no_remote_reference_found"};let a=t?.trim();return a?{checked_at:n,remote_commit:r.commit,available:r.commit!==a}:{checked_at:n,remote_commit:r.commit,available:null,error:"missing_installed_commit"}},gi=async(e,t=en)=>{let n=T();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let i=[e.ref?.trim(),"HEAD"].find(Boolean),r=await t(["ls-remote",e.repository,i,`${i}^{}`],void 0,Xo);return Sm(r,e.commit,n)}catch(i){return{checked_at:n,available:null,error:i instanceof Error?i.message:String(i)}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d34e2cc0-5e58-5534-8480-a9ab47ec4a88")}catch{}})();var Em=4;async function Qo(e,t=!1){let n=await hi(e.entries,Em,async i=>{if(!["github","npm"].includes(i.source.kind))return i;if(t)return{...i,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0};let r=i.source.kind==="github"?await gi(i.source):await Zo(i.source);return{...i,last_update_check_at:r.checked_at,last_update_remote_commit:"remote_commit"in r?r.remote_commit:void 0,last_update_remote_version:"remote_version"in r?r.remote_version:void 0,update_available:r.available,update_error:r.error}});return{...e,entries:gt(n)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fcf7df06-e3b8-5476-a76a-cd391839c13d")}catch{}})();function es(e,t){let n=e.filter(i=>i.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:i,result:r})=>{let a=r.details;return{alias:i,ok:r.ok,extension:a.extension,source:a.source,source_resolution:a.source_resolution,install_plan:a.install_plan,dry_run:a.dry_run,destination_path:a.destination_path,activated:a.activated,settings_changed:a.settings_changed,command_paths:a.command_paths,action_paths:a.action_paths,command_discovery:a.command_discovery,verification:a.verification,runtime_activation_status:a.runtime_activation_status,activation_diagnostics:a.activation_diagnostics,warnings:r.warnings}})}}import $m from"node:fs/promises";import Im from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function Am(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Tm(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function Om(e){let t=Im.join(e,"manifest.json"),n;try{n=await $m.readFile(t,"utf8")}catch(s){if(Ct(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let i;try{i=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof i!="object"||i===null||Array.isArray(i))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let r=i,a=Vi(r),o=Am(r);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:a.findings,warnings:a.findings.map(s=>Tm(o,s)),remediation:a.findings.map(s=>s.message)}}function ts(e){return Om(Gi(e))}import qe from"node:fs/promises";import Cm from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="776854e4-6df4-507e-b21b-a4d320946642")}catch{}})();var yi=async e=>qe.readFile(e).catch(t=>{if(an(t,"ENOENT"))return null;throw t}),ns=async(e,t,n,i,r)=>De("extension_install_backup",async()=>{let a=ht(e),o=zi(t),[s,l]=await Promise.all([yi(a),yi(o)]);return i&&await qe.cp(n,r,{recursive:!0,force:!0}),{backupDirectory:r,destinationDirectory:n,destinationExists:i,managedStatePath:a,managedStateContents:s,settingsPath:o,settingsContents:l}}),is=async e=>De("extension_install_rollback",async()=>{await qe.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await qe.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await qe.rm(t,{force:!0}):(await qe.mkdir(Cm.dirname(t),{recursive:!0}),await qe.writeFile(t,n))});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="549164da-d760-52bc-9950-25dacf286775")}catch{}})();var ss=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],Pm=ss.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Rm={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},Nm="__pm_native_output",Dm=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],cs=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],jm=["disabled","require_trusted","require_provenance"],ls={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},Lm=e=>{let t=e??ls,n={};for(let i of Dm)n[i]=te(t[i]??[]);return n},Fm=(e,t)=>{for(let n of cs)t[n].length>0&&(e[n]=t[n]);return e},Mm=(e,t)=>{for(let n of jm)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Gm=e=>{let t={};for(let n of cs)t[n]=te(e[n]??[]);return t},Um=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Fm(Mm({name:t},e),Gm(e))},zm=e=>(e??[]).map(t=>Um(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Jm=e=>{let t=Object.assign({},ls,e??{}),n=Lm(e),i=zm(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:i}},ds=async(e,t)=>{let n=[t],i=await La(t);i&&n.push(i);let r=[...new Set(n.map(a=>b(a)).filter(a=>a.length>0))];for(let a of r){let o=e.find(l=>b(l.name)===a);if(o)return o;let s=e.find(l=>b(l.directory)===a);if(s)return s}},ps=(e,t)=>{let n=t.trim(),i=new Set(te(e.extensions.enabled));return new Set(te(e.extensions.disabled)).has(n)?!1:i.size===0?!0:i.has(n)},ms=(e,t)=>{let n=t.trim(),i=new Set(te(e.extensions.enabled)),r=new Set(te(e.extensions.disabled)),a=[...i],o=[...r];return r.delete(n),i.size>0&&i.add(n),e.extensions.enabled=[...i].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},qm=(e,t)=>{let n=t.trim(),i=new Set(te(e.extensions.enabled)),r=new Set(te(e.extensions.disabled)),a=[...i],o=[...r];return i.delete(n),r.add(n),e.extensions.enabled=[...i].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Wm=(e,t)=>{let n=t.trim(),i=new Set(te(e.extensions.enabled)),r=new Set(te(e.extensions.disabled)),a=[...i],o=[...r];return i.delete(n),r.delete(n),e.extensions.enabled=[...i].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Bm=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),i=ss.map(([r,a,o])=>({action:a,flag:o,distance:Wi(t,r,n)})).filter(r=>r.distance!==null).sort((r,a)=>r.distance-a.distance)[0];return i?{action:i.action,flag:i.flag}:null},Hm=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",i=Bm(e);if(!i)return new f(`One action flag is required. Use one of: ${Pm}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let r=`pm ${n} ${i.flag}`;return yr({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(us),retry_command:r,message_suffix:`. Did you mean "${i.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:r,reason:`nearest lifecycle action for "${e}"`}]})},Km=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],us={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Vm=e=>us[e]??null,Ym=(e,t)=>{let n=[...new Set(Km.filter(([i])=>t[i]===!0).map(([,i])=>i))];if(n.length===0){if(e===void 0)return"explore";let i=Vm(e.trim().toLowerCase());if(i)return i;throw Hm(e,t)}if(n.length>1)throw new f("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},Xm=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new f('Options "--project/--local" and "--global" are mutually exclusive.',h.USAGE);return n?"global":"project"},Zm=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],fs=e=>{for(let t of Zm){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},hs=(e,t,n,i)=>{let r=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:r.contributions,managed:!!n,source:r.source,update_available:r.update_available,last_update_check_at:r.last_update_check_at,last_update_remote_commit:r.last_update_remote_commit,last_update_remote_version:r.last_update_remote_version,update_error:r.update_error,update_check_status:i.status,update_check_reason:i.reason}},Qm=(e,t,n,i)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},i),a=i?ps(n,i.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:hs({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:a},t,i,fs(i))}},eu=async(e,t,n,i,r,a)=>{let o=ne.join(e,t),s=ne.join(o,"manifest.json"),l=a.get(b(t));if(!await k(s))return Qm(t,n,i,l);let c=Symbol("invalid-extension-manifest-json"),d=await Re.readFile(s,"utf8").then(g=>JSON.parse(g)).catch(()=>c);if(d===c)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Yn(d);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=r.get(b(p.name))??a.get(b(t));return{summary:hs({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:ps(i,p.name)},n,m,fs(m))}},ye=async(e,t,n,i)=>{if(!await k(e))return{extensions:[],warnings:[]};let r=(await Re.readdir(e,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name).sort((c,d)=>c.localeCompare(d)),a=new Map(i.entries.map(c=>[b(c.name),c])),o=new Map(i.entries.map(c=>[b(c.directory),c])),s=[],l=[];for(let c of r){let d=await eu(e,c,t,n,a,o);d.warning&&s.push(d.warning),d.summary&&l.push(d.summary)}return{extensions:l.sort((c,d)=>c.name.localeCompare(d.name)),warnings:s.sort((c,d)=>c.localeCompare(d))}},tu=Xi(),nu=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,iu=(e,t,n,i)=>{let r=n.command_paths.map(s=>`pm ${s} --help`),a=i?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...r]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return a&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:nu(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:r,next_steps:o,...a?{sdk_dependency_status:"missing"}:{}}},ru=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},gs=e=>e.map(t=>ru(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),ys=(e,t,n)=>{let i=b(e);return t.find(r=>(n===void 0||r.layer===n)&&b(r.name)===i)},au=(e,t,n,i)=>n.find(r=>r.scope===t&&b(r.name)===b(e))?.activation_status??(i?"failed":"unknown"),_s=(e,t,n,i,r)=>tu.enqueue(async()=>{let a=process.env.PM_CLI_PACKAGE_ROOT,o=await Re.mkdtemp(ne.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=me(import.meta.url,["../.."]);try{let s=await ke({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:r.noExtensions===!0,reload_token:xn(),cache_bust:!0,module_graph_snapshot_root:o}),l=await xe({...s}),c=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...gs(l.failed)],d=Object.fromEntries(s.loaded.map(p=>[b(p.name),qi(Ke(l,{extensionName:p.name}))]));return{installed:mn(i,s,l),warnings:[...s.warnings,...l.warnings],activation_failures:c,extensions_disabled:s.disabled_by_flag,item_type_registrations:l.registrations.item_types,contribution_inventories:d}}finally{await Re.rm(o,{recursive:!0,force:!0}),a===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=a}}),wi=async(e,t,n,i)=>{let r=n.filter(l=>!l.managed),a=[...r].sort((l,c)=>{let d=l.name.localeCompare(c.name);return d!==0?d:l.directory.localeCompare(c.directory)}),o=i,s=[];for(let l of a){let c=ne.join(e,l.directory),d=await rt(c),p=T(),m={kind:"local",input:l.name,location:c};o=yt(o,{name:d.manifest.name,directory:l.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:p,updated_at:p,source:m}),s.push({name:d.manifest.name,directory:l.directory,version:d.manifest.version,entry:d.manifest.entry,source:m})}return s.length>0&&await at(e,o),{state:o,adopted_entries:s,unmanaged_candidates:a,already_managed_count:n.length-r.length}},ou=(e,t)=>{let n=N(process.cwd(),t.path),i=Nt(n,process.cwd()),r=e==="global"?Ui(process.cwd()):n,a=e==="global"?i.global:i.project;return{pm_root:n,scope:e,settings_root:r,selected_root:a,roots:i}},fn=e=>{let t=[e.gh,e.github].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new f('Options "--gh" and "--github" must match when both are provided.',h.USAGE);return n[0]},su=e=>Rm[e],cu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",i=e==="install"?"source":"name",r=`${n} ${i}`,a=su(e),o=`<${i}>`,s=`pm ${n} ${a} ${o}`;throw new f(`Action "${e}" requires ${r} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${i} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${i} target`}]}})},hn=(e,t,n={})=>{let i=e?.trim();if(i)return i;if(t==="init")throw new f('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',h.USAGE);return cu(t,n)},lu=(e,t)=>{let n=new Set([...t.registrations.item_types.map(i=>({entry:i,count:i.types.length})),...t.registrations.item_fields.map(i=>({entry:i,count:i.fields.length}))].filter(({count:i})=>i>0).map(({entry:i})=>`${i.layer}:${b(i.name)}`));return e.loaded.filter(i=>(i.activation?.commands??[]).length>0).filter(i=>n.has(`${i.layer}:${b(i.name)}`)).map(i=>`extension_schema_narrow_activation:${i.layer}:${i.name}`).filter((i,r,a)=>a.indexOf(i)===r).sort((i,r)=>i.localeCompare(r))},du=(e,t)=>{let n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(i=>i.triggered&&!i.allowed);if(n)throw new f(n.message,h.USAGE)},pu=(e,t,n)=>{let i=String(e??"").trim().toLowerCase(),r=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:r?[]:["init","scaffold"]}[t]??[]).includes(i)?void 0:e},mu=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},uu=(e,t,n)=>{let i={ok:n,action:e.action,scope:e.scope,roots:mu(e),warnings:[...new Set(e.warnings)].sort((r,a)=>r.localeCompare(a)),details:t};return e.action==="doctor"&&Object.defineProperty(i,Nm,{value:!0,enumerable:!1,configurable:!1}),i},vi=async(e,t,n)=>{let i=Ym(e,t);du(i,t);let r=pu(e,i,t),a=Xm(t),o=ou(a,n),s={action:i,normalizedTarget:r,scope:a,resolvedRoots:o,warnings:[],options:t,global:n},l={...s,withResult:(c,d=!0)=>uu(s,c,d)};return await Bu(l)},fu=(e,t)=>{let n=t.vocabulary??"extension",i=e.target_path.replace(/\\/g,"/"),r=er(i),a={package:`Install dependencies: cd ${r}, then run "npm install"`,extension:`Install type-check dependencies: cd ${r}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${r}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${r}, 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."),[a[n],...s,`Install the scaffold: ${st(n==="package"?["install","--project",i]:["extension","--install","--project",i])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},hu=async e=>{let{action:t,normalizedTarget:n,options:i,withResult:r}=e;if([fn(i),i.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new f('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let a=hn(n,t,i),o=await ao(a,i.vocabulary??"extension",i.capability,i.declarative===!0);return r({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:fu(o,i)})},gu=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:i,options:r,global:a,withResult:o}=e;if(t!==void 0)throw new f('Action "reload" does not accept a target argument.',h.USAGE);let s=await A(n.settings_root),l=xn(),c=await ke({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:a.noExtensions,reload_token:l,cache_bust:!0});i.push(...c.warnings);let d=await xe(c);i.push(...d.warnings);let p={reload:{token:l,cache_bust:!0,watch:r.watch===!0},loaded_count:c.loaded.length,failed_count:c.failed.length,activated_count:Math.max(0,c.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:c.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:c.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return r.watch===!0&&i.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(p)},yu=async e=>{let{normalizedTarget:t,scope:n,options:i,global:r,withResult:a}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new f('Action "catalog" does not accept a package target.',h.USAGE);return a(await Fa(n,r,i))},_u=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),wu=e=>({kind:"local",input:e.input,location:e.absolute_path}),vu=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),bu=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),ku=(e,t,n,i)=>e?_u(e,t):n.kind==="local"?wu(n):n.kind==="npm"?vu(n,i):bu(n,i),xu=(e,t,n,i)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:i}:Ca(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:i}:{installed_at:i,updated_at:i},Su=async(e,t)=>{let{scope:n,resolvedRoots:i,warnings:r}=e,{validated:a,destinationDirectoryName:o}=t,s=await A(i.settings_root),l=await he(i.selected_root);r.push(...l.warnings);let c=ne.join(i.selected_root,o),d=await k(c),p=await rn(a.directory,c);await Re.mkdir(i.selected_root,{recursive:!0});let m=await Re.mkdtemp(ne.join(i.selected_root,".pm-extension-install-backup-")),g=ne.join(m,"destination");try{let y=await ns(i.selected_root,i.settings_root,c,d,g),_=ku(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),u=l.state.entries.find(S=>b(S.name)===b(a.manifest.name)),w=xu(u,a.manifest.version,_,T()),v=yt(l.state,{name:a.manifest.name,directory:o,scope:n,manifest_version:a.manifest.version,manifest_entry:a.manifest.entry,capabilities:[...a.manifest.capabilities],contributions:a.manifest.contributions,...w,source:_}),x=ms(s,a.manifest.name);try{p||await vo(a.directory,c),await yo(c),await _o(c),await at(i.selected_root,v),x&&await Ee(i.settings_root,s,"settings:write")}catch(S){try{await is(y)}catch(O){throw new AggregateError([S,O],`Extension install failed: ${String(S)}; rollback failed: ${String(O)}`,{cause:O})}throw S}return{settings:s,managedState:v,sourceRecord:_,destinationDirectory:c,destinationExists:d,installInPlace:p,activationChanged:x}}finally{await Re.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},Eu=async(e,t,n)=>{let i=n.filter(r=>b(r.name)===b(t)).flatMap(r=>r.types.map(a=>({name:a.name,folder:a.folder})));return e.scope==="project"&&i.length>0&&await $t(e.resolvedRoots.pm_root,i,e.warnings,"install:type-folder"),i},$u=(e,t,n,i,r)=>{let a=ys(t,n.activation_failures,e.scope),o=au(t,e.scope,n.installed,a),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let l={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:a,verification:{status:l[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:i.command_paths,registered_actions:i.action_paths,registered_item_types:r,module_graph_verification:"fresh_in_topology_snapshot",health:l[String(s)]}}},Iu=async(e,t)=>{let{scope:n,resolvedRoots:i,warnings:r,global:a,withResult:o}=e,{validated:s,destinationDirectoryName:l}=t,c=await Su(e,t),d=await ye(i.selected_root,n,c.settings,c.managedState);r.push(...d.warnings);let p=await _s(i.pm_root,ne.dirname(i.selected_root),c.settings,d.extensions,a);r.push(...p.warnings);let m=await Eu(e,s.manifest.name,p.item_type_registrations),g=Ho(s.manifest.name,p.installed),y=$u(e,s.manifest.name,p,g,m),_=p.contribution_inventories[b(s.manifest.name)];return _&&(c.managedState=await Pa(i.selected_root,c.managedState,s.manifest.name,_)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:l},source:c.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:c.destinationDirectory,overwritten:[c.destinationExists,!c.installInPlace].every(Boolean),installed_in_place:c.installInPlace,activated:y.activated,settings_changed:c.activationChanged,runtime_activation_status:y.status,command_paths:g.command_paths,action_paths:g.action_paths,contributions:_,command_discovery:iu(s.manifest.name,c.sourceRecord,g,y.failure),verification:y.verification,activation_diagnostics:{failed_count:p.activation_failures.length,failed:p.activation_failures,installed_extension_failed:y.failure??null}},y.activated)},Au=async e=>{let{options:t,global:n,warnings:i,withResult:r}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new f('Action "install all" does not accept --ref.',h.USAGE);let a=[],o=new Map;for(let s of await Qt()){let l=await _t(s),c=ne.resolve(l),d=o.get(c);d===void 0&&(d=await vi(s,{...t,install:!0},n),o.set(c,d)),a.push({alias:s,result:d})}return i.push(...a.flatMap(s=>s.result.warnings)),r(es(a,t.dryRun===!0),a.every(s=>s.result.ok))},Tu=async(e,t,n)=>{let{resolvedRoots:i}=e,{bundledAliasName:r,bundledPackageName:a,installSource:o,sourceResolution:s}=await So(t,n,e.options.ref,(await he(i.selected_root)).state.entries);if(s.ambiguous){let c=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${r}:npm:${c.package}`)}let l=await Ha(o);try{let c=await rt(l.directory,{source_kind:o.kind,source_input:o.input,source_root:l.source_root}),d=Xt(c.manifest.name),p=e.options.dryRun===!0||o.kind==="local"&&r===null?await ko(l,ne.join(i.selected_root,d),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:c.manifest.name,version:c.manifest.version},source_resolution:s,install_plan:p}):await pi(i.settings_root,d,()=>Iu(e,{validated:c,destinationDirectoryName:d,bundledAliasName:r,bundledPackageName:a,sourceResolution:s,installSource:o,resolvedSource:l,installPlan:p}))}finally{l.cleanup&&await l.cleanup()}},Ou=async e=>{let t=fn(e.options),n=t??hn(e.normalizedTarget,e.action,e.options);return[t===void 0,Na(n)].every(Boolean)?Au(e):Tu(e,n,t)},Cu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,withResult:o}=e;if(t!==void 0)throw new f('Action "adopt-all" does not accept a target argument.',h.USAGE);if(fn(a)!==void 0||typeof a.ref=="string"&&a.ref.trim().length>0)throw new f('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let s=await A(i.settings_root),l=await he(i.selected_root);r.push(...l.warnings);let c=await ye(i.selected_root,n,s,l.state);r.push(...c.warnings);let d=await wi(i.selected_root,n,c.extensions,l.state),p=await ye(i.selected_root,n,s,d.state);r.push(...p.warnings);let m=un(n,r,p.extensions,a);r.push(...m.warnings);let g=new Map(p.extensions.map(u=>[`${b(u.name)}:${b(u.directory)}`,u])),y=new Map(p.extensions.map(u=>[b(u.directory),u])),_=d.adopted_entries.map(u=>{let w=b(u.directory),v=g.get(`${b(u.name)}:${w}`)??y.get(w);return{...u,...ws(v)}});return o({adopted_all:_.length>0,adopted_count:_.length,already_managed_count:d.already_managed_count,extensions:_,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},ws=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Pu=(e,t,n,i)=>{if(e===void 0)return{kind:"local",input:t,location:n};let r=wt(e,{forceGithub:!0,ref:i});if(r.kind!=="github")throw new f(`Invalid GitHub shorthand "${e}".`,h.USAGE);return{kind:"github",input:r.input,location:r.subpath??".",repository:r.repository,owner:r.owner,repo:r.repo,ref:r.ref,subpath:r.subpath}},Ru=async e=>{let{action:t,normalizedTarget:n,scope:i,resolvedRoots:r,warnings:a,options:o,withResult:s}=e,l=hn(n,t,o),c=fn(o),d=await A(r.settings_root),p=await he(r.selected_root);a.push(...p.warnings);let m=await ye(r.selected_root,i,d,p.state);a.push(...m.warnings);let g=await ds(m.extensions,l);if(!g)throw new f(`Installed extension "${l}" was not found in ${i} scope.`,h.NOT_FOUND);if(g.managed)return s({adopted:!1,already_managed:!0,extension:{name:g.name,directory:g.directory}});let y=ne.join(r.selected_root,g.directory),_=await rt(y),u=T(),w=Pu(c,l,y,o.ref),v=yt(p.state,{name:_.manifest.name,directory:g.directory,scope:i,manifest_version:_.manifest.version,manifest_entry:_.manifest.entry,capabilities:[..._.manifest.capabilities],contributions:_.manifest.contributions,installed_at:u,updated_at:u,source:w});await at(r.selected_root,v);let x=await ye(r.selected_root,i,d,v);a.push(...x.warnings);let S=x.extensions.find(O=>b(O.name)===b(_.manifest.name))??x.extensions.find(O=>b(O.directory)===b(g.directory));return s({adopted:!0,extension:{name:_.manifest.name,directory:g.directory,version:_.manifest.version,entry:_.manifest.entry},source:w,...ws(S)})},vs=async e=>{let{action:t,normalizedTarget:n,scope:i,resolvedRoots:r,warnings:a,options:o}=e,s=hn(n,t,o),l=await A(r.settings_root),c=await he(r.selected_root);a.push(...c.warnings);let d=await ye(r.selected_root,i,l,c.state);a.push(...d.warnings);let p=await ds(d.extensions,s);if(!p)throw new f(`Installed extension "${s}" was not found in ${i} scope.`,h.NOT_FOUND);return{settings:l,managedStateRead:c,candidate:p}},Nu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:i,managedStateRead:r,candidate:a}=await vs(e),o=ne.join(t.selected_root,a.directory);await Re.rm(o,{recursive:!0,force:!0});let s={...r.state,updated_at:T(),entries:r.state.entries.filter(c=>b(c.name)!==b(a.name)&&b(c.directory)!==b(a.directory))};await at(t.selected_root,s);let l=Wm(i,a.name);return l&&await Ee(t.settings_root,i,"settings:write"),n({removed:!0,extension:{name:a.name,directory:a.directory},destination_path:o,settings_changed:l})},rs=async e=>{let{action:t,resolvedRoots:n,warnings:i,global:r,withResult:a}=e,{settings:o,candidate:s}=await vs(e),l=t==="activate"?ms(o,s.name):qm(o,s.name);l&&await Ee(n.settings_root,o,"settings:write");let c=t==="activate"?await _s(n.pm_root,ne.dirname(n.selected_root),o,[s],r).then(d=>(i.push(...d.warnings),ys(s.name,d.activation_failures,e.scope))):void 0;return c&&i.push(`extension_activate_failed:${e.scope}:${s.name}`),a({extension:{name:s.name,directory:s.directory},active:t==="activate"&&c===void 0,runtime_active:t==="activate"&&c===void 0,activation_failure:c??null,settings_changed:l,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},c===void 0)},Du=(e,t,n,i,r,a)=>{let o=i==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],l=r?.adopted_entries.length??0,c=[[a!==null,a??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[l>0,`Managed-state fix adopted ${l} extension(s).`]];return[...new Set([...e,...c.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},_i=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),ju=(e,t,n,i)=>{if(e!=="project"||t||!_i(i))return null;let r=n==="package"?"package":"extension";return`Global ${r} registrations are included in project diagnostics. For hermetic ${r} smoke tests, rerun pm ${r} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Lu=(e,t,n)=>{if(String(e??"").trim().length>0)throw new f('Action "doctor" does not accept a target argument.',h.USAGE);let i=[n.isolated,n.ignoreGlobal].includes(!0);if([i,t==="global"].every(Boolean))throw new f("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let r=zo(n.detail),a=n.trace===!0;if([a,r!=="deep"].every(Boolean))throw new f("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:i,detailMode:r,includeTrace:a}},Fu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let i=await wi(e.resolvedRoots.selected_root,e.scope,t,n);return{state:i.state,fix:i}},Mu=(e,t,n,i)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:_i(i),rerun_command:null,pm_global_path_recipe:null};let a=`pm ${r} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:_i(i),rerun_command:t?null:a,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},Gu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,global:o,withResult:s}=e,{isolated:l,detailMode:c,includeTrace:d}=Lu(t,n,a),p=await A(i.settings_root),m=await he(i.selected_root);r.push(...m.warnings);let g=await ye(i.selected_root,n,p,m.state);r.push(...g.warnings);let{state:y,fix:_}=await Fu(e,g.extensions,m.state),u=await ye(i.selected_root,n,p,y);r.push(...u.warnings);let w=await ke({pmRoot:i.pm_root,settings:p,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:l}),v=await xe({...w,loaded:w.loaded}),x=await ts(i.pm_root);r.push(...x.warnings,...w.warnings),r.push(...Mo(w.failed)),r.push(...v.warnings),r.push(...Go(v.failed)),r.push(...Uo(w,v)),r.push(...Ko(v,w)),r.push(...lu(w,v)),r.push(...Vo(v));let S=mn(u.extensions,w,v),O=Bo(n,S,w.loaded.map(C=>({layer:C.layer,name:C.name})),w.failed.map(C=>({name:C.name})),w.disabled_by_flag);r.push(...O.warnings);let oe=S.filter(C=>C.update_check_status==="failed").map(C=>`extension_update_check_failed:${C.name}`);r.push(...oe);let L=un(n,r,S,a);r.push(...L.warnings);let E=[...L.warnings],q={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},ot=qo(E),yn=Wo(),Ci=L.warning_codes,ec=ju(n,l,a.vocabulary,w),tc=Du(L.remediation,w.failed.length,v.failed.length,a.vocabulary,_,ec),Pi=Mu(n,l,a.vocabulary,w),nc={status:L.status,scope:n,warning_count:L.warning_count,warning_codes:Ci,total_extensions:S.length,managed_total:S.filter(C=>C.managed).length,enabled_total:S.filter(C=>C.enabled).length,active_total:S.filter(C=>C.active).length,unmanaged_loaded_extension_count:L.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:L.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:L.unmanaged_expected_extension_count,runtime_active_total:S.filter(C=>C.runtime_active===!0).length,activation_status_totals:{ok:S.filter(C=>C.activation_status==="ok").length,failed:S.filter(C=>C.activation_status==="failed").length,not_loaded:S.filter(C=>C.activation_status==="not_loaded").length,unknown:S.filter(C=>C.activation_status==="unknown").length},unknown_capability_count:ot.length,capability_contract_version:yn.version,update_available_total:L.update_available_total,update_check_status_totals:L.update_check_status_totals,update_health_coverage:L.update_health_coverage,update_health_partial:L.update_health_partial,update_check_failed_total:S.filter(C=>C.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:fi(w.failed),activation_failures:fi(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:O.warnings.length,trace_enabled:d,isolation:Pi,policy:q,remediation:tc},ic=_?{requested:!0,applied:_.adopted_entries.length>0,adopted_count:_.adopted_entries.length,already_managed_count:_.already_managed_count,adopted_extensions:_.adopted_entries.map(C=>C.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:u.extensions.filter(C=>C.managed).length,adopted_extensions:[]},_n={mode:c,summary:nc,triage:L,trace_enabled:d,capability_contract:yn,capability_guidance:ot,managed_state_fix:ic,author_manifest:x,isolation:Pi,policy:w.policy};if(c==="deep"){let C=d?v.failed:v.failed.map(D=>{let{trace:Cf,...rc}=D;return rc});_n.deep={warnings:E,warning_codes:Ci,capability_contract:yn,capability_guidance:ot,trace_enabled:d,managed_state:{path:m.path,count:y.entries.length,entries:y.entries},installed_extensions:S,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(D=>({layer:D.layer,directory:D.directory,name:D.name,version:D.version,entry:D.entry,priority:D.priority}))},activation:{failed:C,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:O.summary},d&&(_n.deep.trace={activation_failures:v.failed.filter(D=>D.trace!==void 0).map(D=>({layer:D.layer,name:D.name,entry_path:D.entry_path,error:D.error,method:D.trace.method,command:D.trace.command,capability:D.trace.capability,missing_capability:D.trace.missing_capability,registration_index:D.trace.registration_index,expected_schema:D.trace.expected_schema,hint:D.trace.hint,received:D.trace.received}))})}return s(_n)},Uu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,global:o,withResult:s}=e,l=await A(i.settings_root),c=await ke({pmRoot:i.pm_root,settings:l,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),d=await xe(c);r.push(...c.warnings),r.push(...d.warnings);let p=lo(t,c,d);if(t!==void 0&&p.extensions.length===0){let m=a.vocabulary==="package"?"package":"extension",g=[...new Set(c.loaded.map(_=>a.vocabulary==="package"&&typeof _.source_package=="string"&&_.source_package.trim().length>0?_.source_package.trim():_.name))].sort((_,u)=>_.localeCompare(u)),y=g.length>0?` Loaded ${m} names: ${g.join(", ")}.`:"";throw new f(`No loaded ${m} named "${t}" was found in ${n} scope.${y} Run pm ${m} explore to list discovered ${m}s.`,h.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},zu=async(e,t,n)=>{let i=n,r=null;return[e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await wi(e.resolvedRoots.selected_root,e.scope,t,n),i=r.state),e.action==="manage"&&(i=await Qo(i,e.options.offline)),{state:i,fix:r}},Ju=async(e,t,n)=>{let i=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await xe({...i,loaded:i.loaded});return e.warnings.push(...i.warnings,...r.warnings),{installed:mn(n,i,r),failures:gs(r.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:i.failed.length,activation_failure_count:r.failed.length,warning_count:[...new Set([...i.warnings,...r.warnings])].length,policy:i.policy}}},qu=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},as=async e=>{let{action:t,scope:n,resolvedRoots:i,warnings:r,options:a,withResult:o}=e,s=await A(i.settings_root),l=Jm(s.extensions.policy),c=await he(i.selected_root);r.push(...c.warnings);let d=await ye(i.selected_root,n,s,c.state);r.push(...d.warnings);let{state:p,fix:m}=await zu(e,d.extensions,c.state),g=await ye(i.selected_root,n,s,p);if(r.push(...g.warnings),t==="manage"&&a.offline===!0)for(let v of g.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=g.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);r.push(...v)}let y=await Ju(e,s,g.extensions),_=y.installed,u=un(n,r,_,a);r.push(...u.warnings);let w={total:_.length,managed_total:_.filter(v=>v.managed).length,enabled_total:_.filter(v=>v.enabled).length,active_total:_.filter(v=>v.active).length,extensions:_,triage:u,policy:l};return y.failures!==void 0&&(w.activation_diagnostics={failed_count:y.failures.length,failed:y.failures}),t==="explore"&&(w.runtime_probe=y.summary),t==="manage"&&(w.runtime_probe=y.summary,w.managed_state_fix=qu(m,_)),o(w)},os={init:hu,install:Ou,uninstall:Nu,explore:as,manage:as,describe:Uu,reload:gu,doctor:Gu,catalog:yu,adopt:Ru,"adopt-all":Cu,activate:rs,deactivate:rs,migrate:Nr},Wu=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Bu=e=>Wu(e)?pi(e.resolvedRoots.settings_root,`${e.action}-state`,()=>os[e.action](e)):os[e.action](e);import xi from"node:fs/promises";import J from"node:path";import bs from"node:readline/promises";import{stdin as ks,stdout as At}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a0706e-7162-5cde-9f48-c5de9b2fbd8e")}catch{}})();var xs=["ask","add","skip","status"],Hu=["AGENTS.md","CLAUDE.md"],Ku=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Vu=8,Si=1,Yu="<!-- pm-cli:agent-guidance:start:",Xu=`<!-- pm-cli:agent-guidance:start:v${Si} -->`,bi="<!-- pm-cli:agent-guidance:end -->",Ot="Add workflow guidance later: pm init --agent-guidance add",db={toPortableRelativePath:We,ensureTrailingNewline:ki,detectLineEnding:Es,findGuidanceBlockRange:Ei,buildAgentGuidanceBlock:$s,upsertAgentGuidanceBlock:$i,resolveProjectRoot:As,resolveTargetGuidancePath:Ts,parsePromptChoice:Os,pushUnique:Ne,promptForGuidanceWrite:Cs,normalizeAgentGuidanceState:Ii,applyAgentGuidanceState:Rs,writeGuidanceFile:Ai,setAgentGuidanceReadlineFactoryForTests:Zu},Ss=()=>bs.createInterface({input:ks,output:At});function Zu(e){Ss=e??(()=>bs.createInterface({input:ks,output:At}))}function We(e,t){let n=J.relative(e,t);return n.length===0?J.basename(t):n.split(J.sep).join("/")}function ki(e){return e.endsWith(`
|
|
42
|
+
`}import sn from"node:fs/promises";import on from"node:path";import mo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function kt(e,t,n,i){let r=mo.relative(e,n);if(r!==""&&!K(e,n)||n===t||K(t,n))return!1;let a=r.split(mo.sep);return a.includes(".git")?!1:i?!a.some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as Dp}from"node:crypto";import M from"node:fs/promises";import jp from"node:os";import j from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var uo=3,Lp=120,fo=250,Fp=12e4,Mp=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),ho=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,go=e=>Mp.has(String(ho(e))),an=(e,t)=>ho(e)===t,yo=e=>new Promise(t=>{setTimeout(t,e)}),_o=async e=>{let t=j.join(e,"package.json");await k(t)||await M.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
43
|
+
`,"utf8")},wo=async e=>{let t=pe(import.meta.url,["../../.."]),n=j.join(e,"node_modules","@unbrained"),i=j.join(n,"pm-cli");await M.mkdir(n,{recursive:!0}),await M.rm(i,{recursive:!0,force:!0}),await M.symlink(t,i,process.platform==="win32"?"junction":"dir")},xt=async e=>{let t=j.resolve(e),n=j.dirname(t),i=j.parse(n).root,r=await M.realpath(i).catch(()=>i),a=j.relative(i,n),o=a===""?[]:a.split(j.sep);for(let[s,l]of o.entries()){let c=j.join(r,l);try{r=await M.realpath(c)}catch{r=j.join(r,...o.slice(s));break}}return j.join(r,j.basename(t))},vo=async(e,t,n,i=jp.tmpdir())=>De("extension_install_copy",async()=>{let r=j.resolve(e),a=await M.realpath(r).catch(()=>r),o=await xt(t);if(a===o)return;if(!K(a,o)){await n(a,t,{recursive:!0,force:!0,filter:p=>kt(a,o,j.resolve(p),!1)});return}let s=await M.realpath(j.resolve(i)).catch(()=>xt(i)),l=K(a,s)?j.dirname(a):s;if(K(a,l))throw new f(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,h.USAGE,{code:"extension_install_source_contains_destination"});let c=await M.mkdtemp(j.join(l,"pm-extension-copy-")),d=j.join(c,"extension");try{await n(a,d,{recursive:!0,force:!0,filter:p=>kt(a,o,j.resolve(p),!0)}),await n(d,t,{recursive:!0,force:!0})}finally{await M.rm(c,{recursive:!0,force:!0})}}),bo=async(e,t,n=M.cp)=>{for(let i=1;i<=uo;i+=1)try{await De("extension_install_copy",async()=>{await M.rm(t,{recursive:!0,force:!0}),await vo(e,t,n)});return}catch(r){if(!go(r)||i===uo)throw r;await yo(fo)}},pi=async e=>{let t;try{t=await M.readFile(j.join(e,"owner.json"),"utf8")}catch(r){if(!Pt(r))throw r;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let i=n.token;return typeof i=="string"&&i.length>0?i:null},ko=async(e,t)=>await pi(e)!==t?!1:(await M.rm(e,{recursive:!0,force:!0}),!0),Gp=async(e,t)=>{let n;try{n=await M.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let i=await pi(e);return i===null?(await M.rm(e,{recursive:!0,force:!0}),!0):ko(e,i)},Up=(e,t,n)=>{let i=Promise.resolve(),r=setInterval(()=>{i=i.then(async()=>{if(await pi(e)!==t)return;let a=new Date;await M.utimes(e,a,a)}).catch(()=>{})},n);return r.unref(),async()=>{clearInterval(r),await i}},zp=async(e,t)=>{await M.mkdir(e);try{await M.writeFile(j.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
44
|
+
`,"utf8")}catch(n){throw await M.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Jp=async(e,t,n,i,r)=>{for(let a=1;a<=n;a+=1)try{return await zp(e,t),!0}catch(o){if(!an(o,"EEXIST"))throw o;await Gp(e,r)?a-=1:await yo(i)}return!1},mi=async(e,t,n,i)=>De("extension_install",async()=>{let r=j.join(e,"runtime","extension-install-locks"),a=j.join(r,"scope.lock");await M.mkdir(r,{recursive:!0});let{attempts:o=Lp,delay_ms:s=fo,stale_ms:l=Fp,heartbeat_ms:c}=i??{};if(![o,s,l,c].filter(w=>w!==void 0).every(Number.isFinite))throw new f("Extension install lock timings must be finite numbers.",h.USAGE);let d=Math.max(1,Math.floor(o)),p=Math.max(0,Math.floor(s)),m=Math.floor(l),g=Math.floor(c??m/3);if(m<=0||g<=0||g>=m)throw new f("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",h.USAGE);let y={pid:process.pid,token:Dp(),created_at:T(),destination:t};if(!await Jp(a,y,d,p,m))throw new f(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let _=Up(a,y.token,g),u=!1;try{let w=await n();return u=!0,w}finally{await _(),await ko(a,y.token).catch(w=>{if(u)throw w})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var qp=new Set(["node_modules",".git","dist","build","coverage"]);async function xo(e,t,n,i){let r=e.source.kind==="local"?await sn.stat(e.source.absolute_path):void 0,a=e.source.kind==="local"?r.isDirectory()?"directory":"archive":e.source.kind,o=await Wp(e.directory,t,i),s={source_mode:a,...a==="archive"?{archive_bytes:r.size}:{},copy:o},l=e.source_root??e.directory;if(a==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await k(on.join(l,"package.json"))&&(s.packed_alternative={cwd:l,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),a==="directory"&&!o.complete){let c=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new f(`Local extension source scan stopped at ${c}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,h.USAGE,{code:"extension_install_incomplete_source_scan",reason:o.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function Wp(e,t,n={}){let{maxEntries:i=1e4,maxDepth:r=64,signal:a}=n;if(![i,r].every(p=>Number.isSafeInteger(p)&&p>0))throw new f("maxEntries and maxDepth must be positive safe integers.",h.USAGE);a?.throwIfAborted();let o=await sn.realpath(e),s=await xt(t),l=await rn(o,s);a?.throwIfAborted();let c=l?"in_place":K(o,s)?"nested_filtered_snapshot":"directory_snapshot",d={copy_scope:c,source_directory:o,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:i,max_depth:r};return c==="in_place"||await So(o,0,d,a),d}async function So(e,t,n,i){i?.throwIfAborted();let r=await sn.opendir(e);for await(let a of r){if(i?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=on.join(e,a.name);if(!kt(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(on.relative(n.source_directory,o).split(on.sep).some(s=>qp.has(s))&&(n.development_entries+=1),await Bp(o,t,n,i),!n.complete)return}}async function Bp(e,t,n,i){let r=await sn.lstat(e);if(i?.throwIfAborted(),r.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await So(e,t+1,n,i)}else r.isFile()?(n.files+=1,n.bytes+=r.size):r.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import Hp from"node:fs/promises";import Kp from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bef4424-f5b8-511b-91f7-0b39cf11f515")}catch{}})();async function Vp(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 Hp.lstat(e.absolute_path),e}catch(a){if(!ie(a))throw a}let n=e.input.trim(),i=t.filter(a=>a.source.kind==="npm"),r=(i.find(a=>a.name===n)??i.find(a=>a.directory===n)??i.find(a=>a.source.package===n))?.source.package;if(r===void 0)return e;try{let a=Kp(r);if(!a.registry||a.name!==r)return e}catch{return e}return wt(`npm:${r}`,{})}async function Eo(e,t,n,i=[]){let r=typeof t=="string"?null:await _t(e),a=r===null?null:e.trim().toLowerCase(),o=a===null?null:await La(a),s=await Vp(wt(r??e,{forceGithub:typeof t=="string",ref:n}),i),l=a===null?null:await za(e);return{bundledAliasName:a,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:a===null?s.kind:"builtin",input:a??s.input,...o===null?{}:{package:o}},ambiguous:l!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...a===null?[]:[{kind:"builtin",input:a,...o===null?{}:{package:o},command:`pm install ${a}`}],...l===null?[]:[{kind:"npm",input:`npm:${l.package}`,package:l.package,...l.version===void 0?{}:{version:l.version},directory:l.directory,command:`pm install npm:${l.package}`}]]}}}import Re from"node:fs/promises";import ne from"node:path";import em from"node:path";import{mkdir as tm}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="abb182c9-6d6c-5be4-a2ad-c91b00a098d0")}catch{}})();var St=["agile","ops","research"],Yp={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function cn(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${St.join(", ")}.`)}function Et(e){return Yp[e].map(t=>lt(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var Xp=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Zp(e){let t=Xp.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Qp(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function $o(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,i=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,r=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let l=Zp(s);if(l===void 0)continue;let c=r.get(l)??{count:0,examples:[]};c.count+=1,c.examples.length<i&&c.examples.push(s),r.set(l,c)}let a=[];for(let[o,s]of r.entries()){if(s.count<n)continue;let l=Qp(o);a.push({name:l,prefix:o,count:s.count,examples:s.examples,shadows_builtin:wr(l)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var lw=[...jt,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],ln="schema-types",Io="schema-statuses",Ao="schema-fields";function Ce(e){return He({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 mw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r;try{r=lt({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(g){throw new f(g instanceof Error?g.message:String(g),h.USAGE)}let a=await A(i),o=Y(a.schema),s=re(i,o.files.types,Z.types),l=[],c=B(t.author,a.author_default),d=se(a),p=await V(i,ln,a.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,a.locks.wait_ms),m;try{let g=await G(s),y;try{y=ce(g)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}try{vr(r,y);let _=new Map,u=U(a,W());for(let[w,v]of Object.entries(u.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!_.has(x)&&_.set(x,w)}br(r,y,_)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}m=Ke(y,r),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&l.push(`type_recased:${m.previousName}->${m.definition.name}`),await Ce({pmRoot:i,filePath:s,raw:me(m.file),op:"schema:add-type",author:c,settings:a}),await $t(i,[m.definition],l,"schema:add-type-folder"),l.push(...await H({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await To(i,l),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Pe(l),generated_at:T()}}async function be(e){await Se(e)}async function To(e,t){try{let n=await na(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Pe(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function nm(e,t,n,i){let r=U(t,W()),a=i.trim().toLowerCase();return(await je(e,t.item_format,r.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===a).length}async function im(e,t,n,i){let r=U(t,W()),a=ct(n),o=I(i);return(await je(e,t.item_format,r.type_to_folder,[],n)).filter(s=>{let l=typeof s.status=="string"?s.status:"";return(a.alias_to_id.get(I(l))??I(l))===o}).length}async function rm(e,t,n,i,r){if(r.length===0||Ue.has(r))return;let a=await im(t,n,i,r);a>0&&e.push(`items_using_status:${a}`);let o=Oo(i.workflow,r);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function Oo(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&I(n)===t).map(([n])=>n)}async function uw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r=await A(i),a=Y(r.schema),o=re(i,a.files.types,Z.types),s=[],l=B(t.author,r.author_default),c=se(r),d=await V(i,ln,r.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,r.locks.wait_ms),p;try{let m=await G(o),g;try{g=ce(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=kr(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=(p.definition?.name??e??"").trim();if(y.length>0){let _=await nm(i,r,a,y);_>0&&s.push(`items_using_type:${_}`)}await Ce({pmRoot:i,filePath:o,raw:me(p.file),op:"schema:remove-type",author:l,settings:r}),s.push(...await H({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return p.removed&&await To(i,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:o,definitions:p.file.definitions.length},warnings:Pe(s),generated_at:T()}}function ui(e,t){return re(e,t.files.statuses,Z.statuses)}function dn(e,t){return re(e,t.files.fields,Z.fields)}function Co(e,t){return re(e,t.files.types,Z.types)}async function $t(e,t,n,i){for(let r of t){let a=Gi(r.folder??Mi(r.name)),o=em.join(e,a);await k(o)||(await tm(o,{recursive:!0}),n.push(...await H({path:o,scope:"project",op:i})))}}function fi(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 am(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 om(e){let t=new Map;for(let n of e){let i=I(n.id);if(i.length!==0){t.set(i,i);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let a=I(r);a.length>0&&!t.has(a)&&t.set(a,i)}}}return t}async function fw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r;try{r=ga({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let a=await A(i),o=Y(a.schema),s=ui(i,o),l=ct(o);try{Wn(r,l.alias_to_id)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let c=am(l.by_id.get(r.id));if((r.roles??c?.roles??[]).length===0)throw new f(`Status "${r.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 "${Le(r.id)}" --role active`,`pm schema add-status "${Le(r.id)}" --role blocked`]});let d=[],p=B(t.author,a.author_default),m=se(a),g=await V(i,Io,a.locks.ttl_seconds,p,!!t.force,m.force_required_for_stale_lock,a.locks.wait_ms),y;try{let _=await G(s),u;try{u=Qe(_)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=om(u.statuses);try{Wn(r,w)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.USAGE)}y=ya(u,r,c),await Ce({pmRoot:i,filePath:s,raw:et(y.file),op:"schema:add-status",author:p,settings:a}),d.push(...await H({path:s,scope:"project",op:"schema:add-status"}))}finally{await g()}return{action:"add-status",registered:!0,replaced:y.replaced,status:y.definition,file:{path:s,statuses:y.file.statuses.length},warnings:Pe(d),generated_at:T()}}async function hw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r=await A(i),a=Y(r.schema),o=ui(i,a),s=[],l=B(t.author,r.author_default),c=se(r),d=await V(i,Io,r.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,r.locks.wait_ms),p;try{let m=await G(o),g;try{g=Qe(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=_a(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=I(p.definition?.id??e);await rm(s,i,r,a,y),await Ce({pmRoot:i,filePath:o,raw:et(p.file),op:"schema:remove-status",author:l,settings:r}),s.push(...await H({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:o,statuses:p.file.statuses.length},warnings:Pe(s),generated_at:T()}}function Po(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 sm(e,t,n){return{...Po(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 Ro(e){return{id:e.id,source:Ue.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 No(e,t,n){let i=e.toLowerCase();return n.has(i)?"extension":t.has(i)?"custom":"builtin"}function cm(){let e=new Map,t=W();for(let n of t?.item_types??[]){let i=n.types;if(Array.isArray(i))for(let r of i){if(typeof r!="object"||r===null||Array.isArray(r))continue;let a=r.name;typeof a=="string"&&a.trim().length>0&&e.set(a.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function lm(e){let t=ct(e),n=[],i=[];for(let r of t.definitions){let a=Ro(r);a.source==="builtin"?n.push(a):i.push(a)}return{builtin:n,custom:i}}async function It(e){let t=N(process.cwd(),e.path);await be(t);let n=await A(t),i=Y(n.schema),r=re(t,i.files.types,Z.types),a=ui(t,i),o=U(n,W()),s=cm(),l=new Set((n.item_types?.definitions??[]).map(c=>c.name.trim().toLowerCase()).filter(c=>c.length>0&&!s.has(c)));return{pmRoot:t,typesPath:r,statusesPath:a,byType:o.by_type,customNames:l,extensionProvenance:s,schema:i}}async function gw(e){let t=await It(e),n=[],i=[],r=[];for(let s of Object.values(t.byType).sort((l,c)=>l.name.localeCompare(c.name))){let l=No(s.name,t.customNames,new Set(t.extensionProvenance.keys())),c=Po(s);l==="extension"?r.push(c):l==="custom"?i.push(c):n.push(c)}let a=lm(t.schema),o=Lt(t.schema).definitions.map(fi);return{action:"list",builtin:n,custom:i,extension:r,counts:{builtin:n.length,custom:i.length,extension:r.length,total:n.length+i.length+r.length},statuses:{builtin:a.builtin,custom:a.custom,counts:{builtin:a.builtin.length,custom:a.custom.length,total:a.builtin.length+a.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:T()}}async function yw(e,t){let n=(e??"").trim();if(n.length===0)throw new f("Type name must not be empty.",h.USAGE);let i=await It(t),r=Object.values(i.byType).find(a=>a.name.toLowerCase()===n.toLowerCase()||a.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!r)throw new f(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Le(n)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:sm(r,No(r.name,i.customNames,new Set(i.extensionProvenance.keys())),i.extensionProvenance.get(r.name.toLowerCase())),file:{path:i.typesPath},generated_at:T()}}async function _w(e,t){let n=I(e);if(n.length===0)throw new f("Status id must not be empty.",h.USAGE);let i=await It(t),r=ct(i.schema),a=r.alias_to_id.get(n)??n,o=r.by_id.get(a);if(!o)throw new f(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Le(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Ro(o),file:{path:i.statusesPath},generated_at:T()}}async function ww(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r;try{r=ua({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}let a=await A(i),o=Y(a.schema),s=dn(i,o),l=[],c=Gt(r.key);c&&l.push(`custom_field_mcp_input_collision:${c.field}:${c.property}:${c.owner}:use=${c.nested_path}`);let d=B(t.author,a.author_default),p=se(a),m=await V(i,Ao,a.locks.ttl_seconds,d,!!t.force,p.force_required_for_stale_lock,a.locks.wait_ms),g;try{let y=await G(s),_;try{_=Xe(y)}catch(u){throw new f(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}g=fa(_,r),await Ce({pmRoot:i,filePath:s,raw:Ze(g.file),op:"schema:add-field",author:d,settings:a}),l.push(...await H({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:g.replaced,field:g.definition,file:{path:s,fields:g.file.fields.length},warnings:Pe(l),generated_at:T()}}async function dm(e,t,n,i){let r=U(t,W());return(await je(e,t.item_format,r.type_to_folder,[],n)).filter(a=>{let o=a[i];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function vw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r=await A(i),a=Y(r.schema),o=dn(i,a),s=[],l=B(t.author,r.author_default),c=se(r),d=await V(i,Ao,r.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,r.locks.wait_ms),p;try{let m=await G(o),g;try{g=Xe(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=ha(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=I(p.definition?.key??e),_=I(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(_.length>0){let u=await dm(i,r,a,_);u>0&&s.push(`items_using_field:${u}`)}await Ce({pmRoot:i,filePath:o,raw:Ze(p.file),op:"schema:remove-field",author:l,settings:r}),s.push(...await H({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:o,fields:p.file.fields.length},warnings:Pe(s),generated_at:T()}}async function bw(e){let t=await It(e),n=Lt(t.schema).definitions.map(fi);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:dn(t.pmRoot,t.schema)},generated_at:T()}}async function kw(e,t){let n=I(e);if(n.length===0)throw new f("Field key must not be empty.",h.USAGE);let i=await It(t),r=Lt(i.schema).by_key.get(n);if(!r)throw new f(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Le(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:fi(r),file:{path:dn(i.pmRoot,i.schema)},generated_at:T()}}async function xw(e,t,n){let i=N(process.cwd(),n.path);await be(i);let r;try{let _=cn(e);if(_===void 0)throw new Error(`Type preset name is required. Allowed: ${St.join(", ")}.`);r=_}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let a=await A(i),o=Y(a.schema),s=Co(i,o),l=[],c=B(t.author,a.author_default),d=se(a),p=[],m=[],g,y=await V(i,ln,a.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,a.locks.wait_ms);try{let _=await G(s),u;try{u=ce(_)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=u;for(let v of Et(r)){let x=Ke(w,v);w=x.file,(x.replaced?m:p).push(x.definition.name)}g=w.definitions.length,await Ce({pmRoot:i,filePath:s,raw:me(w),op:"schema:apply-preset",author:c,settings:a}),await $t(i,Et(r),l,"schema:apply-preset-folder"),l.push(...await H({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:r,registered:p,replaced:m,file:{path:s,definitions:g},warnings:Pe(l),generated_at:T()}}function pm(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 Sw(e,t){let n=N(process.cwd(),t.path);await be(n);let i=await A(n),r=Y(i.schema),a=Co(n,r),o=pm(e.minCount),s=U(i,W()),l=(await je(n,i.item_format,s.type_to_folder,[],r)).map(v=>typeof v.title=="string"?v.title:""),c=$o(l,{minCount:o}),d=[],p=[],m=[],g=[],y;if(!e.apply){let v;try{v=ce(await G(a))}catch(x){throw new f(x instanceof Error?x.message:String(x),h.GENERIC_FAILURE)}return y=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:c,registered:p,replaced:m,skipped:g,file:{path:a,definitions:y},warnings:d,generated_at:T()}}let _=B(e.author,i.author_default),u=se(i),w=await V(n,ln,i.locks.ttl_seconds,_,!!e.force,u.force_required_for_stale_lock,i.locks.wait_ms);try{let v=await G(a),x;try{x=ce(v)}catch(O){throw new f(O instanceof Error?O.message:String(O),h.GENERIC_FAILURE)}let S=x;for(let O of c){if(O.shadows_builtin){g.push({name:O.name,reason:"shadows_builtin"});continue}let ae;try{ae=lt({name:O.name})}catch{g.push({name:O.name,reason:"invalid_type_token"});continue}let L=Ke(S,ae);S=L.file,(L.replaced?m:p).push(L.definition.name)}y=S.definitions.length,await Ce({pmRoot:n,filePath:a,raw:me(S),op:"schema:infer-types",author:_,settings:i}),await $t(n,S.definitions.filter(O=>p.includes(O.name)||m.includes(O.name)),d,"schema:infer-types-folder"),d.push(...await H({path:a,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:o,candidates:c,registered:p,replaced:m,skipped:g,file:{path:a,definitions:y},warnings:Pe(d),generated_at:T()}}function Ew(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 "${Le(e.type.name)}" "<title>"`}function $w(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 Iw(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",i=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${i} in ${e.file.path}.`}function Aw(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 Tw(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,i]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])i.length!==0&&t.push(`${n}: ${i.map(r=>r.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,i]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])i.length!==0&&t.push(`${n}: ${i.map(r=>r.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(`
|
|
45
|
+
`)}function Ow(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(`
|
|
46
|
+
`)}function Cw(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(`
|
|
47
|
+
`)}function mm(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 Pw(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 Rw(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 Nw(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${mm(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
|
|
48
|
+
`)}function Dw(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(`
|
|
49
|
+
`)}function jw(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",i=[t,n].filter(r=>r.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${i.length>0?` (${i})`:""}.`}function Lw(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;let t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(let n of e.candidates){let i=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${i}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
|
|
50
|
+
`)}var Fw={workflowSlotsReferencing:Oo};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e6087f2-01b5-59c3-a471-433c722316b0")}catch{}})();function hi(e){return e.map(({layer:t,name:n,error:i})=>({layer:t,name:n,error:i}))}function pn(e,t,n){let i=b(t),r=n.trim();if(i.length===0||r.length===0)return;let a=e.get(i)??new Set;a.add(r),e.set(i,a)}function um(e){let t=new Map,n=new Map;for(let i of e.registrations.commands)pn(t,i.name,i.command),pn(n,i.name,i.action);for(let i of e.commands.handlers)pn(t,i.name,i.command);for(let i of e.commands.overrides)pn(t,i.name,i.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Do(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function fm(e){let{enabled:t,normalizedName:n,loadedNames:i,loadFailedNames:r,activationFailedNames:a}=e;return t?r.has(n)||a.has(n)?{runtime_active:!1,activation_status:"failed"}:i.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function mn(e,t,n){let i=new Set(t.loaded.map(l=>b(l.name))),r=new Set(t.failed.map(l=>b(l.name))),a=new Set(n.failed.map(l=>b(l.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=um(n);return e.map(l=>{let c=b(l.name),d=Do(o.get(c)),p=Do(s.get(c)),m={...d?{command_paths:d}:{},...p?{action_paths:p}:{}},g=fm({enabled:l.enabled,normalizedName:c,loadedNames:i,loadFailedNames:r,activationFailedNames:a});return{...l,...g,...m}})}function hm(e){let t=0,n=0,i=0;for(let r of e)if(r.startsWith("extension_policy_")){if(t+=1,r.startsWith("extension_policy_violation_")){n+=1;continue}r.startsWith("extension_policy_blocked_")&&(i+=1)}return{warning_count:t,violation_count:n,blocked_count:i}}function z(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Fo=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 gm(e){return Fo.has(qo(e))}function jo(e){return e==="project"||e==="global"}function Mo(e){let t=e.split(":"),n=t[0];if(!n||!Fo.has(n))return null;let i=t.at(-4),r=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!jo(i)||!jo(a)||!r||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:i,name:r},displaced:{layer:a,name:o}}}function ym(e){let t=new Set;for(let n of e){let i=Mo(n);i&&(t.add(i.winner.name),t.add(i.displaced.name))}return[...t].sort((n,i)=>n.localeCompare(i))}function _m(e,t){let n=e.filter(gm);if(n.length===0)return null;let i=ym(n);return`Extension registration collisions or handler/override overlaps detected.${i.length>0?` Conflicting extensions: ${i.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function wm(e,t,n,i){let r=t.map(p=>Mo(p)).filter(p=>p!==null).sort((p,m)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(r.length===0)return;let a=e==="global"?"--global":"--project",o=z(i,"deactivate"),s=`${z(i,"doctor")} ${a} --detail deep --trace`,l=new Map(n.map(p=>[b(p.name),p])),c=new Map;for(let p of r)for(let m of[p.winner.name,p.displaced.name]){let g=b(m);c.set(g,(c.get(g)??0)+1)}let d=[...c.entries()].map(([p,m])=>{let g=l.get(p),y=g?.name??p,_=g?.command_paths??[],u=g?.action_paths??[];return{action:"deactivate",extension:y,command:`${o} ${y} ${a}`,affected_collisions:m,feature_loss:{command_paths:[..._].sort((w,v)=>w.localeCompare(v)),action_paths:[...u].sort((w,v)=>w.localeCompare(v))}}}).sort((p,m)=>{let g=m.affected_collisions-p.affected_collisions;if(g!==0)return g;let y=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,_=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return y!==_?y-_:p.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:r.length,extension_count:c.size,next_best_command:s,collisions:r,remediation_candidates:d}}function Go(e){let t=[];for(let n of e){let i=n.error.toLowerCase();(i.includes("cannot find package '@unbrained/pm-cli'")||i.includes('cannot find module "@unbrained/pm-cli"')||i.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(i.includes("cannot use import statement outside a module")||i.includes("to load an es module")||i.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}function Uo(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let i of t){if(!i||typeof i.name!="string")continue;let r=i.trace?.missing_capability??i.trace?.capability;typeof r=="string"&&r.trim().length>0&&n.push(`extension_capability_missing:${i.name}:${r.trim().toLowerCase()}`)}return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}function zo(e,t){let n=[];for(let i of er(e.loaded,t))for(let r of i.unused)n.push(`extension_capability_unused:${i.layer}:${i.name}:${r}`);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}var vm=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${z(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${Di.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${z(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${z(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${z(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function bm(e){let{normalizedWarnings:t,options:n,scope:i,scopeFlag:r,updateCheckFailedTotal:a,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:l,skippedNonGithubTotal:c,updateAvailableTotal:d}=e,p=[],m={options:n,scope:i,scopeFlag:r,updateCheckFailedTotal:a,policyWarningCount:o};if(t.length>0){let g=_m(t,{deactivate:`${z(n,"deactivate")} <name> ${r}`,doctor:`${z(n,"doctor")} ${r} --detail deep --trace`});g&&p.push(g);for(let y of vm)y.matches(t,m)&&p.push(y.build(m))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${z(n,"manage")} ${r} --fix-managed-state (or ${z(n,"adopt-all")} ${r}, ${z(n,"adopt")} <name> ${r}, or reinstall via ${z(n,"install")} ${r} <source>).`),c>0&&p.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),l>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${z(n,"manage")} ${r} to request update checks.`),d>0&&p.push(`Update available managed extensions via ${z(n,"install")} ${r} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${z(n,"manage")} ${r} after extension changes.`),p}function un(e,t,n,i={}){let r=[...new Set(t)].sort((E,q)=>E.localeCompare(q)),a=n.filter(E=>E.managed).length,o=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,l=n.filter(E=>E.update_check_status==="checked"&&E.update_available===!0).length,c=n.filter(E=>E.managed===!1),d=c.filter(E=>Lo(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),p=c.filter(E=>!Lo(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)m[E.update_check_status]+=1;let g=m.failed,y=n.filter(E=>E.update_check_status==="skipped_non_github"&&E.source?.kind!=="builtin").length,_=Object.entries({skipped_unmanaged:p.length,skipped_non_github:y,failed:g,not_checked:m.not_checked}).filter(([,E])=>E>0).map(([E,q])=>`extension_update_health_partial_coverage:${E}:${q}`),u=_.length>0,w=u?"partial":"full",v=[...new Set([...r,..._])].sort((E,q)=>E.localeCompare(q)),x=[...new Set(v.map(E=>qo(E)))].sort((E,q)=>E.localeCompare(q)),S=hm(v),O=e==="global"?"--global":"--project",ae=wm(e,r,n,i),L=bm({normalizedWarnings:v,options:i,scope:e,scopeFlag:O,updateCheckFailedTotal:g,policyWarningCount:S.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:y,updateAvailableTotal:l});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:x,warnings:v,policy_warning_count:S.warning_count,policy_violation_count:S.violation_count,policy_blocked_count:S.blocked_count,total_extensions:n.length,managed_total:a,enabled_total:o,active_total:s,update_available_total:l,update_health_coverage:w,update_health_partial:u,unmanaged_loaded_extension_count:c.length,unmanaged_loaded_extensions:c.map(E=>E.name).sort((E,q)=>E.localeCompare(q)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:m,update_check_failed_total:g,top_warnings:v.slice(0,8),remediation:L,...ae?{collision_plan:ae}:{}}}function Jo(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 qo(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Wo(e){let t=new Set,n=[];for(let i of e){let r=(()=>{let a=Hi(i);return a?[a]:Ki(i)})();for(let a of r){let o=`${a.layer}:${a.name}:${a.capability}`;t.has(o)||(t.add(o),n.push(a))}}return n}function Bo(){return{version:Ct.version,capabilities:[...Ct.capabilities],legacy_aliases:{...Ct.legacy_aliases}}}function Lo(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Ho(e,t,n,i,r){if(e!=="project"||r)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let a=[...new Set(t.filter(c=>c.active).map(c=>b(c.name)))].sort((c,d)=>c.localeCompare(d)),o=[...new Set(n.filter(c=>c.layer==="project").map(c=>b(c.name)))].sort((c,d)=>c.localeCompare(d)),s=new Set(i.map(c=>b(c.name))),l=a.filter(c=>!o.includes(c)&&!s.has(c)).sort((c,d)=>c.localeCompare(d));return{warnings:l.length>0?[`extension_doctor_consistency_active_not_loaded:${l.join(",")}`]:[],summary:{active_project_count:a.length,loaded_project_count:o.length,active_project_names:a,loaded_project_names:o,missing_active_project_names:l}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var gi=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let i=new Array(e.length),r=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let o=r;r+=1,i[o]=await n(e[o])}});return await Promise.all(a),i};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function Ko(e,t){let n=b(e),i=t.find(r=>b(r.name)===n);return{command_paths:[...i?.command_paths??[]].sort((r,a)=>r.localeCompare(a)),action_paths:[...i?.action_paths??[]].sort((r,a)=>r.localeCompare(a))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function Vo(e,t){let n=new Set((t?.loaded??[]).flatMap(a=>(a.activation?.commands?.length??0)>0?[`${a.layer}:${b(a.name)}`]:[])),i=e.services.overrides.filter(a=>a.service==="output_format").filter(a=>a.passThrough!==!0).filter(a=>!n.has(`${a.layer}:${b(a.name)}`)).map(a=>`extension_output_service_override_global:${a.service}:${a.layer}:${a.name}`),r=e.renderers.overrides.filter(a=>(a.commands?.length??0)===0&&a.resultDiscriminator===void 0).map(a=>`extension_output_renderer_override_global:${a.format}:${a.layer}:${a.name}`);return[...new Set([...i,...r])].sort((a,o)=>a.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var Yo=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Gt(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,i)=>i.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{execFile as km}from"node:child_process";import{promisify as xm}from"node:util";import Sm from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b67e46f9-51ff-501b-98da-74353b4c66d9")}catch{}})();var Em=xm(km),Zo=1e4;function Xo(e,t,n){if(typeof t=="string")try{let i=Sm.resolve(e,t);if(i.type==="version")return i.fetchSpec}catch{}throw new Error(n)}async function $m(e,t){try{return(await Em(ai(),e,{encoding:"utf8",timeout:t,maxBuffer:65536,shell:oi(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function Qo(e,t=$m){let n=T();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let i=Xo(e.package,e.version,"missing_or_invalid_installed_npm_version"),r=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],Zo),a;try{a=JSON.parse(r)}catch{throw new Error("invalid_npm_registry_metadata")}let o=Array.isArray(a)&&a.length===1?a[0]:a,s=Xo(e.package,o,"invalid_npm_registry_version");return{checked_at:n,available:s!==i,remote_version:s}}catch(i){return{checked_at:n,available:null,error:i instanceof Error?i.message:String(i)}}}var Im=(e,t,n)=>{let i=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,l=""]=o.split(/\s+/);return{commit:s,ref:l}}),r=i.find(o=>o.ref.endsWith("^{}"))??i[0];if(!r)return{checked_at:n,available:null,error:"no_remote_reference_found"};let a=t?.trim();return a?{checked_at:n,remote_commit:r.commit,available:r.commit!==a}:{checked_at:n,remote_commit:r.commit,available:null,error:"missing_installed_commit"}},yi=async(e,t=en)=>{let n=T();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let i=[e.ref?.trim(),"HEAD"].find(Boolean),r=await t(["ls-remote",e.repository,i,`${i}^{}`],void 0,Zo);return Im(r,e.commit,n)}catch(i){return{checked_at:n,available:null,error:i instanceof Error?i.message:String(i)}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d34e2cc0-5e58-5534-8480-a9ab47ec4a88")}catch{}})();var Am=4;async function es(e,t=!1){let n=await gi(e.entries,Am,async i=>{if(!["github","npm"].includes(i.source.kind))return i;if(t)return{...i,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0};let r=i.source.kind==="github"?await yi(i.source):await Qo(i.source);return{...i,last_update_check_at:r.checked_at,last_update_remote_commit:"remote_commit"in r?r.remote_commit:void 0,last_update_remote_version:"remote_version"in r?r.remote_version:void 0,update_available:r.available,update_error:r.error}});return{...e,entries:gt(n)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fcf7df06-e3b8-5476-a76a-cd391839c13d")}catch{}})();function ts(e,t){let n=e.filter(i=>i.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:i,result:r})=>{let a=r.details;return{alias:i,ok:r.ok,extension:a.extension,source:a.source,source_resolution:a.source_resolution,install_plan:a.install_plan,dry_run:a.dry_run,destination_path:a.destination_path,activated:a.activated,settings_changed:a.settings_changed,command_paths:a.command_paths,action_paths:a.action_paths,command_discovery:a.command_discovery,verification:a.verification,runtime_activation_status:a.runtime_activation_status,activation_diagnostics:a.activation_diagnostics,warnings:r.warnings}})}}import Tm from"node:fs/promises";import Om from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function Cm(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Pm(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 Rm(e){let t=Om.join(e,"manifest.json"),n;try{n=await Tm.readFile(t,"utf8")}catch(s){if(Pt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let i;try{i=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof i!="object"||i===null||Array.isArray(i))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let r=i,a=Yi(r),o=Cm(r);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:a.findings,warnings:a.findings.map(s=>Pm(o,s)),remediation:a.findings.map(s=>s.message)}}function ns(e){return Rm(Ui(e))}import We from"node:fs/promises";import Nm from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="776854e4-6df4-507e-b21b-a4d320946642")}catch{}})();var _i=async e=>We.readFile(e).catch(t=>{if(an(t,"ENOENT"))return null;throw t}),is=async(e,t,n,i,r)=>De("extension_install_backup",async()=>{let a=ht(e),o=Ji(t),[s,l]=await Promise.all([_i(a),_i(o)]);return i&&await We.cp(n,r,{recursive:!0,force:!0}),{backupDirectory:r,destinationDirectory:n,destinationExists:i,managedStatePath:a,managedStateContents:s,settingsPath:o,settingsContents:l}}),rs=async e=>De("extension_install_rollback",async()=>{await We.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await We.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await We.rm(t,{force:!0}):(await We.mkdir(Nm.dirname(t),{recursive:!0}),await We.writeFile(t,n))});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="549164da-d760-52bc-9950-25dacf286775")}catch{}})();var cs=[["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"]],Dm=cs.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),jm={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"},Lm="__pm_native_output",Fm=["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"],ls=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Mm=["disabled","require_trusted","require_provenance"],ds={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:[]},Gm=e=>{let t=e??ds,n={};for(let i of Fm)n[i]=te(t[i]??[]);return n},Um=(e,t)=>{for(let n of ls)t[n].length>0&&(e[n]=t[n]);return e},zm=(e,t)=>{for(let n of Mm)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Jm=e=>{let t={};for(let n of ls)t[n]=te(e[n]??[]);return t},qm=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Um(zm({name:t},e),Jm(e))},Wm=e=>(e??[]).map(t=>qm(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Bm=e=>{let t=Object.assign({},ds,e??{}),n=Gm(e),i=Wm(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:i}},ps=async(e,t)=>{let n=[t],i=await Fa(t);i&&n.push(i);let r=[...new Set(n.map(a=>b(a)).filter(a=>a.length>0))];for(let a of r){let o=e.find(l=>b(l.name)===a);if(o)return o;let s=e.find(l=>b(l.directory)===a);if(s)return s}},ms=(e,t)=>{let n=t.trim(),i=new Set(te(e.extensions.enabled));return new Set(te(e.extensions.disabled)).has(n)?!1:i.size===0?!0:i.has(n)},us=(e,t)=>{let n=t.trim(),i=new Set(te(e.extensions.enabled)),r=new Set(te(e.extensions.disabled)),a=[...i],o=[...r];return r.delete(n),i.size>0&&i.add(n),e.extensions.enabled=[...i].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Hm=(e,t)=>{let n=t.trim(),i=new Set(te(e.extensions.enabled)),r=new Set(te(e.extensions.disabled)),a=[...i],o=[...r];return i.delete(n),r.add(n),e.extensions.enabled=[...i].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Km=(e,t)=>{let n=t.trim(),i=new Set(te(e.extensions.enabled)),r=new Set(te(e.extensions.disabled)),a=[...i],o=[...r];return i.delete(n),r.delete(n),e.extensions.enabled=[...i].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Vm=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),i=cs.map(([r,a,o])=>({action:a,flag:o,distance:Bi(t,r,n)})).filter(r=>r.distance!==null).sort((r,a)=>r.distance-a.distance)[0];return i?{action:i.action,flag:i.flag}:null},Ym=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",i=Vm(e);if(!i)return new f(`One action flag is required. Use one of: ${Dm}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let r=`pm ${n} ${i.flag}`;return _r({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(fs),retry_command:r,message_suffix:`. Did you mean "${i.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:r,reason:`nearest lifecycle action for "${e}"`}]})},Xm=[["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"]],fs={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Zm=e=>fs[e]??null,Qm=(e,t)=>{let n=[...new Set(Xm.filter(([i])=>t[i]===!0).map(([,i])=>i))];if(n.length===0){if(e===void 0)return"explore";let i=Zm(e.trim().toLowerCase());if(i)return i;throw Ym(e,t)}if(n.length>1)throw new f("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},eu=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new f('Options "--project/--local" and "--global" are mutually exclusive.',h.USAGE);return n?"global":"project"},tu=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],hs=e=>{for(let t of tu){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},gs=(e,t,n,i)=>{let r=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:r.contributions,managed:!!n,source:r.source,update_available:r.update_available,last_update_check_at:r.last_update_check_at,last_update_remote_commit:r.last_update_remote_commit,last_update_remote_version:r.last_update_remote_version,update_error:r.update_error,update_check_status:i.status,update_check_reason:i.reason}},nu=(e,t,n,i)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},i),a=i?ms(n,i.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:gs({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:a},t,i,hs(i))}},iu=async(e,t,n,i,r,a)=>{let o=ne.join(e,t),s=ne.join(o,"manifest.json"),l=a.get(b(t));if(!await k(s))return nu(t,n,i,l);let c=Symbol("invalid-extension-manifest-json"),d=await Re.readFile(s,"utf8").then(g=>JSON.parse(g)).catch(()=>c);if(d===c)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Xn(d);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=r.get(b(p.name))??a.get(b(t));return{summary:gs({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:ms(i,p.name)},n,m,hs(m))}},ye=async(e,t,n,i)=>{if(!await k(e))return{extensions:[],warnings:[]};let r=(await Re.readdir(e,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name).sort((c,d)=>c.localeCompare(d)),a=new Map(i.entries.map(c=>[b(c.name),c])),o=new Map(i.entries.map(c=>[b(c.directory),c])),s=[],l=[];for(let c of r){let d=await iu(e,c,t,n,a,o);d.warning&&s.push(d.warning),d.summary&&l.push(d.summary)}return{extensions:l.sort((c,d)=>c.name.localeCompare(d.name)),warnings:s.sort((c,d)=>c.localeCompare(d))}},ru=Zi(),au=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,ou=(e,t,n,i)=>{let r=n.command_paths.map(s=>`pm ${s} --help`),a=i?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...r]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return a&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:au(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:r,next_steps:o,...a?{sdk_dependency_status:"missing"}:{}}},su=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},ys=e=>e.map(t=>su(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),_s=(e,t,n)=>{let i=b(e);return t.find(r=>(n===void 0||r.layer===n)&&b(r.name)===i)},cu=(e,t,n,i)=>n.find(r=>r.scope===t&&b(r.name)===b(e))?.activation_status??(i?"failed":"unknown"),ws=(e,t,n,i,r)=>ru.enqueue(async()=>{let a=process.env.PM_CLI_PACKAGE_ROOT,o=await Re.mkdtemp(ne.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=pe(import.meta.url,["../.."]);try{let s=await ke({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:r.noExtensions===!0,reload_token:xn(),cache_bust:!0,module_graph_snapshot_root:o}),l=await xe({...s}),c=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...ys(l.failed)],d=Object.fromEntries(s.loaded.map(p=>[b(p.name),Wi(Ve(l,{extensionName:p.name}))]));return{installed:mn(i,s,l),warnings:[...s.warnings,...l.warnings],activation_failures:c,extensions_disabled:s.disabled_by_flag,item_type_registrations:l.registrations.item_types,contribution_inventories:d}}finally{await Re.rm(o,{recursive:!0,force:!0}),a===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=a}}),vi=async(e,t,n,i)=>{let r=n.filter(l=>!l.managed),a=[...r].sort((l,c)=>{let d=l.name.localeCompare(c.name);return d!==0?d:l.directory.localeCompare(c.directory)}),o=i,s=[];for(let l of a){let c=ne.join(e,l.directory),d=await rt(c),p=T(),m={kind:"local",input:l.name,location:c};o=yt(o,{name:d.manifest.name,directory:l.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:p,updated_at:p,source:m}),s.push({name:d.manifest.name,directory:l.directory,version:d.manifest.version,entry:d.manifest.entry,source:m})}return s.length>0&&await at(e,o),{state:o,adopted_entries:s,unmanaged_candidates:a,already_managed_count:n.length-r.length}},lu=(e,t)=>{let n=N(process.cwd(),t.path),i=Nt(n,process.cwd()),r=e==="global"?zi(process.cwd()):n,a=e==="global"?i.global:i.project;return{pm_root:n,scope:e,settings_root:r,selected_root:a,roots:i}},fn=e=>{let t=[e.gh,e.github].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new f('Options "--gh" and "--github" must match when both are provided.',h.USAGE);return n[0]},du=e=>jm[e],pu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",i=e==="install"?"source":"name",r=`${n} ${i}`,a=du(e),o=`<${i}>`,s=`pm ${n} ${a} ${o}`;throw new f(`Action "${e}" requires ${r} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${i} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${i} target`}]}})},hn=(e,t,n={})=>{let i=e?.trim();if(i)return i;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 pu(t,n)},mu=(e,t)=>{let n=new Set([...t.registrations.item_types.map(i=>({entry:i,count:i.types.length})),...t.registrations.item_fields.map(i=>({entry:i,count:i.fields.length}))].filter(({count:i})=>i>0).map(({entry:i})=>`${i.layer}:${b(i.name)}`));return e.loaded.filter(i=>(i.activation?.commands??[]).length>0).filter(i=>n.has(`${i.layer}:${b(i.name)}`)).map(i=>`extension_schema_narrow_activation:${i.layer}:${i.name}`).filter((i,r,a)=>a.indexOf(i)===r).sort((i,r)=>i.localeCompare(r))},uu=(e,t)=>{let n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(i=>i.triggered&&!i.allowed);if(n)throw new f(n.message,h.USAGE)},fu=(e,t,n)=>{let i=String(e??"").trim().toLowerCase(),r=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:r?[]:["init","scaffold"]}[t]??[]).includes(i)?void 0:e},hu=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},gu=(e,t,n)=>{let i={ok:n,action:e.action,scope:e.scope,roots:hu(e),warnings:[...new Set(e.warnings)].sort((r,a)=>r.localeCompare(a)),details:t};return e.action==="doctor"&&Object.defineProperty(i,Lm,{value:!0,enumerable:!1,configurable:!1}),i},bi=async(e,t,n)=>{let i=Qm(e,t);uu(i,t);let r=fu(e,i,t),a=eu(t),o=lu(a,n),s={action:i,normalizedTarget:r,scope:a,resolvedRoots:o,warnings:[],options:t,global:n},l={...s,withResult:(c,d=!0)=>gu(s,c,d)};return await Vu(l)},yu=(e,t)=>{let n=t.vocabulary??"extension",i=e.target_path.replace(/\\/g,"/"),r=tr(i),a={package:`Install dependencies: cd ${r}, then run "npm install"`,extension:`Install type-check dependencies: cd ${r}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${r}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${r}, 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."),[a[n],...s,`Install the scaffold: ${st(n==="package"?["install","--project",i]:["extension","--install","--project",i])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},_u=async e=>{let{action:t,normalizedTarget:n,options:i,withResult:r}=e;if([fn(i),i.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new f('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let a=hn(n,t,i),o=await oo(a,i.vocabulary??"extension",i.capability,i.declarative===!0);return r({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:yu(o,i)})},wu=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:i,options:r,global:a,withResult:o}=e;if(t!==void 0)throw new f('Action "reload" does not accept a target argument.',h.USAGE);let s=await A(n.settings_root),l=xn(),c=await ke({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:a.noExtensions,reload_token:l,cache_bust:!0});i.push(...c.warnings);let d=await xe(c);i.push(...d.warnings);let p={reload:{token:l,cache_bust:!0,watch:r.watch===!0},loaded_count:c.loaded.length,failed_count:c.failed.length,activated_count:Math.max(0,c.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:c.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:c.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return r.watch===!0&&i.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(p)},vu=async e=>{let{normalizedTarget:t,scope:n,options:i,global:r,withResult:a}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new f('Action "catalog" does not accept a package target.',h.USAGE);return a(await Ma(n,r,i))},bu=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),ku=e=>({kind:"local",input:e.input,location:e.absolute_path}),xu=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),Su=(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}),Eu=(e,t,n,i)=>e?bu(e,t):n.kind==="local"?ku(n):n.kind==="npm"?xu(n,i):Su(n,i),$u=(e,t,n,i)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:i}:Pa(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:i}:{installed_at:i,updated_at:i},Iu=async(e,t)=>{let{scope:n,resolvedRoots:i,warnings:r}=e,{validated:a,destinationDirectoryName:o}=t,s=await A(i.settings_root),l=await he(i.selected_root);r.push(...l.warnings);let c=ne.join(i.selected_root,o),d=await k(c),p=await rn(a.directory,c);await Re.mkdir(i.selected_root,{recursive:!0});let m=await Re.mkdtemp(ne.join(i.selected_root,".pm-extension-install-backup-")),g=ne.join(m,"destination");try{let y=await is(i.selected_root,i.settings_root,c,d,g),_=Eu(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),u=l.state.entries.find(S=>b(S.name)===b(a.manifest.name)),w=$u(u,a.manifest.version,_,T()),v=yt(l.state,{name:a.manifest.name,directory:o,scope:n,manifest_version:a.manifest.version,manifest_entry:a.manifest.entry,capabilities:[...a.manifest.capabilities],contributions:a.manifest.contributions,...w,source:_}),x=us(s,a.manifest.name);try{p||await bo(a.directory,c),await _o(c),await wo(c),await at(i.selected_root,v),x&&await Ee(i.settings_root,s,"settings:write")}catch(S){try{await rs(y)}catch(O){throw new AggregateError([S,O],`Extension install failed: ${String(S)}; rollback failed: ${String(O)}`,{cause:O})}throw S}return{settings:s,managedState:v,sourceRecord:_,destinationDirectory:c,destinationExists:d,installInPlace:p,activationChanged:x}}finally{await Re.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},Au=async(e,t,n)=>{let i=n.filter(r=>b(r.name)===b(t)).flatMap(r=>r.types.map(a=>({name:a.name,folder:a.folder})));return e.scope==="project"&&i.length>0&&await $t(e.resolvedRoots.pm_root,i,e.warnings,"install:type-folder"),i},Tu=(e,t,n,i,r)=>{let a=_s(t,n.activation_failures,e.scope),o=cu(t,e.scope,n.installed,a),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let l={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:a,verification:{status:l[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:i.command_paths,registered_actions:i.action_paths,registered_item_types:r,module_graph_verification:"fresh_in_topology_snapshot",health:l[String(s)]}}},Ou=async(e,t)=>{let{scope:n,resolvedRoots:i,warnings:r,global:a,withResult:o}=e,{validated:s,destinationDirectoryName:l}=t,c=await Iu(e,t),d=await ye(i.selected_root,n,c.settings,c.managedState);r.push(...d.warnings);let p=await ws(i.pm_root,ne.dirname(i.selected_root),c.settings,d.extensions,a);r.push(...p.warnings);let m=await Au(e,s.manifest.name,p.item_type_registrations),g=Ko(s.manifest.name,p.installed),y=Tu(e,s.manifest.name,p,g,m),_=p.contribution_inventories[b(s.manifest.name)];return _&&(c.managedState=await Ra(i.selected_root,c.managedState,s.manifest.name,_)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:l},source:c.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:c.destinationDirectory,overwritten:[c.destinationExists,!c.installInPlace].every(Boolean),installed_in_place:c.installInPlace,activated:y.activated,settings_changed:c.activationChanged,runtime_activation_status:y.status,command_paths:g.command_paths,action_paths:g.action_paths,contributions:_,command_discovery:ou(s.manifest.name,c.sourceRecord,g,y.failure),verification:y.verification,activation_diagnostics:{failed_count:p.activation_failures.length,failed:p.activation_failures,installed_extension_failed:y.failure??null}},y.activated)},Cu=async e=>{let{options:t,global:n,warnings:i,withResult:r}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new f('Action "install all" does not accept --ref.',h.USAGE);let a=[],o=new Map;for(let s of await Qt()){let l=await _t(s),c=ne.resolve(l),d=o.get(c);d===void 0&&(d=await bi(s,{...t,install:!0},n),o.set(c,d)),a.push({alias:s,result:d})}return i.push(...a.flatMap(s=>s.result.warnings)),r(ts(a,t.dryRun===!0),a.every(s=>s.result.ok))},Pu=async(e,t,n)=>{let{resolvedRoots:i}=e,{bundledAliasName:r,bundledPackageName:a,installSource:o,sourceResolution:s}=await Eo(t,n,e.options.ref,(await he(i.selected_root)).state.entries);if(s.ambiguous){let c=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${r}:npm:${c.package}`)}let l=await Ka(o);try{let c=await rt(l.directory,{source_kind:o.kind,source_input:o.input,source_root:l.source_root}),d=Xt(c.manifest.name),p=e.options.dryRun===!0||o.kind==="local"&&r===null?await xo(l,ne.join(i.selected_root,d),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:c.manifest.name,version:c.manifest.version},source_resolution:s,install_plan:p}):await mi(i.settings_root,d,()=>Ou(e,{validated:c,destinationDirectoryName:d,bundledAliasName:r,bundledPackageName:a,sourceResolution:s,installSource:o,resolvedSource:l,installPlan:p}))}finally{l.cleanup&&await l.cleanup()}},Ru=async e=>{let t=fn(e.options),n=t??hn(e.normalizedTarget,e.action,e.options);return[t===void 0,Da(n)].every(Boolean)?Cu(e):Pu(e,n,t)},Nu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,withResult:o}=e;if(t!==void 0)throw new f('Action "adopt-all" does not accept a target argument.',h.USAGE);if(fn(a)!==void 0||typeof a.ref=="string"&&a.ref.trim().length>0)throw new f('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let s=await A(i.settings_root),l=await he(i.selected_root);r.push(...l.warnings);let c=await ye(i.selected_root,n,s,l.state);r.push(...c.warnings);let d=await vi(i.selected_root,n,c.extensions,l.state),p=await ye(i.selected_root,n,s,d.state);r.push(...p.warnings);let m=un(n,r,p.extensions,a);r.push(...m.warnings);let g=new Map(p.extensions.map(u=>[`${b(u.name)}:${b(u.directory)}`,u])),y=new Map(p.extensions.map(u=>[b(u.directory),u])),_=d.adopted_entries.map(u=>{let w=b(u.directory),v=g.get(`${b(u.name)}:${w}`)??y.get(w);return{...u,...vs(v)}});return o({adopted_all:_.length>0,adopted_count:_.length,already_managed_count:d.already_managed_count,extensions:_,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},vs=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Du=(e,t,n,i)=>{if(e===void 0)return{kind:"local",input:t,location:n};let r=wt(e,{forceGithub:!0,ref:i});if(r.kind!=="github")throw new f(`Invalid GitHub shorthand "${e}".`,h.USAGE);return{kind:"github",input:r.input,location:r.subpath??".",repository:r.repository,owner:r.owner,repo:r.repo,ref:r.ref,subpath:r.subpath}},ju=async e=>{let{action:t,normalizedTarget:n,scope:i,resolvedRoots:r,warnings:a,options:o,withResult:s}=e,l=hn(n,t,o),c=fn(o),d=await A(r.settings_root),p=await he(r.selected_root);a.push(...p.warnings);let m=await ye(r.selected_root,i,d,p.state);a.push(...m.warnings);let g=await ps(m.extensions,l);if(!g)throw new f(`Installed extension "${l}" was not found in ${i} scope.`,h.NOT_FOUND);if(g.managed)return s({adopted:!1,already_managed:!0,extension:{name:g.name,directory:g.directory}});let y=ne.join(r.selected_root,g.directory),_=await rt(y),u=T(),w=Du(c,l,y,o.ref),v=yt(p.state,{name:_.manifest.name,directory:g.directory,scope:i,manifest_version:_.manifest.version,manifest_entry:_.manifest.entry,capabilities:[..._.manifest.capabilities],contributions:_.manifest.contributions,installed_at:u,updated_at:u,source:w});await at(r.selected_root,v);let x=await ye(r.selected_root,i,d,v);a.push(...x.warnings);let S=x.extensions.find(O=>b(O.name)===b(_.manifest.name))??x.extensions.find(O=>b(O.directory)===b(g.directory));return s({adopted:!0,extension:{name:_.manifest.name,directory:g.directory,version:_.manifest.version,entry:_.manifest.entry},source:w,...vs(S)})},bs=async e=>{let{action:t,normalizedTarget:n,scope:i,resolvedRoots:r,warnings:a,options:o}=e,s=hn(n,t,o),l=await A(r.settings_root),c=await he(r.selected_root);a.push(...c.warnings);let d=await ye(r.selected_root,i,l,c.state);a.push(...d.warnings);let p=await ps(d.extensions,s);if(!p)throw new f(`Installed extension "${s}" was not found in ${i} scope.`,h.NOT_FOUND);return{settings:l,managedStateRead:c,candidate:p}},Lu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:i,managedStateRead:r,candidate:a}=await bs(e),o=ne.join(t.selected_root,a.directory);await Re.rm(o,{recursive:!0,force:!0});let s={...r.state,updated_at:T(),entries:r.state.entries.filter(c=>b(c.name)!==b(a.name)&&b(c.directory)!==b(a.directory))};await at(t.selected_root,s);let l=Km(i,a.name);return l&&await Ee(t.settings_root,i,"settings:write"),n({removed:!0,extension:{name:a.name,directory:a.directory},destination_path:o,settings_changed:l})},as=async e=>{let{action:t,resolvedRoots:n,warnings:i,global:r,withResult:a}=e,{settings:o,candidate:s}=await bs(e),l=t==="activate"?us(o,s.name):Hm(o,s.name);l&&await Ee(n.settings_root,o,"settings:write");let c=t==="activate"?await ws(n.pm_root,ne.dirname(n.selected_root),o,[s],r).then(d=>(i.push(...d.warnings),_s(s.name,d.activation_failures,e.scope))):void 0;return c&&i.push(`extension_activate_failed:${e.scope}:${s.name}`),a({extension:{name:s.name,directory:s.directory},active:t==="activate"&&c===void 0,runtime_active:t==="activate"&&c===void 0,activation_failure:c??null,settings_changed:l,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},c===void 0)},Fu=(e,t,n,i,r,a)=>{let o=i==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],l=r?.adopted_entries.length??0,c=[[a!==null,a??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[l>0,`Managed-state fix adopted ${l} extension(s).`]];return[...new Set([...e,...c.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},wi=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Mu=(e,t,n,i)=>{if(e!=="project"||t||!wi(i))return null;let r=n==="package"?"package":"extension";return`Global ${r} registrations are included in project diagnostics. For hermetic ${r} smoke tests, rerun pm ${r} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Gu=(e,t,n)=>{if(String(e??"").trim().length>0)throw new f('Action "doctor" does not accept a target argument.',h.USAGE);let i=[n.isolated,n.ignoreGlobal].includes(!0);if([i,t==="global"].every(Boolean))throw new f("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let r=Jo(n.detail),a=n.trace===!0;if([a,r!=="deep"].every(Boolean))throw new f("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:i,detailMode:r,includeTrace:a}},Uu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let i=await vi(e.resolvedRoots.selected_root,e.scope,t,n);return{state:i.state,fix:i}},zu=(e,t,n,i)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:wi(i),rerun_command:null,pm_global_path_recipe:null};let a=`pm ${r} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:wi(i),rerun_command:t?null:a,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},Ju=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,global:o,withResult:s}=e,{isolated:l,detailMode:c,includeTrace:d}=Gu(t,n,a),p=await A(i.settings_root),m=await he(i.selected_root);r.push(...m.warnings);let g=await ye(i.selected_root,n,p,m.state);r.push(...g.warnings);let{state:y,fix:_}=await Uu(e,g.extensions,m.state),u=await ye(i.selected_root,n,p,y);r.push(...u.warnings);let w=await ke({pmRoot:i.pm_root,settings:p,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:l}),v=await xe({...w,loaded:w.loaded}),x=await ns(i.pm_root);r.push(...x.warnings,...w.warnings),r.push(...Go(w.failed)),r.push(...v.warnings),r.push(...Uo(v.failed)),r.push(...zo(w,v)),r.push(...Vo(v,w)),r.push(...mu(w,v)),r.push(...Yo(v));let S=mn(u.extensions,w,v),O=Ho(n,S,w.loaded.map(C=>({layer:C.layer,name:C.name})),w.failed.map(C=>({name:C.name})),w.disabled_by_flag);r.push(...O.warnings);let ae=S.filter(C=>C.update_check_status==="failed").map(C=>`extension_update_check_failed:${C.name}`);r.push(...ae);let L=un(n,r,S,a);r.push(...L.warnings);let E=[...L.warnings],q={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},ot=Wo(E),yn=Bo(),Pi=L.warning_codes,tc=Mu(n,l,a.vocabulary,w),nc=Fu(L.remediation,w.failed.length,v.failed.length,a.vocabulary,_,tc),Ri=zu(n,l,a.vocabulary,w),ic={status:L.status,scope:n,warning_count:L.warning_count,warning_codes:Pi,total_extensions:S.length,managed_total:S.filter(C=>C.managed).length,enabled_total:S.filter(C=>C.enabled).length,active_total:S.filter(C=>C.active).length,unmanaged_loaded_extension_count:L.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:L.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:L.unmanaged_expected_extension_count,runtime_active_total:S.filter(C=>C.runtime_active===!0).length,activation_status_totals:{ok:S.filter(C=>C.activation_status==="ok").length,failed:S.filter(C=>C.activation_status==="failed").length,not_loaded:S.filter(C=>C.activation_status==="not_loaded").length,unknown:S.filter(C=>C.activation_status==="unknown").length},unknown_capability_count:ot.length,capability_contract_version:yn.version,update_available_total:L.update_available_total,update_check_status_totals:L.update_check_status_totals,update_health_coverage:L.update_health_coverage,update_health_partial:L.update_health_partial,update_check_failed_total:S.filter(C=>C.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:hi(w.failed),activation_failures:hi(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:O.warnings.length,trace_enabled:d,isolation:Ri,policy:q,remediation:nc},rc=_?{requested:!0,applied:_.adopted_entries.length>0,adopted_count:_.adopted_entries.length,already_managed_count:_.already_managed_count,adopted_extensions:_.adopted_entries.map(C=>C.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:u.extensions.filter(C=>C.managed).length,adopted_extensions:[]},_n={mode:c,summary:ic,triage:L,trace_enabled:d,capability_contract:yn,capability_guidance:ot,managed_state_fix:rc,author_manifest:x,isolation:Ri,policy:w.policy};if(c==="deep"){let C=d?v.failed:v.failed.map(D=>{let{trace:Nf,...ac}=D;return ac});_n.deep={warnings:E,warning_codes:Pi,capability_contract:yn,capability_guidance:ot,trace_enabled:d,managed_state:{path:m.path,count:y.entries.length,entries:y.entries},installed_extensions:S,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(D=>({layer:D.layer,directory:D.directory,name:D.name,version:D.version,entry:D.entry,priority:D.priority}))},activation:{failed:C,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:O.summary},d&&(_n.deep.trace={activation_failures:v.failed.filter(D=>D.trace!==void 0).map(D=>({layer:D.layer,name:D.name,entry_path:D.entry_path,error:D.error,method:D.trace.method,command:D.trace.command,capability:D.trace.capability,missing_capability:D.trace.missing_capability,registration_index:D.trace.registration_index,expected_schema:D.trace.expected_schema,hint:D.trace.hint,received:D.trace.received}))})}return s(_n)},qu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,global:o,withResult:s}=e,l=await A(i.settings_root),c=await ke({pmRoot:i.pm_root,settings:l,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),d=await xe(c);r.push(...c.warnings),r.push(...d.warnings);let p=po(t,c,d);if(t!==void 0&&p.extensions.length===0){let m=a.vocabulary==="package"?"package":"extension",g=[...new Set(c.loaded.map(_=>a.vocabulary==="package"&&typeof _.source_package=="string"&&_.source_package.trim().length>0?_.source_package.trim():_.name))].sort((_,u)=>_.localeCompare(u)),y=g.length>0?` Loaded ${m} names: ${g.join(", ")}.`:"";throw new f(`No loaded ${m} named "${t}" was found in ${n} scope.${y} Run pm ${m} explore to list discovered ${m}s.`,h.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},Wu=async(e,t,n)=>{let i=n,r=null;return[e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await vi(e.resolvedRoots.selected_root,e.scope,t,n),i=r.state),e.action==="manage"&&(i=await es(i,e.options.offline)),{state:i,fix:r}},Bu=async(e,t,n)=>{let i=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await xe({...i,loaded:i.loaded});return e.warnings.push(...i.warnings,...r.warnings),{installed:mn(n,i,r),failures:ys(r.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:i.failed.length,activation_failure_count:r.failed.length,warning_count:[...new Set([...i.warnings,...r.warnings])].length,policy:i.policy}}},Hu=(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},os=async e=>{let{action:t,scope:n,resolvedRoots:i,warnings:r,options:a,withResult:o}=e,s=await A(i.settings_root),l=Bm(s.extensions.policy),c=await he(i.selected_root);r.push(...c.warnings);let d=await ye(i.selected_root,n,s,c.state);r.push(...d.warnings);let{state:p,fix:m}=await Wu(e,d.extensions,c.state),g=await ye(i.selected_root,n,s,p);if(r.push(...g.warnings),t==="manage"&&a.offline===!0)for(let v of g.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=g.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);r.push(...v)}let y=await Bu(e,s,g.extensions),_=y.installed,u=un(n,r,_,a);r.push(...u.warnings);let w={total:_.length,managed_total:_.filter(v=>v.managed).length,enabled_total:_.filter(v=>v.enabled).length,active_total:_.filter(v=>v.active).length,extensions:_,triage:u,policy:l};return y.failures!==void 0&&(w.activation_diagnostics={failed_count:y.failures.length,failed:y.failures}),t==="explore"&&(w.runtime_probe=y.summary),t==="manage"&&(w.runtime_probe=y.summary,w.managed_state_fix=Hu(m,_)),o(w)},ss={init:_u,install:Ru,uninstall:Lu,explore:os,manage:os,describe:qu,reload:wu,doctor:Ju,catalog:vu,adopt:ju,"adopt-all":Nu,activate:as,deactivate:as,migrate:Dr},Ku=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),Vu=e=>Ku(e)?mi(e.resolvedRoots.settings_root,`${e.action}-state`,()=>ss[e.action](e)):ss[e.action](e);import Si from"node:fs/promises";import J from"node:path";import ks from"node:readline/promises";import{stdin as xs,stdout as At}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a0706e-7162-5cde-9f48-c5de9b2fbd8e")}catch{}})();var Ss=["ask","add","skip","status"],Yu=["AGENTS.md","CLAUDE.md"],Xu=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Zu=8,Ei=1,Qu="<!-- pm-cli:agent-guidance:start:",ef=`<!-- pm-cli:agent-guidance:start:v${Ei} -->`,ki="<!-- pm-cli:agent-guidance:end -->",Ot="Add workflow guidance later: pm init --agent-guidance add",fb={toPortableRelativePath:Be,ensureTrailingNewline:xi,detectLineEnding:$s,findGuidanceBlockRange:$i,buildAgentGuidanceBlock:Is,upsertAgentGuidanceBlock:Ii,resolveProjectRoot:Ts,resolveTargetGuidancePath:Os,parsePromptChoice:Cs,pushUnique:Ne,promptForGuidanceWrite:Ps,normalizeAgentGuidanceState:Ai,applyAgentGuidanceState:Ns,writeGuidanceFile:Ti,setAgentGuidanceReadlineFactoryForTests:tf},Es=()=>ks.createInterface({input:xs,output:At});function tf(e){Es=e??(()=>ks.createInterface({input:xs,output:At}))}function Be(e,t){let n=J.relative(e,t);return n.length===0?J.basename(t):n.split(J.sep).join("/")}function xi(e){return e.endsWith(`
|
|
50
51
|
`)?e:`${e}
|
|
51
|
-
`}function
|
|
52
|
+
`}function $s(e){return e.includes(`\r
|
|
52
53
|
`)?`\r
|
|
53
54
|
`:`
|
|
54
|
-
`}function
|
|
55
|
+
`}function $i(e){let t=e.indexOf(Qu);if(t===-1)return null;let n=e.indexOf(ki,t);return n===-1?null:{start_index:t,end_index:n+ki.length}}function nf(e){return $i(e)!==null}function Is(e,t="<your project test command>"){return[ef,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and start atomically: `pm claim <id> --start`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",ki,""].join(e)}function Ii(e,t="<your project test command>"){let n=$s(e),i=Is(n,t),r=$i(e);if(r){let s=e.slice(r.end_index),l=s.startsWith(`\r
|
|
55
56
|
`)?s.slice(2):s.startsWith(`
|
|
56
|
-
`)?s.slice(1):s,c=
|
|
57
|
+
`)?s.slice(1):s,c=xi(`${e.slice(0,r.start_index)}${i}${l}`);return{next_content:c,changed:c!==e}}let a=e.length===0?"":e.endsWith(`
|
|
57
58
|
`)?`
|
|
58
59
|
`:`
|
|
59
60
|
|
|
60
|
-
`,o=
|
|
61
|
+
`,o=xi(`${e}${a}${i}`);return{next_content:o,changed:o!==e}}async function As(e){if(await k(J.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Si.readFile(J.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=rf(t);if(n===void 0)return"<your project test command>";let i=n.packageManager?.split("@")[0];return i==="pnpm"?"pnpm test":i==="bun"?"bun run test":i==="yarn"?"yarn test":i==="npm"?"npm test":await k(J.join(e,"pnpm-lock.yaml"))?"pnpm test":await k(J.join(e,"bun.lock"))||await k(J.join(e,"bun.lockb"))?"bun run test":await k(J.join(e,"yarn.lock"))?"yarn test":"npm test"}function rf(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 Ts(e,t){let n=J.dirname(e);return J.basename(e)==="pm"&&J.basename(n)===".agents"?J.dirname(n):J.resolve(t,e)}function Os(e,t){let n=e.find(r=>J.basename(r.file_path)==="AGENTS.md"&&r.exists);if(n)return n.file_path;let i=e.find(r=>r.exists);return i?i.file_path:J.join(t,"AGENTS.md")}function Cs(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 Ps(e){let t=Es();try{At.write(`
|
|
61
62
|
Agent guidance check
|
|
62
63
|
`),At.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
63
64
|
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return At.write(`
|
|
64
|
-
`),Os(n,!0)}finally{t.close()}}function Ii(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:Si,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,i)=>n.localeCompare(i)):[]}}async function Ps(e){let t=[],n=await Is(e);for(let i of Hu){let r=J.join(e,i),a=await k(r);if(!a){t.push({file_path:r,exists:a,has_guidance:!1,has_marker:!1});continue}let o=await xi.readFile(r,"utf8"),s=o.toLowerCase(),l=Ku.filter(d=>s.includes(d)),c=Qu(o);t.push({file_path:r,exists:a,has_guidance:c||l.length>=Vu,has_marker:c,outdated:c&&$i(o,n).changed})}return t}function Ne(e,t){e.includes(t)||e.push(t)}function Rs(e,t){let n=Ii(e),i=JSON.stringify(n)!==JSON.stringify(t);return i&&(e.agent_guidance=t),{changed:i,state:t}}async function Ai(e,t=J.dirname(e)){let n=await k(e)?await xi.readFile(e,"utf8"):"",i=$i(n,await Is(t));return i.changed?(await se(e,i.next_content),{changed:!0,warnings:await H({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function tf(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>We(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>We(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>We(e.projectRoot,t.file_path))}}async function nf(e,t,n){return e?await Ps(n):t}function Tt(e,t,n){e.state={...e.state,...n,template_version:Si,last_checked_files:t}}async function Ns(e,t){if(t.presentBefore)return;let n=await Ai(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function rf(e,t){t||(e.warnings.push("agent_guidance:missing"),Ne(e.nextSteps,Ot))}function af(e,t){e.skipped=!0,Tt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Ne(e.nextSteps,Ot)}async function of(e,t){await Ns(e,t),Tt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function sf(e,t){e.state.declined&&Tt(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function cf(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ne(e.nextSteps,Ot)}async function lf(e,t){if(e.prompted=!0,await Cs(t.targetRelativePath)){await Ns(e,t),Tt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,Tt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ne(e.nextSteps,Ot)}function df(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ne(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Ne(e.nextSteps,Ot)}async function pf(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(rf(n,t.presentBefore),n):t.mode==="skip"?(af(n,t.checkedFiles),n):t.mode==="add"?(await of(n,t),n):t.presentBefore?(sf(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(cf(n),n):t.interactive?(await lf(n,t),n):(df(n),n)}async function Ds(e){let t=As(e.pm_root,e.cwd),n=await Ps(t),i=Ts(n,t),r=We(t,i),a=n.map(d=>We(t,d.file_path)),o=n.some(d=>d.has_guidance),s=await pf(Ii(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:i,targetRelativePath:r,checkedFiles:a,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let d of n.filter(p=>p.outdated)){let p=await Ai(d.file_path,t);s.applied||=p.changed,s.warnings.push(...p.warnings)}let l=Rs(e.settings,s.state);n=await nf(s.applied,n,t);let c=n.filter(d=>d.outdated).map(d=>We(t,d.file_path));return c.length>0&&(s.warnings.push(`agent_guidance_outdated:${c.join(",")}`),Ne(s.nextSteps,"pm init --agent-guidance add")),{summary:tf({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:r,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:l.changed}}import mf from"node:fs/promises";import F from"node:path";import Ls from"node:readline/promises";import{stdin as Fs,stdout as ee}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ffab1407-659d-5bc4-95ff-5efe52baf522")}catch{}})();var uf=Symbol.for("pm.sdk.init-invocation-cwd");function Nb(e,t=!1){if(t){let n=e.warnings.filter(r=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(r)),i=n.includes("agent_guidance:missing_non_interactive")?e.next_steps.filter(r=>r.includes("--agent-guidance")):[];return{ok:e.ok,path:e.path,governance_preset:e.governance_preset,telemetry:`${e.settings.telemetry.enabled?"enabled":"disabled"} (${e.settings.telemetry.capture_level})`,created_count:e.created_dirs.length,next_steps:[...i,...e.next_steps.filter(r=>!i.includes(r))].slice(0,3),...n.length>0?{warnings:n.join("; ")}:{},details:`${st(["--pm-path",e.path,"init","--verbose"])} for full setup details and notices (or --json)`}}return{ok:e.ok,path:e.path,target:e.target,id_prefix:e.settings.id_prefix,governance_preset:e.governance_preset,telemetry:{enabled:e.settings.telemetry.enabled,capture_level:e.settings.telemetry.capture_level},output_format:e.settings.output.default_format,created_dirs_count:e.created_dirs.length,created_dirs:e.created_dirs,warnings:e.warnings,wizard_used:e.wizard_used,...e.registered_type_preset?{registered_type_preset:e.registered_type_preset}:{},...e.installed_packages?{installed_packages:e.installed_packages}:{},next_steps:e.next_steps,agent_guidance:e.agent_guidance,hint:"Re-run with --verbose for the full settings tree."}}var Db={normalizeInitGovernancePreset:Ti,normalizeInitTypePreset:Gs,normalizeOptionalInitAuthor:Us,normalizeInitAgentGuidanceMode:qs,isPathLikeInitTarget:gn,resolveInitInvocation:zs,resolveInitPrefixInput:Js,parseYesNoChoice:Ws,applyGovernancePreset:Oi,runInitWizard:Xs,setInitReadlineFactoryForTests:ff,summarizeInstalledPackages:Bs,buildInitNextSteps:Zs,registerInitTypePreset:Hs,assertExplicitTrackerPathIsNotWorkspaceRoot:Vs,isLikelyWorkspaceRoot:Ks,installInitMergeFence:Qs},Ms=()=>Ls.createInterface({input:Fs,output:ee});function ff(e){Ms=e??(()=>Ls.createInterface({input:Fs,output:ee}))}function hf(){return structuredClone(vn)}var gf=["minimal","default","strict"];function Ti(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new f("--preset must not be empty",h.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new f(`Invalid --preset value "${e}". Allowed: ${gf.join(", ")}`,h.USAGE)}function Gs(e){if(e!==void 0){if(e.trim().length===0)throw new f("--type-preset must not be empty",h.USAGE);try{return cn(e)}catch{throw new f(`Invalid --type-preset value "${e}". Allowed: ${St.join(", ")}`,h.USAGE)}}}function Us(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new f("--author must not be empty",h.USAGE);return t}function gn(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:F.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function zs(e,t,n,i){let r=i?.trim();if(i!==void 0&&r?.length===0)throw new f("--workspace must not be empty",h.USAGE);if(r!==void 0){if(t.path!==void 0||gn(n))throw new f("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",h.USAGE);let c=F.resolve(e,r),d=F.join(c,".agents","pm");return{pmRoot:d,prefixArg:n,target:{mode:"workspace-path",tracker_root:d,workspace_root:c}}}if(t.path===void 0&&gn(n)){let c=F.resolve(e,n.trim());return{pmRoot:c,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:c}}}let a=N(e,t.path),o=F.join(F.resolve(e),".agents","pm"),s=F.dirname(F.dirname(a)),l=F.resolve(a)===o?"current":"ancestor";return{pmRoot:a,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:a,workspace_root:s,discovery:l,requested_cwd:F.resolve(e),...l==="ancestor"?{suggested_current_tracker_root:o}:{}}:{mode:"tracker-path",tracker_root:a}}}function Js(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new f("--id-prefix must not be empty",h.USAGE);if(gn(t))throw new f(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,h.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&$e(e)!==$e(t))throw new f(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,h.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${$e(e)}`,`pm init --id-prefix ${$e(t)}`]});return t}function qs(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new f("--agent-guidance must not be empty",h.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new f(`Invalid --agent-guidance value "${e}". Allowed: ${xs.join(", ")}`,h.USAGE)}function Ws(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Oi(e,t){let n=Li[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function yf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bs(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(yf).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Hs(e,t,n){let i=V(t.schema),r=re(e,i.files.types,Z.types),a=le(await G(r)),o=[],s=[];for(let l of Et(n)){let c=He(a,l);a=c.file,(c.replaced?s:o).push(c.definition.name)}return await Be({pmRoot:e,filePath:r,raw:ue(a),op:"init:type-preset",author:B(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:o,updated:s,file:r}}async function Ks(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",F.join(".agents","pm")];for(let n of t)if(await k(F.join(e,n)))return!0;return!1}async function Vs(e,t,n){if(!t||n||await k(F.join(e,"settings.json"))||!await Ks(e))return;let i=F.join(e,".agents","pm");throw new f(`Refusing to initialize tracker files directly in workspace root "${e}".`,h.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${i} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${i} init --yes`}})}async function Ys(e,t){let n=[],i=[];for(let r of t){let a=r?F.join(e,r):e,o=await k(a);await mf.mkdir(a,{recursive:!0}),o?i.push(`already_exists:${a}`):n.push(a),i.push(...await H({path:a,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:i}}async function Xs(e,t){let n=Ms();try{ee.write(`pm init setup wizard (agent-optimized)
|
|
65
|
+
`),Cs(n,!0)}finally{t.close()}}function Ai(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:Ei,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,i)=>n.localeCompare(i)):[]}}async function Rs(e){let t=[],n=await As(e);for(let i of Yu){let r=J.join(e,i),a=await k(r);if(!a){t.push({file_path:r,exists:a,has_guidance:!1,has_marker:!1});continue}let o=await Si.readFile(r,"utf8"),s=o.toLowerCase(),l=Xu.filter(d=>s.includes(d)),c=nf(o);t.push({file_path:r,exists:a,has_guidance:c||l.length>=Zu,has_marker:c,outdated:c&&Ii(o,n).changed})}return t}function Ne(e,t){e.includes(t)||e.push(t)}function Ns(e,t){let n=Ai(e),i=JSON.stringify(n)!==JSON.stringify(t);return i&&(e.agent_guidance=t),{changed:i,state:t}}async function Ti(e,t=J.dirname(e)){let n=await k(e)?await Si.readFile(e,"utf8"):"",i=Ii(n,await As(t));return i.changed?(await oe(e,i.next_content),{changed:!0,warnings:await H({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function af(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=>Be(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Be(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Be(e.projectRoot,t.file_path))}}async function of(e,t,n){return e?await Rs(n):t}function Tt(e,t,n){e.state={...e.state,...n,template_version:Ei,last_checked_files:t}}async function Ds(e,t){if(t.presentBefore)return;let n=await Ti(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function sf(e,t){t||(e.warnings.push("agent_guidance:missing"),Ne(e.nextSteps,Ot))}function cf(e,t){e.skipped=!0,Tt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Ne(e.nextSteps,Ot)}async function lf(e,t){await Ds(e,t),Tt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function df(e,t){e.state.declined&&Tt(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function pf(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ne(e.nextSteps,Ot)}async function mf(e,t){if(e.prompted=!0,await Ps(t.targetRelativePath)){await Ds(e,t),Tt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,Tt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ne(e.nextSteps,Ot)}function uf(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ne(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Ne(e.nextSteps,Ot)}async function ff(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(sf(n,t.presentBefore),n):t.mode==="skip"?(cf(n,t.checkedFiles),n):t.mode==="add"?(await lf(n,t),n):t.presentBefore?(df(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(pf(n),n):t.interactive?(await mf(n,t),n):(uf(n),n)}async function js(e){let t=Ts(e.pm_root,e.cwd),n=await Rs(t),i=Os(n,t),r=Be(t,i),a=n.map(d=>Be(t,d.file_path)),o=n.some(d=>d.has_guidance),s=await ff(Ai(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:i,targetRelativePath:r,checkedFiles:a,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let d of n.filter(p=>p.outdated)){let p=await Ti(d.file_path,t);s.applied||=p.changed,s.warnings.push(...p.warnings)}let l=Ns(e.settings,s.state);n=await of(s.applied,n,t);let c=n.filter(d=>d.outdated).map(d=>Be(t,d.file_path));return c.length>0&&(s.warnings.push(`agent_guidance_outdated:${c.join(",")}`),Ne(s.nextSteps,"pm init --agent-guidance add")),{summary:af({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:r,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:l.changed}}import hf from"node:fs/promises";import F from"node:path";import Fs from"node:readline/promises";import{stdin as Ms,stdout as ee}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ffab1407-659d-5bc4-95ff-5efe52baf522")}catch{}})();var gf=Symbol.for("pm.sdk.init-invocation-cwd");function Fb(e,t=!1){if(t){let n=e.warnings.filter(r=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(r)),i=n.includes("agent_guidance:missing_non_interactive")?e.next_steps.filter(r=>r.includes("--agent-guidance")):[];return{ok:e.ok,path:e.path,governance_preset:e.governance_preset,telemetry:`${e.settings.telemetry.enabled?"enabled":"disabled"} (${e.settings.telemetry.capture_level})`,created_count:e.created_dirs.length,next_steps:[...i,...e.next_steps.filter(r=>!i.includes(r))].slice(0,3),...n.length>0?{warnings:n.join("; ")}:{},details:`${st(["--pm-path",e.path,"init","--verbose"])} for full setup details and notices (or --json)`}}return{ok:e.ok,path:e.path,target:e.target,id_prefix:e.settings.id_prefix,governance_preset:e.governance_preset,telemetry:{enabled:e.settings.telemetry.enabled,capture_level:e.settings.telemetry.capture_level},output_format:e.settings.output.default_format,created_dirs_count:e.created_dirs.length,created_dirs:e.created_dirs,warnings:e.warnings,wizard_used:e.wizard_used,...e.registered_type_preset?{registered_type_preset:e.registered_type_preset}:{},...e.installed_packages?{installed_packages:e.installed_packages}:{},next_steps:e.next_steps,agent_guidance:e.agent_guidance,hint:"Re-run with --verbose for the full settings tree."}}var Mb={normalizeInitGovernancePreset:Oi,normalizeInitTypePreset:Us,normalizeOptionalInitAuthor:zs,normalizeInitAgentGuidanceMode:Ws,isPathLikeInitTarget:gn,resolveInitInvocation:Js,resolveInitPrefixInput:qs,parseYesNoChoice:Bs,applyGovernancePreset:Ci,runInitWizard:Zs,setInitReadlineFactoryForTests:yf,summarizeInstalledPackages:Hs,buildInitNextSteps:Qs,registerInitTypePreset:Ks,assertExplicitTrackerPathIsNotWorkspaceRoot:Ys,isLikelyWorkspaceRoot:Vs,installInitMergeFence:ec},Gs=()=>Fs.createInterface({input:Ms,output:ee});function yf(e){Gs=e??(()=>Fs.createInterface({input:Ms,output:ee}))}function _f(){return structuredClone(vn)}var wf=["minimal","default","strict"];function Oi(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: ${wf.join(", ")}`,h.USAGE)}function Us(e){if(e!==void 0){if(e.trim().length===0)throw new f("--type-preset must not be empty",h.USAGE);try{return cn(e)}catch{throw new f(`Invalid --type-preset value "${e}". Allowed: ${St.join(", ")}`,h.USAGE)}}}function zs(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new f("--author must not be empty",h.USAGE);return t}function gn(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:F.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function Js(e,t,n,i){let r=i?.trim();if(i!==void 0&&r?.length===0)throw new f("--workspace must not be empty",h.USAGE);if(r!==void 0){if(t.path!==void 0||gn(n))throw new f("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",h.USAGE);let c=F.resolve(e,r),d=F.join(c,".agents","pm");return{pmRoot:d,prefixArg:n,target:{mode:"workspace-path",tracker_root:d,workspace_root:c}}}if(t.path===void 0&&gn(n)){let c=F.resolve(e,n.trim());return{pmRoot:c,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:c}}}let a=N(e,t.path),o=F.join(F.resolve(e),".agents","pm"),s=F.dirname(F.dirname(a)),l=F.resolve(a)===o?"current":"ancestor";return{pmRoot:a,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:a,workspace_root:s,discovery:l,requested_cwd:F.resolve(e),...l==="ancestor"?{suggested_current_tracker_root:o}:{}}:{mode:"tracker-path",tracker_root:a}}}function qs(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new f("--id-prefix must not be empty",h.USAGE);if(gn(t))throw new f(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,h.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&$e(e)!==$e(t))throw new f(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,h.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${$e(e)}`,`pm init --id-prefix ${$e(t)}`]});return t}function Ws(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: ${Ss.join(", ")}`,h.USAGE)}function Bs(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Ci(e,t){let n=Li[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function vf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hs(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(vf).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Ks(e,t,n){let i=Y(t.schema),r=re(e,i.files.types,Z.types),a=ce(await G(r)),o=[],s=[];for(let l of Et(n)){let c=Ke(a,l);a=c.file,(c.replaced?s:o).push(c.definition.name)}return await He({pmRoot:e,filePath:r,raw:me(a),op:"init:type-preset",author:B(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:o,updated:s,file:r}}async function Vs(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",F.join(".agents","pm")];for(let n of t)if(await k(F.join(e,n)))return!0;return!1}async function Ys(e,t,n){if(!t||n||await k(F.join(e,"settings.json"))||!await Vs(e))return;let i=F.join(e,".agents","pm");throw new f(`Refusing to initialize tracker files directly in workspace root "${e}".`,h.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${i} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${i} init --yes`}})}async function Xs(e,t){let n=[],i=[];for(let r of t){let a=r?F.join(e,r):e,o=await k(a);await hf.mkdir(a,{recursive:!0}),o?i.push(`already_exists:${a}`):n.push(a),i.push(...await H({path:a,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:i}}async function Zs(e,t){let n=Gs();try{ee.write(`pm init setup wizard (agent-optimized)
|
|
65
66
|
`),ee.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
66
67
|
|
|
67
68
|
`),ee.write(`1/3 Item ID prefix
|
|
@@ -71,10 +72,10 @@ Agent guidance check
|
|
|
71
72
|
`),ee.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
72
73
|
`),ee.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
73
74
|
`),ee.write(`strict: ownership blocking, strict create defaults, close validation strict.
|
|
74
|
-
`);let a=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),o=a.trim().length>0?a.trim():"minimal",s="minimal";try{s=
|
|
75
|
+
`);let a=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),o=a.trim().length>0?a.trim():"minimal",s="minimal";try{s=Oi(o)}catch{ee.write(`Unrecognized governance preset "${o}"; using minimal.
|
|
75
76
|
`)}ee.write(`
|
|
76
77
|
3/3 Project telemetry
|
|
77
78
|
`),ee.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
|
|
78
|
-
`);let l=t?"Y/n":"y/N",c=await n.question(`Enable telemetry for this project? [${l}] `),d=
|
|
79
|
-
`),{prefix:r,preset:s,telemetry_enabled:d}}finally{n.close()}}function
|
|
80
|
-
//# sourceMappingURL=chunk-
|
|
79
|
+
`);let l=t?"Y/n":"y/N",c=await n.question(`Enable telemetry for this project? [${l}] `),d=Bs(c,t);return ee.write(`
|
|
80
|
+
`),{prefix:r,preset:s,telemetry_enabled:d}}finally{n.close()}}function bf(e){return{presetFromOption:Oi(e.preset),useDefaults:e.defaults===!0,authorFromOption:zs(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:Ws(e.agentGuidance),typePreset:Us(e.typePreset)}}function kf(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 xf(e,t,n,i){if(t.length===0||n)return;let r=i.discovery==="ancestor";throw new f(`${r?`No tracker exists in ${i.requested_cwd}; pm init found an ancestor tracker at ${i.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,h.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:r?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:i.tracker_root,requested_path:i.requested_cwd,suggested_path:i.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...r?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...r?['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 Sf(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&&(Ci(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 Ef(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=kf({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return xf(e.settingsPath,n,e.options.force===!0,e.target),Sf({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Ee(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function $f(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,i,r=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let l=await Zs(t,vn.telemetry.enabled);t=l.prefix,n=l.preset,i=l.telemetry_enabled,r=!0}let a=n??"minimal",o=_f();o.id_prefix=t,Ci(o,a);let s=lr()?.trim()||void 0;return o.author_default=e.normalizedOptions.authorFromOption??s??"",i!==void 0&&(o.telemetry.enabled=i,o.telemetry.first_run_prompt_completed=!0),await Ee(e.pmRoot,o),{settings:o,normalizedPrefix:t,chosenPreset:n,wizardUsed:r}}async function Ls(e){return e.settingsExists?await Ef(e):await $f({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function If(e){let t=await js({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await Ee(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function Af(e,t){let n=[],i=[],r=await cr(e,t.schema);for(let a of r.created_paths)n.push(a),i.push(...await H({path:a,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:i}}async function Tf(e){if(e.typePreset===void 0)return;let t=await Ks(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 Of(e){let t=U(e.settings,W()).folders.filter(i=>!wn.includes(i)),n=await Xs(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function Cf(e){let t=F.resolve(e.tracker_root),n=F.dirname(t);return F.basename(t)==="pm"&&F.basename(n)===".agents"?F.dirname(n):e.workspace_root}async function Pf(e,t,n,i){if(!e)return;let r=await bi("all",{install:!0,project:!0},{...t,path:n});i.push(...r.warnings);let a=Hs(r),o=a.packages.filter(s=>!s.ok).map(s=>s.alias);if(!a.installed_all||o.length>0)throw new f(`pm init --with-packages did not install all bundled packages successfully${o.length>0?`: ${o.join(", ")}`:"."}`,h.GENERIC_FAILURE);return a}function Qs(e){let t=i=>st([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...i]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let i of e.agentGuidanceNextSteps){let r=e.target.mode==="workspace-discovery"?i:i.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(r)||n.push(r)}return n}async function ec(e,t,n,i=qn){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 r=await i({pmRoot:e,workspaceRoot:t});r.gitattributes.changed&&n.push(`updated:merge_fence:${r.gitattributes.path}`)}catch(r){if(!(r instanceof f))throw r;n.push(`merge_fence_skipped:install_failed:${r.context.code??"pm_error"}:${r.message}:run pm merge install after resolving the Git repository error`)}}async function Rf(e,t,n,i){if(e==null||n==="status")return;let r=await Gr(e,{pmRoot:t});r.changed&&i.push(`updated:gitignore:${r.path}`)}async function Gb(e,t,n={}){let i=t[gf],r=typeof i=="string"?i:process.cwd(),a=Js(r,t,e,n.workspace),o=a.pmRoot;e=qs(a.prefixArg,n.idPrefix);let s=bf(n);await Ys(o,a.target.mode==="tracker-path",n.force===!0);let l=[],c=[],d=F.join(o,"settings.json"),p=await k(d),m;p&&(m=await Ls({pmRoot:o,settingsPath:d,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:a.target}));let g=await Xs(o,wn);l.push(...g.createdDirs),c.push(...g.warnings),m??=await Ls({pmRoot:o,settingsPath:d,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:a.target});let{settings:y}=m,_=Cf(a.target),u=await Bt(_??F.dirname(o)),w=_??u,v=await If({pmRoot:o,cwd:w??r,agentGuidanceMode:s.agentGuidanceMode,settings:y,warnings:c}),x=await Af(o,y);l.push(...x.createdDirs),c.push(...x.warnings);let S=await Tf({pmRoot:o,settings:y,typePreset:s.typePreset,warnings:c});S&&(y=await A(o)),await Of({pmRoot:o,settings:y,createdDirs:l,warnings:c}),await Rf(w,o,s.agentGuidanceMode,c),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await ec(o,u,c);let O=await Pf(s.installBundledPackages,t,o,c),ae=Qs({installBundledPackages:s.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:v.next_steps,target:a.target});return{ok:!0,path:o,target:a.target,settings:y,created_dirs:l,warnings:c,governance_preset:y.governance.preset,wizard_used:m.wizardUsed,...S?{registered_type_preset:S}:{},...O?{installed_packages:O}:{},next_steps:ae,agent_guidance:v}}export{Tn as a,mc as b,Pr as c,Pn as d,xc as e,Sc as f,Ec as g,Dr as h,Yp as i,Lr as j,Rn as k,Ac as l,Oc as m,Gr as n,Ve as o,Pc as p,Rc as q,zr as r,qt as s,Me as t,Ut as u,Fn as v,zc as w,Jc as x,sh as y,Wt as z,Zc as A,mt as B,Vr as C,il as D,Bt as E,Jn as F,ta as G,Dh as H,jh as I,na as J,Lh as K,qn as L,ga as M,Qe as N,et as O,ya as P,ua as Q,Xe as R,Ze as S,fa as T,sl as U,Gh as V,qh as W,ra as X,dl as Y,sg as Z,xa as _,Ia as $,Vl as aa,Yl as ba,lw as ca,mw as da,uw as ea,$t as fa,fw as ga,hw as ha,gw as ia,yw as ja,_w as ka,ww as la,vw as ma,bw as na,kw as oa,xw as pa,Sw as qa,Ew as ra,$w as sa,Iw as ta,Aw as ua,Tw as va,Ow as wa,Cw as xa,Pw as ya,Rw as za,Nw as Aa,Dw as Ba,jw as Ca,Lw as Da,Fw as Ea,te as Fa,b as Ga,Xn as Ha,ud as Ia,he as Ja,Vt as Ka,Xl as La,ft as Ma,Yt as Na,za as Oa,Xa as Pa,di as Qa,po as Ra,t_ as Sa,_m as Ta,Wo as Ua,Bo as Va,gi as Wa,xo as Xa,Wp as Ya,Rm as Za,Eo as _a,bi as $a,Ss as ab,fb as bb,js as cb,gf as db,Fb as eb,Mb as fb,Gb as gb};
|
|
81
|
+
//# sourceMappingURL=chunk-5NR6TDYB.js.map
|