@unbrained/pm-cli 2026.9.8 → 2026.9.10
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/.agents/skills/pm-user/SKILL.md +2 -2
- package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +1 -1
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +38 -2
- package/dist/cli/command-namespaces.d.ts +9 -0
- package/dist/cli/command-namespaces.js +2 -0
- package/dist/cli/help-content.js +1 -1
- package/dist/cli/help-json-payload.d.ts +5 -1
- package/dist/cli/help-json-payload.js +2 -2
- package/dist/cli/main.d.ts +1 -0
- package/dist/cli/main.js +3 -3
- package/dist/cli/register-list-query.js +4 -4
- package/dist/cli/register-mutation.d.ts +0 -5
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-operations.d.ts +0 -5
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +154 -154
- package/dist/cli-bundle/chunks/chunk-4SFBH77G.js +2233 -0
- package/dist/cli-bundle/chunks/{chunk-LEZOUXG6.js → chunk-74RGSPLL.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-7WIHZI2M.js +5 -0
- package/dist/cli-bundle/chunks/{chunk-JAAEYHUA.js → chunk-EOCKPCEY.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GLQMKUGP.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-FLDWYEND.js → chunk-I6XT3DLQ.js} +62 -60
- package/dist/cli-bundle/chunks/chunk-MACGGTLQ.js +29 -0
- package/dist/cli-bundle/chunks/chunk-NKOYVKFM.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-YVEQ2AMO.js → chunk-P6BEYAON.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-G5ADGQ2D.js → chunk-PYUITRSV.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-T3AMFUCN.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-XOD2PCB6.js → chunk-TSWEX72T.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-YKQTETJI.js +235 -0
- package/dist/cli-bundle/chunks/{register-list-query-KSK3R63M.js → register-list-query-CUIW7SSE.js} +7 -7
- package/dist/cli-bundle/chunks/register-mutation-5F5CYUWZ.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-XIZPLPQY.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-BQ5SVD4B.js → register-setup-JVGPCAIL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RXT4P5QH.js → chunk-26O2WB73.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5YU75QLV.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-EE5QSM4Z.js → chunk-7N5MRONP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-B2CMFYRZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-OPFHFGDD.js → chunk-CRY5MHEI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-COPBO5HW.js → chunk-F6WKFXBT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HJVARYM3.js → chunk-FHUARRMA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3WRPWLA7.js → chunk-M36SF4GE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-OROZM37I.js +177 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7MBUII7U.js → chunk-PNGYYQY7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SL5YVVPV.js +58 -0
- package/dist/cli-bundle/focused-chunks/chunk-TPOL4TWE.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-RMWES4M6.js → chunk-U5SHHU7E.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XSMA2W6Q.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZAWAL2CG.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZDNAWWQI.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DUN4IXYN.js → chunk-ZJHYQOTM.js} +2 -2
- package/dist/cli-bundle/main.js +26 -26
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +29 -29
- 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 +42 -42
- 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 +10 -10
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/policy/workflow-policy-schema.d.ts +312 -0
- package/dist/core/policy/workflow-policy-schema.js +2 -0
- package/dist/core/policy/workflow-policy-store.d.ts +24 -0
- package/dist/core/policy/workflow-policy-store.js +2 -0
- package/dist/core/policy/workflow-policy.d.ts +139 -0
- package/dist/core/policy/workflow-policy.js +2 -0
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/settings-validator.d.ts +1 -0
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.js +1 -1
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.d.ts +11 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +4 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -3
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -0
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/completion.js +375 -347
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/validate.d.ts +3 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workflow-completeness.d.ts +32 -0
- package/dist/sdk/governance/workflow-completeness.js +2 -0
- package/dist/sdk/governance/workflow-policy.d.ts +47 -0
- package/dist/sdk/governance/workflow-policy.js +4 -0
- package/dist/sdk/governance.d.ts +1 -0
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/index.d.ts +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/lifecycle-transitions.d.ts +1 -1
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/recurrence-parsers.d.ts +1 -1
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/task-composition.d.ts +17 -0
- package/dist/sdk/lifecycle/task-composition.js +2 -0
- package/dist/sdk/lifecycle/update.js +1 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/search-contracts.d.ts +27 -0
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/query/search.d.ts +6 -4
- package/dist/sdk/query/search.js +2 -2
- package/dist/sdk/query/workspace-contracts.d.ts +3 -0
- package/dist/sdk/query/workspace-contracts.js +2 -0
- package/dist/sdk/read-output-contracts.d.ts +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-public-contracts.d.ts +2 -1
- package/dist/sdk/runtime.d.ts +73 -9
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/schema.d.ts +2 -1
- package/dist/sdk/schema.js +1 -1
- package/dist/types.d.ts +4 -0
- package/dist/types.js +1 -1
- package/docs/COMMANDS.md +36 -24
- package/docs/COMMAND_NAMESPACES.md +65 -0
- package/docs/CONFIGURATION.md +12 -1
- package/docs/LIFECYCLE_COMMANDS.md +77 -0
- package/docs/README.md +3 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +5 -0
- package/docs/TESTING.md +10 -0
- package/docs/WORKFLOW_POLICIES.md +129 -0
- package/docs/generated/AGENT_CAPABILITY_ROUTING.md +6 -6
- package/docs/generated/AGENT_COMMAND_SURFACE.md +19 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +23 -5
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +11 -5
- package/marketplace.json +2 -2
- package/package.json +5 -5
- 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/README.md +4 -2
- 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/README.md +6 -4
- 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-codex/.codex-plugin/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3BZZA6A3.js +0 -5
- package/dist/cli-bundle/chunks/chunk-AMRDVX36.js +0 -235
- package/dist/cli-bundle/chunks/chunk-DAM4CBBR.js +0 -2202
- package/dist/cli-bundle/chunks/chunk-KR3RP4FH.js +0 -3
- package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +0 -2
- package/dist/cli-bundle/chunks/chunk-QOEKOECV.js +0 -29
- package/dist/cli-bundle/chunks/chunk-RHSFOMHU.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-IQ5C7U6O.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-DWVHR2NC.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IAUOUGVR.js +0 -177
- package/dist/cli-bundle/focused-chunks/chunk-KOOMJ54F.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-MZDXX7JY.js +0 -56
- package/dist/cli-bundle/focused-chunks/chunk-QHNETP77.js +0 -9
- package/dist/cli-bundle/focused-chunks/chunk-SDOL6FM2.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-SQV4AAUC.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-WE3IUNIW.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-YALOUBWJ.js +0 -2
|
@@ -1,77 +1,79 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)}function
|
|
3
|
-
`)}async function
|
|
1
|
+
import{$a as U,$b as To,Aa as xt,Ba as dn,Bb as Ge,Ca as pn,Cc as No,Cj as or,D as yo,Ec as Et,Fc as Do,Gc as jo,H as cn,Hj as Ee,Ij as Tt,J as _o,Jj as Ot,Le as Mo,M as ln,Md as I,Mj as Re,N as f,Nd as X,Od as Lo,P as m,Pd as Y,Pf as At,Qc as B,Qd as oe,Qe as H,Qf as Uo,Re as Q,Rf as mn,Ri as Ko,Rj as rr,Rk as ir,S as wo,Sb as Io,Sd as Fo,Sf as zo,Si as Ce,Sj as gn,Tb as Ao,Td as nt,Tf as fn,Ti as ot,Ui as Vo,Un as Ct,Vd as $t,Vf as Jo,Vi as Yo,Wf as qo,Wi as ie,Xi as ze,Yi as Xo,Za as ko,Zc as K,Zf as Wo,Zi as le,_a as xo,aa as T,ac as Oo,cc as Co,eg as Bo,gj as ae,hb as P,ib as So,if as Go,j as ho,jb as Eo,jf as It,jj as A,kb as $o,kj as xe,n as k,na as vo,o as bt,p as re,pa as bo,pj as Zo,q as W,qa as V,qj as Qo,r as fe,rj as Se,sc as un,si as hn,sj as er,t as go,tc as Ro,tj as tr,ua as ce,uc as Po,ui as Ho,vc as St,vi as Ue,w as kt,wj as nr,xc as ve,zc as be,zi as ke}from"./chunk-YKQTETJI.js";import{mkdir as js,readFile as Ls}from"node:fs/promises";import pr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d7f490a-03a3-512c-ba3c-b19fcc9a1270")}catch{}})();var yn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Fs="sdk-workspace-transaction",Ms=/^[a-zA-Z0-9._-]+$/,Gs=30,Us=3e3;function ar(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Ms.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 cr(e,t,n){let o=e??t;if(!Number.isInteger(o)||o<=0)throw new TypeError(`${n} must be a positive integer`);return o}function ur(e,t){return pr.join(e,"transactions","sdk",`${t}.json`)}async function $e(e,t){t.updatedAt=T();let n=ur(e,t.transactionId);await js(pr.dirname(n),{recursive:!0}),await fe(n,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`)}function zs(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Pe(e){return Object.assign(Object.create(null),e)}function Js(e,t){try{let n=JSON.stringify(e,(o,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 _n(e,t){return e===void 0?void 0:Js(e,t)}function wn(e,t,n,o){let r=_n(n,o);r===void 0?delete e[t]:e[t]=r}function lr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dr(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function qs(e,t){if(!dr(e.startedStepIds,t)||!dr(e.completedStepIds,t)||!lr(e.results)||!lr(e.compensationData))return!1;let n=e.startedStepIds,o=new Set(n),r=e.completedStepIds,i=new Set(r);return Object.keys(e.compensationData).some(a=>!o.has(a))||Object.keys(e.results).some(a=>!i.has(a))?!1:e.status==="committed"?t.every(a=>i.has(a)):e.status!=="compensated"||i.size===0&&o.size===0}function Ws(e,t,n){let o;try{o=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let r=o,i=r.schemaVersion===1&&r.transactionId===t,a=Array.isArray(r.stepIds)&&r.stepIds.length===n.length&&r.stepIds.every((d,p)=>d===n[p]),s=qs(r,n),c=zs(r),l=["applying","compensating","compensated","committed"].includes(String(r.status));if(!i||!a||!s||!c||!l)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...r,results:Pe(r.results),compensationData:Pe(r.compensationData)}}async function Bs(e,t,n,o,r){let i=r,a=i!==void 0;if(i?.status==="compensating"&&await mr(e,i),i===void 0||i.status==="compensated"){let s=T();i={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(i?.attempt??0)+1,createdAt:i?.createdAt??s,updatedAt:s,stepIds:o,startedStepIds:[],completedStepIds:[],results:Pe(),compensationData:Pe()},await $e(e.pmRoot,i),await he(e,i,"prepared")}return{journal:i,recovered:a}}async function Hs(e,t,n){try{await Vs(t,e.steps),await $e(e.pmRoot,t);let o=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of e.steps){if(o.has(i.id))continue;let a=await i.inspect(),s=_n(a.result,`Step ${i.id} result`);if(a.state!=="applied"){let c=await i.prepareCompensation?.();wn(t.compensationData,i.id,c,`Step ${i.id} compensation data`),r.add(i.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>r.has(d)),await $e(e.pmRoot,t);let l=await i.apply();s=_n(l,`Step ${i.id} result`)}await he(e,t,"step_applied",i.id),o.add(i.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>o.has(c)),wn(t.results,i.id,s,`Step ${i.id} result`),await $e(e.pmRoot,t),await he(e,t,"step_recorded",i.id)}return await he(e,t,"committing"),t.status="committed",await $e(e.pmRoot,t),await he(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Pe(t.results)}}catch(o){if(o instanceof yn||t.status==="committed")throw o;try{await mr(e,t)}catch(r){throw new AggregateError([o,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw o}}async function Ks(e,t,n){try{return Ws(await Ls(ur(e,t),"utf8"),t,n)}catch(o){if(o!==null&&typeof o=="object"&&"code"in o&&re(o))return;throw o}}async function he(e,t,n,o){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...o===void 0?{}:{stepId:o}})}async function Vs(e,t){let n=new Set,o=Pe();for(let r of t){let i=await r.inspect();i.state==="applied"&&(n.add(r.id),wn(o,r.id,i.result,`Step ${r.id} result`))}e.results=o,e.completedStepIds=t.map(r=>r.id).filter(r=>n.has(r))}async function mr(e,t){t.status="compensating",await $e(e.pmRoot,t),await he(e,t,"compensating");let n=new Set(t.completedStepIds),o=new Set(t.startedStepIds);for(let r of[...e.steps].reverse()){if(!o.has(r.id)&&!n.has(r.id))continue;let i;try{i=o.has(r.id)&&(await r.inspect()).state==="applied"}catch{i=o.has(r.id)}i&&(await he(e,t,"step_compensating",r.id),await r.compensate(t.compensationData[r.id])),n.delete(r.id),o.delete(r.id),t.completedStepIds=e.steps.map(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>o.has(a)),delete t.results[r.id],delete t.compensationData[r.id],await $e(e.pmRoot,t),await he(e,t,"step_compensated",r.id)}t.status="compensated",await $e(e.pmRoot,t),await he(e,t,"compensated")}async function fr(e){let t=sr(e.pmRoot,"Transaction pmRoot"),n=ar(e.transactionId,"Transaction id"),o=sr(e.author,"Transaction author"),r=cr(e.lockTtlSeconds,Gs,"Transaction lock TTL"),i=cr(e.lockWaitMs,Us,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(d=>{let p=ar(d.id,"Transaction step id");if(p!==d.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return p});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:o,steps:a,lockTtlSeconds:r,lockWaitMs:i},l=await Q(t,Fs,r,o,!1,!1,i);try{let d=await Ks(t,n,s),p=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Pe(d.results)};let u=await Bs(c,n,o,s,d);return await Hs(c,u.journal,p||u.recovered)}finally{await l()}}import{readFile as Ys,writeFile as Xs}from"node:fs/promises";import rt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5b131b40-e139-5a7d-a6ef-633fe2cbee64")}catch{}})();var gr="# pm-cli:runtime-cache:start",vn="# pm-cli:runtime-cache:end",yr=".agents/pm",Zs=["runtime/","search/","locks/","transactions/","checkpoints/"],Qs=["search/eval-queries.json"];async function hr(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 m("The workspace .gitignore is not writable.",f.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 _r(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function bn(e){let t=e.replaceAll("\\","/");return rt.isAbsolute(e)||t===".."||t.startsWith("../")}function ec(e=yr){let t=_r(e);return[gr,...Zs.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Qs.map(n=>`!${t}/${n}`),vn].join(`
|
|
3
|
+
`)}async function wr(e,t={}){let n=rt.join(e,".gitignore"),o=yr;if(t.pmRoot!==void 0){let d=_r(rt.relative(rt.resolve(e),rt.resolve(t.pmRoot)));if(bn(d))return{path:n,changed:!1};d.length>0&&(o=d)}let r="";try{r=await hr(()=>Ys(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&re(d)))throw d}let i=r.indexOf(gr),a=r.indexOf(vn),c=(i>=0&&a>=i?`${r.slice(0,i)}${r.slice(a+vn.length)}`:r).trimEnd(),l=`${c.length>0?`${c}
|
|
4
4
|
|
|
5
|
-
`:""}${
|
|
6
|
-
`;return l===r?{path:n,changed:!1}:(await
|
|
7
|
-
`),s=
|
|
5
|
+
`:""}${ec(o)}
|
|
6
|
+
`;return l===r?{path:n,changed:!1}:(await hr(()=>Xs(n,l,"utf8")),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7999053-cf48-5588-b8c8-570789086dac")}catch{}})();var tc=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Je(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Et(t.extensionName));for(let g of t.extensionNames??[])n.add(Et(g));let o=g=>n.size===0||n.has(Et(g)),r=(g,w)=>vr(g.filter(v=>o(v.name)).map(w)),i=(g,w)=>vr(g.filter(v=>o(v.name)).flatMap(w)),{registrations:a,commands:s,parsers:c,preflight:l,services:d,renderers:p,hooks:u}=e,h=i(a.relationship_kinds??[],g=>g.definitions.map(w=>w.kind)),y=p.overrides.filter(g=>o(g.name)&&((g.commands?.length??0)>0||g.resultDiscriminator!==void 0)).map(g=>({format:g.format,commands:[...g.commands??[]],result_discriminator:g.resultDiscriminator!==void 0})).sort((g,w)=>g.format.localeCompare(w.format)),_=r(a.assurance_providers??[],g=>g.definition.id);return{capabilities:Do(e,t),commands:r(a.commands,g=>g.command),command_overrides:r(s.overrides,g=>g.command),command_handlers:r(s.handlers,g=>g.command),hooks:tc.filter(([g])=>u[g].some(w=>o(w.name))).map(([,g])=>g),flag_commands:r(a.flags,g=>g.target_command),item_types:i(a.item_types,g=>g.types.map(w=>w.name)),item_fields:i(a.item_fields,g=>g.fields.map(w=>w.name)),...h.length>0?{relationship_kinds:h}:{},migrations:i(a.migrations,g=>typeof g.definition.id=="string"?[g.definition.id]:[]),profiles:r(a.profiles,g=>g.profile.name),importers:r(a.importers,g=>g.importer),exporters:r(a.exporters,g=>g.exporter),search_providers:r(a.search_providers,g=>g.definition.name),vector_store_adapters:r(a.vector_store_adapters,g=>g.definition.name),..._.length>0?{assurance_providers:_}:{},parser_overrides:r(c.overrides,g=>g.command),service_overrides:r(d.overrides,g=>g.service),renderer_overrides:r(p.overrides,g=>g.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:l.overrides.filter(g=>o(g.name)).length,preflight_ownership:l.overrides.filter(g=>o(g.name)).map(g=>({commands:[...g.commands??[]]}))}}function vr(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d1a6b35-70e8-5a61-8ce6-3bea9ed8170b")}catch{}})();var nc="PM_SOURCE_CONTEXT_ACCESS",oc="PM_ALLOW_SOURCE_CONTEXT_WRITES";function br(e){let t=e[nc],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",o=n==="read_only"&&e[oc]?.trim()==="1";return{access:n,write_override_applied:o,source_writes_allowed:n==="write"||o}}import{readFile as Pt,realpath as kn,writeFile as rc}from"node:fs/promises";import{execFile as ic}from"node:child_process";import F from"node:path";import{promisify as ac}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0200a3f7-93f5-5aaf-a6e8-2239e5b2ec3a")}catch{}})();var Sn=ac(ic),Rt="# pm-cli:merge-drivers:start",Er="# pm-cli:merge-drivers:end",qe="# pm-cli:merge-drivers:v2:start",xn="# pm-cli:merge-drivers:v2:end",sc="merge-fence";function kr(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function $r(){let e=ce(import.meta.url,["../../.."]);return`${kr(process.execPath)} ${kr(F.join(e,"dist","cli.js"))}`}var Ir=[{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 cc(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),o=e.environment.PM_SOURCE_PM_PATH?.trim(),r=br(e.environment),i=!!(n&&o),a=t===void 0&&i&&(e.dryRun||r.source_writes_allowed);if(t!==void 0){let s=P(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:i,source_context_selected:!1,source_policy:r}}return a?{pm_root:F.resolve(o),workspace_start:F.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:r}:{pm_root:i?P(e.cwd,".agents/pm"):P(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:r}}async function En(e){try{let{stdout:t}=await Sn("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await kn(t.trim())}catch{return null}}async function Ar(e){let t=await En(e);if(t===null)throw new m("pm merge install requires a git repository (merge drivers are git configuration).",f.USAGE);return t}function $n(e,t){return F.relative(e,t).replaceAll("\\","/")}function de(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function xr(e,t){if(e[t]!=="'")return null;let n="";for(let o=t+1;o<e.length;o+=1){if(e.startsWith(`'"'"'`,o)){n+="'",o+=4;continue}if(e[o]==="'")return{value:n,nextOffset:o+1};n+=e[o]}return null}async function lc(e,t){let n=xr(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let o=xr(e,n.nextOffset+1);if(o===null||e.slice(o.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(F.basename(n.value))||F.basename(o.value)!=="cli.js"||F.basename(F.dirname(o.value))!=="dist"||!await k(n.value)||!await k(o.value))return!1;try{let r=F.dirname(F.dirname(o.value)),i=JSON.parse(await Pt(F.join(r,"package.json"),"utf8")),a=typeof i.bin=="object"&&i.bin!==null&&"pm"in i.bin?i.bin.pm:void 0;return i.name==="@unbrained/pm-cli"&&(i.bin==="dist/cli.js"||a==="dist/cli.js")}catch{return!1}}function In(e,t){let n=e.length>0?`${e}/`:"",o=[`${de(`${n}**/*.toon`)} merge=pm-item-toon`,`${de(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)o.push(`${de(`${n}${r}/*.toon`)} merge=pm-item-toon`),o.push(`${de(`${n}${r}/*.md`)} merge=pm-item-markdown`);return o.push(`${de(`${n}**/*.jsonl`)} merge=pm-relationship`),o.push(`${de(`${n}history/*.jsonl`)} merge=pm-history`),o.push(`${de(`${n}settings.json`)} merge=pm-json`),o.push(`${de(`${n}**/*.json`)} merge=pm-json`),o.push(`${de(`${n}extensions/**`)} -merge`),o.push(`${de(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),o}function Sr(e,t,n){let o=e.indexOf(t),r=e.indexOf(n);return o>=0&&r>o?`${e.slice(0,o)}${e.slice(r+n.length)}`:e.replace(t,"").replace(n,"")}async function Tr(e,t,n){let o=F.join(e,".gitattributes"),r="";try{r=await Pt(o,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&re(l)))throw l}let i=[qe,...t,xn].join(`
|
|
7
|
+
`),s=Sr(Sr(r,qe,xn),Rt,Er).trimEnd(),c=`${s.length>0?`${s}
|
|
8
8
|
|
|
9
9
|
`:""}${i}
|
|
10
|
-
`;return c===r?{path:o,changed:!1}:(n||await
|
|
11
|
-
`).map(v=>v.trim()).filter(v=>v.length>0):[],
|
|
12
|
-
`
|
|
13
|
-
|
|
14
|
-
`}function
|
|
15
|
-
`
|
|
16
|
-
`)}import Oc from"node:path";import{mkdir as Cc}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebcb45a2-996a-5194-8086-efe882dbcacc")}catch{}})();var rt=["agile","ops","research"],$c={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 Ot(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: ${rt.join(", ")}.`)}function it(e){return $c[e].map(t=>nt(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96cec314-edb6-5c51-abc4-d028bdc4f10c")}catch{}})();var Ic=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Ac(e){let t=Ic.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Tc(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Dr(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,o=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,r=new Map;for(let a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=Ac(s);if(c===void 0)continue;let l=r.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<o&&l.examples.push(s),r.set(c,l)}let i=[];for(let[a,s]of r.entries()){if(s.count<n)continue;let c=Tc(a);i.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:No(c)!==void 0})}return i.sort((a,s)=>s.count-a.count||a.name.localeCompare(s.name)),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a1b3ce0-e799-570c-9cec-4e67de048831")}catch{}})();var th=["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"],Ct="schema-types",jr="schema-statuses",Lr="schema-fields";function $e(e){return Me({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 oh(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let r;try{r=nt({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(f){throw new h(f instanceof Error?f.message:String(f),g.USAGE)}let i=await T(o),a=V(i.schema),s=oe(o,a.files.types,Y.types),c=[],l=X(t.author,i.author_default),d=ae(i),p=await Z(o,Ct,i.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let f=await q(s),y;try{y=ie(f)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.GENERIC_FAILURE)}try{Do(r,y);let w=new Map,m=B(i,K());for(let[_,v]of Object.entries(m.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!w.has(x)&&w.set(x,_)}jo(r,y,w)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}u=Ge(y,r),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await $e({pmRoot:o,filePath:s,raw:le(u.file),op:"schema:add-type",author:l,settings:i}),await at(o,[u.definition],c,"schema:add-type-folder"),c.push(...await W({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await Fr(o,c),{action:"add-type",registered:!0,replaced:u.replaced,type:u.definition,file:{path:s,definitions:u.file.definitions.length},warnings:Ie(c),generated_at:A()}}async function ye(e){await Ue(e)}async function Fr(e,t){try{let n=await fr(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 Ie(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Rc(e,t,n,o){let r=B(t,K()),i=o.trim().toLowerCase();return(await Oe(e,t.item_format,r.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===i).length}async function Pc(e,t,n,o){let r=B(t,K()),i=tt(n),a=I(o);return(await Oe(e,t.item_format,r.type_to_folder,[],n)).filter(c=>{let l=typeof c.status=="string"?c.status:"";return(i.alias_to_id.get(I(l))??I(l))===a}).length}async function Nc(e,t,n,o,r){if(r.length===0||Re.has(r))return;let i=await Pc(t,n,o,r);i>0&&e.push(`items_using_status:${i}`);let a=Mr(o.workflow,r);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function Mr(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,o])=>o!==void 0&&I(o)===t).map(([o])=>o)}async function rh(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let r=await T(o),i=V(r.schema),a=oe(o,i.files.types,Y.types),s=[],c=X(t.author,r.author_default),l=ae(r),d=await Z(o,Ct,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await q(a),f;try{f=ie(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=Lo(f,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=(p.definition?.name??e??"").trim();if(y.length>0){let w=await Rc(o,r,i,y);w>0&&s.push(`items_using_type:${w}`)}await $e({pmRoot:o,filePath:a,raw:le(p.file),op:"schema:remove-type",author:c,settings:r}),s.push(...await W({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return p.removed&&await Fr(o,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:a,definitions:p.file.definitions.length},warnings:Ie(s),generated_at:A()}}function En(e,t){return oe(e,t.files.statuses,Y.statuses)}function Rt(e,t){return oe(e,t.files.fields,Y.fields)}function Gr(e,t){return oe(e,t.files.types,Y.types)}async function at(e,t,n,o){for(let r of t){let i=ho(r.folder??fo(r.name)),a=Oc.join(e,i);await k(a)||(await Cc(a,{recursive:!0}),n.push(...await W({path:a,scope:"project",op:o})))}}function $n(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 Dc(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 jc(e){let t=new Map;for(let n of e){let o=I(n.id);if(o.length!==0){t.set(o,o);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let i=I(r);i.length>0&&!t.has(i)&&t.set(i,o)}}}return t}async function ih(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let r;try{r=xr({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(m){throw new h(m instanceof Error?m.message:String(m),g.USAGE)}let i=await T(o),a=V(i.schema),s=En(o,a),c=tt(a);try{bn(r,c.alias_to_id)}catch(m){throw new h(m instanceof Error?m.message:String(m),g.USAGE)}let l=Dc(c.by_id.get(r.id));if((r.roles??l?.roles??[]).length===0)throw new h(`Status "${r.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,g.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Te(r.id)}" --role active`,`pm schema add-status "${Te(r.id)}" --role blocked`]});let p=[],u=X(t.author,i.author_default),f=ae(i),y=await Z(o,jr,i.locks.ttl_seconds,u,!!t.force,f.force_required_for_stale_lock,i.locks.wait_ms),w;try{let m=await q(s),_;try{_=We(m)}catch(x){throw new h(x instanceof Error?x.message:String(x),g.GENERIC_FAILURE)}let v=jc(_.statuses);try{bn(r,v)}catch(x){throw new h(x instanceof Error?x.message:String(x),g.USAGE)}w=Sr(_,r,l),await $e({pmRoot:o,filePath:s,raw:He(w.file),op:"schema:add-status",author:u,settings:i}),p.push(...await W({path:s,scope:"project",op:"schema:add-status"}))}finally{await y()}return{action:"add-status",registered:!0,replaced:w.replaced,status:w.definition,file:{path:s,statuses:w.file.statuses.length},warnings:Ie(p),generated_at:A()}}async function ah(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let r=await T(o),i=V(r.schema),a=En(o,i),s=[],c=X(t.author,r.author_default),l=ae(r),d=await Z(o,jr,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await q(a),f;try{f=We(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=Er(f,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=I(p.definition?.id??e);await Nc(s,o,r,i,y),await $e({pmRoot:o,filePath:a,raw:He(p.file),op:"schema:remove-status",author:c,settings:r}),s.push(...await W({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:a,statuses:p.file.statuses.length},warnings:Ie(s),generated_at:A()}}function Ur(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 Lc(e,t,n){return{...Ur(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 zr(e){return{id:e.id,source:Re.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 Jr(e,t,n){let o=e.toLowerCase();return n.has(o)?"extension":t.has(o)?"custom":"builtin"}function Fc(){let e=new Map,t=K();for(let n of t?.item_types??[]){let o=n.types;if(Array.isArray(o))for(let r of o){if(typeof r!="object"||r===null||Array.isArray(r))continue;let i=r.name;typeof i=="string"&&i.trim().length>0&&e.set(i.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function Mc(e){let t=tt(e),n=[],o=[];for(let r of t.definitions){let i=zr(r);i.source==="builtin"?n.push(i):o.push(i)}return{builtin:n,custom:o}}async function st(e){let t=N(process.cwd(),e.path);await ye(t);let n=await T(t),o=V(n.schema),r=oe(t,o.files.types,Y.types),i=En(t,o),a=B(n,K()),s=Fc(),c=new Set((n.item_types?.definitions??[]).map(l=>l.name.trim().toLowerCase()).filter(l=>l.length>0&&!s.has(l)));return{pmRoot:t,typesPath:r,statusesPath:i,byType:a.by_type,customNames:c,extensionProvenance:s,schema:o}}async function sh(e){let t=await st(e),n=[],o=[],r=[];for(let s of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=Jr(s.name,t.customNames,new Set(t.extensionProvenance.keys())),l=Ur(s);c==="extension"?r.push(l):c==="custom"?o.push(l):n.push(l)}let i=Mc(t.schema),a=St(t.schema).definitions.map($n);return{action:"list",builtin:n,custom:o,extension:r,counts:{builtin:n.length,custom:o.length,extension:r.length,total:n.length+o.length+r.length},statuses:{builtin:i.builtin,custom:i.custom,counts:{builtin:i.builtin.length,custom:i.custom.length,total:i.builtin.length+i.custom.length}},fields:{custom:a,counts:{total:a.length}},file:{path:t.typesPath},generated_at:A()}}async function ch(e,t){let n=(e??"").trim();if(n.length===0)throw new h("Type name must not be empty.",g.USAGE);let o=await st(t),r=Object.values(o.byType).find(i=>i.name.toLowerCase()===n.toLowerCase()||i.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!r)throw new h(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Te(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Lc(r,Jr(r.name,o.customNames,new Set(o.extensionProvenance.keys())),o.extensionProvenance.get(r.name.toLowerCase())),file:{path:o.typesPath},generated_at:A()}}async function lh(e,t){let n=I(e);if(n.length===0)throw new h("Status id must not be empty.",g.USAGE);let o=await st(t),r=tt(o.schema),i=r.alias_to_id.get(n)??n,a=r.by_id.get(i);if(!a)throw new h(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Te(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:zr(a),file:{path:o.statusesPath},generated_at:A()}}async function dh(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let r;try{r=vr({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 h(y instanceof Error?y.message:String(y),g.USAGE)}let i=await T(o),a=V(i.schema),s=Rt(o,a),c=[],l=$t(r.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let d=X(t.author,i.author_default),p=ae(i),u=await Z(o,Lr,i.locks.ttl_seconds,d,!!t.force,p.force_required_for_stale_lock,i.locks.wait_ms),f;try{let y=await q(s),w;try{w=qe(y)}catch(m){throw new h(m instanceof Error?m.message:String(m),g.GENERIC_FAILURE)}f=br(w,r),await $e({pmRoot:o,filePath:s,raw:Be(f.file),op:"schema:add-field",author:d,settings:i}),c.push(...await W({path:s,scope:"project",op:"schema:add-field"}))}finally{await u()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:s,fields:f.file.fields.length},warnings:Ie(c),generated_at:A()}}async function Gc(e,t,n,o){let r=B(t,K());return(await Oe(e,t.item_format,r.type_to_folder,[],n)).filter(a=>{let s=a[o];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function ph(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let r=await T(o),i=V(r.schema),a=Rt(o,i),s=[],c=X(t.author,r.author_default),l=ae(r),d=await Z(o,Lr,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await q(a),f;try{f=qe(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=kr(f,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=I(p.definition?.key??e),w=I(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(w.length>0){let m=await Gc(o,r,i,w);m>0&&s.push(`items_using_field:${m}`)}await $e({pmRoot:o,filePath:a,raw:Be(p.file),op:"schema:remove-field",author:c,settings:r}),s.push(...await W({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:a,fields:p.file.fields.length},warnings:Ie(s),generated_at:A()}}async function uh(e){let t=await st(e),n=St(t.schema).definitions.map($n);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Rt(t.pmRoot,t.schema)},generated_at:A()}}async function mh(e,t){let n=I(e);if(n.length===0)throw new h("Field key must not be empty.",g.USAGE);let o=await st(t),r=St(o.schema).by_key.get(n);if(!r)throw new h(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Te(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:$n(r),file:{path:Rt(o.pmRoot,o.schema)},generated_at:A()}}async function fh(e,t,n){let o=N(process.cwd(),n.path);await ye(o);let r;try{let w=Ot(e);if(w===void 0)throw new Error(`Type preset name is required. Allowed: ${rt.join(", ")}.`);r=w}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}let i=await T(o),a=V(i.schema),s=Gr(o,a),c=[],l=X(t.author,i.author_default),d=ae(i),p=[],u=[],f,y=await Z(o,Ct,i.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms);try{let w=await q(s),m;try{m=ie(w)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let _=m;for(let v of it(r)){let x=Ge(_,v);_=x.file,(x.replaced?u:p).push(x.definition.name)}f=_.definitions.length,await $e({pmRoot:o,filePath:s,raw:le(_),op:"schema:apply-preset",author:l,settings:i}),await at(o,it(r),c,"schema:apply-preset-folder"),c.push(...await W({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:r,registered:p,replaced:u,file:{path:s,definitions:f},warnings:Ie(c),generated_at:A()}}function Uc(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new h("--min-count must be a positive integer (>= 1).",g.USAGE);return e}async function hh(e,t){let n=N(process.cwd(),t.path);await ye(n);let o=await T(n),r=V(o.schema),i=Gr(n,r),a=Uc(e.minCount),s=B(o,K()),l=(await Oe(n,o.item_format,s.type_to_folder,[],r)).map(x=>typeof x.title=="string"?x.title:""),d=Dr(l,{minCount:a}),p=[],u=[],f=[],y=[],w;if(!e.apply){let x;try{x=ie(await q(i))}catch(E){throw new h(E instanceof Error?E.message:String(E),g.GENERIC_FAILURE)}return w=x.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:d,registered:u,replaced:f,skipped:y,file:{path:i,definitions:w},warnings:p,generated_at:A()}}let m=X(e.author,o.author_default),_=ae(o),v=await Z(n,Ct,o.locks.ttl_seconds,m,!!e.force,_.force_required_for_stale_lock,o.locks.wait_ms);try{let x=await q(i),E;try{E=ie(x)}catch(G){throw new h(G instanceof Error?G.message:String(G),g.GENERIC_FAILURE)}let C=E;for(let G of d){if(G.shadows_builtin){y.push({name:G.name,reason:"shadows_builtin"});continue}let L;try{L=nt({name:G.name})}catch{y.push({name:G.name,reason:"invalid_type_token"});continue}let S=Ge(C,L);C=S.file,(S.replaced?f:u).push(S.definition.name)}w=C.definitions.length,await $e({pmRoot:n,filePath:i,raw:le(C),op:"schema:infer-types",author:m,settings:o}),await at(n,C.definitions.filter(G=>u.includes(G.name)||f.includes(G.name)),p,"schema:infer-types-folder"),p.push(...await W({path:i,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:d,registered:u,replaced:f,skipped:y,file:{path:i,definitions:w},warnings:Ie(p),generated_at:A()}}function gh(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 "${Te(e.type.name)}" "<title>"`}function yh(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 _h(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",o=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${o} in ${e.file.path}.`}function wh(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 vh(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,o]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])o.length!==0&&t.push(`${n}: ${o.map(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,o]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])o.length!==0&&t.push(`${n}: ${o.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(`
|
|
17
|
-
`)}function
|
|
18
|
-
`)}function kh(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(`
|
|
19
|
-
`)}function
|
|
20
|
-
`)}function
|
|
21
|
-
`)}function
|
|
22
|
-
`)}var Th={workflowSlotsReferencing:Mr};import Wr from"node:fs/promises";import Ne from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8269d712-f438-5f18-8137-ed9a0358e23b")}catch{}})();var Pt=["extensions","docs","examples","assets","prompts"],Jc=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 qc(e){return Pt.includes(e)}function Bc(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],o=[];for(let r of n){if(typeof r!="string"||r.trim().length===0)throw new h(`Package manifest field pm.${e} must contain string paths.`,g.USAGE);o.push(r.trim())}return[...new Set(o)].sort((r,i)=>r.localeCompare(i))}function Wc(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new h("Package manifest field pm must be an object.",g.USAGE);let t={},n=e;for(let[o,r]of Object.entries(n)){if(!qc(o))continue;let i=Bc(o,r);i.length>0&&(t[o]=i)}return t}function pe(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function In(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,o)=>n.localeCompare(o)):void 0}function qr(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 Hc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:pe(t,"docs"),npm:pe(t,"npm"),repository:pe(t,"repository"),report:pe(t,"report")};return Object.values(n).some(o=>typeof o=="string")?n:void 0}function Kc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:pe(t,"image"),video:pe(t,"video")};return Object.values(n).some(o=>typeof o=="string")?n:void 0}function Vc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:pe(t,"display_name")??pe(t,"displayName"),category:pe(t,"category"),summary:pe(t,"summary"),links:Hc(t.links),media:Kc(t.media),tags:In(t.tags)};return Object.values(n).some(o=>o!==void 0)?n:void 0}async function ct(e){let t=Ne.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await Wr.readFile(t,"utf8"))}catch(s){throw new h(`Failed to parse package manifest at "${t}": ${String(s)}`,g.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new h(`Package manifest at "${t}" must be a JSON object.`,g.USAGE);let o=n,r=o.pm,i=r!=null,a=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{};return{source:i?"pm":"convention",package_json_path:t,package_name:typeof o.name=="string"?o.name:void 0,package_version:typeof o.version=="string"?o.version:void 0,package_private:o.private===!0,package_description:typeof o.description=="string"?o.description:void 0,package_keywords:In(o.keywords),package_homepage:typeof o.homepage=="string"?o.homepage:void 0,package_repository_url:qr(o.repository),package_bugs_url:qr(o.bugs),aliases:In(a.aliases),resources:Wc(r),catalog:Vc(a.catalog)}}async function Br(e){if(!await k(e))return[];let t=await Wr.readdir(e,{withFileTypes:!0}),n=[];for(let o of t){if(!o.isDirectory())continue;let r=Ne.join(e,o.name);await k(Ne.join(r,"manifest.json"))&&n.push(r)}return n.sort((o,r)=>o.localeCompare(r))}async function Nt(e){if(await k(Ne.join(e,"manifest.json")))return[e];let n=(await ct(e)).resources.extensions??[],o=new Set;for(let r of n){if(r.includes("*")||r.startsWith("!"))throw new h(`Package extension entry "${r}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,g.USAGE);let i=Ne.resolve(e,r);if(!H(e,i))throw new h(`Package extension entry "${r}" resolves outside package root.`,g.USAGE);if(await k(Ne.join(i,"manifest.json"))){o.add(i);continue}for(let a of await Br(i))o.add(a)}if(n.length===0)for(let r of Jc.extensions)for(let i of await Br(Ne.join(e,r)))o.add(i);return[...o].sort((r,i)=>r.localeCompare(i))}import{execFile as gl}from"node:child_process";import R from"node:fs/promises";import jn from"node:os";import $ from"node:path";import{fileURLToPath as yl}from"node:url";import{promisify as _l}from"node:util";import wl from"npm-package-arg";import{extract as vl,list as bl}from"tar";import al from"node:fs/promises";import se from"node:path";import Hr from"node:fs/promises";import An from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="209566d6-107e-5c01-995a-96a6dc0e40ed")}catch{}})();function ee(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function b(e){return e.trim().toLowerCase()}function Dt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let o=t.length;for(;o>n&&t[o-1]==="-";)o-=1;let r=t.slice(n,o);if(r.length===0)throw new h("Extension manifest name must resolve to a non-empty directory name.",g.USAGE);if(r==="."||r==="..")throw new h('Extension manifest name must not resolve to "." or "..".',g.USAGE);return r}function Tn(e){return So(e)}async function Xc(e){try{let t=JSON.parse(await Hr.readFile(An.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(o=>typeof t.scripts?.[o]=="string")}}catch{return{has_build_script:!1}}}async function Yc(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new h(`Extension entry file is missing at "${t}".`,g.USAGE);let o=await Xc(n.source_root),r=o.package_name?`pm install npm:${o.package_name}`:void 0,i=n.source_input??n.source_root;return new h(`Extension entry "${e.entry}" is absent from GitHub source "${i}". pm install copies GitHub repositories without running package scripts${o.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."}`,g.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 ${i}`,normalized_args:["install",i],...r?{next_best_command:r}:{}}})}async function Ye(e,t={}){let n=An.join(e,"manifest.json");if(!await k(n))throw new h(`Extension manifest is missing at "${n}".`,g.USAGE);let o;try{o=JSON.parse(await Hr.readFile(n,"utf8"))}catch(a){throw new h(`Failed to parse extension manifest at "${n}": ${Qc(a)}`,g.USAGE)}let r=Tn(o);if(!r)throw new h(`Extension manifest at "${n}" is invalid.`,g.USAGE);let i=An.resolve(e,r.entry);if(!H(e,i))throw new h(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await k(i))throw await Yc(r,i,t);if(!await Eo(e,i))throw new h(`Extension entry "${r.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:i,manifest:r}}function Qc(e){return e instanceof Error?e.message:String(e)}import On from"node:fs/promises";import Zc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="33b7f318-cc64-55d6-8b57-19a618efe6c0")}catch{}})();var el=".managed-extensions.json",jt=1;function lt(e){return Zc.join(e,el)}function tl(){return{version:jt,updated_at:A(),entries:[]}}function dt(e){return[...e].sort((t,n)=>{let o=t.scope.localeCompare(n.scope);if(o!==0)return o;let r=t.name.localeCompare(n.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function Kr(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function te(e){return typeof e=="string"?e:void 0}function nl(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 ol(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:te(t.name),package:te(t.package),version:te(t.version),repository:te(t.repository),owner:te(t.owner),repo:te(t.repo),ref:te(t.ref),subpath:te(t.subpath),commit:te(t.commit)}}function rl(e){if(typeof e!="object"||e===null)return null;let t=e;if(!nl(t))return null;let n=ol(t.source);if(!n)return null;let o=bo(t.contributions);return o===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:ee(t.capabilities),contributions:o,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:te(t.last_update_check_at),last_update_remote_commit:te(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:te(t.update_error)}}function il(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==jt||!Array.isArray(t.entries))return null;let n=[];for(let o of t.entries){let r=rl(o);r&&n.push(r)}return{version:jt,updated_at:te(t.updated_at)??A(),entries:dt(n)}}async function _e(e){let t=lt(e),n=tl();try{let o=await On.readFile(t,"utf8"),r=JSON.parse(o),i=il(r);if(!i)throw new h(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE);return{path:t,state:i,warnings:[]}}catch(o){if(o instanceof h)throw o;if(typeof o=="object"&&o!==null&&"code"in o&&re(o))return{path:t,state:n,warnings:[]};throw new h(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE)}}async function De(e,t){let n=lt(e),o={version:jt,updated_at:A(),entries:dt(t.entries)};await On.mkdir(e,{recursive:!0}),await On.writeFile(n,`${JSON.stringify(o,null,2)}
|
|
23
|
-
|
|
24
|
-
${i}`,g.GENERIC_FAILURE)}}function Sl(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function El(e=process.platform){return e==="win32"}async function ii(e,t,n=oi,o=process.platform,r=process.env){let i=Sl(o),a=Object.fromEntries(Object.entries(r).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(i,e,{cwd:t,encoding:"utf8",env:a,shell:El(o)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",l=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new h(`npm command failed: ${i} ${e.join(" ")}
|
|
25
|
-
|
|
26
|
-
`,
|
|
27
|
-
`,"utf8")}}function Ul(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Mt in t)return!0;return!1}function zl(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let o={...n};delete o[Mt],Object.keys(o).length===0?delete e[t]:e[t]=o}}async function Jl(e){let t=ce(import.meta.url,["../../.."]),[n,o]=Mt.split("/"),r=$.join(e,"node_modules",n),i=$.join(r,o);await R.mkdir(r,{recursive:!0}),await R.rm(i,{recursive:!0,force:!0}),await R.symlink(t,i,ql(process.platform))}function ql(e){return e==="win32"?"junction":"dir"}function Bl(e,t){if(e.startsWith("-"))throw new h(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,g.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(o=>{let r=o.charCodeAt(0);return r<=31||r===127||"&|;()`\"'".includes(o)}))throw new h(`Extension runtime dependency "${e}" has an unsafe version specifier.`,g.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{wl.resolve(e,t)}catch{throw new h(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,g.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function Wl(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[o,r]of Object.entries(n)){if(o===Mt||typeof r!="string"||r.trim().length===0||t.has(o))continue;let i=r.trim();t.set(o,Bl(o,i))}return[...t.values()]}async function Ut(e,t){let n=await Nt(e);if(n.length===1)return n[0];if(n.length>1){let o=n.map(r=>$.relative(e,r).replaceAll($.sep,"/")).sort((r,i)=>r.localeCompare(i));throw new h(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${o.join(", ")}`,g.USAGE)}throw new h(`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.`,g.USAGE)}async function Hl(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 i=$.resolve(e,r);if(H(e,i)&&await k($.join(i,"manifest.json")))return{directory:i,resolved_subpath:r}}if(await k($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let o=await Ut(e,t.input);return{directory:o,resolved_subpath:$.relative(e,o).replaceAll($.sep,"/")}}function Kl(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 Vl(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Kl(n))return new h(t,g.NOT_FOUND);let o=[];try{let i=process.env.PM_CLI_PACKAGE_ROOT,a=typeof i=="string"&&i.trim().length>0?$.resolve(i.trim()):"";Pn?.key!==a&&(Pn={key:a,aliases:await Lt()}),o=Pn.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): ${o.join(", ")}`];return new h(`${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}".`,g.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 di(e){if(e.kind==="local"){let o;try{o=await R.stat(e.absolute_path)}catch{throw await Vl(e)}if(o.isFile()&&li(e.absolute_path)){let i=await Dn(e.absolute_path);return{source:e,directory:i.directory,source_root:$.dirname(i.directory),resolved_subpath:$.relative($.dirname(i.directory),i.directory).replaceAll($.sep,"/"),npm_package:i.package,npm_version:i.version,cleanup:i.cleanup}}if(!o.isDirectory())throw new h(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,g.USAGE);let r=await Ut(e.absolute_path,e.input);return{source:e,directory:r,source_root:e.absolute_path}}if(e.kind==="npm"){let o=await Ll(e);return{source:e,directory:o.directory,source_root:$.dirname(o.directory),cleanup:o.cleanup,resolved_subpath:$.relative($.dirname(o.directory),o.directory).replaceAll($.sep,"/"),npm_package:o.package,npm_version:o.version}}let t=await R.mkdtemp($.join(jn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Ft(n);let o=await Ft(["-C",t,"rev-parse","HEAD"]),r=await Hl(t,e);return{source:e,directory:r.directory,source_root:t,resolved_subpath:r.resolved_subpath,commit:o,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(o){throw await R.rm(t,{recursive:!0,force:!0}),o}}async function zt(e,t){if(!await k(e)||!await k(t))return!1;let[n,o]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===o}import mt from"node:fs/promises";import ft from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60ab864f-43c5-512c-b33f-456de96f8090")}catch{}})();var Ln=1,je="2026.6.24",Xl=">=22.18.0",Yl={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},pi=new Set([...Po.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(ao).map(e=>e.toLowerCase()),"scaffold"]),Ql="^6.0.0",Zl="^22.0.0",fi=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],ue=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function ui(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function hi(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 gi(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 ed={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},mi=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],yi={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"]},td={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"]'},nd={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."},od={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."},_i="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",rd={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."]},id={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."]},ad={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`."]},sd={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 wi(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 vi(e,t){return e==="schema"?ad[t]:e==="profile"?sd[t]:id[t]}function cd(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),o=0;for(;t[o]?.toLowerCase()==="starter";)o+=1;let r=t[o]?.toLowerCase(),i=o>0&&(o===t.length||r!==void 0&&pi.has(r));return`${(pi.has(n)||i?["starter",...t]:t).join(" ")} ping`}function bi(e){let t=e,n=`${e}s`,o=e.replace(/-/g,""),r=o===t?[]:[o],i=`${e.replace(/-/g,"_")}_owner`,a="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(r)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(a)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(i)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(a)}],`,` [${JSON.stringify(a)}, "in_progress"],`,` [${JSON.stringify(a)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function ld(e,t,n){let o=`${e}-search`,r=`${e}-vector`,i=`${e.replace(/-/g," ")} items`,a=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return a;if(n==="search")return[...a,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(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,c=`${e}s`,l=e.replace(/-/g,""),d=l===s?[]:[l],p=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`;return[...a,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(u)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...a,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...bi(e).map(s=>` ${s}`)," });"]:n==="importers"?[...a,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(i)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(i)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...a,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...a,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...a,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...a,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function dd(e,t,n){let o=n==="hooks",r=n==="search",i=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",p=n==="services",u=td[n],f=e,y=`${e}s`,w=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`,_=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=o?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],x=r?Fn(e,t,"search",u):[],E=i?Fn(e,t,"importers",u):[],C=a?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...ui(hi({extensionName:e,itemTypeName:f,itemTypeFolder:y,fieldName:w,migrationId:m,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],G=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...ui(gi(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],L=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],S=l?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],J=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],et=p?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",..._,'} from "@unbrained/pm-cli/sdk/testing";',...r?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...fi,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...l?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...v,...x,...E,...C,...G,...L,...S,...J,...et,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
28
|
-
`)}function pd(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let o=`${e.replace(/-/g," ")} items`;return[t,`${o} import`,`${o} export`]}return[t]}var ud={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"},md={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 fd(e,t,n){let o=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...o?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...o?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function hd(e,t,n){let o=[],r=[...fd(e,t,n)],i=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,l=e,d=`${e}s`,p=e.replace(/-/g,""),u=p===l?[]:[p],f=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":o.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... */ }","});"),i.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":o.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(a)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),i.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":o.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,","}));"),i.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":o.push("defineItemField","defineItemType","defineMigration"),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(f)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(l)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(u)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(y)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),i.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":o.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({",...bi(e),"});"),i.push(" profiles: [starterProfile],");break;case"renderers":o.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);`," },","});"),i.push(" renderers: { toon: toonRenderer },");break;case"parser":o.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 };","});"),i.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":o.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,","});"),i.push(" preflights: [preflightOverride],");break;case"services":o.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 };`,"});"),i.push(" services: { output_format: outputService },");break}return{builderImports:o,definitions:r,blueprintFields:i}}function gd(e,t,n){let o=hd(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...o.builderImports].sort((i,a)=>i.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...o.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...o.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
|
|
29
|
-
`)}function Fn(e,t,n,o){if(n==="commands")return[];let r=`${e}-search`,i=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,l=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${o},`," });"],u=f=>[...p," let deactivated = false;"," try {",...f.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...u([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...u([` ext.assertSearchProvider({ name: ${JSON.stringify(r)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(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(i)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...u([` ext.assertImporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(a)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...u(hi({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:l,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(gi(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...u([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...u([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...u([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...u([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function yd(e,t,n){let o=n==="parser",r=JSON.stringify([...yi[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" };',"",...fi,`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)},`,...o?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...Fn(e,t,n,r)].join(`
|
|
30
|
-
`)}function _d(e,t,n){let o=wi(n,"package"),r=vi(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",o,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${ud[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`.",_i,"- `.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 ${md[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 \`${Ln}\` 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(`
|
|
31
|
-
`)}function wd(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function vd(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function bd(e,t,n,o){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(o.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(o.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&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(o.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(o.itemTypeName)},`,` folder: ${JSON.stringify(o.itemTypeFolder)},`,` aliases: ${JSON.stringify(o.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(o.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&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(o.itemTypeName)}, folder: ${JSON.stringify(o.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 kd(e,t,n){let o=[];return t==="renderers"&&o.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&o.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&o.push(" api.registerPreflight(preflightOverride);"),t==="services"&&o.push(' api.registerService("output_format", outputService);'),t==="hooks"&&o.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&o.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&o.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&o.push(" api.registerProfile(starterProfile);"),t==="importers"&&o.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),o}function xd(e,t,n,o="commands",r=!1){let i=`pm-${e}`,a=yi[o],s=pd(e,t,o),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Ln,pm_min_version:je,trusted:!0,sandbox_profile:"strict",permissions:{...Yl},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
|
|
32
|
-
|
|
33
|
-
`),
|
|
34
|
-
`,
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
10
|
+
`;return c===r?{path:o,changed:!1}:(n||await rc(o,c,"utf8"),{path:o,changed:!0})}function Or(e){let t=U(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,o)=>n.localeCompare(o))}async function yf(e,t){let n=F.resolve(e),o=null,r="",i=n;for(let v=0;v<8;v+=1){let x=F.join(i,".gitattributes");try{let C=await Pt(x,"utf8");if(C.includes(qe)||C.includes(Rt)){o=i,r=C;break}}catch{}let E=F.dirname(i);if(E===i)break;i=E}if(o===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let a=F.join(o,".gitattributes"),s=r.includes(qe),c=s?qe:Rt,l=s?xn:Er,d=r.indexOf(c),p=r.indexOf(l),u=p>d?r.slice(d+c.length,p).split(`
|
|
11
|
+
`).map(v=>v.trim()).filter(v=>v.length>0):[],h=In($n(o,n),t),y=new Set(u),_=new Set(h),g=h.filter(v=>!y.has(v)),w=u.filter(v=>!_.has(v));return{status:g.length>0||w.length>0?"drift":"ok",path:a,missing_patterns:g,stale_patterns:w,schema_scope:"project"}}async function _f(e){let t=$r(),n=[],o=[];for(let r of Ir){let i=`merge.${r.key}.driver`,a=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`,s=`${t}${a}`;try{let{stdout:c}=await Sn("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==s&&!await lc(l,a)&&o.push(i)}catch{n.push(i)}}return{status:n.length>0?"missing":o.length>0?"drift":"ok",missing_keys:n,drifted_keys:o}}async function Cr(e){let t;try{t=await Ar(F.resolve(e))}catch{return{status:"no_git"}}let n=$n(t,F.resolve(e)),o=await A(e),r=H(void 0,o.author_default),i=await Q(e,sc,o.locks.ttl_seconds,r,!1,ae(o).force_required_for_stale_lock,o.locks.wait_ms);try{let a=F.join(t,".gitattributes"),s;try{s=await Pt(a,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&re(p))return{status:"not_installed",path:a};throw p}if(!s.includes(qe)&&!s.includes(Rt))return{status:"not_installed",path:a};let c=await A(e),l=Or(c),d=await Tr(t,In(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await i()}}async function wf(e,t){let n=cc({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),o=n.pm_root;await Ee(o);let r=await Ar(n.workspace_start);return An({pmRoot:o,workspaceRoot:r,dryRun:e.dryRun===!0})}async function An(e){let t=F.resolve(e.pmRoot),n=F.resolve(e.workspaceRoot),o=e.dryRun===!0,r,i;try{[r,i]=await Promise.all([kn(t),kn(n)])}catch(h){throw new m(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(h)}`,f.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let a=$n(i,r);if(bn(a))throw new m(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,f.USAGE);let s=await A(r),c=Or(s),l=In(a,c),d=[],p=$r();for(let h of Ir)d.push({key:`merge.${h.key}.name`,value:h.name}),d.push({key:`merge.${h.key}.driver`,value:`${p} merge driver ${h.artifact} "%O" "%A" "%B"${h.itemPath===void 0?"":` --item-path ${h.itemPath}`}`});if(!o)try{for(let h of d)await Sn("git",["config","--local",h.key,h.value],{cwd:i,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new m(`Cannot install repository-local merge drivers in ${i}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,f.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let u=await Tr(i,l,o);return{ok:!0,dry_run:o,workspace_root:i,pm_root:r,gitattributes:{path:u.path,changed:u.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0daf7c89-abc5-5c35-ba3f-9772a50408c0")}catch{}})();var it={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Nt={type:"array",minItems:1,maxItems:mn,items:it},Rr={...Nt,items:{...it,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},dc={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Nt])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:it,id:it}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Rr}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Nt}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Rr,authors:Nt}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:mn,items:{type:"array",minItems:2,maxItems:2,items:it}}}}]}}},kf={$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:Uo,items:dc}}};(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]="e94b776a-9886-57bc-ba87-06f4a30de578")}catch{}})();async function $f(e,t,n,o){let r=await Se(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"]}:Pr(r,t,n,o)}function Pr(e,t,n=5,o=!1){let r=[],i=new Map,a=0,s=0,c=0,l=Wo(e);for(let p of t){let h=l({operation:"",author:"",before:p,after:p,completeness_only:!0}).decisions.filter(_=>!_.satisfied);if(h.length===0)continue;s+=1;let y=i.get(p.type)??{items:0,violations:0,missing_fields:0};y.items+=1;for(let _ of h)a+=1,y.violations+=1,y.missing_fields+=_.missing_fields.length,_.effect==="refuse"&&(c+=1),r.length<n&&r.push({id:p.id,type:p.type,status:p.status,decision:_});i.set(p.type,y)}let d=o||c>0?"error":a>0?"warn":"ok";return{check:{name:"completeness",status:d,ok:d==="ok",details:{scope:"operation_independent_require_fields",checked_items:t.length,incomplete_items:s,violation_count:a,refused_violations:c,missing_by_type:Object.fromEntries(i),violations:r,violations_truncated:r.length<a,enforcement:e.enforcement}},warnings:[...a>0?[`validate_completeness_missing_fields:${a}`]:[],...o?["validate_completeness_source_incomplete"]:[]]}}import pc 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]="e60a4620-c210-5d5e-baf4-d96467406cf4")}catch{}})();function uc(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([t,n])=>({id:`completeness-${t.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${t} work reaches completion.`,subject:{types:[t],statuses:["closed"]},rule:{kind:"require_fields",fields:[...n]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function Dr(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new m("Policy definition must be valid JSON.",f.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new m("Policy definition must be an object.",f.USAGE);return t}async function mc(e,t){let n=P(process.cwd(),e.path);await Ee(n);let o=await A(n);return{pmRoot:n,settings:o,author:H(t,o.author_default)}}function Nr(e,t,n,o){if(e==="policy-mode")return fn({...n,enforcement:t});let r=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:r};let i=zo(Dr(o.definition));if(i.id!==t)throw new m("Policy definition id must match its operand.",f.USAGE);let a=fn({...n,policies:[...r,i].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(a,null,2)}
|
|
12
|
+
`)>Zo)throw new m("Policy registry exceeds its byte ceiling.",f.USAGE);return a}async function fc(e,t,n,o){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:Nr(e,t,await Se(o.pmRoot),n)};let r=await Ho({pmRoot:o.pmRoot,filePath:pc.join(o.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:o.author,message:n.message,lockTtlSeconds:o.settings.locks.ttl_seconds,lockWaitMs:o.settings.locks.wait_ms,mutate(i){let a=Nr(e,t,Qo(i),n);return{raw:`${JSON.stringify(a,null,2)}
|
|
13
|
+
`,result:a}}});return{policy_result:!0,action:e,changed:r.changed,result:r.result}}async function hc(e,t,n){let o,r=await rr({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:o}),async mutate(i){let s=(await Se(n.pmRoot)).policies.find(c=>c.id===t.policy);if(!s||s.rule.kind!=="approval")throw new m("--policy must name an approval rule.",f.USAGE);if(!s.rule.authors.includes(n.author))throw new m("This actor is not a declared approver.",f.CONFLICT);return await er(n.pmRoot,i.metadata.id),o={policy_id:s.id,policy_fingerprint:Jo(s),content_fingerprint:qo(s,{...i.metadata,body:i.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:r.item.id,...o,warnings:r.warnings}}}async function Jf(e,t,n={},o={}){if(!At.includes(e))throw new m("Unknown workflow policy action.",f.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:uc()};let r=await mc(o,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Se(r.pmRoot)};if(!t?.trim())throw new m(`schema ${e} requires an operand.`,f.USAGE);if(["policy-put","policy-remove","policy-mode"].includes(e))return fc(e,t,n,r);if(e==="policy-approve"){if(n.dryRun)throw new m("Use policy-check to preview; policy-approve records an approval.",f.USAGE);return hc(t,n,r)}let i=U(r.settings,B()),a=await Tt(r.pmRoot,t,r.settings.id_prefix,r.settings.item_format,i.type_to_folder);if(!a)throw new m(`Item ${t} not found.`,f.NOT_FOUND);let{document:s}=await Ot(a,{schema:r.settings.schema}),c={...s.metadata,body:s.body},l=n.definition===void 0?c:{...c,...Dr(n.definition)};if(l.id!==c.id)throw new m("Policy preview cannot change the item id.",f.USAGE);return{policy_result:!0,action:e,changed:!1,result:await tr(r.pmRoot,await Se(r.pmRoot),{operation:"update",author:r.author,before:c,after:l,completeness_only:n.definition===void 0})}}import{createHash as Vr}from"node:crypto";import De from"node:fs/promises";import Ye from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f9535c02-9214-5d5e-bac0-2dabbe5d395e")}catch{}})();var gc=new Set(dn),yc=new Set(pn),jr=new Set([...yo.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"]),_c=["create","update"];function Gr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function Lr(e){return e.replaceAll("_","-")}function wc(e,t){let n=new Set;for(let o of e){let r=Gr(o);r.length>0&&r!==t&&n.add(r)}return[...n].sort((o,r)=>o.localeCompare(r))}function vc(e){let t=new Set;for(let n of e??[]){let o=n.trim();o.length>0&&t.add(o)}return[...t].sort((n,o)=>n.localeCompare(o))}function bc(e){let t=new Set,n=[];for(let o of e??[]){let r=o.trim().toLowerCase();if(r.length!==0){if(!yc.has(r))throw new Error(`Invalid field command "${o}". Allowed: ${pn.join(", ")}.`);t.has(r)||(t.add(r),n.push(r))}}return e===void 0||n.length===0?[..._c]:n}function Ur(e){let t=I(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(jr.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: ${[...jr].sort((d,p)=>d.localeCompare(p)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!gc.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${dn.join(", ")}.`);let o=n,r=bc(e.commands),i=Gr(e.cliFlag),a=i.length>0&&i!==Lr(t)?i:void 0,s=a??Lr(t),c=wc(e.aliases??[],s),l=e.description?.trim();return{key:t,type:o,commands:r,description:l&&l.length>0?l:void 0,cliFlag:a,cliAliases:c,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:vc(e.requiredTypes)}}function kc(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 xc(e){let t=kc(e);if(!t)return[];let n=[];for(let o of t){if(typeof o!="object"||o===null||Array.isArray(o))continue;let r=o;typeof r.key!="string"||r.key.trim().length===0||n.push(r)}return n}function We(e){if(e==null||e.trim().length===0)return{fields:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/fields.json contains invalid JSON.")}return{fields:xc(t)}}function Be(e){return`${JSON.stringify({fields:e.fields},null,2)}
|
|
14
|
+
`}function zr(e,t){let n=e.fields.find(a=>I(a.key)===t.key),o=n!==void 0,r=e.fields.filter(a=>I(a.key)!==t.key),i={...n,key:t.key,type:t.type,commands:[...t.commands]};return Fr(i,"description",t.description),Fr(i,"cli_flag",t.cliFlag),t.cliAliases.length>0?i.cli_aliases=[...t.cliAliases]:delete i.cli_aliases,Mr(i,"required",t.required),Mr(i,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?i.allow_unset=!1:delete i.allow_unset,t.requiredTypes.length>0?i.required_types=[...t.requiredTypes]:delete i.required_types,r.push(i),r.sort((a,s)=>I(a.key).localeCompare(I(s.key))),{file:{fields:r},definition:i,replaced:o}}function Jr(e,t){let n=I(t);if(n.length===0)throw new Error("Field key must not be empty.");let o=[],r=e.fields.filter(i=>I(i.key)===n?(o.push(i),!1):!0);return o.length===0?{file:{fields:r},removed:!1}:{file:{fields:r},removed:!0,definition:o[0]}}function Fr(e,t,n){let o=e;n!==void 0&&n.length>0?o[t]=n:delete o[t]}function Mr(e,t,n){let o=e;n?o[t]=!0:delete o[t]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e3a1e65b-55d7-5206-b3e7-cac3ac29745c")}catch{}})();var Sc=new Set(xt),Ne=new Set(Lo.map(e=>I(e.id)).filter(e=>e.length>0));function Ec(e){let t=new Set;for(let n of e){let o=I(n);o.length>0&&t.add(o)}return[...t].sort((n,o)=>n.localeCompare(o))}function qr(e){let t=I(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(Ne.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...Ne].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let a=new Set;for(let s of e.roles){let c=typeof s=="string"?s.trim().toLowerCase():"";if(c.length!==0){if(!Sc.has(c))throw new Error(`Invalid status role "${s}". Allowed roles: ${xt.join(", ")}.`);a.has(c)||(a.add(c),n.push(c))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${xt.join(", ")}.`)}let o=e.aliases===void 0?void 0:Ec(e.aliases).filter(a=>a!==t),r=e.description?.trim(),i=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:o,description:r&&r.length>0?r:void 0,order:i}}function $c(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function Ic(e){let t=$c(e);if(!t)return[];let n=[];for(let o of t){if(typeof o!="object"||o===null||Array.isArray(o))continue;let r=o;typeof r.id!="string"||r.id.trim().length===0||n.push(r)}return n}function He(e){if(e==null||e.trim().length===0)return{statuses:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/statuses.json contains invalid JSON.")}return{statuses:Ic(t)}}function Ke(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
|
|
15
|
+
`}function Wr(e,t,n){let o=e.statuses.slice(),r=o.findIndex(s=>I(s.id)===t.id),i=r>=0?o[r]:n,a={...i,id:t.id};return t.roles!==void 0&&(t.roles.length>0?a.roles=[...t.roles]:a.roles!==void 0&&delete a.roles),t.aliases!==void 0&&(t.aliases.length>0?a.aliases=[...t.aliases]:a.aliases!==void 0&&delete a.aliases),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),r>=0?o[r]=a:o.push(a),{file:{statuses:o},definition:a,replaced:i!==void 0}}function Br(e,t){let n=I(t);if(n.length===0)throw new Error("Status id must not be empty.");if(Ne.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...Ne].join(", ")}.`);let o=e.statuses.slice(),r=o.findIndex(a=>I(a.id)===n);if(r<0)return{file:{statuses:o},removed:!1};let[i]=o.splice(r,1);return{file:{statuses:o},removed:!0,definition:i}}function Tn(e,t){let n=[e.id,...e.aliases??[]];for(let o of n){let r=I(o);if(r.length===0)continue;let i=t.get(r);if(i!==void 0&&i!==e.id)throw new Error(`Status token "${r}" already belongs to status "${i}". Choose a different id/alias to avoid shadowing it.`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9052af10-ff8c-55db-8a35-b45e1e23a901")}catch{}})();function ge(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Yr(e){let t=ge(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Xr(e,t){let n=Cn(e),o=ge(t,"migrationScope");return`auto-${Vr("sha256").update(JSON.stringify({scope:o,request:n})).digest("hex").slice(0,20)}`}function Cn(e){let t=e.kind==="rename-type"?{kind:e.kind,from:ge(e.from,"source"),to:ge(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:I(ge(e.from,"source")),to:I(ge(e.to,"target")),...e.type===void 0?{}:{type:ge(e.type,"type")}}:{kind:e.kind,from:I(ge(e.from,"source")),to:I(ge(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Ac(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Tc(e,t,n){let o=Y(t.schema),r=Ac(n);return oe(e,o.files[r],X[r])}function Zr(e,t){return Ye.join(e,"transactions","schema",`${t}-plan.json`)}function Dt(e){return e.length===0?null:JSON.parse(e)}async function Ve(e){let t=await W(e);return{exists:t!==null,raw:t??""}}async function Qr(e,t){t.exists?await fe(e,t.raw):await De.rm(e,{force:!0})}function Oc(e,t,n){let o=ie(e),r=o.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),i=o.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(i>=0)return le(o);if(r<0)throw new TypeError(`Unknown custom type "${t.from}".`);o.definitions.push({...o.definitions[r],name:t.to})}else r>=0&&o.definitions.splice(r,1);return le(o)}function Cc(e,t,n){let o=We(e),r=o.fields.findIndex(a=>a.key===t.from),i=o.fields.findIndex(a=>a.key===t.to);if(n==="stage"){if(i>=0)return Be(o);if(r<0)throw new TypeError(`Unknown custom field "${t.from}".`);let a=o.fields[r];o.fields.push({...a,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else r>=0&&o.fields.splice(r,1);return Be(o)}function Rc(e,t,n){let o=He(e),r=o.statuses.findIndex(a=>a.id===t.from),i=o.statuses.findIndex(a=>a.id===t.to);if(n==="stage"){if(i>=0)return Ke(o);if(r<0)throw new TypeError(`Unknown custom status "${t.from}".`);o.statuses.push({...o.statuses[r],id:t.to})}else r>=0&&o.statuses.splice(r,1);return Ke(o)}function Pc(e,t,n){return t.kind==="rename-type"?Oc(e,t,n):t.kind==="rename-field"?Cc(e,t,n):Rc(e,t,n)}function Ie(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Rn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Xe(e){return Array.isArray(e)?e.map(t=>Rn(t)).filter(t=>t!==void 0):[]}function Nc(e,t){for(let n of Xe(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(o=>Ie(o,t)));for(let n of Xe(e.type_workflows))n.type=Ie(n.type,t)}function Dc(e,t){for(let o of Xe(e.definitions))o.default_status=Ie(o.default_status,t);let n=Rn(e.workflow);if(n)for(let[o,r]of Object.entries(n))n[o]=Ie(r,t);for(let o of Xe(e.type_workflows))Array.isArray(o.allowed_transitions)&&(o.allowed_transitions=o.allowed_transitions.map(r=>Array.isArray(r)?r.map(i=>Ie(i,t)):r))}function jc(e,t){for(let n of Xe(e.definitions)){for(let o of["required_create_fields","required_create_repeatables"])Array.isArray(n[o])&&(n[o]=n[o].map(r=>Ie(r,t)));for(let o of["options","command_option_policies"])for(let r of Xe(n[o])){let i=o==="options"?"key":"option";r[i]=Ie(r[i],t)}}}function Lc(e,t){let n=Rn(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let o=t.kind==="rename-type"?"type":"status";n[o]=Ie(n[o],t)}function On(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let o=n;return t.kind==="rename-type"?Nc(o,t):t.kind==="rename-field"?jc(o,t):Dc(o,t),Lc(o,t),`${JSON.stringify(o,null,2)}
|
|
16
|
+
`}function ei(e,t){if(t.kind==="rename-type"){let o=ie(e).definitions;return{source:o.some(r=>r.name.trim().toLowerCase()===t.from.toLowerCase()),target:o.some(r=>r.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let o=We(e).fields;return{source:o.some(r=>r.key===t.from),target:o.some(r=>r.key===t.to)}}let n=He(e).statuses;return{source:n.some(o=>o.id===t.from),target:n.some(o=>o.id===t.to)}}function Fc(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 Mc(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 ti(e,t){let n=Cn(t.request),o=t.migrationId===void 0?Xr(n,t.migrationScope??"plan"):Yr(t.migrationId),r=e.map(c=>Mc(c,n)).filter(c=>c!==null).sort((c,l)=>c.id.localeCompare(l.id)),i=Vr("sha256").update(JSON.stringify({migrationId:o,request:n,items:r})).digest("hex"),a=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=r.filter(c=>!a.has(c.id));return Object.freeze({migration_id:o,request:n,fingerprint:i,affected_item_count:r.length,pending_item_count:s.length,skipped_completed_count:r.length-s.length,items:Object.freeze(s)})}async function Gc(e){let t=U(e.settings,B()),n=[...new Set(Object.values(t.type_to_folder))],o=await or(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]}},i=o?await nr({pmRoot:e.pmRoot,expectedSourceCursor:o.source_cursor,query:r}):null;return i?{items:i.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Re(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Uc(e,t){let n=await W(Zr(e,t));if(n===null)return null;try{let o=JSON.parse(n);if(o.schema_version!==1||o.plan.migration_id!==t||!Array.isArray(o.plan.items))throw new TypeError("invalid plan envelope");return o.plan}catch(o){throw new m(`Stored schema migration plan "${t}" is invalid: ${wo(o)}`,f.GENERIC_FAILURE)}}async function zc(e,t){let n=Zr(e,t.migration_id);await De.mkdir(Ye.dirname(n),{recursive:!0});let o={schema_version:1,plan:t,created_at:new Date().toISOString()};await fe(n,`${JSON.stringify(o,null,2)}
|
|
17
|
+
`)}function Jc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function qc(e){let t=await Tt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new m(`Schema migration item "${e.id}" no longer exists.`,f.NOT_FOUND);return(await Ot(t,{schema:e.settings.schema})).document.metadata}function Hr(e,t,n){let o=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()!==o.toLowerCase())throw new TypeError(`Schema migration expected type "${o}" 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()!==o.toLowerCase())throw new TypeError(`Schema migration expected status "${o}" on item "${e.metadata.id}".`);return e.metadata.status=r,["status"]}let i=e.metadata;if(Object.prototype.hasOwnProperty.call(i,r)&&!Object.prototype.hasOwnProperty.call(i,o))return[];if(!Object.prototype.hasOwnProperty.call(i,o)||Object.prototype.hasOwnProperty.call(i,r))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return i[r]=i[o],delete i[o],[o,r]}function Kr(e){return{id:e.id,inspect:async()=>{let t=await Ve(e.filePath),n=ei(t.raw,e.request),o=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:o?"applied":"pending",...o?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Ve(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ve(e.filePath);return await fe(e.filePath,Pc(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 Qr(e.filePath,{exists:t.exists,raw:t.raw})}}}function Wc(e){return{id:e.stepId,inspect:async()=>{let t=await Ve(e.filePath);return{state:On(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Ve(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ve(e.filePath);return await fe(e.filePath,On(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 Qr(e.filePath,{exists:t.exists,raw:t.raw})}}}function Bc(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await A(e.pmRoot),n=U(t,B()).type_to_folder,o=await qc({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),r=Fc(o,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,B()).type_to_folder,o=await gn({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:Hr(r,e.request,"forward")}}});return{item_id:e.id,changed_fields:o.changedFields}},compensate:async()=>{let t=await A(e.pmRoot),n=U(t,B()).type_to_folder;await gn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(o){return{changedFields:Hr(o,e.request,"reverse")}}})}}}async function Hc(e){let t=await Uc(e.pmRoot,e.migrationId);if(t){if(!Jc(t.request,e.request))throw new m(`Schema migration id "${e.migrationId}" already belongs to a different request.`,f.CONFLICT);return{plan:t,stored:!0}}let n=await Gc({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...ti(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Kc(e){let t=ei(await W(e.schemaPath)??"",e.request);if(!t.source)throw new m(`Schema migration source "${e.request.from}" is not a custom definition.`,f.NOT_FOUND);if(t.target)throw new m(`Schema migration target "${e.request.to}" already exists.`,f.CONFLICT);await zc(e.pmRoot,e.plan)}async function Vc(e){let t=Y(e.settings.schema),n=[...new Set([["types",X.types],["fields",X.fields],["workflows",X.workflows]].map(([r,i])=>oe(e.pmRoot,t.files[r],i)).filter(r=>r!==e.schemaPath))];try{let r=Ye.join(e.pmRoot,"templates"),i=await De.readdir(r,{withFileTypes:!0});n.push(...i.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>Ye.join(r,a.name)))}catch(r){if(typeof r!="object"||r===null||!("code"in r)||!re(r))throw r}n.sort((r,i)=>r.localeCompare(i));let o=[];for(let r of n){let i=await W(r);i!==null&&On(i,e.request)!==i&&o.push({filePath:r,beforeRaw:i})}return{paths:n,snapshots:o}}async function Yc(e){for(let t of e.snapshots){let n=await De.readFile(t.filePath,"utf8"),o=Ye.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await hn({pmRoot:e.pmRoot,author:e.author,documentPath:o,before:Dt(t.beforeRaw),after:Dt(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${o}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function Xc(e,t,n){let o=Cn(e),r=P(process.cwd(),n.path);await Ee(r);let i=t.migrationId===void 0?Xr(o,await De.realpath(r)):Yr(t.migrationId),a=await A(r),s=H(t.author,a.author_default),c=await Hc({pmRoot:r,settings:a,migrationId:i,request:o}),l=c.plan;if(t.dryRun===!0)return{...l,action:o.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=Tc(r,a,o),p=await De.readFile(d,"utf8");c.stored||await Kc({pmRoot:r,schemaPath:d,request:o,plan:l});let u=await Vc({pmRoot:r,schemaPath:d,settings:a,request:o}),h=[Kr({id:"stage-schema",filePath:d,request:o,phase:"stage"}),...u.paths.map((w,v)=>Wc({filePath:w,request:o,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...l.items.map(w=>Bc({pmRoot:r,id:w.id,request:o,author:s,force:t.force===!0})),Kr({id:"retire-source",filePath:d,request:o,phase:"retire"})],y=await fr({pmRoot:r,transactionId:`schema-${i}`,author:s,steps:h,lockTtlSeconds:Math.max(a.locks.ttl_seconds,300),lockWaitMs:a.locks.wait_ms}),_=await De.readFile(d,"utf8"),{historyPath:g}=await hn({pmRoot:r,author:s,documentPath:Ye.relative(r,d).replaceAll("\\","/"),before:Dt(p),after:Dt(_),op:"schema_migration",idempotencyKey:`${l.migration_id}:${l.fingerprint}`,message:`${o.kind}: ${o.from} -> ${o.to}; affected=${l.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await Yc({pmRoot:r,author:s,settings:a,request:o,plan:l,snapshots:u.snapshots}),{...l,action:o.kind,applied:!0,recovered:y.recovered,migrated_item_count:l.affected_item_count,workspace_history_path:g}}function Zc(e){let t=e.applied?"applied":"dry-run",n=e.recovered?" (recovered)":"";return[`${e.action}: ${e.request.from} -> ${e.request.to} [${t}${n}]`,`migration_id: ${e.migration_id}`,`affected: ${e.affected_item_count}`,`pending: ${e.pending_item_count}`,`fingerprint: ${e.fingerprint}`].join(`
|
|
18
|
+
`)}import ol from"node:path";import{mkdir as rl}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebcb45a2-996a-5194-8086-efe882dbcacc")}catch{}})();var at=["agile","ops","research"],Qc={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function jt(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${at.join(", ")}.`)}function st(e){return Qc[e].map(t=>ot(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96cec314-edb6-5c51-abc4-d028bdc4f10c")}catch{}})();var el=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function tl(e){let t=el.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function nl(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function ni(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,o=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,r=new Map;for(let a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=tl(s);if(c===void 0)continue;let l=r.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<o&&l.examples.push(s),r.set(c,l)}let i=[];for(let[a,s]of r.entries()){if(s.count<n)continue;let c=nl(a);i.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:Ko(c)!==void 0})}return i.sort((a,s)=>s.count-a.count||a.name.localeCompare(s.name)),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3b47d4d5-a224-5e46-8f91-9988c353c26b")}catch{}})();var tg=[...At,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Lt="schema-types",oi="schema-statuses",ri="schema-fields";function Ae(e){return Ue({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 og(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let r;try{r=ot({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(h){throw new m(h instanceof Error?h.message:String(h),f.USAGE)}let i=await A(o),a=Y(i.schema),s=oe(o,a.files.types,X.types),c=[],l=H(t.author,i.author_default),d=ae(i),p=await Q(o,Lt,i.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let h=await W(s),y;try{y=ie(h)}catch(_){throw new m(_ instanceof Error?_.message:String(_),f.GENERIC_FAILURE)}try{Vo(r,y);let _=new Map,g=U(i,B());for(let[w,v]of Object.entries(g.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!_.has(x)&&_.set(x,w)}Yo(r,y,_)}catch(_){throw new m(_ instanceof Error?_.message:String(_),f.USAGE)}u=ze(y,r),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await Ae({pmRoot:o,filePath:s,raw:le(u.file),op:"schema:add-type",author:l,settings:i}),await ct(o,[u.definition],c,"schema:add-type-folder"),c.push(...await K({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await ii(o,c),{action:"add-type",registered:!0,replaced:u.replaced,type:u.definition,file:{path:s,definitions:u.file.definitions.length},warnings:Te(c),generated_at:T()}}async function ye(e){await Ee(e)}async function ii(e,t){try{let n=await Cr(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Te(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function il(e,t,n,o){let r=U(t,B()),i=o.trim().toLowerCase();return(await Re(e,t.item_format,r.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===i).length}async function al(e,t,n,o){let r=U(t,B()),i=nt(n),a=I(o);return(await Re(e,t.item_format,r.type_to_folder,[],n)).filter(c=>{let l=typeof c.status=="string"?c.status:"";return(i.alias_to_id.get(I(l))??I(l))===a}).length}async function sl(e,t,n,o,r){if(r.length===0||Ne.has(r))return;let i=await al(t,n,o,r);i>0&&e.push(`items_using_status:${i}`);let a=ai(o.workflow,r);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function ai(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,o])=>o!==void 0&&I(o)===t).map(([o])=>o)}async function rg(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let r=await A(o),i=Y(r.schema),a=oe(o,i.files.types,X.types),s=[],c=H(t.author,r.author_default),l=ae(r),d=await Q(o,Lt,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await W(a),h;try{h=ie(u)}catch(y){throw new m(y instanceof Error?y.message:String(y),f.GENERIC_FAILURE)}try{p=Xo(h,e)}catch(y){throw new m(y instanceof Error?y.message:String(y),f.USAGE)}if(p.removed){let y=(p.definition?.name??e??"").trim();if(y.length>0){let _=await il(o,r,i,y);_>0&&s.push(`items_using_type:${_}`)}await Ae({pmRoot:o,filePath:a,raw:le(p.file),op:"schema:remove-type",author:c,settings:r}),s.push(...await K({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return p.removed&&await ii(o,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:a,definitions:p.file.definitions.length},warnings:Te(s),generated_at:T()}}function Pn(e,t){return oe(e,t.files.statuses,X.statuses)}function Ft(e,t){return oe(e,t.files.fields,X.fields)}function si(e,t){return oe(e,t.files.types,X.types)}async function ct(e,t,n,o){for(let r of t){let i=xo(r.folder??ko(r.name)),a=ol.join(e,i);await k(a)||(await rl(a,{recursive:!0}),n.push(...await K({path:a,scope:"project",op:o})))}}function Nn(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 cl(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 ll(e){let t=new Map;for(let n of e){let o=I(n.id);if(o.length!==0){t.set(o,o);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let i=I(r);i.length>0&&!t.has(i)&&t.set(i,o)}}}return t}async function ig(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let r;try{r=qr({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(g){throw new m(g instanceof Error?g.message:String(g),f.USAGE)}let i=await A(o),a=Y(i.schema),s=Pn(o,a),c=nt(a);try{Tn(r,c.alias_to_id)}catch(g){throw new m(g instanceof Error?g.message:String(g),f.USAGE)}let l=cl(c.by_id.get(r.id));if((r.roles??l?.roles??[]).length===0)throw new m(`Status "${r.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,f.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Ce(r.id)}" --role active`,`pm schema add-status "${Ce(r.id)}" --role blocked`]});let p=[],u=H(t.author,i.author_default),h=ae(i),y=await Q(o,oi,i.locks.ttl_seconds,u,!!t.force,h.force_required_for_stale_lock,i.locks.wait_ms),_;try{let g=await W(s),w;try{w=He(g)}catch(x){throw new m(x instanceof Error?x.message:String(x),f.GENERIC_FAILURE)}let v=ll(w.statuses);try{Tn(r,v)}catch(x){throw new m(x instanceof Error?x.message:String(x),f.USAGE)}_=Wr(w,r,l),await Ae({pmRoot:o,filePath:s,raw:Ke(_.file),op:"schema:add-status",author:u,settings:i}),p.push(...await K({path:s,scope:"project",op:"schema:add-status"}))}finally{await y()}return{action:"add-status",registered:!0,replaced:_.replaced,status:_.definition,file:{path:s,statuses:_.file.statuses.length},warnings:Te(p),generated_at:T()}}async function ag(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let r=await A(o),i=Y(r.schema),a=Pn(o,i),s=[],c=H(t.author,r.author_default),l=ae(r),d=await Q(o,oi,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await W(a),h;try{h=He(u)}catch(y){throw new m(y instanceof Error?y.message:String(y),f.GENERIC_FAILURE)}try{p=Br(h,e)}catch(y){throw new m(y instanceof Error?y.message:String(y),f.USAGE)}if(p.removed){let y=I(p.definition?.id??e);await sl(s,o,r,i,y),await Ae({pmRoot:o,filePath:a,raw:Ke(p.file),op:"schema:remove-status",author:c,settings:r}),s.push(...await K({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:a,statuses:p.file.statuses.length},warnings:Te(s),generated_at:T()}}function ci(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 dl(e,t,n){return{...ci(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 li(e){return{id:e.id,source:Ne.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function di(e,t,n){let o=e.toLowerCase();return n.has(o)?"extension":t.has(o)?"custom":"builtin"}function pl(){let e=new Map,t=B();for(let n of t?.item_types??[]){let o=n.types;if(Array.isArray(o))for(let r of o){if(typeof r!="object"||r===null||Array.isArray(r))continue;let i=r.name;typeof i=="string"&&i.trim().length>0&&e.set(i.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function ul(e){let t=nt(e),n=[],o=[];for(let r of t.definitions){let i=li(r);i.source==="builtin"?n.push(i):o.push(i)}return{builtin:n,custom:o}}async function lt(e){let t=P(process.cwd(),e.path);await ye(t);let n=await A(t),o=Y(n.schema),r=oe(t,o.files.types,X.types),i=Pn(t,o),a=U(n,B()),s=pl(),c=new Set((n.item_types?.definitions??[]).map(l=>l.name.trim().toLowerCase()).filter(l=>l.length>0&&!s.has(l)));return{pmRoot:t,typesPath:r,statusesPath:i,byType:a.by_type,customNames:c,extensionProvenance:s,schema:o}}async function sg(e){let t=await lt(e),n=[],o=[],r=[];for(let s of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=di(s.name,t.customNames,new Set(t.extensionProvenance.keys())),l=ci(s);c==="extension"?r.push(l):c==="custom"?o.push(l):n.push(l)}let i=ul(t.schema),a=$t(t.schema).definitions.map(Nn);return{action:"list",builtin:n,custom:o,extension:r,counts:{builtin:n.length,custom:o.length,extension:r.length,total:n.length+o.length+r.length},statuses:{builtin:i.builtin,custom:i.custom,counts:{builtin:i.builtin.length,custom:i.custom.length,total:i.builtin.length+i.custom.length}},fields:{custom:a,counts:{total:a.length}},file:{path:t.typesPath},generated_at:T()}}async function cg(e,t){let n=(e??"").trim();if(n.length===0)throw new m("Type name must not be empty.",f.USAGE);let o=await lt(t),r=Object.values(o.byType).find(i=>i.name.toLowerCase()===n.toLowerCase()||i.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!r)throw new m(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Ce(n)}" to register it.`,f.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:dl(r,di(r.name,o.customNames,new Set(o.extensionProvenance.keys())),o.extensionProvenance.get(r.name.toLowerCase())),file:{path:o.typesPath},generated_at:T()}}async function lg(e,t){let n=I(e);if(n.length===0)throw new m("Status id must not be empty.",f.USAGE);let o=await lt(t),r=nt(o.schema),i=r.alias_to_id.get(n)??n,a=r.by_id.get(i);if(!a)throw new m(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Ce(e??"")}" to register it.`,f.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:li(a),file:{path:o.statusesPath},generated_at:T()}}async function dg(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let r;try{r=Ur({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 m(y instanceof Error?y.message:String(y),f.USAGE)}let i=await A(o),a=Y(i.schema),s=Ft(o,a),c=[],l=Ct(r.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let d=H(t.author,i.author_default),p=ae(i),u=await Q(o,ri,i.locks.ttl_seconds,d,!!t.force,p.force_required_for_stale_lock,i.locks.wait_ms),h;try{let y=await W(s),_;try{_=We(y)}catch(g){throw new m(g instanceof Error?g.message:String(g),f.GENERIC_FAILURE)}h=zr(_,r),await Ae({pmRoot:o,filePath:s,raw:Be(h.file),op:"schema:add-field",author:d,settings:i}),c.push(...await K({path:s,scope:"project",op:"schema:add-field"}))}finally{await u()}return{action:"add-field",registered:!0,replaced:h.replaced,field:h.definition,file:{path:s,fields:h.file.fields.length},warnings:Te(c),generated_at:T()}}async function ml(e,t,n,o){let r=U(t,B());return(await Re(e,t.item_format,r.type_to_folder,[],n)).filter(a=>{let s=a[o];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function pg(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let r=await A(o),i=Y(r.schema),a=Ft(o,i),s=[],c=H(t.author,r.author_default),l=ae(r),d=await Q(o,ri,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await W(a),h;try{h=We(u)}catch(y){throw new m(y instanceof Error?y.message:String(y),f.GENERIC_FAILURE)}try{p=Jr(h,e)}catch(y){throw new m(y instanceof Error?y.message:String(y),f.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 g=await ml(o,r,i,_);g>0&&s.push(`items_using_field:${g}`)}await Ae({pmRoot:o,filePath:a,raw:Be(p.file),op:"schema:remove-field",author:c,settings:r}),s.push(...await K({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:a,fields:p.file.fields.length},warnings:Te(s),generated_at:T()}}async function ug(e){let t=await lt(e),n=$t(t.schema).definitions.map(Nn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Ft(t.pmRoot,t.schema)},generated_at:T()}}async function mg(e,t){let n=I(e);if(n.length===0)throw new m("Field key must not be empty.",f.USAGE);let o=await lt(t),r=$t(o.schema).by_key.get(n);if(!r)throw new m(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Ce(e??"")}" to register it.`,f.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Nn(r),file:{path:Ft(o.pmRoot,o.schema)},generated_at:T()}}async function fg(e,t,n){let o=P(process.cwd(),n.path);await ye(o);let r;try{let _=jt(e);if(_===void 0)throw new Error(`Type preset name is required. Allowed: ${at.join(", ")}.`);r=_}catch(_){throw new m(_ instanceof Error?_.message:String(_),f.USAGE)}let i=await A(o),a=Y(i.schema),s=si(o,a),c=[],l=H(t.author,i.author_default),d=ae(i),p=[],u=[],h,y=await Q(o,Lt,i.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms);try{let _=await W(s),g;try{g=ie(_)}catch(v){throw new m(v instanceof Error?v.message:String(v),f.GENERIC_FAILURE)}let w=g;for(let v of st(r)){let x=ze(w,v);w=x.file,(x.replaced?u:p).push(x.definition.name)}h=w.definitions.length,await Ae({pmRoot:o,filePath:s,raw:le(w),op:"schema:apply-preset",author:l,settings:i}),await ct(o,st(r),c,"schema:apply-preset-folder"),c.push(...await K({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:r,registered:p,replaced:u,file:{path:s,definitions:h},warnings:Te(c),generated_at:T()}}function fl(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new m("--min-count must be a positive integer (>= 1).",f.USAGE);return e}async function hg(e,t){let n=P(process.cwd(),t.path);await ye(n);let o=await A(n),r=Y(o.schema),i=si(n,r),a=fl(e.minCount),s=U(o,B()),l=(await Re(n,o.item_format,s.type_to_folder,[],r)).map(x=>typeof x.title=="string"?x.title:""),d=ni(l,{minCount:a}),p=[],u=[],h=[],y=[],_;if(!e.apply){let x;try{x=ie(await W(i))}catch(E){throw new m(E instanceof Error?E.message:String(E),f.GENERIC_FAILURE)}return _=x.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:d,registered:u,replaced:h,skipped:y,file:{path:i,definitions:_},warnings:p,generated_at:T()}}let g=H(e.author,o.author_default),w=ae(o),v=await Q(n,Lt,o.locks.ttl_seconds,g,!!e.force,w.force_required_for_stale_lock,o.locks.wait_ms);try{let x=await W(i),E;try{E=ie(x)}catch(G){throw new m(G instanceof Error?G.message:String(G),f.GENERIC_FAILURE)}let C=E;for(let G of d){if(G.shadows_builtin){y.push({name:G.name,reason:"shadows_builtin"});continue}let L;try{L=ot({name:G.name})}catch{y.push({name:G.name,reason:"invalid_type_token"});continue}let S=ze(C,L);C=S.file,(S.replaced?h:u).push(S.definition.name)}_=C.definitions.length,await Ae({pmRoot:n,filePath:i,raw:le(C),op:"schema:infer-types",author:g,settings:o}),await ct(n,C.definitions.filter(G=>u.includes(G.name)||h.includes(G.name)),p,"schema:infer-types-folder"),p.push(...await K({path:i,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:d,registered:u,replaced:h,skipped:y,file:{path:i,definitions:_},warnings:Te(p),generated_at:T()}}function gg(e){let t=e.replaced?"Updated":"Registered",n=e.type.aliases&&e.type.aliases.length>0?` (aliases: ${e.type.aliases.join(", ")})`:"";return`${t} custom item type "${e.type.name}"${n} in ${e.file.path}. Run: pm create "${Ce(e.type.name)}" "<title>"`}function yg(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 _g(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",o=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${o} in ${e.file.path}.`}function wg(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 vg(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,o]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])o.length!==0&&t.push(`${n}: ${o.map(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,o]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])o.length!==0&&t.push(`${n}: ${o.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(`
|
|
19
|
+
`)}function bg(e){let t=[`type: ${e.type.name}`,`source: ${e.type.source}`,`folder: ${e.type.folder}`];return e.type.default_status&&t.push(`default_status: ${e.type.default_status}`),e.type.aliases.length>0&&t.push(`aliases: ${e.type.aliases.join(", ")}`),e.type.description&&t.push(`description: ${e.type.description}`),e.type.options.length>0&&t.push(`options: ${e.type.options.map(n=>n.key).join(", ")}`),t.join(`
|
|
20
|
+
`)}function kg(e){let t=[`status: ${e.status.id}`,`source: ${e.status.source}`];return e.status.roles.length>0&&t.push(`roles: ${e.status.roles.join(", ")}`),e.status.aliases.length>0&&t.push(`aliases: ${e.status.aliases.join(", ")}`),e.status.description&&t.push(`description: ${e.status.description}`),typeof e.status.order=="number"&&t.push(`order: ${e.status.order}`),t.join(`
|
|
21
|
+
`)}function hl(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 xg(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 Sg(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 Eg(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${hl(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
|
|
22
|
+
`)}function $g(e){let t=e.field,n=[`field: ${t.key}`,`type: ${t.type}`,`cli_flag: ${t.cli_flag}`,`commands: ${t.commands.join(", ")}`];return t.cli_aliases.length>0&&n.push(`cli_aliases: ${t.cli_aliases.join(", ")}`),t.description&&n.push(`description: ${t.description}`),t.required&&n.push("required: true"),t.required_on_create&&n.push("required_on_create: true"),t.allow_unset||n.push("allow_unset: false"),t.required_types.length>0&&n.push(`required_types: ${t.required_types.join(", ")}`),n.join(`
|
|
23
|
+
`)}function Ig(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",o=[t,n].filter(r=>r.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${o.length>0?` (${o})`:""}.`}function Ag(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;let t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(let n of e.candidates){let o=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${o}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
|
|
24
|
+
`)}var Tg={workflowSlotsReferencing:ai};import mi from"node:fs/promises";import je from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8269d712-f438-5f18-8137-ed9a0358e23b")}catch{}})();var Mt=["extensions","docs","examples","assets","prompts"],gl=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 yl(e){return Mt.includes(e)}function _l(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],o=[];for(let r of n){if(typeof r!="string"||r.trim().length===0)throw new m(`Package manifest field pm.${e} must contain string paths.`,f.USAGE);o.push(r.trim())}return[...new Set(o)].sort((r,i)=>r.localeCompare(i))}function wl(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new m("Package manifest field pm must be an object.",f.USAGE);let t={},n=e;for(let[o,r]of Object.entries(n)){if(!yl(o))continue;let i=_l(o,r);i.length>0&&(t[o]=i)}return t}function pe(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function Dn(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,o)=>n.localeCompare(o)):void 0}function pi(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 vl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:pe(t,"docs"),npm:pe(t,"npm"),repository:pe(t,"repository"),report:pe(t,"report")};return Object.values(n).some(o=>typeof o=="string")?n:void 0}function bl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:pe(t,"image"),video:pe(t,"video")};return Object.values(n).some(o=>typeof o=="string")?n:void 0}function kl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:pe(t,"display_name")??pe(t,"displayName"),category:pe(t,"category"),summary:pe(t,"summary"),links:vl(t.links),media:bl(t.media),tags:Dn(t.tags)};return Object.values(n).some(o=>o!==void 0)?n:void 0}async function dt(e){let t=je.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await mi.readFile(t,"utf8"))}catch(s){throw new m(`Failed to parse package manifest at "${t}": ${String(s)}`,f.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new m(`Package manifest at "${t}" must be a JSON object.`,f.USAGE);let o=n,r=o.pm,i=r!=null,a=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{};return{source:i?"pm":"convention",package_json_path:t,package_name:typeof o.name=="string"?o.name:void 0,package_version:typeof o.version=="string"?o.version:void 0,package_private:o.private===!0,package_description:typeof o.description=="string"?o.description:void 0,package_keywords:Dn(o.keywords),package_homepage:typeof o.homepage=="string"?o.homepage:void 0,package_repository_url:pi(o.repository),package_bugs_url:pi(o.bugs),aliases:Dn(a.aliases),resources:wl(r),catalog:kl(a.catalog)}}async function ui(e){if(!await k(e))return[];let t=await mi.readdir(e,{withFileTypes:!0}),n=[];for(let o of t){if(!o.isDirectory())continue;let r=je.join(e,o.name);await k(je.join(r,"manifest.json"))&&n.push(r)}return n.sort((o,r)=>o.localeCompare(r))}async function Gt(e){if(await k(je.join(e,"manifest.json")))return[e];let n=(await dt(e)).resources.extensions??[],o=new Set;for(let r of n){if(r.includes("*")||r.startsWith("!"))throw new m(`Package extension entry "${r}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,f.USAGE);let i=je.resolve(e,r);if(!V(e,i))throw new m(`Package extension entry "${r}" resolves outside package root.`,f.USAGE);if(await k(je.join(i,"manifest.json"))){o.add(i);continue}for(let a of await ui(i))o.add(a)}if(n.length===0)for(let r of gl.extensions)for(let i of await ui(je.join(e,r)))o.add(i);return[...o].sort((r,i)=>r.localeCompare(i))}import{execFile as Jl}from"node:child_process";import R from"node:fs/promises";import qn from"node:os";import $ from"node:path";import{fileURLToPath as ql}from"node:url";import{promisify as Wl}from"node:util";import Bl from"npm-package-arg";import{extract as Hl,list as Kl}from"tar";import Pl from"node:fs/promises";import se from"node:path";import fi from"node:fs/promises";import jn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="209566d6-107e-5c01-995a-96a6dc0e40ed")}catch{}})();function ee(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function b(e){return e.trim().toLowerCase()}function Ut(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let o=t.length;for(;o>n&&t[o-1]==="-";)o-=1;let r=t.slice(n,o);if(r.length===0)throw new m("Extension manifest name must resolve to a non-empty directory name.",f.USAGE);if(r==="."||r==="..")throw new m('Extension manifest name must not resolve to "." or "..".',f.USAGE);return r}function Ln(e){return Ro(e)}async function xl(e){try{let t=JSON.parse(await fi.readFile(jn.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(o=>typeof t.scripts?.[o]=="string")}}catch{return{has_build_script:!1}}}async function Sl(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new m(`Extension entry file is missing at "${t}".`,f.USAGE);let o=await xl(n.source_root),r=o.package_name?`pm install npm:${o.package_name}`:void 0,i=n.source_input??n.source_root;return new m(`Extension entry "${e.entry}" is absent from GitHub source "${i}". pm install copies GitHub repositories without running package scripts${o.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."}`,f.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 ${i}`,normalized_args:["install",i],...r?{next_best_command:r}:{}}})}async function Ze(e,t={}){let n=jn.join(e,"manifest.json");if(!await k(n))throw new m(`Extension manifest is missing at "${n}".`,f.USAGE);let o;try{o=JSON.parse(await fi.readFile(n,"utf8"))}catch(a){throw new m(`Failed to parse extension manifest at "${n}": ${El(a)}`,f.USAGE)}let r=Ln(o);if(!r)throw new m(`Extension manifest at "${n}" is invalid.`,f.USAGE);let i=jn.resolve(e,r.entry);if(!V(e,i))throw new m(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,f.USAGE);if(!await k(i))throw await Sl(r,i,t);if(!await Po(e,i))throw new m(`Extension entry "${r.entry}" resolves outside extension directory after symlink resolution.`,f.USAGE);return{directory:e,manifest_path:n,entry_path:i,manifest:r}}function El(e){return e instanceof Error?e.message:String(e)}import Fn from"node:fs/promises";import $l from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="33b7f318-cc64-55d6-8b57-19a618efe6c0")}catch{}})();var Il=".managed-extensions.json",zt=1;function pt(e){return $l.join(e,Il)}function Al(){return{version:zt,updated_at:T(),entries:[]}}function ut(e){return[...e].sort((t,n)=>{let o=t.scope.localeCompare(n.scope);if(o!==0)return o;let r=t.name.localeCompare(n.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function hi(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function te(e){return typeof e=="string"?e:void 0}function Tl(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 Ol(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:te(t.name),package:te(t.package),version:te(t.version),repository:te(t.repository),owner:te(t.owner),repo:te(t.repo),ref:te(t.ref),subpath:te(t.subpath),commit:te(t.commit)}}function Cl(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Tl(t))return null;let n=Ol(t.source);if(!n)return null;let o=To(t.contributions);return o===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:ee(t.capabilities),contributions:o,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:te(t.last_update_check_at),last_update_remote_commit:te(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:te(t.update_error)}}function Rl(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==zt||!Array.isArray(t.entries))return null;let n=[];for(let o of t.entries){let r=Cl(o);r&&n.push(r)}return{version:zt,updated_at:te(t.updated_at)??T(),entries:ut(n)}}async function _e(e){let t=pt(e),n=Al();try{let o=await Fn.readFile(t,"utf8"),r=JSON.parse(o),i=Rl(r);if(!i)throw new m(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,f.GENERIC_FAILURE);return{path:t,state:i,warnings:[]}}catch(o){if(o instanceof m)throw o;if(typeof o=="object"&&o!==null&&"code"in o&&re(o))return{path:t,state:n,warnings:[]};throw new m(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,f.GENERIC_FAILURE)}}async function Le(e,t){let n=pt(e),o={version:zt,updated_at:T(),entries:ut(t.entries)};await Fn.mkdir(e,{recursive:!0}),await Fn.writeFile(n,`${JSON.stringify(o,null,2)}
|
|
25
|
+
`,"utf8")}function mt(e,t){let n=e.entries.filter(o=>b(o.name)!==b(t.name)&&b(o.directory)!==b(t.directory));return n.push(t),{...e,updated_at:T(),entries:ut(n)}}async function gi(e,t,n,o){let r=t.entries.find(a=>b(a.name)===b(n));if(!r)return t;let i=mt(t,{...r,contributions:o});return await Le(e,i),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96c5708d-1f4d-5f94-9945-7f8baa337106")}catch{}})();var Nl="PM_CLI_PACKAGE_ROOT",yi={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Dl=new Set(["*","all"]);function Mn(){let e=[],t=process.env[Nl];return typeof t=="string"&&t.trim().length>0&&e.push(se.resolve(t.trim())),e.push(ce(import.meta.url,["../../.."])),[...new Set(e)]}async function ft(e){let t=e.trim().toLowerCase(),n=await wi(t);if(n)return n;let o=yi[t];if(!o)return null;for(let r of Mn()){let i=se.join(r,".agents","pm","extensions",o.legacy_extension_directory);if(await k(se.join(i,"manifest.json")))return i}return null}function _i(e){return Dl.has(e.trim().toLowerCase())}function jl(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Ll(e,t){let n=await Pl.readdir(e,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!o.name.startsWith("pm-"))continue;let r=se.join(e,o.name);if(!await k(se.join(r,"package.json")))continue;let i=await dt(r),a=i.aliases&&i.aliases.length>0?i.aliases:[jl(o.name)];for(let s of a){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:o.name,package_root:r,package_name:i.package_name??null})}}}async function Gn(){let e=new Map;for(let t of Mn()){let n=se.join(t,"packages");await k(n)&&await Ll(n,e)}for(let[t,n]of Object.entries(yi))if(!e.has(t))for(let o of Mn()){let r=se.join(o,"packages",n.package_directory);if(await k(se.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 Jt(){return(await Gn()).map(e=>e.alias)}async function wi(e){let t=e.trim().toLowerCase();return(await Gn()).find(o=>o.alias===t||o.package_directory.toLowerCase()===t||o.package_name?.toLowerCase()===t)?.package_root??null}async function vi(e){let t=await wi(e);return t?(await dt(t)).package_name??null:null}async function bi(e){let t=await ft(e);if(!t)return null;try{let n=await Gt(t);return n.length!==1?null:(await Ze(n[0])).manifest.name}catch{return null}}function Fl(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 Ml(e,t,n,o,r,i){let a=o==="global"?"--global":"--project",s=Object.fromEntries(Mt.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>r.has(c))||i.has(se.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${a}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:Fl(e),media:e.catalog?.media}}}async function ki(e,t,n={}){let o=St(P(process.cwd(),t.path),process.cwd()),r=e==="global"?o.global:o.project,i=await _e(r),a=new Set(i.state.entries.filter(u=>u.scope===e).filter(u=>u.source.kind!=="builtin").map(u=>se.resolve(u.source.location))),s=new Set(i.state.entries.filter(u=>u.scope===e&&u.source.kind==="builtin").flatMap(u=>[u.source.name,u.source.input,u.source.location]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toLowerCase())),c=[],l=new Map;for(let u of await Gn()){let h=se.resolve(u.package_root),y=l.get(h)??[];y.push(u),l.set(h,y)}for(let u of l.values()){let h=u[0],y=u.map(g=>g.alias).sort((g,w)=>g.localeCompare(w)),_=await dt(h.package_root);c.push(Ml(_,h,y,e,s,a))}let d=Ul(n.fields),p=d?c.map(u=>zl(u,d)):c;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Mt.filter(u=>u!=="extensions"),packages:p}}var Gl=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 Ul(e){if(e===void 0)return;let t=ir(e);if(t.length===0)throw new m("Package catalog --fields requires a comma-separated list of field names",f.USAGE);let n=t.filter(o=>!Gl.has(o));if(n.length>0)throw new m(`Unknown package catalog --fields value(s): ${n.join(", ")}`,f.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function zl(e,t){let n={};for(let o of t)o==="category"?n[o]=e.catalog?.category??null:o==="display_name"?n[o]=e.catalog?.display_name??null:n[o]=e[o]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="68a37ea1-3571-59ab-b72c-0195efa84e3c")}catch{}})();var Si=Wl(Jl),Wt="@unbrained/pm-cli",Vl={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},Un;async function Ei(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let o=$.resolve(t);for(;;){let r=$.join(o,"node_modules",...n.split("/")),i=$.join(r,"package.json");if(await k(i))try{let s=JSON.parse(await R.readFile(i,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:r}}catch{return null}let a=$.dirname(o);if(a===o)return null;o=a}}function zn(e,t,n){let o=e.split("/").map(l=>l.trim()).filter(l=>l.length>0);if(o.length<2)return null;let r=o[0],i=o[1].replace(/\.git$/i,"");if(r.length===0||i.length===0)return null;let a=o.slice(2),s,c;return a[0]==="tree"&&a.length>=2?(s=a[1],c=a.slice(2).join("/")):a.length>0&&(c=a.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:r,repo:i,repository:`https://github.com/${r}/${i}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function Yl(e,t,n){let o=e.slice(4).trim();if(o.length===0)throw new m('npm package source must include a package spec after "npm:".',f.USAGE);if(t)throw new m('Options "--gh/--github" cannot be combined with npm: package sources.',f.USAGE);if(n)throw new m('Option "--ref" cannot be combined with npm: package sources.',f.USAGE);return{kind:"npm",input:e,spec:o}}function Bt(e,t={}){let n=e.trim();if(n.length===0)throw new m("Extension source is required for --install.",f.USAGE);let o=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Yl(n,t.forceGithub===!0,o);let r=(()=>{try{let a=new URL(n);if(a.hostname!=="github.com")return null;let s=a.pathname.replace(/^\/+/,"");return zn(s,n,o)}catch{return null}})();if(r)return r;let i=n.startsWith("github.com/")?n.slice(11):null;if(i){let a=zn(i,n,o);if(!a)throw new m(`Invalid GitHub source "${n}".`,f.USAGE);return a}if(t.forceGithub){let a=zn(n,n,o);if(!a)throw new m(`Invalid GitHub shorthand "${n}".`,f.USAGE);return a}if(/^https?:\/\//i.test(n))throw new m(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,f.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function qt(e,t=Si,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(o){let r=typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr):"",i=r.trim().length>0?r.trim():o instanceof Error?o.message:String(o);throw new m(`Git command failed: git ${e.join(" ")}
|
|
26
|
+
${i}`,f.GENERIC_FAILURE)}}function Xl(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Zl(e=process.platform){return e==="win32"}async function $i(e,t,n=Si,o=process.platform,r=process.env){let i=Xl(o),a=Object.fromEntries(Object.entries(r).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(i,e,{cwd:t,encoding:"utf8",env:a,shell:Zl(o)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",l=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new m(`npm command failed: ${i} ${e.join(" ")}
|
|
27
|
+
${l}`,f.GENERIC_FAILURE)}}function Ii(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 Ai(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 Ql(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("npm err! code e404")||n.includes("404 not found")||n.includes("is not in this registry")}function ed(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return Ql(e)||n.includes("not found")}function td(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function nd(e){let t=Ii(e),n=td(t),o=t.replace(/^.*\//,""),r=n?`github.com/unbraind/${o}`:void 0,i=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:i?[i,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:i?[`Try ${i} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...r&&i?{fallback_candidates:[{source:r,command:i,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:i}:{}}}}}function od(e,t){if(!ed(t))return null;let n=nd(e);return new m(n.message,f.NOT_FOUND,n.context)}async function Ti(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=ql(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 rd(e){let t=await Ti(e);if(t)return t;let n=id(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function id(e,t=process.cwd()){let n="@file:",o=e.lastIndexOf(n);if(!Ai(e))return e;let r=e.slice(0,o),i=e.slice(o+n.length);if(i.startsWith("//")&&!i.startsWith("///"))return e;if(!i.startsWith("/"))return`${r}@${$.resolve(t,i)}`;let a;try{a=decodeURIComponent(new URL(`file:${i}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(a)?a.slice(1):a;return`${r}@${s}`}function xi(e,t){let n=$.resolve(e,t),o=$.relative(e,n);if(o.length===0||o===".."||o.startsWith(`..${$.sep}`)||$.isAbsolute(o))throw new m("npm pack reported a package archive outside its isolated destination.",f.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 ad(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 sd(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,o])=>({key:n,value:o})):[]).flatMap(({key:n,value:o})=>{let r=ad(o,n);return r?[r]:[]})}function cd(e,t){let n=t?.trim().toLowerCase(),o=n?e.filter(a=>{let s=a.name?.trim().toLowerCase();return s!==void 0?s===n:a.key?.trim().toLowerCase()===n}):[];if(o.length===1)return o[0];if(e.length!==1)return;let r=e[0],i=r.name??r.key;return n&&i!==void 0&&i.trim().toLowerCase()!==n?void 0:r}function ld(e,t,n){let o;try{o=JSON.parse(e)}catch{let a=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!a)throw new m("npm pack did not report a tarball filename.",f.GENERIC_FAILURE);return{tarball:xi(t,a)}}let r=sd(o),i=cd(r,n);if(!i)throw new m("npm pack --json returned an unsupported or ambiguous package receipt.",f.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:xi(t,i.filename),package:i.name??i.key,version:i.version}}async function dd(e){return pd(e,$i)}async function pd(e,t){let n=await Ti(e.spec);if(n){if((await R.stat(n)).isFile()&&Oi(n))return Jn(n);let a=$.join(n,"package.json"),s=await k(a)?JSON.parse(await R.readFile(a,"utf8")):{};return{directory:await Ht(n,e.input),package:typeof s.name=="string"?s.name:void 0,version:typeof s.version=="string"?s.version:void 0,cleanup:async()=>{}}}let o=await R.mkdtemp($.join(qn.tmpdir(),"pm-npm-package-source-")),r=$.join(o,"pack");await R.mkdir(r,{recursive:!0});try{let i=await rd(e.spec),a=await t(["pack",i,"--json","--pack-destination",r]),s=ld(a,r,Ai(e.spec)?void 0:Ii(e.spec));if(!await k(s.tarball))throw new m("npm pack did not create its reported package archive.",f.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await Jn(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await R.rm(o,{recursive:!0,force:!0})}}}}catch(i){await R.rm(o,{recursive:!0,force:!0});let a=od(e.spec,i);throw a||i}}function Oi(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function we(e){throw new m(e,f.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 ud(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&we(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let o=e.path,r=o.split("/");(o.includes("\\")||o.startsWith("/")||/^[A-Za-z]:/u.test(o)||r.some(i=>i===".."))&&we(`Local package archive contains an escaping path: "${o}".`),r[0]!=="package"&&we(`Local package archive entry "${o}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&we(`Local package archive link "${o}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&we(`Local package archive entry "${o}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&we(`Local package archive entry "${o}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&we(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),o==="package/package.json"&&(n.packageJsonEntries+=1)}async function Jn(e,t=Vl){(await R.stat(e)).size>t.maxArchiveBytes&&we(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let o=await R.mkdtemp($.join(qn.tmpdir(),"pm-local-package-archive-")),r=$.join(o,"extract");await R.mkdir(r,{recursive:!0});let i={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await Kl({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(a===void 0)try{ud(d,t,i)}catch(p){a=p}}}),a!==void 0)throw a;i.packageJsonEntries!==1&&we(`Local package archive must contain exactly one package/package.json entry; found ${i.packageJsonEntries}.`),await Hl({file:e,cwd:r,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=$.join(r,"package"),c=$.join(s,"package.json"),l=JSON.parse(await R.readFile(c,"utf8"));return await md(s),{directory:await Ht(s,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.version:void 0,cleanup:async()=>{await R.rm(o,{recursive:!0,force:!0})}}}catch(s){throw await R.rm(o,{recursive:!0,force:!0}),s}}async function md(e,t=$i){let n=$.join(e,"package.json");if(!await k(n))return;let o;try{o=JSON.parse(await R.readFile(n,"utf8"))}catch{return}if(typeof o!="object"||o===null)return;let r=o,i=wd(r),a=fd(r);if(i.length===0&&!a)return;let s={...o};delete s.devDependencies;let c={...s};hd(c),await R.writeFile(n,`${JSON.stringify(c,null,2)}
|
|
28
|
+
`,"utf8");try{await Promise.all([R.rm($.join(e,"package-lock.json"),{force:!0}),R.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),i.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),a&&await gd(e)}finally{await R.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
29
|
+
`,"utf8")}}function fd(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Wt in t)return!0;return!1}function hd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let o={...n};delete o[Wt],Object.keys(o).length===0?delete e[t]:e[t]=o}}async function gd(e){let t=ce(import.meta.url,["../../.."]),[n,o]=Wt.split("/"),r=$.join(e,"node_modules",n),i=$.join(r,o);await R.mkdir(r,{recursive:!0}),await R.rm(i,{recursive:!0,force:!0}),await R.symlink(t,i,yd(process.platform))}function yd(e){return e==="win32"?"junction":"dir"}function _d(e,t){if(e.startsWith("-"))throw new m(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,f.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(o=>{let r=o.charCodeAt(0);return r<=31||r===127||"&|;()`\"'".includes(o)}))throw new m(`Extension runtime dependency "${e}" has an unsafe version specifier.`,f.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{Bl.resolve(e,t)}catch{throw new m(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,f.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 wd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[o,r]of Object.entries(n)){if(o===Wt||typeof r!="string"||r.trim().length===0||t.has(o))continue;let i=r.trim();t.set(o,_d(o,i))}return[...t.values()]}async function Ht(e,t){let n=await Gt(e);if(n.length===1)return n[0];if(n.length>1){let o=n.map(r=>$.relative(e,r).replaceAll($.sep,"/")).sort((r,i)=>r.localeCompare(i));throw new m(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${o.join(", ")}`,f.USAGE)}throw new m(`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.`,f.USAGE)}async function vd(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 i=$.resolve(e,r);if(V(e,i)&&await k($.join(i,"manifest.json")))return{directory:i,resolved_subpath:r}}if(await k($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let o=await Ht(e,t.input);return{directory:o,resolved_subpath:$.relative(e,o).replaceAll($.sep,"/")}}function bd(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 kd(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!bd(n))return new m(t,f.NOT_FOUND);let o=[];try{let i=process.env.PM_CLI_PACKAGE_ROOT,a=typeof i=="string"&&i.trim().length>0?$.resolve(i.trim()):"";Un?.key!==a&&(Un={key:a,aliases:await Jt()}),o=Un.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): ${o.join(", ")}`];return new m(`${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}".`,f.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 Ci(e){if(e.kind==="local"){let o;try{o=await R.stat(e.absolute_path)}catch{throw await kd(e)}if(o.isFile()&&Oi(e.absolute_path)){let i=await Jn(e.absolute_path);return{source:e,directory:i.directory,source_root:$.dirname(i.directory),resolved_subpath:$.relative($.dirname(i.directory),i.directory).replaceAll($.sep,"/"),npm_package:i.package,npm_version:i.version,cleanup:i.cleanup}}if(!o.isDirectory())throw new m(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,f.USAGE);let r=await Ht(e.absolute_path,e.input);return{source:e,directory:r,source_root:e.absolute_path}}if(e.kind==="npm"){let o=await dd(e);return{source:e,directory:o.directory,source_root:$.dirname(o.directory),cleanup:o.cleanup,resolved_subpath:$.relative($.dirname(o.directory),o.directory).replaceAll($.sep,"/"),npm_package:o.package,npm_version:o.version}}let t=await R.mkdtemp($.join(qn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await qt(n);let o=await qt(["-C",t,"rev-parse","HEAD"]),r=await vd(t,e);return{source:e,directory:r.directory,source_root:t,resolved_subpath:r.resolved_subpath,commit:o,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(o){throw await R.rm(t,{recursive:!0,force:!0}),o}}async function Kt(e,t){if(!await k(e)||!await k(t))return!1;let[n,o]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===o}import ht from"node:fs/promises";import gt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60ab864f-43c5-512c-b33f-456de96f8090")}catch{}})();var Wn=1,Fe="2026.6.24",xd=">=22.18.0",Sd={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Ri=new Set([...Bo.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(ho).map(e=>e.toLowerCase()),"scaffold"]),Ed="^6.0.0",$d="^22.0.0",Di=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],ue=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Pi(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function ji(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 Li(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 Id={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Ni=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Fi={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"]},Ad={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"]'},Td={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."},Od={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."},Mi="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Cd={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."]},Rd={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."]},Pd={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`."]},Nd={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 Gi(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 Ui(e,t){return e==="schema"?Pd[t]:e==="profile"?Nd[t]:Rd[t]}function Dd(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),o=0;for(;t[o]?.toLowerCase()==="starter";)o+=1;let r=t[o]?.toLowerCase(),i=o>0&&(o===t.length||r!==void 0&&Ri.has(r));return`${(Ri.has(n)||i?["starter",...t]:t).join(" ")} ping`}function zi(e){let t=e,n=`${e}s`,o=e.replace(/-/g,""),r=o===t?[]:[o],i=`${e.replace(/-/g,"_")}_owner`,a="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(r)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(a)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(i)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(a)}],`,` [${JSON.stringify(a)}, "in_progress"],`,` [${JSON.stringify(a)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function jd(e,t,n){let o=`${e}-search`,r=`${e}-vector`,i=`${e.replace(/-/g," ")} items`,a=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return a;if(n==="search")return[...a,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(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,c=`${e}s`,l=e.replace(/-/g,""),d=l===s?[]:[l],p=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`;return[...a,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(u)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...a,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...zi(e).map(s=>` ${s}`)," });"]:n==="importers"?[...a,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(i)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(i)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...a,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...a,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...a,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...a,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function Ld(e,t,n){let o=n==="hooks",r=n==="search",i=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",p=n==="services",u=Ad[n],h=e,y=`${e}s`,_=`${e.replace(/-/g,"_")}_note`,g=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=o?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],x=r?Bn(e,t,"search",u):[],E=i?Bn(e,t,"importers",u):[],C=a?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...Pi(ji({extensionName:e,itemTypeName:h,itemTypeFolder:y,fieldName:_,migrationId:g,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],G=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...Pi(Li(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],L=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],S=l?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],q=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],tt=p?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...r?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Di,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...l?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...v,...x,...E,...C,...G,...L,...S,...q,...tt,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
30
|
+
`)}function Fd(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let o=`${e.replace(/-/g," ")} items`;return[t,`${o} import`,`${o} export`]}return[t]}var Md={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"},Gd={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 Ud(e,t,n){let o=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...o?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...o?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function zd(e,t,n){let o=[],r=[...Ud(e,t,n)],i=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,l=e,d=`${e}s`,p=e.replace(/-/g,""),u=p===l?[]:[p],h=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":o.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... */ }","});"),i.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":o.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(a)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),i.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":o.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,","}));"),i.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":o.push("defineItemField","defineItemType","defineMigration"),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(h)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(l)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(u)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(y)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),i.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":o.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({",...zi(e),"});"),i.push(" profiles: [starterProfile],");break;case"renderers":o.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);`," },","});"),i.push(" renderers: { toon: toonRenderer },");break;case"parser":o.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 };","});"),i.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":o.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,","});"),i.push(" preflights: [preflightOverride],");break;case"services":o.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 };`,"});"),i.push(" services: { output_format: outputService },");break}return{builderImports:o,definitions:r,blueprintFields:i}}function Jd(e,t,n){let o=zd(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...o.builderImports].sort((i,a)=>i.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...o.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...o.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
|
|
31
|
+
`)}function Bn(e,t,n,o){if(n==="commands")return[];let r=`${e}-search`,i=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,l=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${o},`," });"],u=h=>[...p," let deactivated = false;"," try {",...h.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...u([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...u([` ext.assertSearchProvider({ name: ${JSON.stringify(r)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(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(i)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...u([` ext.assertImporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(a)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...u(ji({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:l,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(Li(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...u([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...u([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...u([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...u([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function qd(e,t,n){let o=n==="parser",r=JSON.stringify([...Fi[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" };',"",...Di,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(Fe)},`," },",` target: { pmVersion: ${JSON.stringify(Fe)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${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)},`,...o?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...Bn(e,t,n,r)].join(`
|
|
32
|
+
`)}function Wd(e,t,n){let o=Gi(n,"package"),r=Ui(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",o,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${Md[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`.",Mi,"- `.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 ${Gd[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 \`${Wn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Fe}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
|
|
33
|
+
`)}function Bd(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 Hd(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 Kd(e,t,n,o){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(o.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(o.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&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(o.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(o.itemTypeName)},`,` folder: ${JSON.stringify(o.itemTypeFolder)},`,` aliases: ${JSON.stringify(o.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(o.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&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(o.itemTypeName)}, folder: ${JSON.stringify(o.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 Vd(e,t,n){let o=[];return t==="renderers"&&o.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&o.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&o.push(" api.registerPreflight(preflightOverride);"),t==="services"&&o.push(' api.registerService("output_format", outputService);'),t==="hooks"&&o.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&o.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&o.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&o.push(" api.registerProfile(starterProfile);"),t==="importers"&&o.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),o}function Yd(e,t,n,o="commands",r=!1){let i=`pm-${e}`,a=Fi[o],s=Fd(e,t,o),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Wn,pm_min_version:Fe,trusted:!0,sandbox_profile:"strict",permissions:{...Sd},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
|
|
34
|
+
`,l=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...jd(e,t,o),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
|
|
35
|
+
`),d=`${JSON.stringify(Id,null,2)}
|
|
36
|
+
`,p=Td[o],u=Gi(o,"package"),h=`${JSON.stringify({name:i,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:xd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Fe}`},devDependencies:{"@types/node":$d,typescript:Ed},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
|
|
37
|
+
`,y=Ld(e,t,o),_=Od[o],g=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
38
|
+
`),w=Bd(e),x=["```ts",`import { ${Hd(o)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Kd(e,t,o,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Vd(t,o,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],E=[`# ${i}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",u,p,_,Mi,"- `.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:",...x,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Cd[o],...Ui(o,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Fe}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Wn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Fe}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
|
|
39
|
+
`);return{"package.json":h,"manifest.json":c,"index.ts":r?Jd(e,t,o):l,"index.test.ts":r?qd(e,t,o):y,"tsconfig.json":d,".gitignore":g,"README.md":r?Wd(i,t,o):E}}async function Ji(e,t="extension",n="commands",o=!1){let r=n.trim().toLowerCase();if(!Ni.includes(r))throw new m(`Unknown scaffold capability "${n}". Supported capabilities: ${Ni.join(", ")}.`,f.USAGE);let i=r;if(o&&t!=="package")throw new m("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",f.USAGE);let a=o?"declarative":"imperative",s=e.trim(),c=gt.resolve(process.cwd(),s),l=Ut(gt.basename(c)).replace(/^(?:pm-)+/u,""),d=Dd(l),p=Yd(l,d,t,i,o),u=!1;if(await k(c)){if(!(await ht.stat(c)).isDirectory())throw new m(`Scaffold target "${c}" exists and is not a directory.`,f.CONFLICT)}else await ht.mkdir(c,{recursive:!0}),u=!0;for(let[y,_]of Object.entries(p)){let g=gt.join(c,y);if(!await k(g))continue;if(await ht.readFile(g,"utf8")!==_)throw new m(`Scaffold file "${y}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,f.CONFLICT)}let h=[];for(let[y,_]of Object.entries(p)){let g=gt.join(c,y);if(await k(g)){h.push({path:y,status:"unchanged"});continue}await ht.mkdir(gt.dirname(g),{recursive:!0}),await ht.writeFile(g,_,"utf8"),h.push({path:y,status:"created"})}return{extension_name:l,package_name:`pm-${l}`,command_name:d,invocation_command:`pm ${d}`,capability:i,style:a,target_path:c,created_directory:u,files:h}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bc00b8e-0d9f-5af8-9667-d46136ff52b0")}catch{}})();var qi=1,Hn=6,Wi=[["commands","Commands"],["command_overrides","Command overrides"],["flag_commands","Flag commands"],["item_types","Item types"],["item_fields","Item fields"],["migrations","Migrations"],["profiles","Profiles"],["importers","Importers"],["exporters","Exporters"],["search_providers","Search providers"],["vector_store_adapters","Vector store adapters"],["assurance_providers","Assurance measurement providers"],["hooks","Lifecycle hooks"],["parser_overrides","Parser overrides"],["service_overrides","Service overrides"],["renderer_overrides","Renderer overrides"]];function Kn(e){return"#".repeat(e)}function Bi(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let i of e)n=i==="`"?n+1:0,t=Math.max(t,n);let o="`".repeat(t+1),r=e.startsWith("`")||e.endsWith("`")?" ":"";return`${o}${r}${e}${r}${o}`}function Xd(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(Bi).join(", ")}`}function Zd(e,t,n){let o=[`${Kn(t)} ${e}`,""];return n.length===0?(o.push("_None._",""),o):(o.push(...n.map(r=>`- ${Bi(r)}`),""),o)}function Qd(e,t,n){return e===0&&!n?[]:[`${Kn(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function Vn(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<qi||n>Hn)throw new RangeError(`headingLevel must be an integer in [${qi}, ${Hn}], received ${String(t.headingLevel)}`);let o=Math.min(n+1,Hn),r=t.includeEmpty===!0,i=t.title??"Extension surfaces",a=[`${Kn(n)} ${i}`,""];(r||e.capabilities.length>0)&&a.push(Xd(e.capabilities),"");for(let[c,l]of Wi){let d=e[c]??[];d.length===0&&!r||a.push(...Zd(l,o,d))}return a.push(...Qd(e.preflight_overrides,o,r)),!(e.preflight_overrides>0||Wi.some(([c])=>(e[c]?.length??0)>0))&&!r&&a.push("_This extension registers no surfaces._",""),`${a.join(`
|
|
38
40
|
`).trimEnd()}
|
|
39
|
-
`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6c9e36f8-0f95-5768-8893-bf33bbb4d848")}catch{}})();function
|
|
41
|
+
`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6c9e36f8-0f95-5768-8893-bf33bbb4d848")}catch{}})();function Hi(e,t){return`${e}:${b(t)}`}function ep(e,t){let n=[];for(let[o,r]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let i=new Map;for(let a of r){let s=i.get(a.command)??[];i.set(a.command,[...s,a])}for(let[a,s]of i){if(t!==null&&!s.some(l=>t.has(b(l.name))))continue;let c=s.at(-1);n.push({command:a,surface:o,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(l=>({name:l.name,layer:l.layer,winner:l===c}))})}}return n.sort((o,r)=>o.command.localeCompare(r.command)||o.surface.localeCompare(r.surface))}function Ki(e,t,n){let o=new Set(n.failed.map(l=>Hi(l.layer,l.name))),r=[...t.loaded.map(l=>({name:l.name,layer:l.layer,version:l.version,activation_status:o.has(Hi(l.layer,l.name))?"failed":"ok",surfaces:Je(n,{extensionName:l.name})})),...t.failed.map(l=>({name:l.name,layer:l.layer,version:"unknown",activation_status:"not_loaded",surfaces:Je(n,{extensionName:l.name})}))].sort((l,d)=>l.name.localeCompare(d.name)||l.layer.localeCompare(d.layer)),i=typeof e=="string"?b(e):null,a=i===null?null:new Set(t.loaded.filter(l=>b(l.name)===i||typeof l.source_package=="string"&&b(l.source_package)===i||(l.source_aliases??[]).some(d=>b(d)===i)).map(l=>b(l.name)).concat(i)),s=a===null?r:r.filter(l=>a.has(b(l.name))),c=a===null?{}:{extensionNames:[...a]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Je(n,c),command_ownership:ep(n,a)}}var tp={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function qy(e,t){let o=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(o.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),o.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){o.push("## Command ownership","");for(let r of e.command_ownership){let i=r.claimants.find(s=>s.winner),a=r.claimants.map(s=>`${s.layer}:${s.name}`).join(", ");o.push(`- \`${r.command}\` (${r.surface}): ${i.layer}:${i.name}; policy=${r.policy}; collision=${String(r.collision)}; claimants=${a}`)}o.push("")}if(e.extensions.length===0)return o.push(`_No ${t}s are loaded._`,""),`${o.join(`
|
|
40
42
|
`).trimEnd()}
|
|
41
|
-
`;for(let r of e.extensions){let i=`${r.name} (${r.layer} v${r.version}, ${
|
|
43
|
+
`;for(let r of e.extensions){let i=`${r.name} (${r.layer} v${r.version}, ${tp[r.activation_status]})`;o.push(Vn(r.surfaces,{title:i,headingLevel:2}))}return e.extensions.length>1&&o.push(Vn(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${o.join(`
|
|
42
44
|
`).trimEnd()}
|
|
43
|
-
`}import
|
|
44
|
-
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let a=o.filter(d=>d.outcome==="pending").length,s=o.filter(d=>d.outcome==="applied").length,c=o.filter(d=>d.outcome==="skipped").length,l=o.filter(d=>d.outcome==="failed").length;return{ok:l===0,dry_run:e.dryRun===!0,state_path:
|
|
45
|
-
`,"utf8")},
|
|
46
|
-
`,"utf8")}catch(n){throw await M.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},zd=async(e,t,n,o,r)=>{for(let i=1;i<=n;i+=1)try{return await Ud(e,t),!0}catch(a){if(!qt(a,"EEXIST"))throw a;await Md(e,r)?i-=1:await ji(o)}return!1},qn=async(e,t,n,o)=>{let r=D.join(e,"runtime","extension-install-locks"),i=D.join(r,"scope.lock");await M.mkdir(r,{recursive:!0});let{attempts:a=jd,delay_ms:s=Pi,stale_ms:c=Ld,heartbeat_ms:l}=o??{};if(![a,s,c,l].filter(_=>_!==void 0).every(Number.isFinite))throw new h("Extension install lock timings must be finite numbers.",g.USAGE);let d=Math.max(1,Math.floor(a)),p=Math.max(0,Math.floor(s)),u=Math.floor(c),f=Math.floor(l??u/3);if(u<=0||f<=0||f>=u)throw new h("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",g.USAGE);let y={pid:process.pid,token:Nd(),created_at:A(),destination:t};if(!await zd(i,y,d,p,u))throw new h(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let m=Gd(i,y.token,f);try{return await n()}finally{await m(),await Ui(i,y.token).catch(()=>!1)}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4b9502f-f742-5f11-b341-56763bbed7c2")}catch{}})();var Jd=new Set(["node_modules",".git","dist","build","coverage"]);async function zi(e,t,n,o){let r=e.source.kind==="local"?await Wt.stat(e.source.absolute_path):void 0,i=e.source.kind==="local"?r.isDirectory()?"directory":"archive":e.source.kind,a=await qd(e.directory,t,o),s={source_mode:i,...i==="archive"?{archive_bytes:r.size}:{},copy:a},c=e.source_root??e.directory;return i==="directory"&&(!a.complete||a.development_entries>0||a.bytes>=16*1024*1024)&&await k(Bt.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),s}async function qd(e,t,n={}){let{maxEntries:o=1e4,maxDepth:r=64,signal:i}=n;if(![o,r].every(p=>Number.isSafeInteger(p)&&p>0))throw new h("maxEntries and maxDepth must be positive safe integers.",g.USAGE);i?.throwIfAborted();let a=await Wt.realpath(e),s=await ht(t),c=await zt(a,s);i?.throwIfAborted();let l=c?"in_place":H(a,s)?"nested_filtered_snapshot":"directory_snapshot",d={copy_scope:l,source_directory:a,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:o,max_depth:r};return l==="in_place"||await Ji(a,0,d,i),d}async function Ji(e,t,n,o){o?.throwIfAborted();let r=await Wt.opendir(e);for await(let i of r){if(o?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let a=Bt.join(e,i.name);if(n.copy_scope==="nested_filtered_snapshot"&&!Jt(n.source_directory,n.destination_directory,a)){n.excluded_entries+=1;continue}if(Bt.relative(n.source_directory,a).split(Bt.sep).some(s=>Jd.has(s))&&(n.development_entries+=1),await Bd(a,t,n,o),!n.complete)return}}async function Bd(e,t,n,o){let r=await Wt.lstat(e);if(o?.throwIfAborted(),r.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await Ji(e,t+1,n,o)}else r.isFile()?(n.files+=1,n.bytes+=r.size):r.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcdfdabd-8862-502f-8cd1-298c08825985")}catch{}})();async function qi(e,t,n){let o=typeof t=="string"?null:await ut(e),r=o===null?null:e.trim().toLowerCase(),i=r===null?null:await Zr(r),a=Gt(o??e,{forceGithub:typeof t=="string",ref:n}),s=r===null?null:await ri(e);return{bundledAliasName:r,bundledPackageName:i,installSource:a,sourceResolution:{requested:e,selected:{kind:r===null?a.kind:"builtin",input:r??a.input,...i===null?{}:{package:i}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...r===null?[]:[{kind:"builtin",input:r,...i===null?{}:{package:i},command:`pm install ${r}`}],...s===null?[]:[{kind:"npm",input:`npm:${s.package}`,package:s.package,...s.version===void 0?{}:{version:s.version},directory:s.directory,command:`pm install npm:${s.package}`}]]}}}import Ae from"node:fs/promises";import ne from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="df60255d-fdd6-594a-9e17-547d53f7b3bb")}catch{}})();function Bn(e){return e.map(({layer:t,name:n,error:o})=>({layer:t,name:n,error:o}))}function Ht(e,t,n){let o=b(t),r=n.trim();if(o.length===0||r.length===0)return;let i=e.get(o)??new Set;i.add(r),e.set(o,i)}function Wd(e){let t=new Map,n=new Map;for(let o of e.registrations.commands)Ht(t,o.name,o.command),Ht(n,o.name,o.action);for(let o of e.commands.handlers)Ht(t,o.name,o.command);for(let o of e.commands.overrides)Ht(t,o.name,o.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Bi(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Hd(e){let{enabled:t,normalizedName:n,loadedNames:o,loadFailedNames:r,activationFailedNames:i}=e;return t?r.has(n)||i.has(n)?{runtime_active:!1,activation_status:"failed"}:o.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function Kt(e,t,n){let o=new Set(t.loaded.map(c=>b(c.name))),r=new Set(t.failed.map(c=>b(c.name))),i=new Set(n.failed.map(c=>b(c.name))),{commandPathsByExtension:a,actionPathsByExtension:s}=Wd(n);return e.map(c=>{let l=b(c.name),d=Bi(a.get(l)),p=Bi(s.get(l)),u={...d?{command_paths:d}:{},...p?{action_paths:p}:{}},f=Hd({enabled:c.enabled,normalizedName:l,loadedNames:o,loadFailedNames:r,activationFailedNames:i});return{...c,...f,...u}})}function Kd(e){let t=0,n=0,o=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_")&&(o+=1)}return{warning_count:t,violation_count:n,blocked_count:o}}function U(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Ki=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 Vd(e){return Ki.has(ea(e))}function Wi(e){return e==="project"||e==="global"}function Vi(e){let t=e.split(":"),n=t[0];if(!n||!Ki.has(n))return null;let o=t.at(-4),r=t.at(-3)?.trim(),i=t.at(-2),a=t.at(-1)?.trim();return!Wi(o)||!Wi(i)||!r||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:o,name:r},displaced:{layer:i,name:a}}}function Xd(e){let t=new Set;for(let n of e){let o=Vi(n);o&&(t.add(o.winner.name),t.add(o.displaced.name))}return[...t].sort((n,o)=>n.localeCompare(o))}function Yd(e,t){let n=e.filter(Vd);if(n.length===0)return null;let o=Xd(n);return`Extension registration collisions or handler/override overlaps detected.${o.length>0?` Conflicting extensions: ${o.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function Qd(e,t,n,o){let r=t.map(p=>Vi(p)).filter(p=>p!==null).sort((p,u)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`));if(r.length===0)return;let i=e==="global"?"--global":"--project",a=U(o,"deactivate"),s=`${U(o,"doctor")} ${i} --detail deep --trace`,c=new Map(n.map(p=>[b(p.name),p])),l=new Map;for(let p of r)for(let u of[p.winner.name,p.displaced.name]){let f=b(u);l.set(f,(l.get(f)??0)+1)}let d=[...l.entries()].map(([p,u])=>{let f=c.get(p),y=f?.name??p,w=f?.command_paths??[],m=f?.action_paths??[];return{action:"deactivate",extension:y,command:`${a} ${y} ${i}`,affected_collisions:u,feature_loss:{command_paths:[...w].sort((_,v)=>_.localeCompare(v)),action_paths:[...m].sort((_,v)=>_.localeCompare(v))}}}).sort((p,u)=>{let f=u.affected_collisions-p.affected_collisions;if(f!==0)return f;let y=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,w=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length;return y!==w?y-w:p.extension.localeCompare(u.extension)});return{status:"conflicts_detected",collision_count:r.length,extension_count:l.size,next_best_command:s,collisions:r,remediation_candidates:d}}function Xi(e){let t=[];for(let n of e){let o=n.error.toLowerCase();(o.includes("cannot find package '@unbrained/pm-cli'")||o.includes('cannot find module "@unbrained/pm-cli"')||o.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(o.includes("cannot use import statement outside a module")||o.includes("to load an es module")||o.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,o)=>n.localeCompare(o))}function Yi(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let o of t){if(!o||typeof o.name!="string")continue;let r=o.trace?.missing_capability??o.trace?.capability;typeof r=="string"&&r.trim().length>0&&n.push(`extension_capability_missing:${o.name}:${r.trim().toLowerCase()}`)}return[...new Set(n)].sort((o,r)=>o.localeCompare(r))}function Qi(e,t){let n=[];for(let o of Ao(e.loaded,t))for(let r of o.unused)n.push(`extension_capability_unused:${o.layer}:${o.name}:${r}`);return[...new Set(n)].sort((o,r)=>o.localeCompare(r))}var Zd=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${U(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${so.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${U(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${U(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${U(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function ep(e){let{normalizedWarnings:t,options:n,scope:o,scopeFlag:r,updateCheckFailedTotal:i,policyWarningCount:a,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,p=[],u={options:n,scope:o,scopeFlag:r,updateCheckFailedTotal:i,policyWarningCount:a};if(t.length>0){let f=Yd(t,{deactivate:`${U(n,"deactivate")} <name> ${r}`,doctor:`${U(n,"doctor")} ${r} --detail deep --trace`});f&&p.push(f);for(let y of Zd)y.matches(t,u)&&p.push(y.build(u))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${U(n,"manage")} ${r} --fix-managed-state (or ${U(n,"adopt-all")} ${r}, ${U(n,"adopt")} <name> ${r}, or reinstall via ${U(n,"install")} ${r} <source>).`),l>0&&p.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${U(n,"manage")} ${r} to request update checks.`),d>0&&p.push(`Update available managed extensions via ${U(n,"install")} ${r} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${U(n,"manage")} ${r} after extension changes.`),p}function Vt(e,t,n,o={}){let r=[...new Set(t)].sort((S,J)=>S.localeCompare(J)),i=n.filter(S=>S.managed).length,a=n.filter(S=>S.enabled).length,s=n.filter(S=>S.active).length,c=n.filter(S=>S.update_check_status==="checked"&&S.update_available===!0).length,l=n.filter(S=>S.managed===!1),d=l.filter(S=>Hi(S)).map(S=>S.name).sort((S,J)=>S.localeCompare(J)),p=l.filter(S=>!Hi(S)).map(S=>S.name).sort((S,J)=>S.localeCompare(J)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let S of n)u[S.update_check_status]+=1;let f=u.failed,y=n.filter(S=>S.update_check_status==="skipped_non_github"&&S.source?.kind!=="builtin").length,w=Object.entries({skipped_unmanaged:p.length,skipped_non_github:y,failed:f,not_checked:u.not_checked}).filter(([,S])=>S>0).map(([S,J])=>`extension_update_health_partial_coverage:${S}:${J}`),m=w.length>0,_=m?"partial":"full",v=[...new Set([...r,...w])].sort((S,J)=>S.localeCompare(J)),x=[...new Set(v.map(S=>ea(S)))].sort((S,J)=>S.localeCompare(J)),E=Kd(v),C=e==="global"?"--global":"--project",G=Qd(e,r,n,o),L=ep({normalizedWarnings:v,options:o,scope:e,scopeFlag:C,updateCheckFailedTotal:f,policyWarningCount:E.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:u.not_checked,skippedNonGithubTotal:y,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:x,warnings:v,policy_warning_count:E.warning_count,policy_violation_count:E.violation_count,policy_blocked_count:E.blocked_count,total_extensions:n.length,managed_total:i,enabled_total:a,active_total:s,update_available_total:c,update_health_coverage:_,update_health_partial:m,unmanaged_loaded_extension_count:l.length,unmanaged_loaded_extensions:l.map(S=>S.name).sort((S,J)=>S.localeCompare(J)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:u,update_check_failed_total:f,top_warnings:v.slice(0,8),remediation:L,...G?{collision_plan:G}:{}}}function Zi(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new h(`Invalid --detail value "${e}". Expected summary or deep.`,g.USAGE)}function ea(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function ta(e){let t=new Set,n=[];for(let o of e){let r=(()=>{let i=wo(o);return i?[i]:vo(o)})();for(let i of r){let a=`${i.layer}:${i.name}:${i.capability}`;t.has(a)||(t.add(a),n.push(i))}}return n}function na(){return{version:vt.version,capabilities:[...vt.capabilities],legacy_aliases:{...vt.legacy_aliases}}}function Hi(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function oa(e,t,n,o,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 i=[...new Set(t.filter(d=>d.active).map(d=>b(d.name)))].sort((d,p)=>d.localeCompare(p)),a=[...new Set(n.filter(d=>d.layer==="project").map(d=>b(d.name)))].sort((d,p)=>d.localeCompare(p)),s=new Set(o.map(d=>b(d.name))),c=i.filter(d=>!a.includes(d)&&!s.has(d)).sort((d,p)=>d.localeCompare(p));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:i.length,loaded_project_count:a.length,active_project_names:i,loaded_project_names:a,missing_active_project_names:c}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96a05fa4-b833-56ca-b501-40a427d03201")}catch{}})();var ra=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let o=new Array(e.length),r=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let a=r;r+=1,o[a]=await n(e[a])}});return await Promise.all(i),o};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="37f2dced-3b93-5c64-85ae-56e62c95e8eb")}catch{}})();function ia(e,t){let n=b(e),o=t.find(r=>b(r.name)===n);return{command_paths:[...o?.command_paths??[]].sort((r,i)=>r.localeCompare(i)),action_paths:[...o?.action_paths??[]].sort((r,i)=>r.localeCompare(i))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fcc97434-1ef5-5c47-b491-f00e9d19b2c6")}catch{}})();function aa(e,t){let n=new Set((t?.loaded??[]).flatMap(i=>(i.activation?.commands?.length??0)>0?[`${i.layer}:${b(i.name)}`]:[])),o=e.services.overrides.filter(i=>i.service==="output_format").filter(i=>i.passThrough!==!0).filter(i=>!n.has(`${i.layer}:${b(i.name)}`)).map(i=>`extension_output_service_override_global:${i.service}:${i.layer}:${i.name}`),r=e.renderers.overrides.filter(i=>(i.commands?.length??0)===0&&i.resultDiscriminator===void 0).map(i=>`extension_output_renderer_override_global:${i.format}:${i.layer}:${i.name}`);return[...new Set([...o,...r])].sort((i,a)=>i.localeCompare(a))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var sa=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=$t(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,o)=>o.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8507f364-e079-5743-a54b-bb3a68ab66d0")}catch{}})();var tp=1e4,np=(e,t,n)=>{let o=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),r=o.find(a=>a.ref.endsWith("^{}"))??o[0];if(!r)return{checked_at:n,available:null,error:"no_remote_reference_found"};let i=t?.trim();return i?{checked_at:n,remote_commit:r.commit,available:r.commit!==i}:{checked_at:n,remote_commit:r.commit,available:null,error:"missing_installed_commit"}},ca=async(e,t=Ft)=>{let n=A();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let o=[e.ref?.trim(),"HEAD"].find(Boolean),r=await t(["ls-remote",e.repository,o,`${o}^{}`],void 0,tp);return np(r,e.commit,n)}catch(o){return{checked_at:n,available:null,error:o instanceof Error?o.message:String(o)}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ee1bfa77-6687-578c-9cd6-639fc702c48c")}catch{}})();function la(e,t){let n=e.filter(o=>o.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:o,result:r})=>{let i=r.details;return{alias:o,ok:r.ok,extension:i.extension,source:i.source,source_resolution:i.source_resolution,install_plan:i.install_plan,dry_run:i.dry_run,destination_path:i.destination_path,activated:i.activated,settings_changed:i.settings_changed,command_paths:i.command_paths,action_paths:i.action_paths,command_discovery:i.command_discovery,verification:i.verification,runtime_activation_status:i.runtime_activation_status,activation_diagnostics:i.activation_diagnostics,warnings:r.warnings}})}}import op from"node:fs/promises";import rp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1bf79a0-1f04-590f-b613-45ca1b534d5d")}catch{}})();function ip(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function ap(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 sp(e){let t=rp.join(e,"manifest.json"),n;try{n=await op.readFile(t,"utf8")}catch(s){if(wt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let o;try{o=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof o!="object"||o===null||Array.isArray(o))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let r=o,i=xo(r),a=ip(r);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:i.findings,warnings:i.findings.map(s=>ap(a,s)),remediation:i.findings.map(s=>s.message)}}function da(e){return sp(go(e))}import Le from"node:fs/promises";import cp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7afb9a1-be35-5dfd-a52e-2525598b68d8")}catch{}})();var Wn=async e=>Le.readFile(e).catch(t=>{if(qt(t,"ENOENT"))return null;throw t}),pa=async(e,t,n,o,r)=>Fe("extension_install_backup",async()=>{let i=lt(e),a=_o(t),[s,c]=await Promise.all([Wn(i),Wn(a)]);return o&&await Le.cp(n,r,{recursive:!0,force:!0}),{backupDirectory:r,destinationDirectory:n,destinationExists:o,managedStatePath:i,managedStateContents:s,settingsPath:a,settingsContents:c}}),ua=async e=>Fe("extension_install_rollback",async()=>{await Le.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Le.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 Le.rm(t,{force:!0}):(await Le.mkdir(cp.dirname(t),{recursive:!0}),await Le.writeFile(t,n))});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f8fc1a7-748d-559d-9de8-835d0428c6a7")}catch{}})();var lp=4,ga=[["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"]],dp=ga.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),pp={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"},up="__pm_native_output",mp=["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"],ya=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],fp=["disabled","require_trusted","require_provenance"],_a={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:[]},hp=e=>{let t=e??_a,n={};for(let o of mp)n[o]=ee(t[o]??[]);return n},gp=(e,t)=>{for(let n of ya)t[n].length>0&&(e[n]=t[n]);return e},yp=(e,t)=>{for(let n of fp)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},_p=e=>{let t={};for(let n of ya)t[n]=ee(e[n]??[]);return t},wp=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:gp(yp({name:t},e),_p(e))},vp=e=>(e??[]).map(t=>wp(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),bp=e=>{let t=Object.assign({},_a,e??{}),n=hp(e),o=vp(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:o}},wa=async(e,t)=>{let n=[t],o=await ei(t);o&&n.push(o);let r=[...new Set(n.map(i=>b(i)).filter(i=>i.length>0))];for(let i of r){let a=e.find(c=>b(c.name)===i);if(a)return a;let s=e.find(c=>b(c.directory)===i);if(s)return s}},va=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled));return new Set(ee(e.extensions.disabled)).has(n)?!1:o.size===0?!0:o.has(n)},ba=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),r=new Set(ee(e.extensions.disabled)),i=[...o],a=[...r];return r.delete(n),o.size>0&&o.add(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},kp=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),r=new Set(ee(e.extensions.disabled)),i=[...o],a=[...r];return o.delete(n),r.add(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},xp=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),r=new Set(ee(e.extensions.disabled)),i=[...o],a=[...r];return o.delete(n),r.delete(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Sp=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),o=ga.map(([r,i,a])=>({action:i,flag:a,distance:uo(t,r,n)})).filter(r=>r.distance!==null).sort((r,i)=>r.distance-i.distance)[0];return o?{action:o.action,flag:o.flag}:null},Ep=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=Sp(e);if(!o)return new h(`One action flag is required. Use one of: ${dp}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let r=`pm ${n} ${o.flag}`;return mo({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(ka),retry_command:r,message_suffix:`. Did you mean "${o.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:r,reason:`nearest lifecycle action for "${e}"`}]})},$p=[["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"]],ka={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Ip=e=>ka[e]??null,Ap=(e,t)=>{let n=[...new Set($p.filter(([o])=>t[o]===!0).map(([,o])=>o))];if(n.length===0){if(e===void 0)return"explore";let o=Ip(e.trim().toLowerCase());if(o)return o;throw Ep(e,t)}if(n.length>1)throw new h("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},Tp=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new h('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"},Op=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&e.source.kind!=="github"?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],xa=e=>{for(let t of Op){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Sa=(e,t,n,o)=>{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,update_error:r.update_error,update_check_status:o.status,update_check_reason:o.reason}},Cp=(e,t,n,o)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},o),i=o?va(n,o.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Sa({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:i},t,o,xa(o))}},Rp=async(e,t,n,o,r,i)=>{let a=ne.join(e,t),s=ne.join(a,"manifest.json"),c=i.get(b(t));if(!await k(s))return Cp(t,n,o,c);let l=Symbol("invalid-extension-manifest-json"),d=await Ae.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>l);if(d===l)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Tn(d);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=r.get(b(p.name))??i.get(b(t));return{summary:Sa({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:va(o,p.name)},n,u,xa(u))}},me=async(e,t,n,o)=>{if(!await k(e))return{extensions:[],warnings:[]};let i=(await Ae.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,p)=>d.localeCompare(p)),a=new Map(o.entries.map(d=>[b(d.name),d])),s=new Map(o.entries.map(d=>[b(d.directory),d])),c=[],l=[];for(let d of i){let p=await Rp(e,d,t,n,a,s);p.warning&&c.push(p.warning),p.summary&&l.push(p.summary)}return{extensions:l.sort((d,p)=>d.name.localeCompare(p.name)),warnings:c.sort((d,p)=>d.localeCompare(p))}},Pp=$o(),Np=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Dp=(e,t,n,o)=>{let r=n.command_paths.map(s=>`pm ${s} --help`),i=o?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...r]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return i&&a.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Np(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:r,next_steps:a,...i?{sdk_dependency_status:"missing"}:{}}},jp=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,o])=>o!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},Ea=e=>e.map(t=>jp(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),$a=(e,t,n)=>{let o=b(e);return t.find(r=>(n===void 0||r.layer===n)&&b(r.name)===o)},Lp=(e,t,n,o)=>n.find(i=>i.scope===t&&b(i.name)===b(e))?.activation_status??(o?"failed":"unknown"),Ia=(e,t,n,o,r)=>Pp.enqueue(async()=>{let i=process.env.PM_CLI_PACKAGE_ROOT,a=await Ae.mkdtemp(ne.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=ce(import.meta.url,["../.."]);try{let s=await ve({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:r.noExtensions===!0,reload_token:an(),cache_bust:!0,module_graph_snapshot_root:a}),c=await be({...s}),l=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...Ea(c.failed)],d=Object.fromEntries(s.loaded.map(p=>[b(p.name),ko(ze(c,{extensionName:p.name}))]));return{installed:Kt(o,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:l,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:d}}finally{await Ae.rm(a,{recursive:!0,force:!0}),i===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=i}}),Kn=async(e,t,n,o)=>{let r=n.filter(c=>!c.managed),i=[...r].sort((c,l)=>{let d=c.name.localeCompare(l.name);return d!==0?d:c.directory.localeCompare(l.directory)}),a=o,s=[];for(let c of i){let l=ne.join(e,c.directory),d=await Ye(l),p=A(),u={kind:"local",input:c.name,location:l};a=pt(a,{name:d.manifest.name,directory:c.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:p,updated_at:p,source:u}),s.push({name:d.manifest.name,directory:c.directory,version:d.manifest.version,entry:d.manifest.entry,source:u})}return s.length>0&&await De(e,a),{state:a,adopted_entries:s,unmanaged_candidates:i,already_managed_count:n.length-r.length}},Fp=(e,t)=>{let n=N(process.cwd(),t.path),o=kt(n,process.cwd()),r=e==="global"?yo(process.cwd()):n,i=e==="global"?o.global:o.project;return{pm_root:n,scope:e,settings_root:r,selected_root:i,roots:o}},Xt=e=>{let t=[e.gh,e.github].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new h('Options "--gh" and "--github" must match when both are provided.',g.USAGE);return n[0]},Mp=e=>pp[e],Gp=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=e==="install"?"source":"name",r=`${n} ${o}`,i=Mp(e),a=`<${o}>`,s=`pm ${n} ${i} ${a}`;throw new h(`Action "${e}" requires ${r} input.`,g.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${o} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${o} target`}]}})},Yt=(e,t,n={})=>{let o=e?.trim();if(o)return o;if(t==="init")throw new h('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',g.USAGE);return Gp(t,n)},Up=(e,t)=>{let n=new Set([...t.registrations.item_types.map(o=>({entry:o,count:o.types.length})),...t.registrations.item_fields.map(o=>({entry:o,count:o.fields.length}))].filter(({count:o})=>o>0).map(({entry:o})=>`${o.layer}:${b(o.name)}`));return e.loaded.filter(o=>(o.activation?.commands??[]).length>0).filter(o=>n.has(`${o.layer}:${b(o.name)}`)).map(o=>`extension_schema_narrow_activation:${o.layer}:${o.name}`).filter((o,r,i)=>i.indexOf(o)===r).sort((o,r)=>o.localeCompare(r))},zp=(e,t)=>{let o=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(r=>r.triggered&&!r.allowed);if(o)throw new h(o.message,g.USAGE)},Jp=(e,t,n)=>{let o=String(e??"").trim().toLowerCase(),r=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:r?[]:["init","scaffold"]}[t]??[]).includes(o)?void 0:e},qp=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},Bp=(e,t,n)=>{let o={ok:n,action:e.action,scope:e.scope,roots:qp(e),warnings:[...new Set(e.warnings)].sort((r,i)=>r.localeCompare(i)),details:t};return e.action==="doctor"&&Object.defineProperty(o,up,{value:!0,enumerable:!1,configurable:!1}),o},Vn=async(e,t,n)=>{let o=Ap(e,t);zp(o,t);let r=Jp(e,o,t),i=Tp(t),a=Fp(i,n),c={action:o,normalizedTarget:r,scope:i,resolvedRoots:a,warnings:[],options:t,global:n},d={...c,withResult:(p,u=!0)=>Bp(c,p,u)};return await Su(d)},Wp=(e,t)=>{let n=t.vocabulary??"extension",o=e.target_path.replace(/\\/g,"/"),r=Ro(o),i={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"`},a={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."),[i[n],...s,`Install the scaffold: ${Et(n==="package"?["install","--project",o]:["extension","--install","--project",o])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},Hp=async e=>{let{action:t,normalizedTarget:n,options:o,withResult:r}=e;if([Xt(o),o.ref].filter(l=>typeof l=="string").map(l=>l.trim()).filter(Boolean).length>0)throw new h('Action "init" does not accept --gh/--github/--ref options.',g.USAGE);let s=Yt(n,t,o),c=await ki(s,o.vocabulary??"extension",o.capability,o.declarative===!0);return r({scaffolded:c.created_directory||c.files.some(l=>l.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:Wp(c,o)})},Kp=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:o,options:r,global:i,withResult:a}=e;if(t!==void 0)throw new h('Action "reload" does not accept a target argument.',g.USAGE);let s=await T(n.settings_root),c=an(),l=await ve({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:i.noExtensions,reload_token:c,cache_bust:!0});o.push(...l.warnings);let d=await be(l);o.push(...d.warnings);let p={reload:{token:c,cache_bust:!0,watch:r.watch===!0},loaded_count:l.loaded.length,failed_count:l.failed.length,activated_count:Math.max(0,l.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:l.loaded.map(u=>({name:u.name,layer:u.layer,version:u.version})),failed_extensions:l.failed.map(u=>({name:u.name,layer:u.layer,error:u.error})),activation_failures:d.failed.map(u=>({name:u.name,layer:u.layer,error:u.error}))};return r.watch===!0&&o.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},Vp=async e=>{let{normalizedTarget:t,scope:n,options:o,global:r,withResult:i}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new h('Action "catalog" does not accept a package target.',g.USAGE);return i(await ti(n,r,o))},Xp=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Yp=e=>({kind:"local",input:e.input,location:e.absolute_path}),Qp=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),Zp=(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,o)=>e?Xp(e,t):n.kind==="local"?Yp(n):n.kind==="npm"?Qp(n,o):Zp(n,o),tu=(e,t,n,o)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:o}:Kr(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:o}:{installed_at:o,updated_at:o},nu=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:r}=e,{validated:i,destinationDirectoryName:a}=t,s=await T(o.settings_root),c=await _e(o.selected_root);r.push(...c.warnings);let l=ne.join(o.selected_root,a),d=await k(l),p=await zt(i.directory,l);await Ae.mkdir(o.selected_root,{recursive:!0});let u=await Ae.mkdtemp(ne.join(o.selected_root,".pm-extension-install-backup-")),f=ne.join(u,"destination");try{let y=await pa(o.selected_root,o.settings_root,l,d,f),w=eu(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),m=c.state.entries.find(E=>b(E.name)===b(i.manifest.name)),_=tu(m,i.manifest.version,w,A()),v=pt(c.state,{name:i.manifest.name,directory:a,scope:n,manifest_version:i.manifest.version,manifest_entry:i.manifest.entry,capabilities:[...i.manifest.capabilities],contributions:i.manifest.contributions,..._,source:w}),x=ba(s,i.manifest.name);try{p||await Gi(i.directory,l),await Li(l),await Fi(l),await De(o.selected_root,v),x&&await xe(o.settings_root,s,"settings:write")}catch(E){try{await ua(y)}catch(C){throw new AggregateError([E,C],`Extension install failed: ${String(E)}; rollback failed: ${String(C)}`,{cause:C})}throw E}return{settings:s,managedState:v,sourceRecord:w,destinationDirectory:l,destinationExists:d,installInPlace:p,activationChanged:x}}finally{await Ae.rm(u,{recursive:!0,force:!0}).catch(()=>{})}},ou=async(e,t,n)=>{let o=n.filter(r=>b(r.name)===b(t)).flatMap(r=>r.types.map(i=>({name:i.name,folder:i.folder})));return e.scope==="project"&&o.length>0&&await at(e.resolvedRoots.pm_root,o,e.warnings,"install:type-folder"),o},ru=(e,t,n,o,r)=>{let i=$a(t,n.activation_failures,e.scope),a=Lp(t,e.scope,n.installed,i),s=[!n.extensions_disabled,a==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${a}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:a,failure:i,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:a,activated:s,registered_commands:o.command_paths,registered_actions:o.action_paths,registered_item_types:r,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},iu=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:r,global:i,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,l=await nu(e,t),d=await me(o.selected_root,n,l.settings,l.managedState);r.push(...d.warnings);let p=await Ia(o.pm_root,ne.dirname(o.selected_root),l.settings,d.extensions,i);r.push(...p.warnings);let u=await ou(e,s.manifest.name,p.item_type_registrations),f=ia(s.manifest.name,p.installed),y=ru(e,s.manifest.name,p,f,u),w=p.contribution_inventories[b(s.manifest.name)];return w&&(l.managedState=await Vr(o.selected_root,l.managedState,s.manifest.name,w)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:l.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:l.destinationDirectory,overwritten:[l.destinationExists,!l.installInPlace].every(Boolean),installed_in_place:l.installInPlace,activated:y.activated,settings_changed:l.activationChanged,runtime_activation_status:y.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:w,command_discovery:Dp(s.manifest.name,l.sourceRecord,f,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:o,withResult:r}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new h('Action "install all" does not accept --ref.',g.USAGE);let i=[],a=new Map;for(let s of await Lt()){let c=await ut(s),l=ne.resolve(c),d=a.get(l);d===void 0&&(d=await Vn(s,{...t,install:!0},n),a.set(l,d)),i.push({alias:s,result:d})}return o.push(...i.flatMap(s=>s.result.warnings)),r(la(i,t.dryRun===!0),i.every(s=>s.result.ok))},su=async(e,t,n)=>{let{resolvedRoots:o}=e,{bundledAliasName:r,bundledPackageName:i,installSource:a,sourceResolution:s}=await qi(t,n,e.options.ref);if(s.ambiguous){let l=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${r}:npm:${l.package}`)}let c=await di(a);try{let l=await Ye(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),d=Dt(l.manifest.name),p=e.options.dryRun===!0||a.kind==="local"&&r===null?await zi(c,ne.join(o.selected_root,d),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:l.manifest.name,version:l.manifest.version},source_resolution:s,install_plan:p}):await qn(o.settings_root,d,()=>iu(e,{validated:l,destinationDirectoryName:d,bundledAliasName:r,bundledPackageName:i,sourceResolution:s,installSource:a,resolvedSource:c,installPlan:p}))}finally{c.cleanup&&await c.cleanup()}},cu=async e=>{let t=Xt(e.options),n=t??Yt(e.normalizedTarget,e.action,e.options);return[t===void 0,Yr(n)].every(Boolean)?au(e):su(e,n,t)},lu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:r,options:i,withResult:a}=e;if(t!==void 0)throw new h('Action "adopt-all" does not accept a target argument.',g.USAGE);if(Xt(i)!==void 0||typeof i.ref=="string"&&i.ref.trim().length>0)throw new h('Action "adopt-all" does not accept --gh/--github/--ref options.',g.USAGE);let c=await T(o.settings_root),l=await _e(o.selected_root);r.push(...l.warnings);let d=await me(o.selected_root,n,c,l.state);r.push(...d.warnings);let p=await Kn(o.selected_root,n,d.extensions,l.state),u=await me(o.selected_root,n,c,p.state);r.push(...u.warnings);let f=Vt(n,r,u.extensions,i);r.push(...f.warnings);let y=new Map(u.extensions.map(_=>[`${b(_.name)}:${b(_.directory)}`,_])),w=new Map(u.extensions.map(_=>[b(_.directory),_])),m=p.adopted_entries.map(_=>{let v=b(_.directory),x=y.get(`${b(_.name)}:${v}`)??w.get(v);return{..._,...Aa(x)}});return a({adopted_all:m.length>0,adopted_count:m.length,already_managed_count:p.already_managed_count,extensions:m,triage:f,warning_codes:f.warning_codes,update_health_partial:f.update_health_partial,update_health_coverage:f.update_health_coverage})},Aa=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),du=(e,t,n,o)=>{if(e===void 0)return{kind:"local",input:t,location:n};let r=Gt(e,{forceGithub:!0,ref:o});if(r.kind!=="github")throw new h(`Invalid GitHub shorthand "${e}".`,g.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}},pu=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:r,warnings:i,options:a,withResult:s}=e,c=Yt(n,t,a),l=Xt(a),d=await T(r.settings_root),p=await _e(r.selected_root);i.push(...p.warnings);let u=await me(r.selected_root,o,d,p.state);i.push(...u.warnings);let f=await wa(u.extensions,c);if(!f)throw new h(`Installed extension "${c}" was not found in ${o} scope.`,g.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let y=ne.join(r.selected_root,f.directory),w=await Ye(y),m=A(),_=du(l,c,y,a.ref),v=pt(p.state,{name:w.manifest.name,directory:f.directory,scope:o,manifest_version:w.manifest.version,manifest_entry:w.manifest.entry,capabilities:[...w.manifest.capabilities],contributions:w.manifest.contributions,installed_at:m,updated_at:m,source:_});await De(r.selected_root,v);let x=await me(r.selected_root,o,d,v);i.push(...x.warnings);let E=x.extensions.find(C=>b(C.name)===b(w.manifest.name))??x.extensions.find(C=>b(C.directory)===b(f.directory));return s({adopted:!0,extension:{name:w.manifest.name,directory:f.directory,version:w.manifest.version,entry:w.manifest.entry},source:_,...Aa(E)})},Ta=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:r,warnings:i,options:a}=e,s=Yt(n,t,a),c=await T(r.settings_root),l=await _e(r.selected_root);i.push(...l.warnings);let d=await me(r.selected_root,o,c,l.state);i.push(...d.warnings);let p=await wa(d.extensions,s);if(!p)throw new h(`Installed extension "${s}" was not found in ${o} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:l,candidate:p}},uu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:o,managedStateRead:r,candidate:i}=await Ta(e),a=ne.join(t.selected_root,i.directory);await Ae.rm(a,{recursive:!0,force:!0});let s={...r.state,updated_at:A(),entries:r.state.entries.filter(l=>b(l.name)!==b(i.name)&&b(l.directory)!==b(i.directory))};await De(t.selected_root,s);let c=xp(o,i.name);return c&&await xe(t.settings_root,o,"settings:write"),n({removed:!0,extension:{name:i.name,directory:i.directory},destination_path:a,settings_changed:c})},ma=async e=>{let{action:t,resolvedRoots:n,warnings:o,global:r,withResult:i}=e,{settings:a,candidate:s}=await Ta(e),c=t==="activate"?ba(a,s.name):kp(a,s.name);c&&await xe(n.settings_root,a,"settings:write");let l=t==="activate"?await Ia(n.pm_root,ne.dirname(n.selected_root),a,[s],r).then(d=>(o.push(...d.warnings),$a(s.name,d.activation_failures,e.scope))):void 0;return l&&o.push(`extension_activate_failed:${e.scope}:${s.name}`),i({extension:{name:s.name,directory:s.directory},active:t==="activate"&&l===void 0,runtime_active:t==="activate"&&l===void 0,activation_failure:l??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},l===void 0)},mu=(e,t,n,o,r,i)=>{let a=o==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=r?.adopted_entries.length??0,l=[[i!==null,i??""],[t>0,`Run pm ${a} explore --project and pm ${a} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${a} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...l.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},Hn=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),fu=(e,t,n,o)=>{if(e!=="project"||t||!Hn(o))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.`},hu=(e,t,n)=>{if(String(e??"").trim().length>0)throw new h('Action "doctor" does not accept a target argument.',g.USAGE);let o=[n.isolated,n.ignoreGlobal].includes(!0);if([o,t==="global"].every(Boolean))throw new h("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",g.USAGE);let r=Zi(n.detail),i=n.trace===!0;if([i,r!=="deep"].every(Boolean))throw new h("--trace requires --detail deep with --doctor.",g.USAGE);return{isolated:o,detailMode:r,includeTrace:i}},gu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let o=await Kn(e.resolvedRoots.selected_root,e.scope,t,n);return{state:o.state,fix:o}},yu=(e,t,n,o)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:Hn(o),rerun_command:null,pm_global_path_recipe:null};let i=`pm ${r} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:Hn(o),rerun_command:t?null:i,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},_u=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:r,options:i,global:a,withResult:s}=e,{isolated:c,detailMode:l,includeTrace:d}=hu(t,n,i),p=await T(o.settings_root),u=await _e(o.selected_root);r.push(...u.warnings);let f=await me(o.selected_root,n,p,u.state);r.push(...f.warnings);let{state:y,fix:w}=await gu(e,f.extensions,u.state),m=await me(o.selected_root,n,p,y);r.push(...m.warnings);let _=await ve({pmRoot:o.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await be({..._,loaded:_.loaded}),x=await da(o.pm_root);r.push(...x.warnings,..._.warnings),r.push(...Xi(_.failed)),r.push(...v.warnings),r.push(...Yi(v.failed)),r.push(...Qi(_,v)),r.push(...aa(v,_)),r.push(...Up(_,v)),r.push(...sa(v));let E=Kt(m.extensions,_,v),C=oa(n,E,_.loaded.map(O=>({layer:O.layer,name:O.name})),_.failed.map(O=>({name:O.name})),_.disabled_by_flag);r.push(...C.warnings);let G=E.filter(O=>O.update_check_status==="failed").map(O=>`extension_update_check_failed:${O.name}`);r.push(...G);let L=Vt(n,r,E,i);r.push(...L.warnings);let S=[...L.warnings],J={mode:_.policy.mode,trust_mode:_.policy.trust_mode,require_provenance:_.policy.require_provenance,default_sandbox_profile:_.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:_.policy.trusted_extensions.length,allowed_extensions_count:_.policy.allowed_extensions.length,blocked_extensions_count:_.policy.blocked_extensions.length,allowed_capabilities_count:_.policy.allowed_capabilities.length,blocked_capabilities_count:_.policy.blocked_capabilities.length,allowed_surfaces_count:_.policy.allowed_surfaces.length,blocked_surfaces_count:_.policy.blocked_surfaces.length,allowed_commands_count:_.policy.allowed_commands.length,blocked_commands_count:_.policy.blocked_commands.length,allowed_actions_count:_.policy.allowed_actions.length,blocked_actions_count:_.policy.blocked_actions.length,allowed_services_count:_.policy.allowed_services.length,blocked_services_count:_.policy.blocked_services.length,extension_override_count:_.policy.extension_overrides.length},et=ta(S),Zt=na(),ro=L.warning_codes,ds=fu(n,c,i.vocabulary,_),ps=mu(L.remediation,_.failed.length,v.failed.length,i.vocabulary,w,ds),io=yu(n,c,i.vocabulary,_),us={status:L.status,scope:n,warning_count:L.warning_count,warning_codes:ro,total_extensions:E.length,managed_total:E.filter(O=>O.managed).length,enabled_total:E.filter(O=>O.enabled).length,active_total:E.filter(O=>O.active).length,unmanaged_loaded_extension_count:L.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:L.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:L.unmanaged_expected_extension_count,runtime_active_total:E.filter(O=>O.runtime_active===!0).length,activation_status_totals:{ok:E.filter(O=>O.activation_status==="ok").length,failed:E.filter(O=>O.activation_status==="failed").length,not_loaded:E.filter(O=>O.activation_status==="not_loaded").length,unknown:E.filter(O=>O.activation_status==="unknown").length},unknown_capability_count:et.length,capability_contract_version:Zt.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:E.filter(O=>O.update_check_status==="failed").length,load_failure_count:_.failed.length,activation_failure_count:v.failed.length,load_failures:Bn(_.failed),activation_failures:Bn(v.failed),blocking_failure_count:_.failed.length+v.failed.length,has_blocking_failures:_.failed.length+v.failed.length>0,consistency_warning_count:C.warnings.length,trace_enabled:d,isolation:io,policy:J,remediation:ps},ms=w?{requested:!0,applied:w.adopted_entries.length>0,adopted_count:w.adopted_entries.length,already_managed_count:w.already_managed_count,adopted_extensions:w.adopted_entries.map(O=>O.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:m.extensions.filter(O=>O.managed).length,adopted_extensions:[]},en={mode:l,summary:us,triage:L,trace_enabled:d,capability_contract:Zt,capability_guidance:et,managed_state_fix:ms,author_manifest:x,isolation:io,policy:_.policy};if(l==="deep"){let O=d?v.failed:v.failed.map(P=>{let{trace:lm,...fs}=P;return fs});en.deep={warnings:S,warning_codes:ro,capability_contract:Zt,capability_guidance:et,trace_enabled:d,managed_state:{path:u.path,count:y.entries.length,entries:y.entries},installed_extensions:E,load:{roots:_.roots,policy:_.policy,warnings:_.warnings,failed:_.failed,loaded:_.loaded.map(P=>({layer:P.layer,directory:P.directory,name:P.name,version:P.version,entry:P.entry,priority:P.priority}))},activation:{failed:O,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:C.summary},d&&(en.deep.trace={activation_failures:v.failed.filter(P=>P.trace!==void 0).map(P=>({layer:P.layer,name:P.name,entry_path:P.entry_path,error:P.error,method:P.trace.method,command:P.trace.command,capability:P.trace.capability,missing_capability:P.trace.missing_capability,registration_index:P.trace.registration_index,expected_schema:P.trace.expected_schema,hint:P.trace.hint,received:P.trace.received}))})}return s(en)},wu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:r,options:i,global:a,withResult:s}=e,c=await T(o.settings_root),l=await ve({pmRoot:o.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),d=await be(l);r.push(...l.warnings),r.push(...d.warnings);let p=Ii(t,l,d);if(t!==void 0&&p.extensions.length===0){let u=i.vocabulary==="package"?"package":"extension",f=[...new Set(l.loaded.map(w=>i.vocabulary==="package"&&typeof w.source_package=="string"&&w.source_package.trim().length>0?w.source_package.trim():w.name))].sort((w,m)=>w.localeCompare(m)),y=f.length>0?` Loaded ${u} names: ${f.join(", ")}.`:"";throw new h(`No loaded ${u} named "${t}" was found in ${n} scope.${y} Run pm ${u} explore to list discovered ${u}s.`,g.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},vu=async(e,t,n)=>{let o=n,r=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await Kn(e.resolvedRoots.selected_root,e.scope,t,n),o=r.state),e.action==="manage"){let i=await ra(o.entries,lp,async a=>{if(a.source.kind!=="github")return a;let s=await ca(a.source);return{...a,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});o={...o,updated_at:A(),entries:dt(i)},await De(e.resolvedRoots.selected_root,o)}return{state:o,fix:r}},bu=async(e,t,n)=>{let o=await ve({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await be({...o,loaded:o.loaded});return e.warnings.push(...o.warnings,...r.warnings),{installed:Kt(n,o,r),failures:Ea(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:o.failed.length,activation_failure_count:r.failed.length,warning_count:[...new Set([...o.warnings,...r.warnings])].length,policy:o.policy}}},ku=(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},fa=async e=>{let{action:t,scope:n,resolvedRoots:o,warnings:r,options:i,withResult:a}=e,s=await T(o.settings_root),c=bp(s.extensions.policy),l=await _e(o.selected_root);r.push(...l.warnings);let d=await me(o.selected_root,n,s,l.state);r.push(...d.warnings);let{state:p,fix:u}=await vu(e,d.extensions,l.state),f=await me(o.selected_root,n,s,p);if(r.push(...f.warnings),t==="manage"){let v=f.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,f.extensions),w=y.installed,m=Vt(n,r,w,i);r.push(...m.warnings);let _={total:w.length,managed_total:w.filter(v=>v.managed).length,enabled_total:w.filter(v=>v.enabled).length,active_total:w.filter(v=>v.active).length,extensions:w,triage:m,policy:c};return y.failures!==void 0&&(_.activation_diagnostics={failed_count:y.failures.length,failed:y.failures}),t==="explore"&&(_.runtime_probe=y.summary),t==="manage"&&(_.runtime_probe=y.summary,_.managed_state_fix=ku(u,w)),a(_)},ha={init:Hp,install:cu,uninstall:uu,explore:fa,manage:fa,describe:wu,reload:Kp,doctor:_u,catalog:Vp,adopt:pu,"adopt-all":lu,activate:ma,deactivate:ma,migrate:Oi},xu=e=>[e.action==="uninstall",e.action==="manage",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[e.action==="doctor",e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Su=e=>xu(e)?qn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>ha[e.action](e)):ha[e.action](e);import Qn from"node:fs/promises";import z from"node:path";import Oa from"node:readline/promises";import{stdin as Ca,stdout as gt}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5ae3e66-4a45-5c62-9144-46f8f5bff7cf")}catch{}})();var Ra=["ask","add","skip","status"],Eu=["AGENTS.md","CLAUDE.md"],$u=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Iu=8,Zn=1,Au="<!-- pm-cli:agent-guidance:start:",Tu=`<!-- pm-cli:agent-guidance:start:v${Zn} -->`,Xn="<!-- pm-cli:agent-guidance:end -->",_t="Add workflow guidance later: pm init --agent-guidance add",W_={toPortableRelativePath:Qe,ensureTrailingNewline:Yn,detectLineEnding:Na,findGuidanceBlockRange:eo,buildAgentGuidanceBlock:Da,upsertAgentGuidanceBlock:ja,resolveProjectRoot:La,resolveTargetGuidancePath:Fa,parsePromptChoice:Ma,pushUnique:Ze,promptForGuidanceWrite:Ga,normalizeAgentGuidanceState:to,applyAgentGuidanceState:za,writeGuidanceFile:Ja,setAgentGuidanceReadlineFactoryForTests:Ou},Pa=()=>Oa.createInterface({input:Ca,output:gt});function Ou(e){Pa=e??(()=>Oa.createInterface({input:Ca,output:gt}))}function Qe(e,t){let n=z.relative(e,t);return n.length===0?z.basename(t):n.split(z.sep).join("/")}function Yn(e){return e.endsWith(`
|
|
45
|
+
`}import np from"node:fs/promises";import op from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4dc16d1-672a-5b1c-b681-97a7b3febd69")}catch{}})();function Yn(e){return op.join(e,"extension-migrations.json")}function Vi(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 Yi(e,t){return`${e.layer}:${e.name}:${t}`}async function rp(e){let t=Yn(e);if(!await k(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await np.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(o=>typeof o?.key=="string"&&(o.status==="applied"||o.status==="failed")):[]}}async function ip(e,t){let n=await rp(e),o=new Map(n.entries.map(r=>[r.key,r]));return t.forEach((r,i)=>{let a=Vi(r,i),s=o.get(Yi(r,a));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 ap(e){let t=await ip(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),o=[],r=!1,i=e.migrations.map((d,p)=>({migration:d,index:p})).filter(({migration:d})=>e.scope===void 0||d.layer===e.scope);for(let{migration:d,index:p}of i){let u=Vi(d,p),h=Yi(d,u),y=n.get(h),_=String(d.definition.status??"pending").toLowerCase(),g=y?.status??(_==="applied"||_==="failed"?_:"pending");if(g==="applied"){o.push({key:h,layer:d.layer,extension:d.name,id:u,before:g,outcome:"skipped"});continue}if(e.dryRun===!0){o.push({key:h,layer:d.layer,extension:d.name,id:u,before:g,outcome:"pending"});continue}let w=d.runtime_definition?.run??d.definition.run;if(typeof w!="function"){o.push({key:h,layer:d.layer,extension:d.name,id:u,before:g,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:u,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:g}));let x={key:h,layer:d.layer,extension:d.name,id:u,status:"applied",attempted_at:v};n.set(h,x),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,o.push({key:h,layer:d.layer,extension:d.name,id:u,before:g,outcome:"applied"}),r=!0}catch(x){let E=x instanceof Error?x.message:String(x),C={key:h,layer:d.layer,extension:d.name,id:u,status:"failed",attempted_at:v,error:E};n.set(h,C),d.definition.status="failed",d.definition.reason=E,o.push({key:h,layer:d.layer,extension:d.name,id:u,before:g,outcome:"failed",error:E}),r=!0}}if(r){let d=await A(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((u,h)=>u.key.localeCompare(h.key))};await Ue({pmRoot:e.pmRoot,filePath:Yn(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
|
|
46
|
+
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let a=o.filter(d=>d.outcome==="pending").length,s=o.filter(d=>d.outcome==="applied").length,c=o.filter(d=>d.outcome==="skipped").length,l=o.filter(d=>d.outcome==="failed").length;return{ok:l===0,dry_run:e.dryRun===!0,state_path:Yn(e.pmRoot),total:o.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:l,migrations:o}}async function Xi(e){let t=await A(e.resolvedRoots.settings_root),n=await ve({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),o=await be(n);e.warnings.push(...n.warnings,...o.warnings);let r=await ap({pmRoot:e.resolvedRoots.pm_root,migrations:o.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:r,load_failure_count:n.failed.length,activation_failure_count:o.failed.length},r.ok)}import Zt from"node:fs/promises";import Xt from"node:path";import Zi from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a77d8d8d-f429-5154-ab3a-2caddc44472e")}catch{}})();function Vt(e,t,n){let o=Zi.relative(e,n);return o!==""&&!V(e,n)||n===t||V(t,n)?!1:!o.split(Zi.sep).some(i=>i===".agents"||i==="node_modules"||i.startsWith(".pm-extension-install-backup-"))}import{randomUUID as sp}from"node:crypto";import M from"node:fs/promises";import cp from"node:os";import D from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67e85146-6994-5c3b-bcaa-d7001b9b1703")}catch{}})();var Qi=3,lp=120,ea=250,dp=12e4,pp=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),ta=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,na=e=>pp.has(String(ta(e))),Yt=(e,t)=>ta(e)===t,oa=e=>new Promise(t=>{setTimeout(t,e)}),ra=async e=>{let t=D.join(e,"package.json");await k(t)||await M.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
47
|
+
`,"utf8")},ia=async e=>{let t=ce(import.meta.url,["../../.."]),n=D.join(e,"node_modules","@unbrained"),o=D.join(n,"pm-cli");await M.mkdir(n,{recursive:!0}),await M.rm(o,{recursive:!0,force:!0}),await M.symlink(t,o,process.platform==="win32"?"junction":"dir")},yt=async e=>{let t=D.resolve(e),n=D.dirname(t),o=D.parse(n).root,r=await M.realpath(o).catch(()=>o),i=D.relative(o,n),a=i===""?[]:i.split(D.sep);for(let[s,c]of a.entries()){let l=D.join(r,c);try{r=await M.realpath(l)}catch{r=D.join(r,...a.slice(s));break}}return D.join(r,D.basename(t))},aa=async(e,t,n,o=cp.tmpdir())=>Ge("extension_install_copy",async()=>{let r=D.resolve(e),i=await M.realpath(r).catch(()=>r),a=await yt(t);if(i===a)return;if(!V(i,a)){await n(i,t,{recursive:!0,force:!0});return}let s=await M.realpath(D.resolve(o)).catch(()=>yt(o)),c=V(i,s)?D.dirname(i):s;if(V(i,c))throw new m(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,f.USAGE,{code:"extension_install_source_contains_destination"});let l=await M.mkdtemp(D.join(c,"pm-extension-copy-")),d=D.join(l,"extension");try{await n(i,d,{recursive:!0,force:!0,filter:p=>Vt(i,a,D.resolve(p))}),await n(d,t,{recursive:!0,force:!0})}finally{await M.rm(l,{recursive:!0,force:!0})}}),sa=async(e,t,n=M.cp)=>{for(let o=1;o<=Qi;o+=1)try{await Ge("extension_install_copy",async()=>{await M.rm(t,{recursive:!0,force:!0}),await aa(e,t,n)});return}catch(r){if(!na(r)||o===Qi)throw r;await oa(ea)}},Xn=async e=>{let t;try{t=await M.readFile(D.join(e,"owner.json"),"utf8")}catch(r){if(!bt(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 o=n.token;return typeof o=="string"&&o.length>0?o:null},ca=async(e,t)=>await Xn(e)!==t?!1:(await M.rm(e,{recursive:!0,force:!0}),!0),up=async(e,t)=>{let n;try{n=await M.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let o=await Xn(e);return o===null?(await M.rm(e,{recursive:!0,force:!0}),!0):ca(e,o)},mp=(e,t,n)=>{let o=Promise.resolve(),r=setInterval(()=>{o=o.then(async()=>{if(await Xn(e)!==t)return;let i=new Date;await M.utimes(e,i,i)}).catch(()=>{})},n);return r.unref(),async()=>{clearInterval(r),await o}},fp=async(e,t)=>{await M.mkdir(e);try{await M.writeFile(D.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
48
|
+
`,"utf8")}catch(n){throw await M.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},hp=async(e,t,n,o,r)=>{for(let i=1;i<=n;i+=1)try{return await fp(e,t),!0}catch(a){if(!Yt(a,"EEXIST"))throw a;await up(e,r)?i-=1:await oa(o)}return!1},Zn=async(e,t,n,o)=>{let r=D.join(e,"runtime","extension-install-locks"),i=D.join(r,"scope.lock");await M.mkdir(r,{recursive:!0});let{attempts:a=lp,delay_ms:s=ea,stale_ms:c=dp,heartbeat_ms:l}=o??{};if(![a,s,c,l].filter(w=>w!==void 0).every(Number.isFinite))throw new m("Extension install lock timings must be finite numbers.",f.USAGE);let d=Math.max(1,Math.floor(a)),p=Math.max(0,Math.floor(s)),u=Math.floor(c),h=Math.floor(l??u/3);if(u<=0||h<=0||h>=u)throw new m("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",f.USAGE);let y={pid:process.pid,token:sp(),created_at:T(),destination:t};if(!await hp(i,y,d,p,u))throw new m(`Timed out waiting for extension install lock for "${t}".`,f.CONFLICT);let g=mp(i,y.token,h);try{return await n()}finally{await g(),await ca(i,y.token).catch(()=>!1)}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4b9502f-f742-5f11-b341-56763bbed7c2")}catch{}})();var gp=new Set(["node_modules",".git","dist","build","coverage"]);async function la(e,t,n,o){let r=e.source.kind==="local"?await Zt.stat(e.source.absolute_path):void 0,i=e.source.kind==="local"?r.isDirectory()?"directory":"archive":e.source.kind,a=await yp(e.directory,t,o),s={source_mode:i,...i==="archive"?{archive_bytes:r.size}:{},copy:a},c=e.source_root??e.directory;return i==="directory"&&(!a.complete||a.development_entries>0||a.bytes>=16*1024*1024)&&await k(Xt.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),s}async function yp(e,t,n={}){let{maxEntries:o=1e4,maxDepth:r=64,signal:i}=n;if(![o,r].every(p=>Number.isSafeInteger(p)&&p>0))throw new m("maxEntries and maxDepth must be positive safe integers.",f.USAGE);i?.throwIfAborted();let a=await Zt.realpath(e),s=await yt(t),c=await Kt(a,s);i?.throwIfAborted();let l=c?"in_place":V(a,s)?"nested_filtered_snapshot":"directory_snapshot",d={copy_scope:l,source_directory:a,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:o,max_depth:r};return l==="in_place"||await da(a,0,d,i),d}async function da(e,t,n,o){o?.throwIfAborted();let r=await Zt.opendir(e);for await(let i of r){if(o?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let a=Xt.join(e,i.name);if(n.copy_scope==="nested_filtered_snapshot"&&!Vt(n.source_directory,n.destination_directory,a)){n.excluded_entries+=1;continue}if(Xt.relative(n.source_directory,a).split(Xt.sep).some(s=>gp.has(s))&&(n.development_entries+=1),await _p(a,t,n,o),!n.complete)return}}async function _p(e,t,n,o){let r=await Zt.lstat(e);if(o?.throwIfAborted(),r.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await da(e,t+1,n,o)}else r.isFile()?(n.files+=1,n.bytes+=r.size):r.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcdfdabd-8862-502f-8cd1-298c08825985")}catch{}})();async function pa(e,t,n){let o=typeof t=="string"?null:await ft(e),r=o===null?null:e.trim().toLowerCase(),i=r===null?null:await vi(r),a=Bt(o??e,{forceGithub:typeof t=="string",ref:n}),s=r===null?null:await Ei(e);return{bundledAliasName:r,bundledPackageName:i,installSource:a,sourceResolution:{requested:e,selected:{kind:r===null?a.kind:"builtin",input:r??a.input,...i===null?{}:{package:i}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...r===null?[]:[{kind:"builtin",input:r,...i===null?{}:{package:i},command:`pm install ${r}`}],...s===null?[]:[{kind:"npm",input:`npm:${s.package}`,package:s.package,...s.version===void 0?{}:{version:s.version},directory:s.directory,command:`pm install npm:${s.package}`}]]}}}import Oe from"node:fs/promises";import ne from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="df60255d-fdd6-594a-9e17-547d53f7b3bb")}catch{}})();function Qn(e){return e.map(({layer:t,name:n,error:o})=>({layer:t,name:n,error:o}))}function Qt(e,t,n){let o=b(t),r=n.trim();if(o.length===0||r.length===0)return;let i=e.get(o)??new Set;i.add(r),e.set(o,i)}function wp(e){let t=new Map,n=new Map;for(let o of e.registrations.commands)Qt(t,o.name,o.command),Qt(n,o.name,o.action);for(let o of e.commands.handlers)Qt(t,o.name,o.command);for(let o of e.commands.overrides)Qt(t,o.name,o.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function ua(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function vp(e){let{enabled:t,normalizedName:n,loadedNames:o,loadFailedNames:r,activationFailedNames:i}=e;return t?r.has(n)||i.has(n)?{runtime_active:!1,activation_status:"failed"}:o.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function en(e,t,n){let o=new Set(t.loaded.map(c=>b(c.name))),r=new Set(t.failed.map(c=>b(c.name))),i=new Set(n.failed.map(c=>b(c.name))),{commandPathsByExtension:a,actionPathsByExtension:s}=wp(n);return e.map(c=>{let l=b(c.name),d=ua(a.get(l)),p=ua(s.get(l)),u={...d?{command_paths:d}:{},...p?{action_paths:p}:{}},h=vp({enabled:c.enabled,normalizedName:l,loadedNames:o,loadFailedNames:r,activationFailedNames:i});return{...c,...h,...u}})}function bp(e){let t=0,n=0,o=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_")&&(o+=1)}return{warning_count:t,violation_count:n,blocked_count:o}}function z(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var ha=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 kp(e){return ha.has(ba(e))}function ma(e){return e==="project"||e==="global"}function ga(e){let t=e.split(":"),n=t[0];if(!n||!ha.has(n))return null;let o=t.at(-4),r=t.at(-3)?.trim(),i=t.at(-2),a=t.at(-1)?.trim();return!ma(o)||!ma(i)||!r||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:o,name:r},displaced:{layer:i,name:a}}}function xp(e){let t=new Set;for(let n of e){let o=ga(n);o&&(t.add(o.winner.name),t.add(o.displaced.name))}return[...t].sort((n,o)=>n.localeCompare(o))}function Sp(e,t){let n=e.filter(kp);if(n.length===0)return null;let o=xp(n);return`Extension registration collisions or handler/override overlaps detected.${o.length>0?` Conflicting extensions: ${o.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function Ep(e,t,n,o){let r=t.map(p=>ga(p)).filter(p=>p!==null).sort((p,u)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`));if(r.length===0)return;let i=e==="global"?"--global":"--project",a=z(o,"deactivate"),s=`${z(o,"doctor")} ${i} --detail deep --trace`,c=new Map(n.map(p=>[b(p.name),p])),l=new Map;for(let p of r)for(let u of[p.winner.name,p.displaced.name]){let h=b(u);l.set(h,(l.get(h)??0)+1)}let d=[...l.entries()].map(([p,u])=>{let h=c.get(p),y=h?.name??p,_=h?.command_paths??[],g=h?.action_paths??[];return{action:"deactivate",extension:y,command:`${a} ${y} ${i}`,affected_collisions:u,feature_loss:{command_paths:[..._].sort((w,v)=>w.localeCompare(v)),action_paths:[...g].sort((w,v)=>w.localeCompare(v))}}}).sort((p,u)=>{let h=u.affected_collisions-p.affected_collisions;if(h!==0)return h;let y=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,_=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length;return y!==_?y-_:p.extension.localeCompare(u.extension)});return{status:"conflicts_detected",collision_count:r.length,extension_count:l.size,next_best_command:s,collisions:r,remediation_candidates:d}}function ya(e){let t=[];for(let n of e){let o=n.error.toLowerCase();(o.includes("cannot find package '@unbrained/pm-cli'")||o.includes('cannot find module "@unbrained/pm-cli"')||o.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(o.includes("cannot use import statement outside a module")||o.includes("to load an es module")||o.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,o)=>n.localeCompare(o))}function _a(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let o of t){if(!o||typeof o.name!="string")continue;let r=o.trace?.missing_capability??o.trace?.capability;typeof r=="string"&&r.trim().length>0&&n.push(`extension_capability_missing:${o.name}:${r.trim().toLowerCase()}`)}return[...new Set(n)].sort((o,r)=>o.localeCompare(r))}function wa(e,t){let n=[];for(let o of jo(e.loaded,t))for(let r of o.unused)n.push(`extension_capability_unused:${o.layer}:${o.name}:${r}`);return[...new Set(n)].sort((o,r)=>o.localeCompare(r))}var $p=[{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: ${go.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 Ip(e){let{normalizedWarnings:t,options:n,scope:o,scopeFlag:r,updateCheckFailedTotal:i,policyWarningCount:a,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,p=[],u={options:n,scope:o,scopeFlag:r,updateCheckFailedTotal:i,policyWarningCount:a};if(t.length>0){let h=Sp(t,{deactivate:`${z(n,"deactivate")} <name> ${r}`,doctor:`${z(n,"doctor")} ${r} --detail deep --trace`});h&&p.push(h);for(let y of $p)y.matches(t,u)&&p.push(y.build(u))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${z(n,"manage")} ${r} --fix-managed-state (or ${z(n,"adopt-all")} ${r}, ${z(n,"adopt")} <name> ${r}, or reinstall via ${z(n,"install")} ${r} <source>).`),l>0&&p.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${z(n,"manage")} ${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 tn(e,t,n,o={}){let r=[...new Set(t)].sort((S,q)=>S.localeCompare(q)),i=n.filter(S=>S.managed).length,a=n.filter(S=>S.enabled).length,s=n.filter(S=>S.active).length,c=n.filter(S=>S.update_check_status==="checked"&&S.update_available===!0).length,l=n.filter(S=>S.managed===!1),d=l.filter(S=>fa(S)).map(S=>S.name).sort((S,q)=>S.localeCompare(q)),p=l.filter(S=>!fa(S)).map(S=>S.name).sort((S,q)=>S.localeCompare(q)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let S of n)u[S.update_check_status]+=1;let h=u.failed,y=n.filter(S=>S.update_check_status==="skipped_non_github"&&S.source?.kind!=="builtin").length,_=Object.entries({skipped_unmanaged:p.length,skipped_non_github:y,failed:h,not_checked:u.not_checked}).filter(([,S])=>S>0).map(([S,q])=>`extension_update_health_partial_coverage:${S}:${q}`),g=_.length>0,w=g?"partial":"full",v=[...new Set([...r,..._])].sort((S,q)=>S.localeCompare(q)),x=[...new Set(v.map(S=>ba(S)))].sort((S,q)=>S.localeCompare(q)),E=bp(v),C=e==="global"?"--global":"--project",G=Ep(e,r,n,o),L=Ip({normalizedWarnings:v,options:o,scope:e,scopeFlag:C,updateCheckFailedTotal:h,policyWarningCount:E.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:u.not_checked,skippedNonGithubTotal:y,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:x,warnings:v,policy_warning_count:E.warning_count,policy_violation_count:E.violation_count,policy_blocked_count:E.blocked_count,total_extensions:n.length,managed_total:i,enabled_total:a,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:g,unmanaged_loaded_extension_count:l.length,unmanaged_loaded_extensions:l.map(S=>S.name).sort((S,q)=>S.localeCompare(q)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:u,update_check_failed_total:h,top_warnings:v.slice(0,8),remediation:L,...G?{collision_plan:G}:{}}}function va(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new m(`Invalid --detail value "${e}". Expected summary or deep.`,f.USAGE)}function ba(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function ka(e){let t=new Set,n=[];for(let o of e){let r=(()=>{let i=Io(o);return i?[i]:Ao(o)})();for(let i of r){let a=`${i.layer}:${i.name}:${i.capability}`;t.has(a)||(t.add(a),n.push(i))}}return n}function xa(){return{version:kt.version,capabilities:[...kt.capabilities],legacy_aliases:{...kt.legacy_aliases}}}function fa(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Sa(e,t,n,o,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 i=[...new Set(t.filter(d=>d.active).map(d=>b(d.name)))].sort((d,p)=>d.localeCompare(p)),a=[...new Set(n.filter(d=>d.layer==="project").map(d=>b(d.name)))].sort((d,p)=>d.localeCompare(p)),s=new Set(o.map(d=>b(d.name))),c=i.filter(d=>!a.includes(d)&&!s.has(d)).sort((d,p)=>d.localeCompare(p));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:i.length,loaded_project_count:a.length,active_project_names:i,loaded_project_names:a,missing_active_project_names:c}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96a05fa4-b833-56ca-b501-40a427d03201")}catch{}})();var Ea=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let o=new Array(e.length),r=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let a=r;r+=1,o[a]=await n(e[a])}});return await Promise.all(i),o};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="37f2dced-3b93-5c64-85ae-56e62c95e8eb")}catch{}})();function $a(e,t){let n=b(e),o=t.find(r=>b(r.name)===n);return{command_paths:[...o?.command_paths??[]].sort((r,i)=>r.localeCompare(i)),action_paths:[...o?.action_paths??[]].sort((r,i)=>r.localeCompare(i))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fcc97434-1ef5-5c47-b491-f00e9d19b2c6")}catch{}})();function Ia(e,t){let n=new Set((t?.loaded??[]).flatMap(i=>(i.activation?.commands?.length??0)>0?[`${i.layer}:${b(i.name)}`]:[])),o=e.services.overrides.filter(i=>i.service==="output_format").filter(i=>i.passThrough!==!0).filter(i=>!n.has(`${i.layer}:${b(i.name)}`)).map(i=>`extension_output_service_override_global:${i.service}:${i.layer}:${i.name}`),r=e.renderers.overrides.filter(i=>(i.commands?.length??0)===0&&i.resultDiscriminator===void 0).map(i=>`extension_output_renderer_override_global:${i.format}:${i.layer}:${i.name}`);return[...new Set([...o,...r])].sort((i,a)=>i.localeCompare(a))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var Aa=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Ct(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,o)=>o.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8507f364-e079-5743-a54b-bb3a68ab66d0")}catch{}})();var Ap=1e4,Tp=(e,t,n)=>{let o=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),r=o.find(a=>a.ref.endsWith("^{}"))??o[0];if(!r)return{checked_at:n,available:null,error:"no_remote_reference_found"};let i=t?.trim();return i?{checked_at:n,remote_commit:r.commit,available:r.commit!==i}:{checked_at:n,remote_commit:r.commit,available:null,error:"missing_installed_commit"}},Ta=async(e,t=qt)=>{let n=T();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let o=[e.ref?.trim(),"HEAD"].find(Boolean),r=await t(["ls-remote",e.repository,o,`${o}^{}`],void 0,Ap);return Tp(r,e.commit,n)}catch(o){return{checked_at:n,available:null,error:o instanceof Error?o.message:String(o)}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ee1bfa77-6687-578c-9cd6-639fc702c48c")}catch{}})();function Oa(e,t){let n=e.filter(o=>o.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:o,result:r})=>{let i=r.details;return{alias:o,ok:r.ok,extension:i.extension,source:i.source,source_resolution:i.source_resolution,install_plan:i.install_plan,dry_run:i.dry_run,destination_path:i.destination_path,activated:i.activated,settings_changed:i.settings_changed,command_paths:i.command_paths,action_paths:i.action_paths,command_discovery:i.command_discovery,verification:i.verification,runtime_activation_status:i.runtime_activation_status,activation_diagnostics:i.activation_diagnostics,warnings:r.warnings}})}}import Op from"node:fs/promises";import Cp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1bf79a0-1f04-590f-b613-45ca1b534d5d")}catch{}})();function Rp(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Pp(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 Np(e){let t=Cp.join(e,"manifest.json"),n;try{n=await Op.readFile(t,"utf8")}catch(s){if(bt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let o;try{o=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof o!="object"||o===null||Array.isArray(o))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let r=o,i=Co(r),a=Rp(r);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:i.findings,warnings:i.findings.map(s=>Pp(a,s)),remediation:i.findings.map(s=>s.message)}}function Ca(e){return Np(So(e))}import Me from"node:fs/promises";import Dp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7afb9a1-be35-5dfd-a52e-2525598b68d8")}catch{}})();var eo=async e=>Me.readFile(e).catch(t=>{if(Yt(t,"ENOENT"))return null;throw t}),Ra=async(e,t,n,o,r)=>Ge("extension_install_backup",async()=>{let i=pt(e),a=$o(t),[s,c]=await Promise.all([eo(i),eo(a)]);return o&&await Me.cp(n,r,{recursive:!0,force:!0}),{backupDirectory:r,destinationDirectory:n,destinationExists:o,managedStatePath:i,managedStateContents:s,settingsPath:a,settingsContents:c}}),Pa=async e=>Ge("extension_install_rollback",async()=>{await Me.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Me.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await Me.rm(t,{force:!0}):(await Me.mkdir(Dp.dirname(t),{recursive:!0}),await Me.writeFile(t,n))});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f8fc1a7-748d-559d-9de8-835d0428c6a7")}catch{}})();var jp=4,La=[["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"]],Lp=La.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Fp={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"},Mp="__pm_native_output",Gp=["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"],Fa=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Up=["disabled","require_trusted","require_provenance"],Ma={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:[]},zp=e=>{let t=e??Ma,n={};for(let o of Gp)n[o]=ee(t[o]??[]);return n},Jp=(e,t)=>{for(let n of Fa)t[n].length>0&&(e[n]=t[n]);return e},qp=(e,t)=>{for(let n of Up)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Wp=e=>{let t={};for(let n of Fa)t[n]=ee(e[n]??[]);return t},Bp=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Jp(qp({name:t},e),Wp(e))},Hp=e=>(e??[]).map(t=>Bp(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Kp=e=>{let t=Object.assign({},Ma,e??{}),n=zp(e),o=Hp(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:o}},Ga=async(e,t)=>{let n=[t],o=await bi(t);o&&n.push(o);let r=[...new Set(n.map(i=>b(i)).filter(i=>i.length>0))];for(let i of r){let a=e.find(c=>b(c.name)===i);if(a)return a;let s=e.find(c=>b(c.directory)===i);if(s)return s}},Ua=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled));return new Set(ee(e.extensions.disabled)).has(n)?!1:o.size===0?!0:o.has(n)},za=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),r=new Set(ee(e.extensions.disabled)),i=[...o],a=[...r];return r.delete(n),o.size>0&&o.add(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Vp=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),r=new Set(ee(e.extensions.disabled)),i=[...o],a=[...r];return o.delete(n),r.add(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Yp=(e,t)=>{let n=t.trim(),o=new Set(ee(e.extensions.enabled)),r=new Set(ee(e.extensions.disabled)),i=[...o],a=[...r];return o.delete(n),r.delete(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Xp=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),o=La.map(([r,i,a])=>({action:i,flag:a,distance:vo(t,r,n)})).filter(r=>r.distance!==null).sort((r,i)=>r.distance-i.distance)[0];return o?{action:o.action,flag:o.flag}:null},Zp=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=Xp(e);if(!o)return new m(`One action flag is required. Use one of: ${Lp}. Bare \`pm package\` and \`pm extension\` default to --explore.`,f.USAGE);let r=`pm ${n} ${o.flag}`;return bo({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(Ja),retry_command:r,message_suffix:`. Did you mean "${o.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:r,reason:`nearest lifecycle action for "${e}"`}]})},Qp=[["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"]],Ja={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},eu=e=>Ja[e]??null,tu=(e,t)=>{let n=[...new Set(Qp.filter(([o])=>t[o]===!0).map(([,o])=>o))];if(n.length===0){if(e===void 0)return"explore";let o=eu(e.trim().toLowerCase());if(o)return o;throw Zp(e,t)}if(n.length>1)throw new m("Extension action flags are mutually exclusive.",f.USAGE);return n[0]},nu=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new m('Options "--project/--local" and "--global" are mutually exclusive.',f.USAGE);return n?"global":"project"},ou=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&e.source.kind!=="github"?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],qa=e=>{for(let t of ou){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Wa=(e,t,n,o)=>{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,update_error:r.update_error,update_check_status:o.status,update_check_reason:o.reason}},ru=(e,t,n,o)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},o),i=o?Ua(n,o.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Wa({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:i},t,o,qa(o))}},iu=async(e,t,n,o,r,i)=>{let a=ne.join(e,t),s=ne.join(a,"manifest.json"),c=i.get(b(t));if(!await k(s))return ru(t,n,o,c);let l=Symbol("invalid-extension-manifest-json"),d=await Oe.readFile(s,"utf8").then(h=>JSON.parse(h)).catch(()=>l);if(d===l)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Ln(d);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=r.get(b(p.name))??i.get(b(t));return{summary:Wa({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:Ua(o,p.name)},n,u,qa(u))}},me=async(e,t,n,o)=>{if(!await k(e))return{extensions:[],warnings:[]};let i=(await Oe.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,p)=>d.localeCompare(p)),a=new Map(o.entries.map(d=>[b(d.name),d])),s=new Map(o.entries.map(d=>[b(d.directory),d])),c=[],l=[];for(let d of i){let p=await iu(e,d,t,n,a,s);p.warning&&c.push(p.warning),p.summary&&l.push(p.summary)}return{extensions:l.sort((d,p)=>d.name.localeCompare(p.name)),warnings:c.sort((d,p)=>d.localeCompare(p))}},au=No(),su=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,cu=(e,t,n,o)=>{let r=n.command_paths.map(s=>`pm ${s} --help`),i=o?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...r]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return i&&a.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:su(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:r,next_steps:a,...i?{sdk_dependency_status:"missing"}:{}}},lu=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,o])=>o!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},Ba=e=>e.map(t=>lu(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),Ha=(e,t,n)=>{let o=b(e);return t.find(r=>(n===void 0||r.layer===n)&&b(r.name)===o)},du=(e,t,n,o)=>n.find(i=>i.scope===t&&b(i.name)===b(e))?.activation_status??(o?"failed":"unknown"),Ka=(e,t,n,o,r)=>au.enqueue(async()=>{let i=process.env.PM_CLI_PACKAGE_ROOT,a=await Oe.mkdtemp(ne.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=ce(import.meta.url,["../.."]);try{let s=await ve({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:r.noExtensions===!0,reload_token:un(),cache_bust:!0,module_graph_snapshot_root:a}),c=await be({...s}),l=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...Ba(c.failed)],d=Object.fromEntries(s.loaded.map(p=>[b(p.name),Oo(Je(c,{extensionName:p.name}))]));return{installed:en(o,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:l,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:d}}finally{await Oe.rm(a,{recursive:!0,force:!0}),i===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=i}}),no=async(e,t,n,o)=>{let r=n.filter(c=>!c.managed),i=[...r].sort((c,l)=>{let d=c.name.localeCompare(l.name);return d!==0?d:c.directory.localeCompare(l.directory)}),a=o,s=[];for(let c of i){let l=ne.join(e,c.directory),d=await Ze(l),p=T(),u={kind:"local",input:c.name,location:l};a=mt(a,{name:d.manifest.name,directory:c.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:p,updated_at:p,source:u}),s.push({name:d.manifest.name,directory:c.directory,version:d.manifest.version,entry:d.manifest.entry,source:u})}return s.length>0&&await Le(e,a),{state:a,adopted_entries:s,unmanaged_candidates:i,already_managed_count:n.length-r.length}},pu=(e,t)=>{let n=P(process.cwd(),t.path),o=St(n,process.cwd()),r=e==="global"?Eo(process.cwd()):n,i=e==="global"?o.global:o.project;return{pm_root:n,scope:e,settings_root:r,selected_root:i,roots:o}},nn=e=>{let t=[e.gh,e.github].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new m('Options "--gh" and "--github" must match when both are provided.',f.USAGE);return n[0]},uu=e=>Fp[e],mu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=e==="install"?"source":"name",r=`${n} ${o}`,i=uu(e),a=`<${o}>`,s=`pm ${n} ${i} ${a}`;throw new m(`Action "${e}" requires ${r} input.`,f.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${o} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${o} target`}]}})},on=(e,t,n={})=>{let o=e?.trim();if(o)return o;if(t==="init")throw new m('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',f.USAGE);return mu(t,n)},fu=(e,t)=>{let n=new Set([...t.registrations.item_types.map(o=>({entry:o,count:o.types.length})),...t.registrations.item_fields.map(o=>({entry:o,count:o.fields.length}))].filter(({count:o})=>o>0).map(({entry:o})=>`${o.layer}:${b(o.name)}`));return e.loaded.filter(o=>(o.activation?.commands??[]).length>0).filter(o=>n.has(`${o.layer}:${b(o.name)}`)).map(o=>`extension_schema_narrow_activation:${o.layer}:${o.name}`).filter((o,r,i)=>i.indexOf(o)===r).sort((o,r)=>o.localeCompare(r))},hu=(e,t)=>{let o=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(r=>r.triggered&&!r.allowed);if(o)throw new m(o.message,f.USAGE)},gu=(e,t,n)=>{let o=String(e??"").trim().toLowerCase(),r=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:r?[]:["init","scaffold"]}[t]??[]).includes(o)?void 0:e},yu=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},_u=(e,t,n)=>{let o={ok:n,action:e.action,scope:e.scope,roots:yu(e),warnings:[...new Set(e.warnings)].sort((r,i)=>r.localeCompare(i)),details:t};return e.action==="doctor"&&Object.defineProperty(o,Mp,{value:!0,enumerable:!1,configurable:!1}),o},oo=async(e,t,n)=>{let o=tu(e,t);hu(o,t);let r=gu(e,o,t),i=nu(t),a=pu(i,n),c={action:o,normalizedTarget:r,scope:i,resolvedRoots:a,warnings:[],options:t,global:n},d={...c,withResult:(p,u=!0)=>_u(c,p,u)};return await Xu(d)},wu=(e,t)=>{let n=t.vocabulary??"extension",o=e.target_path.replace(/\\/g,"/"),r=Go(o),i={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"`},a={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."),[i[n],...s,`Install the scaffold: ${It(n==="package"?["install","--project",o]:["extension","--install","--project",o])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},vu=async e=>{let{action:t,normalizedTarget:n,options:o,withResult:r}=e;if([nn(o),o.ref].filter(l=>typeof l=="string").map(l=>l.trim()).filter(Boolean).length>0)throw new m('Action "init" does not accept --gh/--github/--ref options.',f.USAGE);let s=on(n,t,o),c=await Ji(s,o.vocabulary??"extension",o.capability,o.declarative===!0);return r({scaffolded:c.created_directory||c.files.some(l=>l.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:wu(c,o)})},bu=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:o,options:r,global:i,withResult:a}=e;if(t!==void 0)throw new m('Action "reload" does not accept a target argument.',f.USAGE);let s=await A(n.settings_root),c=un(),l=await ve({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:i.noExtensions,reload_token:c,cache_bust:!0});o.push(...l.warnings);let d=await be(l);o.push(...d.warnings);let p={reload:{token:c,cache_bust:!0,watch:r.watch===!0},loaded_count:l.loaded.length,failed_count:l.failed.length,activated_count:Math.max(0,l.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:l.loaded.map(u=>({name:u.name,layer:u.layer,version:u.version})),failed_extensions:l.failed.map(u=>({name:u.name,layer:u.layer,error:u.error})),activation_failures:d.failed.map(u=>({name:u.name,layer:u.layer,error:u.error}))};return r.watch===!0&&o.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},ku=async e=>{let{normalizedTarget:t,scope:n,options:o,global:r,withResult:i}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new m('Action "catalog" does not accept a package target.',f.USAGE);return i(await ki(n,r,o))},xu=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Su=e=>({kind:"local",input:e.input,location:e.absolute_path}),Eu=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),$u=(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}),Iu=(e,t,n,o)=>e?xu(e,t):n.kind==="local"?Su(n):n.kind==="npm"?Eu(n,o):$u(n,o),Au=(e,t,n,o)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:o}:hi(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:o}:{installed_at:o,updated_at:o},Tu=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:r}=e,{validated:i,destinationDirectoryName:a}=t,s=await A(o.settings_root),c=await _e(o.selected_root);r.push(...c.warnings);let l=ne.join(o.selected_root,a),d=await k(l),p=await Kt(i.directory,l);await Oe.mkdir(o.selected_root,{recursive:!0});let u=await Oe.mkdtemp(ne.join(o.selected_root,".pm-extension-install-backup-")),h=ne.join(u,"destination");try{let y=await Ra(o.selected_root,o.settings_root,l,d,h),_=Iu(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),g=c.state.entries.find(E=>b(E.name)===b(i.manifest.name)),w=Au(g,i.manifest.version,_,T()),v=mt(c.state,{name:i.manifest.name,directory:a,scope:n,manifest_version:i.manifest.version,manifest_entry:i.manifest.entry,capabilities:[...i.manifest.capabilities],contributions:i.manifest.contributions,...w,source:_}),x=za(s,i.manifest.name);try{p||await sa(i.directory,l),await ra(l),await ia(l),await Le(o.selected_root,v),x&&await xe(o.settings_root,s,"settings:write")}catch(E){try{await Pa(y)}catch(C){throw new AggregateError([E,C],`Extension install failed: ${String(E)}; rollback failed: ${String(C)}`,{cause:C})}throw E}return{settings:s,managedState:v,sourceRecord:_,destinationDirectory:l,destinationExists:d,installInPlace:p,activationChanged:x}}finally{await Oe.rm(u,{recursive:!0,force:!0}).catch(()=>{})}},Ou=async(e,t,n)=>{let o=n.filter(r=>b(r.name)===b(t)).flatMap(r=>r.types.map(i=>({name:i.name,folder:i.folder})));return e.scope==="project"&&o.length>0&&await ct(e.resolvedRoots.pm_root,o,e.warnings,"install:type-folder"),o},Cu=(e,t,n,o,r)=>{let i=Ha(t,n.activation_failures,e.scope),a=du(t,e.scope,n.installed,i),s=[!n.extensions_disabled,a==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${a}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:a,failure:i,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:a,activated:s,registered_commands:o.command_paths,registered_actions:o.action_paths,registered_item_types:r,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},Ru=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:r,global:i,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,l=await Tu(e,t),d=await me(o.selected_root,n,l.settings,l.managedState);r.push(...d.warnings);let p=await Ka(o.pm_root,ne.dirname(o.selected_root),l.settings,d.extensions,i);r.push(...p.warnings);let u=await Ou(e,s.manifest.name,p.item_type_registrations),h=$a(s.manifest.name,p.installed),y=Cu(e,s.manifest.name,p,h,u),_=p.contribution_inventories[b(s.manifest.name)];return _&&(l.managedState=await gi(o.selected_root,l.managedState,s.manifest.name,_)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:l.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:l.destinationDirectory,overwritten:[l.destinationExists,!l.installInPlace].every(Boolean),installed_in_place:l.installInPlace,activated:y.activated,settings_changed:l.activationChanged,runtime_activation_status:y.status,command_paths:h.command_paths,action_paths:h.action_paths,contributions:_,command_discovery:cu(s.manifest.name,l.sourceRecord,h,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)},Pu=async e=>{let{options:t,global:n,warnings:o,withResult:r}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new m('Action "install all" does not accept --ref.',f.USAGE);let i=[],a=new Map;for(let s of await Jt()){let c=await ft(s),l=ne.resolve(c),d=a.get(l);d===void 0&&(d=await oo(s,{...t,install:!0},n),a.set(l,d)),i.push({alias:s,result:d})}return o.push(...i.flatMap(s=>s.result.warnings)),r(Oa(i,t.dryRun===!0),i.every(s=>s.result.ok))},Nu=async(e,t,n)=>{let{resolvedRoots:o}=e,{bundledAliasName:r,bundledPackageName:i,installSource:a,sourceResolution:s}=await pa(t,n,e.options.ref);if(s.ambiguous){let l=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${r}:npm:${l.package}`)}let c=await Ci(a);try{let l=await Ze(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),d=Ut(l.manifest.name),p=e.options.dryRun===!0||a.kind==="local"&&r===null?await la(c,ne.join(o.selected_root,d),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:l.manifest.name,version:l.manifest.version},source_resolution:s,install_plan:p}):await Zn(o.settings_root,d,()=>Ru(e,{validated:l,destinationDirectoryName:d,bundledAliasName:r,bundledPackageName:i,sourceResolution:s,installSource:a,resolvedSource:c,installPlan:p}))}finally{c.cleanup&&await c.cleanup()}},Du=async e=>{let t=nn(e.options),n=t??on(e.normalizedTarget,e.action,e.options);return[t===void 0,_i(n)].every(Boolean)?Pu(e):Nu(e,n,t)},ju=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:r,options:i,withResult:a}=e;if(t!==void 0)throw new m('Action "adopt-all" does not accept a target argument.',f.USAGE);if(nn(i)!==void 0||typeof i.ref=="string"&&i.ref.trim().length>0)throw new m('Action "adopt-all" does not accept --gh/--github/--ref options.',f.USAGE);let c=await A(o.settings_root),l=await _e(o.selected_root);r.push(...l.warnings);let d=await me(o.selected_root,n,c,l.state);r.push(...d.warnings);let p=await no(o.selected_root,n,d.extensions,l.state),u=await me(o.selected_root,n,c,p.state);r.push(...u.warnings);let h=tn(n,r,u.extensions,i);r.push(...h.warnings);let y=new Map(u.extensions.map(w=>[`${b(w.name)}:${b(w.directory)}`,w])),_=new Map(u.extensions.map(w=>[b(w.directory),w])),g=p.adopted_entries.map(w=>{let v=b(w.directory),x=y.get(`${b(w.name)}:${v}`)??_.get(v);return{...w,...Va(x)}});return a({adopted_all:g.length>0,adopted_count:g.length,already_managed_count:p.already_managed_count,extensions:g,triage:h,warning_codes:h.warning_codes,update_health_partial:h.update_health_partial,update_health_coverage:h.update_health_coverage})},Va=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Lu=(e,t,n,o)=>{if(e===void 0)return{kind:"local",input:t,location:n};let r=Bt(e,{forceGithub:!0,ref:o});if(r.kind!=="github")throw new m(`Invalid GitHub shorthand "${e}".`,f.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}},Fu=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:r,warnings:i,options:a,withResult:s}=e,c=on(n,t,a),l=nn(a),d=await A(r.settings_root),p=await _e(r.selected_root);i.push(...p.warnings);let u=await me(r.selected_root,o,d,p.state);i.push(...u.warnings);let h=await Ga(u.extensions,c);if(!h)throw new m(`Installed extension "${c}" was not found in ${o} scope.`,f.NOT_FOUND);if(h.managed)return s({adopted:!1,already_managed:!0,extension:{name:h.name,directory:h.directory}});let y=ne.join(r.selected_root,h.directory),_=await Ze(y),g=T(),w=Lu(l,c,y,a.ref),v=mt(p.state,{name:_.manifest.name,directory:h.directory,scope:o,manifest_version:_.manifest.version,manifest_entry:_.manifest.entry,capabilities:[..._.manifest.capabilities],contributions:_.manifest.contributions,installed_at:g,updated_at:g,source:w});await Le(r.selected_root,v);let x=await me(r.selected_root,o,d,v);i.push(...x.warnings);let E=x.extensions.find(C=>b(C.name)===b(_.manifest.name))??x.extensions.find(C=>b(C.directory)===b(h.directory));return s({adopted:!0,extension:{name:_.manifest.name,directory:h.directory,version:_.manifest.version,entry:_.manifest.entry},source:w,...Va(E)})},Ya=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:r,warnings:i,options:a}=e,s=on(n,t,a),c=await A(r.settings_root),l=await _e(r.selected_root);i.push(...l.warnings);let d=await me(r.selected_root,o,c,l.state);i.push(...d.warnings);let p=await Ga(d.extensions,s);if(!p)throw new m(`Installed extension "${s}" was not found in ${o} scope.`,f.NOT_FOUND);return{settings:c,managedStateRead:l,candidate:p}},Mu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:o,managedStateRead:r,candidate:i}=await Ya(e),a=ne.join(t.selected_root,i.directory);await Oe.rm(a,{recursive:!0,force:!0});let s={...r.state,updated_at:T(),entries:r.state.entries.filter(l=>b(l.name)!==b(i.name)&&b(l.directory)!==b(i.directory))};await Le(t.selected_root,s);let c=Yp(o,i.name);return c&&await xe(t.settings_root,o,"settings:write"),n({removed:!0,extension:{name:i.name,directory:i.directory},destination_path:a,settings_changed:c})},Na=async e=>{let{action:t,resolvedRoots:n,warnings:o,global:r,withResult:i}=e,{settings:a,candidate:s}=await Ya(e),c=t==="activate"?za(a,s.name):Vp(a,s.name);c&&await xe(n.settings_root,a,"settings:write");let l=t==="activate"?await Ka(n.pm_root,ne.dirname(n.selected_root),a,[s],r).then(d=>(o.push(...d.warnings),Ha(s.name,d.activation_failures,e.scope))):void 0;return l&&o.push(`extension_activate_failed:${e.scope}:${s.name}`),i({extension:{name:s.name,directory:s.directory},active:t==="activate"&&l===void 0,runtime_active:t==="activate"&&l===void 0,activation_failure:l??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},l===void 0)},Gu=(e,t,n,o,r,i)=>{let a=o==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=r?.adopted_entries.length??0,l=[[i!==null,i??""],[t>0,`Run pm ${a} explore --project and pm ${a} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${a} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...l.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},to=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Uu=(e,t,n,o)=>{if(e!=="project"||t||!to(o))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.`},zu=(e,t,n)=>{if(String(e??"").trim().length>0)throw new m('Action "doctor" does not accept a target argument.',f.USAGE);let o=[n.isolated,n.ignoreGlobal].includes(!0);if([o,t==="global"].every(Boolean))throw new m("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",f.USAGE);let r=va(n.detail),i=n.trace===!0;if([i,r!=="deep"].every(Boolean))throw new m("--trace requires --detail deep with --doctor.",f.USAGE);return{isolated:o,detailMode:r,includeTrace:i}},Ju=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let o=await no(e.resolvedRoots.selected_root,e.scope,t,n);return{state:o.state,fix:o}},qu=(e,t,n,o)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:to(o),rerun_command:null,pm_global_path_recipe:null};let i=`pm ${r} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:to(o),rerun_command:t?null:i,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},Wu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:r,options:i,global:a,withResult:s}=e,{isolated:c,detailMode:l,includeTrace:d}=zu(t,n,i),p=await A(o.settings_root),u=await _e(o.selected_root);r.push(...u.warnings);let h=await me(o.selected_root,n,p,u.state);r.push(...h.warnings);let{state:y,fix:_}=await Ju(e,h.extensions,u.state),g=await me(o.selected_root,n,p,y);r.push(...g.warnings);let w=await ve({pmRoot:o.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await be({...w,loaded:w.loaded}),x=await Ca(o.pm_root);r.push(...x.warnings,...w.warnings),r.push(...ya(w.failed)),r.push(...v.warnings),r.push(..._a(v.failed)),r.push(...wa(w,v)),r.push(...Ia(v,w)),r.push(...fu(w,v)),r.push(...Aa(v));let E=en(g.extensions,w,v),C=Sa(n,E,w.loaded.map(O=>({layer:O.layer,name:O.name})),w.failed.map(O=>({name:O.name})),w.disabled_by_flag);r.push(...C.warnings);let G=E.filter(O=>O.update_check_status==="failed").map(O=>`extension_update_check_failed:${O.name}`);r.push(...G);let L=tn(n,r,E,i);r.push(...L.warnings);let S=[...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},tt=ka(S),an=xa(),mo=L.warning_codes,Cs=Uu(n,c,i.vocabulary,w),Rs=Gu(L.remediation,w.failed.length,v.failed.length,i.vocabulary,_,Cs),fo=qu(n,c,i.vocabulary,w),Ps={status:L.status,scope:n,warning_count:L.warning_count,warning_codes:mo,total_extensions:E.length,managed_total:E.filter(O=>O.managed).length,enabled_total:E.filter(O=>O.enabled).length,active_total:E.filter(O=>O.active).length,unmanaged_loaded_extension_count:L.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:L.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:L.unmanaged_expected_extension_count,runtime_active_total:E.filter(O=>O.runtime_active===!0).length,activation_status_totals:{ok:E.filter(O=>O.activation_status==="ok").length,failed:E.filter(O=>O.activation_status==="failed").length,not_loaded:E.filter(O=>O.activation_status==="not_loaded").length,unknown:E.filter(O=>O.activation_status==="unknown").length},unknown_capability_count:tt.length,capability_contract_version:an.version,update_available_total:L.update_available_total,update_check_status_totals:L.update_check_status_totals,update_health_coverage:L.update_health_coverage,update_health_partial:L.update_health_partial,update_check_failed_total:E.filter(O=>O.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Qn(w.failed),activation_failures:Qn(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:C.warnings.length,trace_enabled:d,isolation:fo,policy:q,remediation:Rs},Ns=_?{requested:!0,applied:_.adopted_entries.length>0,adopted_count:_.adopted_entries.length,already_managed_count:_.already_managed_count,adopted_extensions:_.adopted_entries.map(O=>O.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:g.extensions.filter(O=>O.managed).length,adopted_extensions:[]},sn={mode:l,summary:Ps,triage:L,trace_enabled:d,capability_contract:an,capability_guidance:tt,managed_state_fix:Ns,author_manifest:x,isolation:fo,policy:w.policy};if(l==="deep"){let O=d?v.failed:v.failed.map(N=>{let{trace:jm,...Ds}=N;return Ds});sn.deep={warnings:S,warning_codes:mo,capability_contract:an,capability_guidance:tt,trace_enabled:d,managed_state:{path:u.path,count:y.entries.length,entries:y.entries},installed_extensions:E,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(N=>({layer:N.layer,directory:N.directory,name:N.name,version:N.version,entry:N.entry,priority:N.priority}))},activation:{failed:O,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:C.summary},d&&(sn.deep.trace={activation_failures:v.failed.filter(N=>N.trace!==void 0).map(N=>({layer:N.layer,name:N.name,entry_path:N.entry_path,error:N.error,method:N.trace.method,command:N.trace.command,capability:N.trace.capability,missing_capability:N.trace.missing_capability,registration_index:N.trace.registration_index,expected_schema:N.trace.expected_schema,hint:N.trace.hint,received:N.trace.received}))})}return s(sn)},Bu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:r,options:i,global:a,withResult:s}=e,c=await A(o.settings_root),l=await ve({pmRoot:o.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),d=await be(l);r.push(...l.warnings),r.push(...d.warnings);let p=Ki(t,l,d);if(t!==void 0&&p.extensions.length===0){let u=i.vocabulary==="package"?"package":"extension",h=[...new Set(l.loaded.map(_=>i.vocabulary==="package"&&typeof _.source_package=="string"&&_.source_package.trim().length>0?_.source_package.trim():_.name))].sort((_,g)=>_.localeCompare(g)),y=h.length>0?` Loaded ${u} names: ${h.join(", ")}.`:"";throw new m(`No loaded ${u} named "${t}" was found in ${n} scope.${y} Run pm ${u} explore to list discovered ${u}s.`,f.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},Hu=async(e,t,n)=>{let o=n,r=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await no(e.resolvedRoots.selected_root,e.scope,t,n),o=r.state),e.action==="manage"){let i=await Ea(o.entries,jp,async a=>{if(a.source.kind!=="github")return a;let s=await Ta(a.source);return{...a,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});o={...o,updated_at:T(),entries:ut(i)},await Le(e.resolvedRoots.selected_root,o)}return{state:o,fix:r}},Ku=async(e,t,n)=>{let o=await ve({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await be({...o,loaded:o.loaded});return e.warnings.push(...o.warnings,...r.warnings),{installed:en(n,o,r),failures:Ba(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:o.failed.length,activation_failure_count:r.failed.length,warning_count:[...new Set([...o.warnings,...r.warnings])].length,policy:o.policy}}},Vu=(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},Da=async e=>{let{action:t,scope:n,resolvedRoots:o,warnings:r,options:i,withResult:a}=e,s=await A(o.settings_root),c=Kp(s.extensions.policy),l=await _e(o.selected_root);r.push(...l.warnings);let d=await me(o.selected_root,n,s,l.state);r.push(...d.warnings);let{state:p,fix:u}=await Hu(e,d.extensions,l.state),h=await me(o.selected_root,n,s,p);if(r.push(...h.warnings),t==="manage"){let v=h.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);r.push(...v)}let y=await Ku(e,s,h.extensions),_=y.installed,g=tn(n,r,_,i);r.push(...g.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:g,policy:c};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=Vu(u,_)),a(w)},ja={init:vu,install:Du,uninstall:Mu,explore:Da,manage:Da,describe:Bu,reload:bu,doctor:Wu,catalog:ku,adopt:Fu,"adopt-all":ju,activate:Na,deactivate:Na,migrate:Xi},Yu=e=>[e.action==="uninstall",e.action==="manage",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[e.action==="doctor",e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Xu=e=>Yu(e)?Zn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>ja[e.action](e)):ja[e.action](e);import ao from"node:fs/promises";import J from"node:path";import Xa from"node:readline/promises";import{stdin as Za,stdout as _t}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5ae3e66-4a45-5c62-9144-46f8f5bff7cf")}catch{}})();var Qa=["ask","add","skip","status"],Zu=["AGENTS.md","CLAUDE.md"],Qu=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],em=8,so=1,tm="<!-- pm-cli:agent-guidance:start:",nm=`<!-- pm-cli:agent-guidance:start:v${so} -->`,ro="<!-- pm-cli:agent-guidance:end -->",vt="Add workflow guidance later: pm init --agent-guidance add",Hw={toPortableRelativePath:Qe,ensureTrailingNewline:io,detectLineEnding:ts,findGuidanceBlockRange:co,buildAgentGuidanceBlock:ns,upsertAgentGuidanceBlock:os,resolveProjectRoot:rs,resolveTargetGuidancePath:is,parsePromptChoice:as,pushUnique:et,promptForGuidanceWrite:ss,normalizeAgentGuidanceState:lo,applyAgentGuidanceState:ls,writeGuidanceFile:ds,setAgentGuidanceReadlineFactoryForTests:om},es=()=>Xa.createInterface({input:Za,output:_t});function om(e){es=e??(()=>Xa.createInterface({input:Za,output:_t}))}function Qe(e,t){let n=J.relative(e,t);return n.length===0?J.basename(t):n.split(J.sep).join("/")}function io(e){return e.endsWith(`
|
|
47
49
|
`)?e:`${e}
|
|
48
|
-
`}function
|
|
50
|
+
`}function ts(e){return e.includes(`\r
|
|
49
51
|
`)?`\r
|
|
50
52
|
`:`
|
|
51
|
-
`}function
|
|
53
|
+
`}function co(e){let t=e.indexOf(tm);if(t===-1)return null;let n=e.indexOf(ro,t);return n===-1?null:{start_index:t,end_index:n+ro.length}}function rm(e){return co(e)!==null}function ns(e,t="<your project test command>"){return[nm,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",ro,""].join(e)}function os(e,t="<your project test command>"){let n=ts(e),o=ns(n,t),r=co(e);if(r){let s=e.slice(r.end_index),c=s.startsWith(`\r
|
|
52
54
|
`)?s.slice(2):s.startsWith(`
|
|
53
|
-
`)?s.slice(1):s,l=
|
|
55
|
+
`)?s.slice(1):s,l=io(`${e.slice(0,r.start_index)}${o}${c}`);return{next_content:l,changed:l!==e}}let i=e.length===0?"":e.endsWith(`
|
|
54
56
|
`)?`
|
|
55
57
|
`:`
|
|
56
58
|
|
|
57
|
-
`,a=
|
|
59
|
+
`,a=io(`${e}${i}${o}`);return{next_content:a,changed:a!==e}}async function im(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 ao.readFile(J.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=am(t);if(n===void 0)return"<your project test command>";let o=n.packageManager?.split("@")[0];return o==="pnpm"?"pnpm test":o==="bun"?"bun run test":o==="yarn"?"yarn test":o==="npm"?"npm test":await 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 am(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function rs(e,t){let n=J.dirname(e);return J.basename(e)==="pm"&&J.basename(n)===".agents"?J.dirname(n):J.resolve(t,e)}function is(e,t){let n=e.find(r=>J.basename(r.file_path)==="AGENTS.md"&&r.exists);if(n)return n.file_path;let o=e.find(r=>r.exists);return o?o.file_path:J.join(t,"AGENTS.md")}function as(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function ss(e){let t=es();try{_t.write(`
|
|
58
60
|
Agent guidance check
|
|
59
|
-
`),
|
|
60
|
-
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return
|
|
61
|
-
`),Ma(n,!0)}finally{t.close()}}function to(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:Zn,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o)):[]}}async function Ua(e){let t=[];for(let n of Eu){let o=z.join(e,n),r=await k(o);if(!r){t.push({file_path:o,exists:r,has_guidance:!1,has_marker:!1});continue}let i=await Qn.readFile(o,"utf8"),a=i.toLowerCase(),s=$u.filter(l=>a.includes(l)),c=Cu(i);t.push({file_path:o,exists:r,has_guidance:c||s.length>=Iu,has_marker:c})}return t}function Ze(e,t){e.includes(t)||e.push(t)}function za(e,t){let n=to(e),o=JSON.stringify(n)!==JSON.stringify(t);return o&&(e.agent_guidance=t),{changed:o,state:t}}async function Ja(e,t=z.dirname(e)){let o=await k(e)?await Qn.readFile(e,"utf8"):"",r=ja(o,await Ru(t));return r.changed?(await fe(e,r.next_content),{changed:!0,warnings:await W({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function Nu(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Qe(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Qe(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Qe(e.projectRoot,t.file_path))}}async function Du(e,t,n){return e?await Ua(n):t}function yt(e,t,n){e.state={...e.state,...n,template_version:Zn,last_checked_files:t}}async function qa(e,t){if(t.presentBefore)return;let n=await Ja(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function ju(e,t){t||(e.warnings.push("agent_guidance:missing"),Ze(e.nextSteps,_t))}function Lu(e,t){e.skipped=!0,yt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Ze(e.nextSteps,_t)}async function Fu(e,t){await qa(e,t),yt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Mu(e,t){e.state.declined&&yt(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Gu(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ze(e.nextSteps,_t)}async function Uu(e,t){if(e.prompted=!0,await Ga(t.targetRelativePath)){await qa(e,t),yt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,yt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ze(e.nextSteps,_t)}function zu(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ze(e.nextSteps,_t)}async function Ju(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(ju(n,t.presentBefore),n):t.mode==="skip"?(Lu(n,t.checkedFiles),n):t.mode==="add"?(await Fu(n,t),n):t.presentBefore?(Mu(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Gu(n),n):t.interactive?(await Uu(n,t),n):(zu(n),n)}async function Ba(e){let t=La(e.pm_root,e.cwd),n=await Ua(t),o=Fa(n,t),r=Qe(t,o),i=n.map(d=>Qe(t,d.file_path)),a=n.some(d=>d.has_guidance),s=await Ju(to(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:o,targetRelativePath:r,checkedFiles:i,presentBefore:a,projectRoot:t}),c=za(e.settings,s.state);return n=await Du(s.applied,n,t),{summary:Nu({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:c.changed}}import qu from"node:fs/promises";import j from"node:path";import Ha from"node:readline/promises";import{stdin as Ka,stdout as Q}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="55f7a34f-05d6-507f-a46c-1da0d957f2e3")}catch{}})();var Bu=Symbol.for("pm.sdk.init-invocation-cwd");function gw(e){return{ok:e.ok,path:e.path,target:e.target,id_prefix:e.settings.id_prefix,governance_preset:e.governance_preset,telemetry:{enabled:e.settings.telemetry.enabled,capture_level:e.settings.telemetry.capture_level},output_format:e.settings.output.default_format,created_dirs_count:e.created_dirs.length,created_dirs:e.created_dirs,warnings:e.warnings,wizard_used:e.wizard_used,...e.registered_type_preset?{registered_type_preset:e.registered_type_preset}:{},...e.installed_packages?{installed_packages:e.installed_packages}:{},next_steps:e.next_steps,agent_guidance:e.agent_guidance,hint:"Re-run with --verbose for the full settings tree."}}var yw={normalizeInitGovernancePreset:no,normalizeInitTypePreset:Xa,normalizeOptionalInitAuthor:Ya,normalizeInitAgentGuidanceMode:es,isPathLikeInitTarget:Qt,resolveInitInvocation:Qa,resolveInitPrefixInput:Za,parseYesNoChoice:ts,applyGovernancePreset:oo,runInitWizard:ss,setInitReadlineFactoryForTests:Wu,summarizeInstalledPackages:ns,buildInitNextSteps:cs,registerInitTypePreset:os,assertExplicitTrackerPathIsNotWorkspaceRoot:is,isLikelyWorkspaceRoot:rs,installInitMergeFence:ls},Va=()=>Ha.createInterface({input:Ka,output:Q});function Wu(e){Va=e??(()=>Ha.createInterface({input:Ka,output:Q}))}function Hu(){return structuredClone(nn)}var Ku=["minimal","default","strict"];function no(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new h("--preset must not be empty",g.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new h(`Invalid --preset value "${e}". Allowed: ${Ku.join(", ")}`,g.USAGE)}function Xa(e){if(e!==void 0){if(e.trim().length===0)throw new h("--type-preset must not be empty",g.USAGE);try{return Ot(e)}catch{throw new h(`Invalid --type-preset value "${e}". Allowed: ${rt.join(", ")}`,g.USAGE)}}}function Ya(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new h("--author must not be empty",g.USAGE);return t}function Qt(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:j.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function Qa(e,t,n,o){let r=o?.trim();if(o!==void 0&&r?.length===0)throw new h("--workspace must not be empty",g.USAGE);if(r!==void 0){if(t.path!==void 0||Qt(n))throw new h("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",g.USAGE);let l=j.resolve(e,r),d=j.join(l,".agents","pm");return{pmRoot:d,prefixArg:n,target:{mode:"workspace-path",tracker_root:d,workspace_root:l}}}if(t.path===void 0&&Qt(n)){let l=j.resolve(e,n.trim());return{pmRoot:l,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:l}}}let i=N(e,t.path),a=j.join(j.resolve(e),".agents","pm"),s=j.dirname(j.dirname(i)),c=j.resolve(i)===a?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:c,requested_cwd:j.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function Za(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new h("--id-prefix must not be empty",g.USAGE);if(Qt(t))throw new h(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,g.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&ke(e)!==ke(t))throw new h(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,g.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${ke(e)}`,`pm init --id-prefix ${ke(t)}`]});return t}function es(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new h("--agent-guidance must not be empty",g.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new h(`Invalid --agent-guidance value "${e}". Allowed: ${Ra.join(", ")}`,g.USAGE)}function ts(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function oo(e,t){let n=lo[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function Vu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ns(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(Vu).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function os(e,t,n){let o=V(t.schema),r=oe(e,o.files.types,Y.types),a=ie(await q(r)),s=[],c=[];for(let l of it(n)){let d=Ge(a,l);a=d.file,(d.replaced?c:s).push(d.definition.name)}return await Me({pmRoot:e,filePath:r,raw:le(a),op:"init:type-preset",author:X(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:s,updated:c,file:r}}async function rs(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",j.join(".agents","pm")];for(let n of t)if(await k(j.join(e,n)))return!0;return!1}async function is(e,t,n){if(!t||n||await k(j.join(e,"settings.json"))||!await rs(e))return;let o=j.join(e,".agents","pm");throw new h(`Refusing to initialize tracker files directly in workspace root "${e}".`,g.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${o} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${o} init --yes`}})}async function as(e,t){let n=[],o=[];for(let r of t){let i=r?j.join(e,r):e,a=await k(i);await qu.mkdir(i,{recursive:!0}),a?o.push(`already_exists:${i}`):n.push(i),o.push(...await W({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:o}}async function ss(e,t){let n=Va();try{Q.write(`pm init setup wizard (agent-optimized)
|
|
62
|
-
`),
|
|
61
|
+
`),_t.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
62
|
+
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return _t.write(`
|
|
63
|
+
`),as(n,!0)}finally{t.close()}}function lo(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:so,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o)):[]}}async function cs(e){let t=[];for(let n of Zu){let o=J.join(e,n),r=await k(o);if(!r){t.push({file_path:o,exists:r,has_guidance:!1,has_marker:!1});continue}let i=await ao.readFile(o,"utf8"),a=i.toLowerCase(),s=Qu.filter(l=>a.includes(l)),c=rm(i);t.push({file_path:o,exists:r,has_guidance:c||s.length>=em,has_marker:c})}return t}function et(e,t){e.includes(t)||e.push(t)}function ls(e,t){let n=lo(e),o=JSON.stringify(n)!==JSON.stringify(t);return o&&(e.agent_guidance=t),{changed:o,state:t}}async function ds(e,t=J.dirname(e)){let o=await k(e)?await ao.readFile(e,"utf8"):"",r=os(o,await im(t));return r.changed?(await fe(e,r.next_content),{changed:!0,warnings:await K({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function sm(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Qe(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Qe(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Qe(e.projectRoot,t.file_path))}}async function cm(e,t,n){return e?await cs(n):t}function wt(e,t,n){e.state={...e.state,...n,template_version:so,last_checked_files:t}}async function ps(e,t){if(t.presentBefore)return;let n=await ds(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function lm(e,t){t||(e.warnings.push("agent_guidance:missing"),et(e.nextSteps,vt))}function dm(e,t){e.skipped=!0,wt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),et(e.nextSteps,vt)}async function pm(e,t){await ps(e,t),wt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function um(e,t){e.state.declined&&wt(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function mm(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),et(e.nextSteps,vt)}async function fm(e,t){if(e.prompted=!0,await ss(t.targetRelativePath)){await ps(e,t),wt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,wt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),et(e.nextSteps,vt)}function hm(e){e.warnings.push("agent_guidance:missing_non_interactive"),et(e.nextSteps,vt)}async function gm(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(lm(n,t.presentBefore),n):t.mode==="skip"?(dm(n,t.checkedFiles),n):t.mode==="add"?(await pm(n,t),n):t.presentBefore?(um(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(mm(n),n):t.interactive?(await fm(n,t),n):(hm(n),n)}async function us(e){let t=rs(e.pm_root,e.cwd),n=await cs(t),o=is(n,t),r=Qe(t,o),i=n.map(d=>Qe(t,d.file_path)),a=n.some(d=>d.has_guidance),s=await gm(lo(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:o,targetRelativePath:r,checkedFiles:i,presentBefore:a,projectRoot:t}),c=ls(e.settings,s.state);return n=await cm(s.applied,n,t),{summary:sm({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:c.changed}}import ym from"node:fs/promises";import j from"node:path";import fs from"node:readline/promises";import{stdin as hs,stdout as Z}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="55f7a34f-05d6-507f-a46c-1da0d957f2e3")}catch{}})();var _m=Symbol.for("pm.sdk.init-invocation-cwd");function yv(e){return{ok:e.ok,path:e.path,target:e.target,id_prefix:e.settings.id_prefix,governance_preset:e.governance_preset,telemetry:{enabled:e.settings.telemetry.enabled,capture_level:e.settings.telemetry.capture_level},output_format:e.settings.output.default_format,created_dirs_count:e.created_dirs.length,created_dirs:e.created_dirs,warnings:e.warnings,wizard_used:e.wizard_used,...e.registered_type_preset?{registered_type_preset:e.registered_type_preset}:{},...e.installed_packages?{installed_packages:e.installed_packages}:{},next_steps:e.next_steps,agent_guidance:e.agent_guidance,hint:"Re-run with --verbose for the full settings tree."}}var _v={normalizeInitGovernancePreset:po,normalizeInitTypePreset:ys,normalizeOptionalInitAuthor:_s,normalizeInitAgentGuidanceMode:bs,isPathLikeInitTarget:rn,resolveInitInvocation:ws,resolveInitPrefixInput:vs,parseYesNoChoice:ks,applyGovernancePreset:uo,runInitWizard:As,setInitReadlineFactoryForTests:wm,summarizeInstalledPackages:xs,buildInitNextSteps:Ts,registerInitTypePreset:Ss,assertExplicitTrackerPathIsNotWorkspaceRoot:$s,isLikelyWorkspaceRoot:Es,installInitMergeFence:Os},gs=()=>fs.createInterface({input:hs,output:Z});function wm(e){gs=e??(()=>fs.createInterface({input:hs,output:Z}))}function vm(){return structuredClone(ln)}var bm=["minimal","default","strict"];function po(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new m("--preset must not be empty",f.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new m(`Invalid --preset value "${e}". Allowed: ${bm.join(", ")}`,f.USAGE)}function ys(e){if(e!==void 0){if(e.trim().length===0)throw new m("--type-preset must not be empty",f.USAGE);try{return jt(e)}catch{throw new m(`Invalid --type-preset value "${e}". Allowed: ${at.join(", ")}`,f.USAGE)}}}function _s(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new m("--author must not be empty",f.USAGE);return t}function rn(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:j.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function ws(e,t,n,o){let r=o?.trim();if(o!==void 0&&r?.length===0)throw new m("--workspace must not be empty",f.USAGE);if(r!==void 0){if(t.path!==void 0||rn(n))throw new m("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",f.USAGE);let l=j.resolve(e,r),d=j.join(l,".agents","pm");return{pmRoot:d,prefixArg:n,target:{mode:"workspace-path",tracker_root:d,workspace_root:l}}}if(t.path===void 0&&rn(n)){let l=j.resolve(e,n.trim());return{pmRoot:l,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:l}}}let i=P(e,t.path),a=j.join(j.resolve(e),".agents","pm"),s=j.dirname(j.dirname(i)),c=j.resolve(i)===a?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:c,requested_cwd:j.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function vs(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new m("--id-prefix must not be empty",f.USAGE);if(rn(t))throw new m(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,f.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&ke(e)!==ke(t))throw new m(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,f.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${ke(e)}`,`pm init --id-prefix ${ke(t)}`]});return t}function bs(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new m("--agent-guidance must not be empty",f.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new m(`Invalid --agent-guidance value "${e}". Allowed: ${Qa.join(", ")}`,f.USAGE)}function ks(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function uo(e,t){let n=_o[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function km(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xs(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(km).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Ss(e,t,n){let o=Y(t.schema),r=oe(e,o.files.types,X.types),a=ie(await W(r)),s=[],c=[];for(let l of st(n)){let d=ze(a,l);a=d.file,(d.replaced?c:s).push(d.definition.name)}return await Ue({pmRoot:e,filePath:r,raw:le(a),op:"init:type-preset",author:H(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:s,updated:c,file:r}}async function Es(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",j.join(".agents","pm")];for(let n of t)if(await k(j.join(e,n)))return!0;return!1}async function $s(e,t,n){if(!t||n||await k(j.join(e,"settings.json"))||!await Es(e))return;let o=j.join(e,".agents","pm");throw new m(`Refusing to initialize tracker files directly in workspace root "${e}".`,f.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${o} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${o} init --yes`}})}async function Is(e,t){let n=[],o=[];for(let r of t){let i=r?j.join(e,r):e,a=await k(i);await ym.mkdir(i,{recursive:!0}),a?o.push(`already_exists:${i}`):n.push(i),o.push(...await K({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:o}}async function As(e,t){let n=gs();try{Z.write(`pm init setup wizard (agent-optimized)
|
|
64
|
+
`),Z.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
63
65
|
|
|
64
|
-
`),
|
|
65
|
-
`),
|
|
66
|
-
`);let o=await n.question(`Item ID prefix [${e}]: `),r=o.trim().length>0?ke(o):e;
|
|
66
|
+
`),Z.write(`1/3 Item ID prefix
|
|
67
|
+
`),Z.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
|
|
68
|
+
`);let o=await n.question(`Item ID prefix [${e}]: `),r=o.trim().length>0?ke(o):e;Z.write(`
|
|
67
69
|
2/3 Governance preset
|
|
68
|
-
`),
|
|
69
|
-
`),
|
|
70
|
-
`),
|
|
71
|
-
`);let i=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),a=i.trim().length>0?i.trim():"minimal",s="minimal";try{s=
|
|
72
|
-
`)}
|
|
70
|
+
`),Z.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
71
|
+
`),Z.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
72
|
+
`),Z.write(`strict: ownership blocking, strict create defaults, close validation strict.
|
|
73
|
+
`);let i=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),a=i.trim().length>0?i.trim():"minimal",s="minimal";try{s=po(a)}catch{Z.write(`Unrecognized governance preset "${a}"; using minimal.
|
|
74
|
+
`)}Z.write(`
|
|
73
75
|
3/3 Project telemetry
|
|
74
|
-
`),
|
|
75
|
-
`);let c=t?"Y/n":"y/N",l=await n.question(`Enable telemetry for this project? [${c}] `),d=
|
|
76
|
-
`),{prefix:r,preset:s,telemetry_enabled:d}}finally{n.close()}}function
|
|
77
|
-
//# sourceMappingURL=chunk-
|
|
76
|
+
`),Z.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
|
|
77
|
+
`);let c=t?"Y/n":"y/N",l=await n.question(`Enable telemetry for this project? [${c}] `),d=ks(l,t);return Z.write(`
|
|
78
|
+
`),{prefix:r,preset:s,telemetry_enabled:d}}finally{n.close()}}function xm(e){return{presetFromOption:po(e.preset),useDefaults:e.defaults===!0,authorFromOption:_s(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:bs(e.agentGuidance),typePreset:ys(e.typePreset)}}function Sm(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 Em(e,t,n,o){if(t.length===0||n)return;let r=o.discovery==="ancestor";throw new m(`${r?`No tracker exists in ${o.requested_cwd}; pm init found an ancestor tracker at ${o.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,f.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:o.tracker_root,requested_path:o.requested_cwd,suggested_path:o.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 $m(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&&(uo(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 Im(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=Sm({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return Em(e.settingsPath,n,e.options.force===!0,e.target),$m({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await xe(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function Am(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,o,r=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await As(t,ln.telemetry.enabled);t=c.prefix,n=c.preset,o=c.telemetry_enabled,r=!0}let i=n??"minimal",a=vm();a.id_prefix=t,uo(a,i);let s=Mo()?.trim()||void 0;return a.author_default=e.normalizedOptions.authorFromOption??s??"",o!==void 0&&(a.telemetry.enabled=o,a.telemetry.first_run_prompt_completed=!0),await xe(e.pmRoot,a),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:r}}async function ms(e){return e.settingsExists?await Im(e):await Am({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function Tm(e){let t=await us({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await xe(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function Om(e,t){let n=[],o=[],r=await Fo(e,t.schema);for(let i of r.created_paths)n.push(i),o.push(...await K({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:o}}async function Cm(e){if(e.typePreset===void 0)return;let t=await Ss(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await K({path:t.file,scope:"project",op:"init:type_preset"})),t}async function Rm(e){let n=U(e.settings,B()).folders.filter(r=>!cn.includes(r)),o=await Is(e.pmRoot,n);e.createdDirs.push(...o.createdDirs),e.warnings.push(...o.warnings)}function Pm(e){let t=j.resolve(e.tracker_root),n=j.dirname(t);return j.basename(t)==="pm"&&j.basename(n)===".agents"?j.dirname(n):e.workspace_root}async function Nm(e,t,n,o){if(!e)return;let r=await oo("all",{install:!0,project:!0},{...t,path:n});o.push(...r.warnings);let i=xs(r),a=i.packages.filter(s=>!s.ok).map(s=>s.alias);if(!i.installed_all||a.length>0)throw new m(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,f.GENERIC_FAILURE);return i}function Ts(e){let t=o=>It([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...o]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let o of e.agentGuidanceNextSteps){let r=e.target.mode==="workspace-discovery"?o:o.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(r)||n.push(r)}return n}async function Os(e,t,n,o=An){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 o({pmRoot:e,workspaceRoot:t});r.gitattributes.changed&&n.push(`updated:merge_fence:${r.gitattributes.path}`)}catch(r){if(!(r instanceof m))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 Dm(e,t,n,o){if(e==null||n==="status")return;let r=await wr(e,{pmRoot:t});r.changed&&o.push(`updated:gitignore:${r.path}`)}async function wv(e,t,n={}){let o=t[_m],r=typeof o=="string"?o:process.cwd(),i=ws(r,t,e,n.workspace),a=i.pmRoot;e=vs(i.prefixArg,n.idPrefix);let s=xm(n);await $s(a,i.target.mode==="tracker-path",n.force===!0);let c=[],l=[],d=j.join(a,"settings.json"),p=await k(d),u;p&&(u=await ms({pmRoot:a,settingsPath:d,settingsExists:p,normalizedPrefix:ke(e),prefixArg:e,options:n,normalizedOptions:s,warnings:l,target:i.target}));let h=await Is(a,cn);c.push(...h.createdDirs),l.push(...h.warnings),u??=await ms({pmRoot:a,settingsPath:d,settingsExists:p,normalizedPrefix:ke(e),prefixArg:e,options:n,normalizedOptions:s,warnings:l,target:i.target});let{settings:y}=u,_=Pm(i.target),g=await En(_??j.dirname(a)),w=_??g,v=await Tm({pmRoot:a,cwd:w??r,agentGuidanceMode:s.agentGuidanceMode,settings:y,warnings:l}),x=await Om(a,y);c.push(...x.createdDirs),l.push(...x.warnings);let E=await Cm({pmRoot:a,settings:y,typePreset:s.typePreset,warnings:l});E&&(y=await A(a)),await Rm({pmRoot:a,settings:y,createdDirs:c,warnings:l}),await Dm(w,a,s.agentGuidanceMode,l),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await Os(a,g,l);let C=await Nm(s.installBundledPackages,t,a,l),G=Ts({installBundledPackages:s.installBundledPackages,registeredTypePreset:E,agentGuidanceNextSteps:v.next_steps,target:i.target});return{ok:!0,path:a,target:i.target,settings:y,created_dirs:c,warnings:l,governance_preset:y.governance.preset,wizard_used:u.wizardUsed,...E?{registered_type_preset:E}:{},...C?{installed_packages:C}:{},next_steps:G,agent_guidance:v}}export{yn as a,fr as b,gr as c,vn as d,Zs as e,ec as f,wr as g,Je as h,nc as i,oc as j,br as k,Rt as l,Er as m,qe as n,xn as o,cc as p,En as q,In as r,Or as s,yf as t,_f as u,Cr as v,wf as w,An as x,qr as y,He as z,Ke as A,Wr as B,Ur as C,We as D,Be as E,zr as F,Qc as G,dc as H,kf as I,$f as J,Pr as K,uc as L,Jf as M,Xr as N,ti as O,Xc as P,Zc as Q,tg as R,og as S,rg as T,ct as U,ig as V,ag as W,sg as X,cg as Y,lg as Z,dg as _,pg as $,ug as aa,mg as ba,fg as ca,hg as da,gg as ea,yg as fa,_g as ga,wg as ha,vg as ia,bg as ja,kg as ka,xg as la,Sg as ma,Eg as na,$g as oa,Ig as pa,Ag as qa,Tg as ra,b as sa,_e as ta,Mt as ua,gl as va,dt as wa,Gt as xa,Ei as ya,Ni as za,Vn as Aa,Ki as Ba,qy as Ca,Sp as Da,ka as Ea,xa as Fa,Ea as Ga,Yn as Ha,rp as Ia,ip as Ja,ap as Ka,Xi as La,la as Ma,yp as Na,Np as Oa,pa as Pa,oo as Qa,Qa as Ra,Hw as Sa,us as Ta,_m as Ua,yv as Va,_v as Wa,wv as Xa};
|
|
79
|
+
//# sourceMappingURL=chunk-I6XT3DLQ.js.map
|