@unbrained/pm-cli 2026.8.17 → 2026.8.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/AGENTS.md +4 -3
- package/CHANGELOG.md +51 -5
- package/README.md +3 -3
- package/dist/cli/error-guidance.js +8 -4
- package/dist/cli/help-content.js +32 -13
- package/dist/cli/help-json-payload.d.ts +15 -0
- package/dist/cli/help-json-payload.js +101 -23
- package/dist/cli/main.js +6 -2
- package/dist/cli/register-list-query.js +138 -54
- package/dist/cli/register-mutation.js +8 -8
- package/dist/cli/register-operations.js +6 -6
- package/dist/cli-bundle/bundle-manifest.json +149 -149
- package/dist/cli-bundle/chunks/chunk-4NRRH7AM.js +2 -0
- package/dist/cli-bundle/chunks/chunk-4THEB6PD.js +13 -0
- package/dist/cli-bundle/chunks/{chunk-HBJAS566.js → chunk-BHYMXLAE.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GWMXAQOD.js +197 -0
- package/dist/cli-bundle/chunks/chunk-HVFQTLYM.js +35 -0
- package/dist/cli-bundle/chunks/chunk-OI4XI562.js +5 -0
- package/dist/cli-bundle/chunks/{chunk-3UEGXBMR.js → chunk-OIOKV6NO.js} +58 -54
- package/dist/cli-bundle/chunks/chunk-QXSH7BLM.js +3 -0
- package/dist/cli-bundle/chunks/chunk-SARFF5H5.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-7IBRGCHX.js → chunk-TOXJM4WA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JOKATURE.js → chunk-YBMRWW4E.js} +44 -44
- package/dist/cli-bundle/chunks/register-list-query-Y56KINDU.js +11 -0
- package/dist/cli-bundle/chunks/register-mutation-AUWVCW4M.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-PZQPHXW5.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-DOSFBGKE.js → register-setup-I4LUHGVW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-34QBIYZI.js +155 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MHPIL773.js → chunk-BJRYFVSH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-DKPLYW3L.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SALH6B6K.js → chunk-EF6ZS5GH.js} +44 -44
- package/dist/cli-bundle/focused-chunks/{chunk-XKAMP5OU.js → chunk-ESISGDAY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SYZENPIT.js → chunk-EXBCLIBU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JDOMQ7VQ.js +4 -0
- package/dist/cli-bundle/focused-chunks/chunk-L623ZPNK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-MCZXYZAF.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-ODHQEECS.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZQPGZZWQ.js → chunk-PRHY2IMX.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-RZU5U6Q7.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ATEY76SX.js → chunk-US7VEYZG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VXDSU5MC.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-YBMGXBFV.js +16 -0
- package/dist/cli-bundle/focused-chunks/chunk-YLVBJ6GF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-CYFK5UPB.js → chunk-ZBIQQYMI.js} +2 -2
- package/dist/cli-bundle/main.js +13 -13
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -1
- package/dist/cli-bundle/sdk-core.js +28 -28
- 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 +32 -32
- 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 +5 -4
- package/dist/core/config/nested-settings.js +8 -2
- package/dist/core/extensions/exporter-output-contract.d.ts +12 -0
- package/dist/core/extensions/exporter-output-contract.js +67 -0
- package/dist/core/extensions/extension-types.d.ts +36 -1
- package/dist/core/extensions/extension-types.js +2 -2
- package/dist/core/extensions/loader.js +35 -44
- package/dist/core/history/event-index.d.ts +5 -0
- package/dist/core/history/event-index.js +133 -27
- package/dist/core/sentry/helpers.js +3 -3
- package/dist/core/shared/constants.js +5 -2
- package/dist/core/shared/errors.d.ts +2 -0
- package/dist/core/shared/errors.js +2 -2
- package/dist/core/store/settings-validator.d.ts +4 -0
- package/dist/core/store/settings-validator.js +3 -2
- package/dist/core/store/settings.js +8 -2
- package/dist/mcp/tool-definitions.js +12 -7
- package/dist/sdk/agent/refusal-closure.d.ts +41 -0
- package/dist/sdk/agent/refusal-closure.js +92 -0
- package/dist/sdk/agent/refusal-reachability.d.ts +1 -1
- package/dist/sdk/agent/refusal-reachability.js +4 -4
- package/dist/sdk/agent-capability-contracts.d.ts +13 -0
- package/dist/sdk/agent-capability-contracts.js +104 -7
- package/dist/sdk/authoring.d.ts +1 -1
- package/dist/sdk/authoring.js +2 -2
- package/dist/sdk/cli-bootstrap.d.ts +2 -2
- package/dist/sdk/cli-bootstrap.js +4 -4
- package/dist/sdk/cli-contracts/command-aliases.d.ts +34 -2
- package/dist/sdk/cli-contracts/command-aliases.js +80 -13
- package/dist/sdk/cli-contracts/commander-mutation-options.js +30 -6
- package/dist/sdk/cli-contracts/commander-types.js +5 -4
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +4 -0
- package/dist/sdk/cli-contracts/enum-contracts.js +9 -2
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +5 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +84 -13
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.d.ts +55 -0
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +240 -0
- package/dist/sdk/cli-contracts/grammar-contracts.d.ts +151 -0
- package/dist/sdk/cli-contracts/grammar-contracts.js +958 -0
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +33 -5
- package/dist/sdk/cli-contracts/runtime-contracts.js +100 -23
- package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +28 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.js +38 -3
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +7 -2
- package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
- package/dist/sdk/cli-contracts/tool-schema.js +20 -11
- package/dist/sdk/cli-contracts.d.ts +5 -4
- package/dist/sdk/cli-contracts.js +7 -6
- package/dist/sdk/completion.js +13 -15
- package/dist/sdk/compose.d.ts +3 -3
- package/dist/sdk/compose.js +2 -2
- package/dist/sdk/context-intent-contracts.d.ts +2 -2
- package/dist/sdk/context-intent-contracts.js +22 -7
- package/dist/sdk/contracts.d.ts +3 -0
- package/dist/sdk/contracts.js +5 -2
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +3 -3
- package/dist/sdk/environment/host-environment-errors.js +3 -3
- package/dist/sdk/flag-invocation-contracts.d.ts +37 -0
- package/dist/sdk/flag-invocation-contracts.js +218 -9
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +186 -14
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +194 -26
- package/dist/sdk/guide-topics.js +5 -5
- package/dist/sdk/index.d.ts +10 -7
- package/dist/sdk/index.js +10 -7
- package/dist/sdk/init-agent-guidance.js +3 -3
- package/dist/sdk/mutation-events.d.ts +18 -2
- package/dist/sdk/mutation-events.js +59 -16
- package/dist/sdk/output-projection.d.ts +2 -0
- package/dist/sdk/output-projection.js +11 -5
- package/dist/sdk/output.d.ts +44 -0
- package/dist/sdk/output.js +28 -2
- package/dist/sdk/query/complete-list.d.ts +94 -0
- package/dist/sdk/query/complete-list.js +173 -0
- package/dist/sdk/query/get.js +25 -6
- package/dist/sdk/query/list.js +19 -2
- package/dist/sdk/query/search-contracts.d.ts +1 -1
- package/dist/sdk/query/search-contracts.js +23 -9
- package/dist/sdk/query/search.js +3 -3
- package/dist/sdk/query.d.ts +1 -0
- package/dist/sdk/query.js +3 -2
- package/dist/sdk/read-output/continuation.d.ts +1 -1
- package/dist/sdk/read-output/continuation.js +7 -24
- package/dist/sdk/read-output-contracts.d.ts +2 -2
- package/dist/sdk/read-output-contracts.js +89 -13
- package/dist/sdk/read-output-rows.d.ts +4 -0
- package/dist/sdk/read-output-rows.js +47 -18
- package/dist/sdk/runtime-extended-actions.js +10 -2
- package/dist/sdk/runtime.d.ts +8 -2
- package/dist/sdk/runtime.js +18 -11
- package/dist/sdk/workspace-snapshot.d.ts +2 -0
- package/dist/sdk/workspace-snapshot.js +10 -2
- package/dist/types.d.ts +5 -0
- package/dist/types.js +2 -2
- package/docs/AGENT_GUIDE.md +25 -9
- package/docs/CLI_GRAMMAR.md +106 -0
- package/docs/COMMANDS.md +39 -27
- package/docs/ONBOARDING.md +4 -4
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +11 -2
- package/docs/QUICKSTART.md +1 -1
- package/docs/README.md +2 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +10 -6
- package/docs/RELEASING.md +30 -6
- package/docs/SDK.md +42 -2
- package/docs/SDK_ARTIFACT_OUTPUT.md +72 -0
- package/docs/SDK_CONTEXT_COORDINATION.md +46 -12
- package/docs/TESTING.md +14 -1
- package/docs/agent-task-token-baseline.json +5 -5
- package/docs/generated/AGENT_COMMAND_SURFACE.md +78 -78
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +76 -0
- package/marketplace.json +2 -2
- package/package.json +5 -2
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/scripts/generate-agent-capability-surfaces.mjs +20 -14
- package/sdk/public-surface.json +1245 -60
- package/dist/cli-bundle/chunks/chunk-2QLOXC3V.js +0 -3
- package/dist/cli-bundle/chunks/chunk-4JPYF536.js +0 -35
- package/dist/cli-bundle/chunks/chunk-6VDLG2FC.js +0 -13
- package/dist/cli-bundle/chunks/chunk-ION3E43Q.js +0 -197
- package/dist/cli-bundle/chunks/chunk-OAC5NIV4.js +0 -3
- package/dist/cli-bundle/chunks/chunk-TPXZIBIV.js +0 -5
- package/dist/cli-bundle/chunks/chunk-YM2YAMF7.js +0 -2
- package/dist/cli-bundle/chunks/register-list-query-Q7KII4G5.js +0 -10
- package/dist/cli-bundle/chunks/register-mutation-4WBRPXLV.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-SSENDH5B.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-267MUUS6.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-2NNFLLNG.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2QSAKMIH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-BUCG4ZI2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-EHXIKD6K.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-KGEXTMPG.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-KP2VQQVQ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-POEEAD2V.js +0 -4
- package/dist/cli-bundle/focused-chunks/chunk-XPIC53VA.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-ZT2DJS27.js +0 -155
|
@@ -1,64 +1,64 @@
|
|
|
1
|
-
import{$b as
|
|
1
|
+
import{$b as Xt,$c as ee,Ab as co,B as Ht,Bb as lo,Bh as O,C as g,Cg as Me,Ch as Ee,E as h,Gc as q,Gg as Se,H as no,Hh as To,Jb as po,Je as ko,Kb as uo,La as io,Ma as ao,Ml as xt,Na as J,Nh as Io,Q as A,Qh as Oo,Rh as Co,Sd as vo,Se as xo,Th as Ce,Va as j,Wi as Ro,Xa as so,Xc as $,Xd as H,Xh as Zt,Ya as be,Yc as K,Zc as _o,_c as W,aa as oo,ac as mo,bc as fo,bd as wo,c as x,ca as ro,cc as wt,cd as Ze,ce as bo,d as Qn,da as Z,de as kt,e as ne,ec as ke,ed as bt,f as z,g as he,gc as xe,ha as ce,hh as So,i as Zn,ih as et,jc as ho,jh as tt,kh as Eo,l as _t,lc as vt,lh as $o,mc as go,mh as oe,na as Kt,nc as yo,nh as Ue,oa as Vt,oh as Ao,pa as Yt,ph as de,u as Wt,vg as Y,x as eo,xc as B,y as to,yh as re,zg as Qt}from"./chunk-GWMXAQOD.js";import{mkdir as es,readFile as ts}from"node:fs/promises";import Lo 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]="6ed4a26f-2ae2-556a-87db-56844108757f")}catch{}})();var en=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},ns="sdk-workspace-transaction",os=/^[a-zA-Z0-9._-]+$/,rs=30,is=3e3;function Po(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!os.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function No(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 Do(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 Mo(e,t){return Lo.join(e,"transactions","sdk",`${t}.json`)}async function $e(e,t){t.updatedAt=A();let n=Mo(e,t.transactionId);await es(Lo.dirname(n),{recursive:!0}),await he(n,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`)}function as(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Re(e){return Object.assign(Object.create(null),e)}function ss(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 tn(e,t){return e===void 0?void 0:ss(e,t)}function nn(e,t,n,o){let r=tn(n,o);r===void 0?delete e[t]:e[t]=r}function jo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Fo(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function cs(e,t){if(!Fo(e.startedStepIds,t)||!Fo(e.completedStepIds,t)||!jo(e.results)||!jo(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 ds(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((l,p)=>l===n[p]),s=cs(r,n),c=as(r),d=["applying","compensating","compensated","committed"].includes(String(r.status));if(!i||!a||!s||!c||!d)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...r,results:Re(r.results),compensationData:Re(r.compensationData)}}async function ls(e,t,n,o,r){let i=r,a=i!==void 0;if(i?.status==="compensating"&&await Uo(e,i),i===void 0||i.status==="compensated"){let s=A();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:Re(),compensationData:Re()},await $e(e.pmRoot,i),await ge(e,i,"prepared")}return{journal:i,recovered:a}}async function ps(e,t,n){try{await ms(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=tn(a.result,`Step ${i.id} result`);if(a.state!=="applied"){let c=await i.prepareCompensation?.();nn(t.compensationData,i.id,c,`Step ${i.id} compensation data`),r.add(i.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>r.has(l)),await $e(e.pmRoot,t);let d=await i.apply();s=tn(d,`Step ${i.id} result`)}await ge(e,t,"step_applied",i.id),o.add(i.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>o.has(c)),nn(t.results,i.id,s,`Step ${i.id} result`),await $e(e.pmRoot,t),await ge(e,t,"step_recorded",i.id)}return await ge(e,t,"committing"),t.status="committed",await $e(e.pmRoot,t),await ge(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Re(t.results)}}catch(o){if(o instanceof en||t.status==="committed")throw o;try{await Uo(e,t)}catch(r){throw new AggregateError([o,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw o}}async function us(e,t,n){try{return ds(await ts(Mo(e,t),"utf8"),t,n)}catch(o){if(o!==null&&typeof o=="object"&&"code"in o&&ne(o))return;throw o}}async function ge(e,t,n,o){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...o===void 0?{}:{stepId:o}})}async function ms(e,t){let n=new Set,o=Re();for(let r of t){let i=await r.inspect();i.state==="applied"&&(n.add(r.id),nn(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 Uo(e,t){t.status="compensating",await $e(e.pmRoot,t),await ge(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 ge(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 ge(e,t,"step_compensated",r.id)}t.status="compensated",await $e(e.pmRoot,t),await ge(e,t,"compensated")}async function Go(e){let t=No(e.pmRoot,"Transaction pmRoot"),n=Po(e.transactionId,"Transaction id"),o=No(e.author,"Transaction author"),r=Do(e.lockTtlSeconds,rs,"Transaction lock TTL"),i=Do(e.lockWaitMs,is,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(l=>{let p=Po(l.id,"Transaction step id");if(p!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return p});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:o,steps:a,lockTtlSeconds:r,lockWaitMs:i},d=await Y(t,ns,r,o,!1,!1,i);try{let l=await us(t,n,s),p=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Re(l.results)};let u=await ls(c,n,o,s,l);return await ps(c,u.journal,p||u.recovered)}finally{await d()}}import{readFile as fs,writeFile as hs}from"node:fs/promises";import nt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="89261a49-97e5-5ffc-a81c-2409f0b529cf")}catch{}})();var Jo="# pm-cli:runtime-cache:start",on="# pm-cli:runtime-cache:end",qo=".agents/pm",gs=["runtime/","search/","locks/","transactions/","checkpoints/"],ys=["search/eval-queries.json"];async function zo(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 h("The workspace .gitignore is not writable.",g.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 Bo(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function rn(e){let t=e.replaceAll("\\","/");return nt.isAbsolute(e)||t===".."||t.startsWith("../")}function _s(e=qo){let t=Bo(e);return[Jo,...gs.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...ys.map(n=>`!${t}/${n}`),on].join(`
|
|
3
3
|
`)}async function Wo(e,t={}){let n=nt.join(e,".gitignore"),o=qo;if(t.pmRoot!==void 0){let l=Bo(nt.relative(nt.resolve(e),nt.resolve(t.pmRoot)));if(rn(l))return{path:n,changed:!1};l.length>0&&(o=l)}let r="";try{r=await zo(()=>fs(n,"utf8"))}catch(l){if(!(l instanceof Error&&"code"in l&&ne(l)))throw l}let i=r.indexOf(Jo),a=r.indexOf(on),c=(i>=0&&a>=i?`${r.slice(0,i)}${r.slice(a+on.length)}`:r).trimEnd(),d=`${c.length>0?`${c}
|
|
4
4
|
|
|
5
5
|
`:""}${_s(o)}
|
|
6
|
-
`;return d===r?{path:n,changed:!1}:(await zo(()=>hs(n,d,"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]="2c514907-377f-59f9-bfdd-a184abf7ffb7")}catch{}})();var ws=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Ge(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(vt(t.extensionName));for(let f of t.extensionNames??[])n.add(vt(f));let o=f=>n.size===0||n.has(vt(f)),r=(f,_)=>Ho(f.filter(v=>o(v.name)).map(_)),i=(f,_)=>Ho(f.filter(v=>o(v.name)).flatMap(_)),{registrations:a,commands:s,parsers:c,preflight:d,services:l,renderers:p,hooks:u}=e,m=i(a.relationship_kinds??[],f=>f.definitions.map(_=>_.kind)),y=p.overrides.filter(f=>o(f.name)&&((f.commands?.length??0)>0||f.resultDiscriminator!==void 0)).map(f=>({format:f.format,commands:[...f.commands??[]],result_discriminator:f.resultDiscriminator!==void 0})).sort((f,_)=>f.format.localeCompare(_.format)),w=r(a.assurance_providers??[],f=>f.definition.id);return{capabilities:
|
|
7
|
-
`),s=Xo(Xo(r,ze,
|
|
6
|
+
`;return d===r?{path:n,changed:!1}:(await zo(()=>hs(n,d,"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]="2c514907-377f-59f9-bfdd-a184abf7ffb7")}catch{}})();var ws=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Ge(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(vt(t.extensionName));for(let f of t.extensionNames??[])n.add(vt(f));let o=f=>n.size===0||n.has(vt(f)),r=(f,_)=>Ho(f.filter(v=>o(v.name)).map(_)),i=(f,_)=>Ho(f.filter(v=>o(v.name)).flatMap(_)),{registrations:a,commands:s,parsers:c,preflight:d,services:l,renderers:p,hooks:u}=e,m=i(a.relationship_kinds??[],f=>f.definitions.map(_=>_.kind)),y=p.overrides.filter(f=>o(f.name)&&((f.commands?.length??0)>0||f.resultDiscriminator!==void 0)).map(f=>({format:f.format,commands:[...f.commands??[]],result_discriminator:f.resultDiscriminator!==void 0})).sort((f,_)=>f.format.localeCompare(_.format)),w=r(a.assurance_providers??[],f=>f.definition.id);return{capabilities:go(e,t),commands:r(a.commands,f=>f.command),command_overrides:r(s.overrides,f=>f.command),command_handlers:r(s.handlers,f=>f.command),hooks:ws.filter(([f])=>u[f].some(_=>o(_.name))).map(([,f])=>f),flag_commands:r(a.flags,f=>f.target_command),item_types:i(a.item_types,f=>f.types.map(_=>_.name)),item_fields:i(a.item_fields,f=>f.fields.map(_=>_.name)),...m.length>0?{relationship_kinds:m}:{},migrations:i(a.migrations,f=>typeof f.definition.id=="string"?[f.definition.id]:[]),profiles:r(a.profiles,f=>f.profile.name),importers:r(a.importers,f=>f.importer),exporters:r(a.exporters,f=>f.exporter),search_providers:r(a.search_providers,f=>f.definition.name),vector_store_adapters:r(a.vector_store_adapters,f=>f.definition.name),...w.length>0?{assurance_providers:w}:{},parser_overrides:r(c.overrides,f=>f.command),service_overrides:r(l.overrides,f=>f.service),renderer_overrides:r(p.overrides,f=>f.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:d.overrides.filter(f=>o(f.name)).length,preflight_ownership:d.overrides.filter(f=>o(f.name)).map(f=>({commands:[...f.commands??[]]}))}}function Ho(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]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var vs="PM_SOURCE_CONTEXT_ACCESS",bs="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Ko(e){let t=e[vs],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",o=n==="read_only"&&e[bs]?.trim()==="1";return{access:n,write_override_applied:o,source_writes_allowed:n==="write"||o}}import{readFile as Et,realpath as an,writeFile as ks}from"node:fs/promises";import{execFile as xs}from"node:child_process";import L from"node:path";import{promisify as Ss}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]="5e1810a5-04b8-5929-8eee-7a63f1684860")}catch{}})();var cn=Ss(xs),St="# pm-cli:merge-drivers:start",Qo="# pm-cli:merge-drivers:end",ze="# pm-cli:merge-drivers:v2:start",sn="# pm-cli:merge-drivers:v2:end",Es="merge-fence";function Vo(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Zo(){let e=ce(import.meta.url,["../../.."]);return`${Vo(process.execPath)} ${Vo(L.join(e,"dist","cli.js"))}`}var er=[{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 $s(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),o=e.environment.PM_SOURCE_PM_PATH?.trim(),r=Ko(e.environment),i=!!(n&&o),a=t===void 0&&i&&(e.dryRun||r.source_writes_allowed);if(t!==void 0){let s=j(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:L.resolve(o),workspace_start:L.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:r}:{pm_root:i?j(e.cwd,".agents/pm"):j(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:r}}async function dn(e){try{let{stdout:t}=await cn("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await an(t.trim())}catch{return null}}async function tr(e){let t=await dn(e);if(t===null)throw new h("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function ln(e,t){return L.relative(e,t).replaceAll("\\","/")}function le(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Yo(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 As(e,t){let n=Yo(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let o=Yo(e,n.nextOffset+1);if(o===null||e.slice(o.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(L.basename(n.value))||L.basename(o.value)!=="cli.js"||L.basename(L.dirname(o.value))!=="dist"||!await x(n.value)||!await x(o.value))return!1;try{let r=L.dirname(L.dirname(o.value)),i=JSON.parse(await Et(L.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 pn(e,t){let n=e.length>0?`${e}/`:"",o=[`${le(`${n}**/*.toon`)} merge=pm-item-toon`,`${le(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)o.push(`${le(`${n}${r}/*.toon`)} merge=pm-item-toon`),o.push(`${le(`${n}${r}/*.md`)} merge=pm-item-markdown`);return o.push(`${le(`${n}**/*.jsonl`)} merge=pm-relationship`),o.push(`${le(`${n}history/*.jsonl`)} merge=pm-history`),o.push(`${le(`${n}settings.json`)} merge=pm-json`),o.push(`${le(`${n}**/*.json`)} merge=pm-json`),o.push(`${le(`${n}extensions/**`)} -merge`),o.push(`${le(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),o}function Xo(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 nr(e,t,n){let o=L.join(e,".gitattributes"),r="";try{r=await Et(o,"utf8")}catch(d){if(!(d instanceof Error&&"code"in d&&ne(d)))throw d}let i=[ze,...t,sn].join(`
|
|
7
|
+
`),s=Xo(Xo(r,ze,sn),St,Qo).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):[],m=
|
|
12
|
-
`}function pr(e,t){let n=e.fields.find(a=>$(a.key)===t.key),o=n!==void 0,r=e.fields.filter(a=>$(a.key)!==t.key),i={...n,key:t.key,type:t.type,commands:[...t.commands]};return sr(i,"description",t.description),sr(i,"cli_flag",t.cliFlag),t.cliAliases.length>0?i.cli_aliases=[...t.cliAliases]:delete i.cli_aliases,cr(i,"required",t.required),cr(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)=>$(a.key).localeCompare($(s.key))),{file:{fields:r},definition:i,replaced:o}}function ur(e,t){let n=$(t);if(n.length===0)throw new Error("Field key must not be empty.");let o=[],r=e.fields.filter(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 sr(e,t,n){let o=e;n!==void 0&&n.length>0?o[t]=n:delete o[t]}function cr(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]="3eac0218-43c9-5bd2-8eaf-589d02d2c8ad")}catch{}})();var
|
|
13
|
-
`}function fr(e,t,n){let o=e.statuses.slice(),r=o.findIndex(s=>$(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 hr(e,t){let n=$(t);if(n.length===0)throw new Error("Status id must not be empty.");if(Pe.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...Pe].join(", ")}.`);let o=e.statuses.slice(),r=o.findIndex(a=>$(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
|
|
14
|
-
`}function xr(e,t){if(t.kind==="rename-type"){let o=oe(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=Je(e).fields;return{source:o.some(r=>r.key===t.from),target:o.some(r=>r.key===t.to)}}let n=Be(e).statuses;return{source:n.some(o=>o.id===t.from),target:n.some(o=>o.id===t.to)}}function
|
|
15
|
-
`)}function
|
|
16
|
-
`)}import yc from"node:path";import{mkdir as _c}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]="e3f016bb-8add-5765-bb1a-a7b22423f8d1")}catch{}})();var ot=["agile","ops","research"],mc={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 At(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: ${ot.join(", ")}.`)}function rt(e){return mc[e].map(t=>tt(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]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();var fc=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function hc(e){let t=fc.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function gc(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Er(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=hc(s);if(c===void 0)continue;let d=r.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<o&&d.examples.push(s),r.set(c,d)}let i=[];for(let[a,s]of r.entries()){if(s.count<n)continue;let c=gc(a);i.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:xo(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]="2ab8a5a9-dbea-526f-a541-b7ca2b106ac5")}catch{}})();var $f=["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"],Tt="schema-types",$r="schema-statuses",Ar="schema-fields";function Te(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 Af(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r;try{r=tt({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(m){throw new h(m instanceof Error?m.message:String(m),g.USAGE)}let i=await O(o),a=W(i.schema),s=ee(o,a.files.types,K.types),c=[],d=H(t.author,i.author_default),l=re(i),p=await Y(o,Tt,i.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await z(s),y;try{y=oe(m)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.GENERIC_FAILURE)}try{So(r,y);let w=new Map,f=J(i,B());for(let[_,v]of Object.entries(f.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!w.has(k)&&w.set(k,_)}Eo(r,y,w)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}u=Ue(y,r),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await Te({pmRoot:o,filePath:s,raw:de(u.file),op:"schema:add-type",author:d,settings:i}),await it(o,[u.definition],c,"schema:add-type-folder"),c.push(...await q({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await Tr(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 _e(e){if(!await x(be(e)))throw new h(`Tracker is not initialized at ${e}. Run pm init first.`,g.NOT_FOUND)}async function Tr(e,t){try{let n=await rr(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 wc(e,t,n,o){let r=J(t,B()),i=o.trim().toLowerCase();return(await Ce(e,t.item_format,r.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===i).length}async function vc(e,t,n,o){let r=J(t,B()),i=Qe(n),a=$(o);return(await Ce(e,t.item_format,r.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(i.alias_to_id.get($(d))??$(d))===a}).length}async function bc(e,t,n,o,r){if(r.length===0||Pe.has(r))return;let i=await vc(t,n,o,r);i>0&&e.push(`items_using_status:${i}`);let a=Ir(o.workflow,r);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function Ir(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&&$(o)===t).map(([o])=>o)}async function Tf(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r=await O(o),i=W(r.schema),a=ee(o,i.files.types,K.types),s=[],c=H(t.author,r.author_default),d=re(r),l=await Y(o,Tt,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await z(a),m;try{m=oe(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=$o(m,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 wc(o,r,i,y);w>0&&s.push(`items_using_type:${w}`)}await Te({pmRoot:o,filePath:a,raw:de(p.file),op:"schema:remove-type",author:c,settings:r}),s.push(...await q({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return p.removed&&await Tr(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 _n(e,t){return ee(e,t.files.statuses,K.statuses)}function It(e,t){return ee(e,t.files.fields,K.fields)}function Or(e,t){return ee(e,t.files.types,K.types)}async function it(e,t,n,o){for(let r of t){let i=so(r.folder??ao(r.name)),a=yc.join(e,i);await x(a)||(await _c(a,{recursive:!0}),n.push(...await q({path:a,scope:"project",op:o})))}}function wn(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 kc(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 xc(e){let t=new Map;for(let n of e){let o=$(n.id);if(o.length!==0){t.set(o,o);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let i=$(r);i.length>0&&!t.has(i)&&t.set(i,o)}}}return t}async function If(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r;try{r=mr({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}let i=await O(o),a=W(i.schema),s=_n(o,a),c=Qe(a);try{fn(r,c.alias_to_id)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}let d=kc(c.by_id.get(r.id)),l=[],p=H(t.author,i.author_default),u=re(i),m=await Y(o,$r,i.locks.ttl_seconds,p,!!t.force,u.force_required_for_stale_lock,i.locks.wait_ms),y;try{let w=await z(s),f;try{f=Be(w)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let _=xc(f.statuses);try{fn(r,_)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.USAGE)}y=fr(f,r,d),await Te({pmRoot:o,filePath:s,raw:We(y.file),op:"schema:add-status",author:p,settings:i}),l.push(...await q({path:s,scope:"project",op:"schema:add-status"}))}finally{await m()}return{action:"add-status",registered:!0,replaced:y.replaced,status:y.definition,file:{path:s,statuses:y.file.statuses.length},warnings:Ie(l),generated_at:A()}}async function Of(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r=await O(o),i=W(r.schema),a=_n(o,i),s=[],c=H(t.author,r.author_default),d=re(r),l=await Y(o,$r,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await z(a),m;try{m=Be(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=hr(m,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=$(p.definition?.id??e);await bc(s,o,r,i,y),await Te({pmRoot:o,filePath:a,raw:We(p.file),op:"schema:remove-status",author:c,settings:r}),s.push(...await q({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:a,statuses:p.file.statuses.length},warnings:Ie(s),generated_at:A()}}function Cr(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 Sc(e,t,n){return{...Cr(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 Rr(e){return{id:e.id,source:Pe.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 Pr(e,t,n){let o=e.toLowerCase();return n.has(o)?"extension":t.has(o)?"custom":"builtin"}function Ec(){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 $c(e){let t=Qe(e),n=[],o=[];for(let r of t.definitions){let i=Rr(r);i.source==="builtin"?n.push(i):o.push(i)}return{builtin:n,custom:o}}async function at(e){let t=j(process.cwd(),e.path);await _e(t);let n=await O(t),o=W(n.schema),r=ee(t,o.files.types,K.types),i=_n(t,o),a=J(n,B()),s=Ec(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:r,statusesPath:i,byType:a.by_type,customNames:c,extensionProvenance:s,schema:o}}async function Cf(e){let t=await at(e),n=[],o=[],r=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Pr(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=Cr(s);c==="extension"?r.push(d):c==="custom"?o.push(d):n.push(d)}let i=$c(t.schema),a=bt(t.schema).definitions.map(wn);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 Rf(e,t){let n=(e??"").trim();if(n.length===0)throw new h("Type name must not be empty.",g.USAGE);let o=await at(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 "${et(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Sc(r,Pr(r.name,o.customNames,new Set(o.extensionProvenance.keys())),o.extensionProvenance.get(r.name.toLowerCase())),file:{path:o.typesPath},generated_at:A()}}async function Pf(e,t){let n=$(e);if(n.length===0)throw new h("Status id must not be empty.",g.USAGE);let o=await at(t),r=Qe(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 "${et(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Rr(a),file:{path:o.statusesPath},generated_at:A()}}async function Nf(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r;try{r=lr({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 O(o),a=W(i.schema),s=It(o,a),c=[],d=kt(r.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=H(t.author,i.author_default),p=re(i),u=await Y(o,Ar,i.locks.ttl_seconds,l,!!t.force,p.force_required_for_stale_lock,i.locks.wait_ms),m;try{let y=await z(s),w;try{w=Je(y)}catch(f){throw new h(f instanceof Error?f.message:String(f),g.GENERIC_FAILURE)}m=pr(w,r),await Te({pmRoot:o,filePath:s,raw:qe(m.file),op:"schema:add-field",author:l,settings:i}),c.push(...await q({path:s,scope:"project",op:"schema:add-field"}))}finally{await u()}return{action:"add-field",registered:!0,replaced:m.replaced,field:m.definition,file:{path:s,fields:m.file.fields.length},warnings:Ie(c),generated_at:A()}}async function Ac(e,t,n,o){let r=J(t,B());return(await Ce(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 Df(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r=await O(o),i=W(r.schema),a=It(o,i),s=[],c=H(t.author,r.author_default),d=re(r),l=await Y(o,Ar,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await z(a),m;try{m=Je(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=ur(m,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=$(p.definition?.key??e),w=$(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(w.length>0){let f=await Ac(o,r,i,w);f>0&&s.push(`items_using_field:${f}`)}await Te({pmRoot:o,filePath:a,raw:qe(p.file),op:"schema:remove-field",author:c,settings:r}),s.push(...await q({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:a,fields:p.file.fields.length},warnings:Ie(s),generated_at:A()}}async function jf(e){let t=await at(e),n=bt(t.schema).definitions.map(wn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:It(t.pmRoot,t.schema)},generated_at:A()}}async function Ff(e,t){let n=$(e);if(n.length===0)throw new h("Field key must not be empty.",g.USAGE);let o=await at(t),r=bt(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 "${et(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:wn(r),file:{path:It(o.pmRoot,o.schema)},generated_at:A()}}async function Lf(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r;try{let w=At(e);if(w===void 0)throw new Error(`Type preset name is required. Allowed: ${ot.join(", ")}.`);r=w}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}let i=await O(o),a=W(i.schema),s=Or(o,a),c=[],d=H(t.author,i.author_default),l=re(i),p=[],u=[],m,y=await Y(o,Tt,i.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms);try{let w=await z(s),f;try{f=oe(w)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let _=f;for(let v of rt(r)){let k=Ue(_,v);_=k.file,(k.replaced?u:p).push(k.definition.name)}m=_.definitions.length,await Te({pmRoot:o,filePath:s,raw:de(_),op:"schema:apply-preset",author:d,settings:i}),await it(o,rt(r),c,"schema:apply-preset-folder"),c.push(...await q({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:m},warnings:Ie(c),generated_at:A()}}function Tc(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 Mf(e,t){let n=j(process.cwd(),t.path);await _e(n);let o=await O(n),r=W(o.schema),i=Or(n,r),a=Tc(e.minCount),s=J(o,B()),d=(await Ce(n,o.item_format,s.type_to_folder,[],r)).map(k=>typeof k.title=="string"?k.title:""),l=Er(d,{minCount:a}),p=[],u=[],m=[],y=[],w;if(!e.apply){let k;try{k=oe(await z(i))}catch(T){throw new h(T instanceof Error?T.message:String(T),g.GENERIC_FAILURE)}return w=k.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:l,registered:u,replaced:m,skipped:y,file:{path:i,definitions:w},warnings:p,generated_at:A()}}let f=H(e.author,o.author_default),_=re(o),v=await Y(n,Tt,o.locks.ttl_seconds,f,!!e.force,_.force_required_for_stale_lock,o.locks.wait_ms);try{let k=await z(i),T;try{T=oe(k)}catch(C){throw new h(C instanceof Error?C.message:String(C),g.GENERIC_FAILURE)}let R=T;for(let C of l){if(C.shadows_builtin){y.push({name:C.name,reason:"shadows_builtin"});continue}let se;try{se=tt({name:C.name})}catch{y.push({name:C.name,reason:"invalid_type_token"});continue}let fe=Ue(R,se);R=fe.file,(fe.replaced?m:u).push(fe.definition.name)}w=R.definitions.length,await Te({pmRoot:n,filePath:i,raw:de(R),op:"schema:infer-types",author:f,settings:o}),await it(n,R.definitions.filter(C=>u.includes(C.name)||m.includes(C.name)),p,"schema:infer-types-folder"),p.push(...await q({path:i,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:l,registered:u,replaced:m,skipped:y,file:{path:i,definitions:w},warnings:Ie(p),generated_at:A()}}function Uf(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 "${et(e.type.name)}" "<title>"`}function Gf(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 zf(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 Jf(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 qf(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
|
|
19
|
-
`)}function
|
|
20
|
-
`)}function
|
|
21
|
-
`)}function
|
|
22
|
-
`)}var Qf={workflowSlotsReferencing:Ir};import jr from"node:fs/promises";import De 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]="6fc24a7c-a359-51fd-a432-4c8037d10e9e")}catch{}})();var Ot=["extensions","docs","examples","assets","prompts"],Oc=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 Cc(e){return Ot.includes(e)}function Rc(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 Pc(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(!Cc(o))continue;let i=Rc(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 vn(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,o)=>n.localeCompare(o)):void 0}function Nr(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 Nc(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 Dc(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 jc(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:Nc(t.links),media:Dc(t.media),tags:vn(t.tags)};return Object.values(n).some(o=>o!==void 0)?n:void 0}async function st(e){let t=De.join(e,"package.json");if(!await x(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await jr.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:vn(o.keywords),package_homepage:typeof o.homepage=="string"?o.homepage:void 0,package_repository_url:Nr(o.repository),package_bugs_url:Nr(o.bugs),aliases:vn(a.aliases),resources:Pc(r),catalog:jc(a.catalog)}}async function Dr(e){if(!await x(e))return[];let t=await jr.readdir(e,{withFileTypes:!0}),n=[];for(let o of t){if(!o.isDirectory())continue;let r=De.join(e,o.name);await x(De.join(r,"manifest.json"))&&n.push(r)}return n.sort((o,r)=>o.localeCompare(r))}async function Ct(e){if(await x(De.join(e,"manifest.json")))return[e];let n=(await st(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=De.resolve(e,r);if(!Q(e,i))throw new h(`Package extension entry "${r}" resolves outside package root.`,g.USAGE);if(await x(De.join(i,"manifest.json"))){o.add(i);continue}for(let a of await Dr(i))o.add(a)}if(n.length===0)for(let r of Oc.extensions)for(let i of await Dr(De.join(e,r)))o.add(i);return[...o].sort((r,i)=>r.localeCompare(i))}import{execFile as od}from"node:child_process";import P from"node:fs/promises";import Tn from"node:os";import S from"node:path";import{fileURLToPath as rd}from"node:url";import{promisify as id}from"node:util";import ad from"npm-package-arg";import{extract as sd,list as cd}from"tar";import Hc from"node:fs/promises";import ie from"node:path";import Fr from"node:fs/promises";import bn 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]="af718efb-d1cf-5adc-9518-c858627e1b54")}catch{}})();function X(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 Rt(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 kn(e){return fo(e)}async function Fc(e){try{let t=JSON.parse(await Fr.readFile(bn.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 Lc(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 Fc(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=bn.join(e,"manifest.json");if(!await x(n))throw new h(`Extension manifest is missing at "${n}".`,g.USAGE);let o;try{o=JSON.parse(await Fr.readFile(n,"utf8"))}catch(a){throw new h(`Failed to parse extension manifest at "${n}": ${Mc(a)}`,g.USAGE)}let r=kn(o);if(!r)throw new h(`Extension manifest at "${n}" is invalid.`,g.USAGE);let i=bn.resolve(e,r.entry);if(!Q(e,i))throw new h(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await x(i))throw await Lc(r,i,t);if(!await ho(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 Mc(e){return e instanceof Error?e.message:String(e)}import xn from"node:fs/promises";import Uc 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]="159d7bbd-1d2a-503d-b3ce-f32dcc6f6547")}catch{}})();var Gc=".managed-extensions.json",Pt=1;function ct(e){return Uc.join(e,Gc)}function zc(){return{version:Pt,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 Lr(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 Z(e){return typeof e=="string"?e:void 0}function Jc(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 qc(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:Z(t.name),package:Z(t.package),version:Z(t.version),repository:Z(t.repository),owner:Z(t.owner),repo:Z(t.repo),ref:Z(t.ref),subpath:Z(t.subpath),commit:Z(t.commit)}}function Bc(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Jc(t))return null;let n=qc(t.source);if(!n)return null;let o=uo(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:X(t.capabilities),contributions:o,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Z(t.last_update_check_at),last_update_remote_commit:Z(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Z(t.update_error)}}function Wc(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Pt||!Array.isArray(t.entries))return null;let n=[];for(let o of t.entries){let r=Bc(o);r&&n.push(r)}return{version:Pt,updated_at:Z(t.updated_at)??A(),entries:dt(n)}}async function we(e){let t=ct(e),n=zc();try{let o=await xn.readFile(t,"utf8"),r=JSON.parse(o),i=Wc(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&&ne(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 je(e,t){let n=ct(e),o={version:Pt,updated_at:A(),entries:dt(t.entries)};await xn.mkdir(e,{recursive:!0}),await xn.writeFile(n,`${JSON.stringify(o,null,2)}
|
|
23
|
-
`,"utf8")}function lt(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:A(),entries:dt(n)}}async function Mr(e,t,n,o){let r=t.entries.find(a=>b(a.name)===b(n));if(!r)return t;let i=lt(t,{...r,contributions:o});return await je(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]="259656b0-09b7-52c5-8f54-52ac29eec607")}catch{}})();var
|
|
24
|
-
${i}`,g.GENERIC_FAILURE)}}function
|
|
25
|
-
${s}`,g.GENERIC_FAILURE)}}function
|
|
26
|
-
`,"utf8");try{await Promise.all([P.rm(S.join(e,"package-lock.json"),{force:!0}),P.rm(S.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
|
|
27
|
-
`,"utf8")}}function Ed(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&jt in t)return!0;return!1}function $d(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let o={...n};delete o[jt],Object.keys(o).length===0?delete e[t]:e[t]=o}}async function Ad(e){let t=ce(import.meta.url,["../../.."]),[n,o]=jt.split("/"),r=S.join(e,"node_modules",n),i=S.join(r,o);await P.mkdir(r,{recursive:!0}),await P.rm(i,{recursive:!0,force:!0}),await P.symlink(t,i,Td(process.platform))}function Td(e){return e==="win32"?"junction":"dir"}function Id(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{ad.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 Od(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===jt||typeof r!="string"||r.trim().length===0||t.has(o))continue;let i=r.trim();t.set(o,Id(o,i))}return[...t.values()]}async function ut(e,t){let n=await Ct(e);if(n.length===1)return n[0];if(n.length>1){let o=n.map(r=>S.relative(e,r).replaceAll(S.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 Cd(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(S.posix.join(".agents/pm/extensions",t.subpath)),n.push(S.posix.join(".custom/pm-extensions",t.subpath)),n.push(S.posix.join(".custom/pm-extension",t.subpath)));for(let r of n){let i=S.resolve(e,r);if(Q(e,i)&&await x(S.join(i,"manifest.json")))return{directory:i,resolved_subpath:r}}if(await x(S.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let o=await ut(e,t.input);return{directory:o,resolved_subpath:S.relative(e,o).replaceAll(S.sep,"/")}}function Rd(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 Pd(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Rd(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?S.resolve(i.trim()):"";$n?.key!==a&&($n={key:a,aliases:await Nt()}),o=$n.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 Zr(e){if(e.kind==="local"){let o;try{o=await P.stat(e.absolute_path)}catch{throw await Pd(e)}if(o.isFile()&&Vr(e.absolute_path)){let i=await Yr(e.absolute_path);return{source:e,directory:i.directory,source_root:S.dirname(i.directory),resolved_subpath:S.relative(S.dirname(i.directory),i.directory).replaceAll(S.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 kd(e);return{source:e,directory:o.directory,source_root:S.dirname(o.directory),cleanup:o.cleanup,resolved_subpath:S.relative(S.dirname(o.directory),o.directory).replaceAll(S.sep,"/"),npm_package:o.package,npm_version:o.version}}let t=await P.mkdtemp(S.join(Tn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Dt(n);let o=await Dt(["-C",t,"rev-parse","HEAD"]),r=await Cd(t,e);return{source:e,directory:r.directory,source_root:t,resolved_subpath:r.resolved_subpath,commit:o,cleanup:async()=>{await P.rm(t,{recursive:!0,force:!0})}}}catch(o){throw await P.rm(t,{recursive:!0,force:!0}),o}}async function Qr(e,t){if(!await x(e)||!await x(t))return!1;let[n,o]=await Promise.all([P.realpath(e),P.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]="30dfc6e4-27c5-56c0-981b-94e85b780f1f")}catch{}})();var On=1,Fe="2026.6.24",Nd=">=22.18.0",Dd={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},ei=new Set([...ko.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Ro).map(e=>e.toLowerCase()),"scaffold"]),jd="^6.0.0",Fd="^22.0.0",oi=["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 ti(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function ri(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 ii(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 Ld={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"],ai={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"]},Md={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"]'},Ud={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."},Gd={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."},si="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",zd={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."]},Jd={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."]},qd={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`."]},Bd={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 ci(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 di(e,t){return e==="schema"?qd[t]:e==="profile"?Bd[t]:Jd[t]}function Wd(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&&ei.has(r));return`${(ei.has(n)||i?["starter",...t]:t).join(" ")} ping`}function li(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 Hd(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`,d=e.replace(/-/g,""),l=d===s?[]:[d],p=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`;return[...a,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(u)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...a,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...li(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 Kd(e,t,n){let o=n==="hooks",r=n==="search",i=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",p=n==="services",u=Md[n],m=e,y=`${e}s`,w=`${e.replace(/-/g,"_")}_note`,f=`${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,"});",""]:[],k=r?Cn(e,t,"search",u):[],T=i?Cn(e,t,"importers",u):[],R=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 {",...ti(ri({extensionName:e,itemTypeName:m,itemTypeFolder:y,fieldName:w,migrationId:f,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],C=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 {",...ti(ii(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],se=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,"});",""]:[],fe=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],E=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],G=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";',"",...oi,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...v,...k,...T,...R,...C,...se,...fe,...E,...G,`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 Vd(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 Yd={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"},Xd={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 Zd(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 Qd(e,t,n){let o=[],r=[...Zd(e,t,n)],i=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,p=e.replace(/-/g,""),u=p===d?[]:[p],m=`${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(m)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(u)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(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({",...li(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 el(e,t,n){let o=Qd(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 Cn(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`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${o},`," });"],u=m=>[...p," let deactivated = false;"," try {",...m.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 query = await ext.runSearchProvider({",` provider: ${JSON.stringify(r)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings: {} as PmSettings,"," 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: {} as PmSettings, 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: {} as PmSettings },"," });",' 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(ri({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(ii(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 tl(e,t,n){let o=n==="parser",r=JSON.stringify([...ai[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" };',"",...oi,`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,"});","",...Cn(e,t,n,r)].join(`
|
|
30
|
-
`)}function
|
|
31
|
-
`)}function
|
|
32
|
-
`,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...
|
|
33
|
-
`),l=`${JSON.stringify(
|
|
34
|
-
`,p=
|
|
35
|
-
`,y=
|
|
36
|
-
`),_=
|
|
37
|
-
`);return{"package.json":m,"manifest.json":c,"index.ts":r?
|
|
10
|
+
`;return c===r?{path:o,changed:!1}:(n||await ks(o,c,"utf8"),{path:o,changed:!0})}function or(e){let t=J(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,o)=>n.localeCompare(o))}async function um(e,t){let n=L.resolve(e),o=null,r="",i=n;for(let v=0;v<8;v+=1){let k=L.join(i,".gitattributes");try{let R=await Et(k,"utf8");if(R.includes(ze)||R.includes(St)){o=i,r=R;break}}catch{}let T=L.dirname(i);if(T===i)break;i=T}if(o===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let a=L.join(o,".gitattributes"),s=r.includes(ze),c=s?ze:St,d=s?sn:Qo,l=r.indexOf(c),p=r.indexOf(d),u=p>l?r.slice(l+c.length,p).split(`
|
|
11
|
+
`).map(v=>v.trim()).filter(v=>v.length>0):[],m=pn(ln(o,n),t),y=new Set(u),w=new Set(m),f=m.filter(v=>!y.has(v)),_=u.filter(v=>!w.has(v));return{status:f.length>0||_.length>0?"drift":"ok",path:a,missing_patterns:f,stale_patterns:_,schema_scope:"project"}}async function mm(e){let t=Zo(),n=[],o=[];for(let r of er){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 cn("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),d=c.trim();d!==s&&!await As(d,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 rr(e){let t;try{t=await tr(L.resolve(e))}catch{return{status:"no_git"}}let n=ln(t,L.resolve(e)),o=await O(e),r=H(void 0,o.author_default),i=await Y(e,Es,o.locks.ttl_seconds,r,!1,re(o).force_required_for_stale_lock,o.locks.wait_ms);try{let a=L.join(t,".gitattributes"),s;try{s=await Et(a,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&ne(p))return{status:"not_installed",path:a};throw p}if(!s.includes(ze)&&!s.includes(St))return{status:"not_installed",path:a};let c=await O(e),d=or(c),l=await nr(t,pn(n,d),!1);return{status:l.changed?"refreshed":"unchanged",path:l.path}}finally{await i()}}async function fm(e,t){let n=$s({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),o=n.pm_root;if(!await x(be(o)))throw new h(`Tracker is not initialized at ${o}. Run pm init first.`,g.NOT_FOUND);let r=await tr(n.workspace_start);return un({pmRoot:o,workspaceRoot:r,dryRun:e.dryRun===!0})}async function un(e){let t=L.resolve(e.pmRoot),n=L.resolve(e.workspaceRoot),o=e.dryRun===!0,r,i;try{[r,i]=await Promise.all([an(t),an(n)])}catch(m){throw new h(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(m)}`,g.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=ln(i,r);if(rn(a))throw new h(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let s=await O(r),c=or(s),d=pn(a,c),l=[],p=Zo();for(let m of er)l.push({key:`merge.${m.key}.name`,value:m.name}),l.push({key:`merge.${m.key}.driver`,value:`${p} merge driver ${m.artifact} "%O" "%A" "%B"${m.itemPath===void 0?"":` --item-path ${m.itemPath}`}`});if(!o)try{for(let m of l)await cn("git",["config","--local",m.key,m.value],{cwd:i,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new h(`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.`,g.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 nr(i,d,o);return{ok:!0,dry_run:o,workspace_root:i,pm_root:r,gitattributes:{path:u.path,changed:u.changed,patterns:d,schema_scope:"project"},git_config:l,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:A()}}import{createHash as _r}from"node:crypto";import Ne from"node:fs/promises";import Ke 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]="2b5a573e-1e36-58b9-b93b-4a4088f71e9a")}catch{}})();var Ts=new Set(Vt),Is=new Set(Yt),ir=new Set([...eo.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"]),Os=["create","update"];function dr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function ar(e){return e.replaceAll("_","-")}function Cs(e,t){let n=new Set;for(let o of e){let r=dr(o);r.length>0&&r!==t&&n.add(r)}return[...n].sort((o,r)=>o.localeCompare(r))}function Rs(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 Ps(e){let t=new Set,n=[];for(let o of e??[]){let r=o.trim().toLowerCase();if(r.length!==0){if(!Is.has(r))throw new Error(`Invalid field command "${o}". Allowed: ${Yt.join(", ")}.`);t.has(r)||(t.add(r),n.push(r))}}return e===void 0||n.length===0?[...Os]:n}function lr(e){let t=$(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(ir.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: ${[...ir].sort((l,p)=>l.localeCompare(p)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!Ts.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${Vt.join(", ")}.`);let o=n,r=Ps(e.commands),i=dr(e.cliFlag),a=i.length>0&&i!==ar(t)?i:void 0,s=a??ar(t),c=Cs(e.aliases??[],s),d=e.description?.trim();return{key:t,type:o,commands:r,description:d&&d.length>0?d:void 0,cliFlag:a,cliAliases:c,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:Rs(e.requiredTypes)}}function Ns(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 Ds(e){let t=Ns(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 Je(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:Ds(t)}}function qe(e){return`${JSON.stringify({fields:e.fields},null,2)}
|
|
12
|
+
`}function pr(e,t){let n=e.fields.find(a=>$(a.key)===t.key),o=n!==void 0,r=e.fields.filter(a=>$(a.key)!==t.key),i={...n,key:t.key,type:t.type,commands:[...t.commands]};return sr(i,"description",t.description),sr(i,"cli_flag",t.cliFlag),t.cliAliases.length>0?i.cli_aliases=[...t.cliAliases]:delete i.cli_aliases,cr(i,"required",t.required),cr(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)=>$(a.key).localeCompare($(s.key))),{file:{fields:r},definition:i,replaced:o}}function ur(e,t){let n=$(t);if(n.length===0)throw new Error("Field key must not be empty.");let o=[],r=e.fields.filter(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 sr(e,t,n){let o=e;n!==void 0&&n.length>0?o[t]=n:delete o[t]}function cr(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]="3eac0218-43c9-5bd2-8eaf-589d02d2c8ad")}catch{}})();var js=new Set(Kt),Pe=new Set(_o.map(e=>$(e.id)).filter(e=>e.length>0));function Fs(e){let t=new Set;for(let n of e){let o=$(n);o.length>0&&t.add(o)}return[...t].sort((n,o)=>n.localeCompare(o))}function mr(e){let t=$(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(Pe.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...Pe].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(!js.has(c))throw new Error(`Invalid status role "${s}". Allowed roles: ${Kt.join(", ")}.`);a.has(c)||(a.add(c),n.push(c))}}}let o=e.aliases===void 0?void 0:Fs(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 Ls(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 Ms(e){let t=Ls(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 Be(e){if(e==null||e.trim().length===0)return{statuses:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/statuses.json contains invalid JSON.")}return{statuses:Ms(t)}}function We(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
|
|
13
|
+
`}function fr(e,t,n){let o=e.statuses.slice(),r=o.findIndex(s=>$(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 hr(e,t){let n=$(t);if(n.length===0)throw new Error("Status id must not be empty.");if(Pe.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...Pe].join(", ")}.`);let o=e.statuses.slice(),r=o.findIndex(a=>$(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 mn(e,t){let n=[e.id,...e.aliases??[]];for(let o of n){let r=$(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]="cd777de3-665f-5e01-ac98-8986f2a5a4c2")}catch{}})();function ye(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function wr(e){let t=ye(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function vr(e,t){let n=hn(e),o=ye(t,"migrationScope");return`auto-${_r("sha256").update(JSON.stringify({scope:o,request:n})).digest("hex").slice(0,20)}`}function hn(e){let t=e.kind==="rename-type"?{kind:e.kind,from:ye(e.from,"source"),to:ye(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:$(ye(e.from,"source")),to:$(ye(e.to,"target")),...e.type===void 0?{}:{type:ye(e.type,"type")}}:{kind:e.kind,from:$(ye(e.from,"source")),to:$(ye(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Us(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Gs(e,t,n){let o=W(t.schema),r=Us(n);return ee(e,o.files[r],K[r])}function br(e,t){return Ke.join(e,"transactions","schema",`${t}-plan.json`)}function $t(e){return e.length===0?null:JSON.parse(e)}async function He(e){let t=await z(e);return{exists:t!==null,raw:t??""}}async function kr(e,t){t.exists?await he(e,t.raw):await Ne.rm(e,{force:!0})}function zs(e,t,n){let o=oe(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 de(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 de(o)}function Js(e,t,n){let o=Je(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 qe(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 qe(o)}function qs(e,t,n){let o=Be(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 We(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 We(o)}function Bs(e,t,n){return t.kind==="rename-type"?zs(e,t,n):t.kind==="rename-field"?Js(e,t,n):qs(e,t,n)}function Ae(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Ve(e){return Array.isArray(e)?e.map(t=>gn(t)).filter(t=>t!==void 0):[]}function Ws(e,t){for(let n of Ve(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(o=>Ae(o,t)));for(let n of Ve(e.type_workflows))n.type=Ae(n.type,t)}function Hs(e,t){for(let o of Ve(e.definitions))o.default_status=Ae(o.default_status,t);let n=gn(e.workflow);if(n)for(let[o,r]of Object.entries(n))n[o]=Ae(r,t);for(let o of Ve(e.type_workflows))Array.isArray(o.allowed_transitions)&&(o.allowed_transitions=o.allowed_transitions.map(r=>Array.isArray(r)?r.map(i=>Ae(i,t)):r))}function Ks(e,t){for(let n of Ve(e.definitions)){for(let o of["required_create_fields","required_create_repeatables"])Array.isArray(n[o])&&(n[o]=n[o].map(r=>Ae(r,t)));for(let o of["options","command_option_policies"])for(let r of Ve(n[o])){let i=o==="options"?"key":"option";r[i]=Ae(r[i],t)}}}function Vs(e,t){let n=gn(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]=Ae(n[o],t)}function fn(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"?Ws(o,t):t.kind==="rename-field"?Ks(o,t):Hs(o,t),Vs(o,t),`${JSON.stringify(o,null,2)}
|
|
14
|
+
`}function xr(e,t){if(t.kind==="rename-type"){let o=oe(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=Je(e).fields;return{source:o.some(r=>r.key===t.from),target:o.some(r=>r.key===t.to)}}let n=Be(e).statuses;return{source:n.some(o=>o.id===t.from),target:n.some(o=>o.id===t.to)}}function Ys(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 Xs(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 Sr(e,t){let n=hn(t.request),o=t.migrationId===void 0?vr(n,t.migrationScope??"plan"):wr(t.migrationId),r=e.map(c=>Xs(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),i=_r("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 Qs(e){let t=J(e.settings,B()),n=[...new Set(Object.values(t.type_to_folder))],o=await Io(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 To({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 Ce(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Zs(e,t){let n=await z(br(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 h(`Stored schema migration plan "${t}" is invalid: ${no(o)}`,g.GENERIC_FAILURE)}}async function ec(e,t){let n=br(e,t.migration_id);await Ne.mkdir(Ke.dirname(n),{recursive:!0});let o={schema_version:1,plan:t,created_at:new Date().toISOString()};await he(n,`${JSON.stringify(o,null,2)}
|
|
15
|
+
`)}function tc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function nc(e){let t=await Oo(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new h(`Schema migration item "${e.id}" no longer exists.`,g.NOT_FOUND);return(await Co(t,{schema:e.settings.schema})).document.metadata}function gr(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 yr(e){return{id:e.id,inspect:async()=>{let t=await He(e.filePath),n=xr(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 He(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await He(e.filePath);return await he(e.filePath,Bs(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 kr(e.filePath,{exists:t.exists,raw:t.raw})}}}function oc(e){return{id:e.stepId,inspect:async()=>{let t=await He(e.filePath);return{state:fn(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await He(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await He(e.filePath);return await he(e.filePath,fn(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 kr(e.filePath,{exists:t.exists,raw:t.raw})}}}function rc(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await O(e.pmRoot),n=J(t,B()).type_to_folder,o=await nc({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),r=Ys(o,e.request).length===0;return{state:r?"applied":"pending",...r?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await O(e.pmRoot),n=J(t,B()).type_to_folder,o=await Zt({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:gr(r,e.request,"forward")}}});return{item_id:e.id,changed_fields:o.changedFields}},compensate:async()=>{let t=await O(e.pmRoot),n=J(t,B()).type_to_folder;await Zt({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:gr(o,e.request,"reverse")}}})}}}async function ic(e){let t=await Zs(e.pmRoot,e.migrationId);if(t){if(!tc(t.request,e.request))throw new h(`Schema migration id "${e.migrationId}" already belongs to a different request.`,g.CONFLICT);return{plan:t,stored:!0}}let n=await Qs({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Sr(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function ac(e){let t=xr(await z(e.schemaPath)??"",e.request);if(!t.source)throw new h(`Schema migration source "${e.request.from}" is not a custom definition.`,g.NOT_FOUND);if(t.target)throw new h(`Schema migration target "${e.request.to}" already exists.`,g.CONFLICT);await ec(e.pmRoot,e.plan)}async function sc(e){let t=W(e.settings.schema),n=[...new Set([["types",K.types],["fields",K.fields],["workflows",K.workflows]].map(([r,i])=>ee(e.pmRoot,t.files[r],i)).filter(r=>r!==e.schemaPath))];try{let r=Ke.join(e.pmRoot,"templates"),i=await Ne.readdir(r,{withFileTypes:!0});n.push(...i.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>Ke.join(r,a.name)))}catch(r){if(typeof r!="object"||r===null||!("code"in r)||!ne(r))throw r}n.sort((r,i)=>r.localeCompare(i));let o=[];for(let r of n){let i=await z(r);i!==null&&fn(i,e.request)!==i&&o.push({filePath:r,beforeRaw:i})}return{paths:n,snapshots:o}}async function cc(e){for(let t of e.snapshots){let n=await Ne.readFile(t.filePath,"utf8"),o=Ke.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await Qt({pmRoot:e.pmRoot,author:e.author,documentPath:o,before:$t(t.beforeRaw),after:$t(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 dc(e,t,n){let o=hn(e),r=j(process.cwd(),n.path);if(!await x(be(r)))throw new h(`Tracker is not initialized at ${r}. Run pm init first.`,g.NOT_FOUND);let i=t.migrationId===void 0?vr(o,await Ne.realpath(r)):wr(t.migrationId),a=await O(r),s=H(t.author,a.author_default),c=await ic({pmRoot:r,settings:a,migrationId:i,request:o}),d=c.plan;if(t.dryRun===!0)return{...d,action:o.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Gs(r,a,o),p=await Ne.readFile(l,"utf8");c.stored||await ac({pmRoot:r,schemaPath:l,request:o,plan:d});let u=await sc({pmRoot:r,schemaPath:l,settings:a,request:o}),m=[yr({id:"stage-schema",filePath:l,request:o,phase:"stage"}),...u.paths.map((_,v)=>oc({filePath:_,request:o,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(_=>rc({pmRoot:r,id:_.id,request:o,author:s,force:t.force===!0})),yr({id:"retire-source",filePath:l,request:o,phase:"retire"})],y=await Go({pmRoot:r,transactionId:`schema-${i}`,author:s,steps:m,lockTtlSeconds:Math.max(a.locks.ttl_seconds,300),lockWaitMs:a.locks.wait_ms}),w=await Ne.readFile(l,"utf8"),{historyPath:f}=await Qt({pmRoot:r,author:s,documentPath:Ke.relative(r,l).replaceAll("\\","/"),before:$t(p),after:$t(w),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${o.kind}: ${o.from} -> ${o.to}; affected=${d.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await cc({pmRoot:r,author:s,settings:a,request:o,plan:d,snapshots:u.snapshots}),{...d,action:o.kind,applied:!0,recovered:y.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:f}}function lc(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(`
|
|
16
|
+
`)}import hc from"node:path";import{mkdir as gc}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]="e3f016bb-8add-5765-bb1a-a7b22423f8d1")}catch{}})();var ot=["agile","ops","research"],pc={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 At(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: ${ot.join(", ")}.`)}function rt(e){return pc[e].map(t=>tt(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]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();var uc=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function mc(e){let t=uc.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function fc(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Er(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=mc(s);if(c===void 0)continue;let d=r.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<o&&d.examples.push(s),r.set(c,d)}let i=[];for(let[a,s]of r.entries()){if(s.count<n)continue;let c=fc(a);i.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:So(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]="2ab8a5a9-dbea-526f-a541-b7ca2b106ac5")}catch{}})();var kf=["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"],Tt="schema-types",$r="schema-statuses",Ar="schema-fields";function Te(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 xf(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r;try{r=tt({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(m){throw new h(m instanceof Error?m.message:String(m),g.USAGE)}let i=await O(o),a=W(i.schema),s=ee(o,a.files.types,K.types),c=[],d=H(t.author,i.author_default),l=re(i),p=await Y(o,Tt,i.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await z(s),y;try{y=oe(m)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.GENERIC_FAILURE)}try{Eo(r,y);let w=new Map,f=J(i,B());for(let[_,v]of Object.entries(f.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!w.has(k)&&w.set(k,_)}$o(r,y,w)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}u=Ue(y,r),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await Te({pmRoot:o,filePath:s,raw:de(u.file),op:"schema:add-type",author:d,settings:i}),await it(o,[u.definition],c,"schema:add-type-folder"),c.push(...await q({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await Tr(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 _e(e){if(!await x(be(e)))throw new h(`Tracker is not initialized at ${e}. Run pm init first.`,g.NOT_FOUND)}async function Tr(e,t){try{let n=await rr(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 yc(e,t,n,o){let r=J(t,B()),i=o.trim().toLowerCase();return(await Ce(e,t.item_format,r.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===i).length}async function _c(e,t,n,o){let r=J(t,B()),i=Ze(n),a=$(o);return(await Ce(e,t.item_format,r.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(i.alias_to_id.get($(d))??$(d))===a}).length}async function wc(e,t,n,o,r){if(r.length===0||Pe.has(r))return;let i=await _c(t,n,o,r);i>0&&e.push(`items_using_status:${i}`);let a=Ir(o.workflow,r);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function Ir(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&&$(o)===t).map(([o])=>o)}async function Sf(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r=await O(o),i=W(r.schema),a=ee(o,i.files.types,K.types),s=[],c=H(t.author,r.author_default),d=re(r),l=await Y(o,Tt,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await z(a),m;try{m=oe(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=Ao(m,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 yc(o,r,i,y);w>0&&s.push(`items_using_type:${w}`)}await Te({pmRoot:o,filePath:a,raw:de(p.file),op:"schema:remove-type",author:c,settings:r}),s.push(...await q({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return p.removed&&await Tr(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 yn(e,t){return ee(e,t.files.statuses,K.statuses)}function It(e,t){return ee(e,t.files.fields,K.fields)}function Or(e,t){return ee(e,t.files.types,K.types)}async function it(e,t,n,o){for(let r of t){let i=ao(r.folder??io(r.name)),a=hc.join(e,i);await x(a)||(await gc(a,{recursive:!0}),n.push(...await q({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 vc(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 bc(e){let t=new Map;for(let n of e){let o=$(n.id);if(o.length!==0){t.set(o,o);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let i=$(r);i.length>0&&!t.has(i)&&t.set(i,o)}}}return t}async function Ef(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r;try{r=mr({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}let i=await O(o),a=W(i.schema),s=yn(o,a),c=Ze(a);try{mn(r,c.alias_to_id)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}let d=vc(c.by_id.get(r.id)),l=[],p=H(t.author,i.author_default),u=re(i),m=await Y(o,$r,i.locks.ttl_seconds,p,!!t.force,u.force_required_for_stale_lock,i.locks.wait_ms),y;try{let w=await z(s),f;try{f=Be(w)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let _=bc(f.statuses);try{mn(r,_)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.USAGE)}y=fr(f,r,d),await Te({pmRoot:o,filePath:s,raw:We(y.file),op:"schema:add-status",author:p,settings:i}),l.push(...await q({path:s,scope:"project",op:"schema:add-status"}))}finally{await m()}return{action:"add-status",registered:!0,replaced:y.replaced,status:y.definition,file:{path:s,statuses:y.file.statuses.length},warnings:Ie(l),generated_at:A()}}async function $f(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r=await O(o),i=W(r.schema),a=yn(o,i),s=[],c=H(t.author,r.author_default),d=re(r),l=await Y(o,$r,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await z(a),m;try{m=Be(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=hr(m,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=$(p.definition?.id??e);await wc(s,o,r,i,y),await Te({pmRoot:o,filePath:a,raw:We(p.file),op:"schema:remove-status",author:c,settings:r}),s.push(...await q({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:a,statuses:p.file.statuses.length},warnings:Ie(s),generated_at:A()}}function Cr(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 kc(e,t,n){return{...Cr(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 Rr(e){return{id:e.id,source:Pe.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 Pr(e,t,n){let o=e.toLowerCase();return n.has(o)?"extension":t.has(o)?"custom":"builtin"}function xc(){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 Sc(e){let t=Ze(e),n=[],o=[];for(let r of t.definitions){let i=Rr(r);i.source==="builtin"?n.push(i):o.push(i)}return{builtin:n,custom:o}}async function at(e){let t=j(process.cwd(),e.path);await _e(t);let n=await O(t),o=W(n.schema),r=ee(t,o.files.types,K.types),i=yn(t,o),a=J(n,B()),s=xc(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:r,statusesPath:i,byType:a.by_type,customNames:c,extensionProvenance:s,schema:o}}async function Af(e){let t=await at(e),n=[],o=[],r=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Pr(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=Cr(s);c==="extension"?r.push(d):c==="custom"?o.push(d):n.push(d)}let i=Sc(t.schema),a=bt(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 Tf(e,t){let n=(e??"").trim();if(n.length===0)throw new h("Type name must not be empty.",g.USAGE);let o=await at(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 "${et(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:kc(r,Pr(r.name,o.customNames,new Set(o.extensionProvenance.keys())),o.extensionProvenance.get(r.name.toLowerCase())),file:{path:o.typesPath},generated_at:A()}}async function If(e,t){let n=$(e);if(n.length===0)throw new h("Status id must not be empty.",g.USAGE);let o=await at(t),r=Ze(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 "${et(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Rr(a),file:{path:o.statusesPath},generated_at:A()}}async function Of(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r;try{r=lr({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 O(o),a=W(i.schema),s=It(o,a),c=[],d=xt(r.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=H(t.author,i.author_default),p=re(i),u=await Y(o,Ar,i.locks.ttl_seconds,l,!!t.force,p.force_required_for_stale_lock,i.locks.wait_ms),m;try{let y=await z(s),w;try{w=Je(y)}catch(f){throw new h(f instanceof Error?f.message:String(f),g.GENERIC_FAILURE)}m=pr(w,r),await Te({pmRoot:o,filePath:s,raw:qe(m.file),op:"schema:add-field",author:l,settings:i}),c.push(...await q({path:s,scope:"project",op:"schema:add-field"}))}finally{await u()}return{action:"add-field",registered:!0,replaced:m.replaced,field:m.definition,file:{path:s,fields:m.file.fields.length},warnings:Ie(c),generated_at:A()}}async function Ec(e,t,n,o){let r=J(t,B());return(await Ce(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 Cf(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r=await O(o),i=W(r.schema),a=It(o,i),s=[],c=H(t.author,r.author_default),d=re(r),l=await Y(o,Ar,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),p;try{let u=await z(a),m;try{m=Je(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=ur(m,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=$(p.definition?.key??e),w=$(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(w.length>0){let f=await Ec(o,r,i,w);f>0&&s.push(`items_using_field:${f}`)}await Te({pmRoot:o,filePath:a,raw:qe(p.file),op:"schema:remove-field",author:c,settings:r}),s.push(...await q({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:a,fields:p.file.fields.length},warnings:Ie(s),generated_at:A()}}async function Rf(e){let t=await at(e),n=bt(t.schema).definitions.map(_n);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:It(t.pmRoot,t.schema)},generated_at:A()}}async function Pf(e,t){let n=$(e);if(n.length===0)throw new h("Field key must not be empty.",g.USAGE);let o=await at(t),r=bt(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 "${et(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:_n(r),file:{path:It(o.pmRoot,o.schema)},generated_at:A()}}async function Nf(e,t,n){let o=j(process.cwd(),n.path);await _e(o);let r;try{let w=At(e);if(w===void 0)throw new Error(`Type preset name is required. Allowed: ${ot.join(", ")}.`);r=w}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}let i=await O(o),a=W(i.schema),s=Or(o,a),c=[],d=H(t.author,i.author_default),l=re(i),p=[],u=[],m,y=await Y(o,Tt,i.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms);try{let w=await z(s),f;try{f=oe(w)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let _=f;for(let v of rt(r)){let k=Ue(_,v);_=k.file,(k.replaced?u:p).push(k.definition.name)}m=_.definitions.length,await Te({pmRoot:o,filePath:s,raw:de(_),op:"schema:apply-preset",author:d,settings:i}),await it(o,rt(r),c,"schema:apply-preset-folder"),c.push(...await q({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:m},warnings:Ie(c),generated_at:A()}}function $c(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 Df(e,t){let n=j(process.cwd(),t.path);await _e(n);let o=await O(n),r=W(o.schema),i=Or(n,r),a=$c(e.minCount),s=J(o,B()),d=(await Ce(n,o.item_format,s.type_to_folder,[],r)).map(k=>typeof k.title=="string"?k.title:""),l=Er(d,{minCount:a}),p=[],u=[],m=[],y=[],w;if(!e.apply){let k;try{k=oe(await z(i))}catch(T){throw new h(T instanceof Error?T.message:String(T),g.GENERIC_FAILURE)}return w=k.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:l,registered:u,replaced:m,skipped:y,file:{path:i,definitions:w},warnings:p,generated_at:A()}}let f=H(e.author,o.author_default),_=re(o),v=await Y(n,Tt,o.locks.ttl_seconds,f,!!e.force,_.force_required_for_stale_lock,o.locks.wait_ms);try{let k=await z(i),T;try{T=oe(k)}catch(C){throw new h(C instanceof Error?C.message:String(C),g.GENERIC_FAILURE)}let R=T;for(let C of l){if(C.shadows_builtin){y.push({name:C.name,reason:"shadows_builtin"});continue}let se;try{se=tt({name:C.name})}catch{y.push({name:C.name,reason:"invalid_type_token"});continue}let fe=Ue(R,se);R=fe.file,(fe.replaced?m:u).push(fe.definition.name)}w=R.definitions.length,await Te({pmRoot:n,filePath:i,raw:de(R),op:"schema:infer-types",author:f,settings:o}),await it(n,R.definitions.filter(C=>u.includes(C.name)||m.includes(C.name)),p,"schema:infer-types-folder"),p.push(...await q({path:i,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:l,registered:u,replaced:m,skipped:y,file:{path:i,definitions:w},warnings:Ie(p),generated_at:A()}}function jf(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 "${et(e.type.name)}" "<title>"`}function Ff(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 Lf(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 Mf(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 Uf(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 Gf(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(`
|
|
18
|
+
`)}function zf(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 Ac(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 Jf(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 qf(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 Bf(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${Ac(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
|
|
20
|
+
`)}function Wf(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(`
|
|
21
|
+
`)}function Hf(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 Kf(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(`
|
|
22
|
+
`)}var Vf={workflowSlotsReferencing:Ir};import jr from"node:fs/promises";import De 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]="6fc24a7c-a359-51fd-a432-4c8037d10e9e")}catch{}})();var Ot=["extensions","docs","examples","assets","prompts"],Tc=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 Ic(e){return Ot.includes(e)}function Oc(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 Cc(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(!Ic(o))continue;let i=Oc(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 wn(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 Nr(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 Rc(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 Pc(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 Nc(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:Rc(t.links),media:Pc(t.media),tags:wn(t.tags)};return Object.values(n).some(o=>o!==void 0)?n:void 0}async function st(e){let t=De.join(e,"package.json");if(!await x(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await jr.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:wn(o.keywords),package_homepage:typeof o.homepage=="string"?o.homepage:void 0,package_repository_url:Nr(o.repository),package_bugs_url:Nr(o.bugs),aliases:wn(a.aliases),resources:Cc(r),catalog:Nc(a.catalog)}}async function Dr(e){if(!await x(e))return[];let t=await jr.readdir(e,{withFileTypes:!0}),n=[];for(let o of t){if(!o.isDirectory())continue;let r=De.join(e,o.name);await x(De.join(r,"manifest.json"))&&n.push(r)}return n.sort((o,r)=>o.localeCompare(r))}async function Ct(e){if(await x(De.join(e,"manifest.json")))return[e];let n=(await st(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=De.resolve(e,r);if(!Z(e,i))throw new h(`Package extension entry "${r}" resolves outside package root.`,g.USAGE);if(await x(De.join(i,"manifest.json"))){o.add(i);continue}for(let a of await Dr(i))o.add(a)}if(n.length===0)for(let r of Tc.extensions)for(let i of await Dr(De.join(e,r)))o.add(i);return[...o].sort((r,i)=>r.localeCompare(i))}import{execFile as td}from"node:child_process";import P from"node:fs/promises";import An from"node:os";import S from"node:path";import{fileURLToPath as nd}from"node:url";import{promisify as od}from"node:util";import rd from"npm-package-arg";import{extract as id,list as ad}from"tar";import Bc from"node:fs/promises";import ie from"node:path";import Fr from"node:fs/promises";import vn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af718efb-d1cf-5adc-9518-c858627e1b54")}catch{}})();function X(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 Rt(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 bn(e){return mo(e)}async function Dc(e){try{let t=JSON.parse(await Fr.readFile(vn.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(o=>typeof t.scripts?.[o]=="string")}}catch{return{has_build_script:!1}}}async function jc(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 Dc(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=vn.join(e,"manifest.json");if(!await x(n))throw new h(`Extension manifest is missing at "${n}".`,g.USAGE);let o;try{o=JSON.parse(await Fr.readFile(n,"utf8"))}catch(a){throw new h(`Failed to parse extension manifest at "${n}": ${Fc(a)}`,g.USAGE)}let r=bn(o);if(!r)throw new h(`Extension manifest at "${n}" is invalid.`,g.USAGE);let i=vn.resolve(e,r.entry);if(!Z(e,i))throw new h(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await x(i))throw await jc(r,i,t);if(!await fo(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 Fc(e){return e instanceof Error?e.message:String(e)}import kn from"node:fs/promises";import Lc 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]="159d7bbd-1d2a-503d-b3ce-f32dcc6f6547")}catch{}})();var Mc=".managed-extensions.json",Pt=1;function ct(e){return Lc.join(e,Mc)}function Uc(){return{version:Pt,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 Lr(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function Q(e){return typeof e=="string"?e:void 0}function Gc(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 zc(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:Q(t.name),package:Q(t.package),version:Q(t.version),repository:Q(t.repository),owner:Q(t.owner),repo:Q(t.repo),ref:Q(t.ref),subpath:Q(t.subpath),commit:Q(t.commit)}}function Jc(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Gc(t))return null;let n=zc(t.source);if(!n)return null;let o=po(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:X(t.capabilities),contributions:o,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Q(t.last_update_check_at),last_update_remote_commit:Q(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Q(t.update_error)}}function qc(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Pt||!Array.isArray(t.entries))return null;let n=[];for(let o of t.entries){let r=Jc(o);r&&n.push(r)}return{version:Pt,updated_at:Q(t.updated_at)??A(),entries:dt(n)}}async function we(e){let t=ct(e),n=Uc();try{let o=await kn.readFile(t,"utf8"),r=JSON.parse(o),i=qc(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&&ne(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 je(e,t){let n=ct(e),o={version:Pt,updated_at:A(),entries:dt(t.entries)};await kn.mkdir(e,{recursive:!0}),await kn.writeFile(n,`${JSON.stringify(o,null,2)}
|
|
23
|
+
`,"utf8")}function lt(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:A(),entries:dt(n)}}async function Mr(e,t,n,o){let r=t.entries.find(a=>b(a.name)===b(n));if(!r)return t;let i=lt(t,{...r,contributions:o});return await je(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]="259656b0-09b7-52c5-8f54-52ac29eec607")}catch{}})();var Wc="PM_CLI_PACKAGE_ROOT",Ur={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Hc=new Set(["*","all"]);function xn(){let e=[],t=process.env[Wc];return typeof t=="string"&&t.trim().length>0&&e.push(ie.resolve(t.trim())),e.push(ce(import.meta.url,["../../.."])),[...new Set(e)]}async function pt(e){let t=e.trim().toLowerCase(),n=await zr(t);if(n)return n;let o=Ur[t];if(!o)return null;for(let r of xn()){let i=ie.join(r,".agents","pm","extensions",o.legacy_extension_directory);if(await x(ie.join(i,"manifest.json")))return i}return null}function Gr(e){return Hc.has(e.trim().toLowerCase())}function Kc(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Vc(e,t){let n=await Bc.readdir(e,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!o.name.startsWith("pm-"))continue;let r=ie.join(e,o.name);if(!await x(ie.join(r,"package.json")))continue;let i=await st(r),a=i.aliases&&i.aliases.length>0?i.aliases:[Kc(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 Sn(){let e=new Map;for(let t of xn()){let n=ie.join(t,"packages");await x(n)&&await Vc(n,e)}for(let[t,n]of Object.entries(Ur))if(!e.has(t))for(let o of xn()){let r=ie.join(o,"packages",n.package_directory);if(await x(ie.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 Nt(){return(await Sn()).map(e=>e.alias)}async function zr(e){let t=e.trim().toLowerCase();return(await Sn()).find(o=>o.alias===t||o.package_directory.toLowerCase()===t||o.package_name?.toLowerCase()===t)?.package_root??null}async function Jr(e){let t=await zr(e);return t?(await st(t)).package_name??null:null}async function qr(e){let t=await pt(e);if(!t)return null;try{let n=await Ct(t);return n.length!==1?null:(await Ye(n[0])).manifest.name}catch{return null}}function Yc(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 Xc(e,t,n,o,r,i){let a=o==="global"?"--global":"--project",s=Object.fromEntries(Ot.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(ie.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${a}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:Yc(e),media:e.catalog?.media}}}async function Br(e,t,n={}){let o=wt(j(process.cwd(),t.path),process.cwd()),r=e==="global"?o.global:o.project,i=await we(r),a=new Set(i.state.entries.filter(u=>u.scope===e).filter(u=>u.source.kind!=="builtin").map(u=>ie.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=[],d=new Map;for(let u of await Sn()){let m=ie.resolve(u.package_root),y=d.get(m)??[];y.push(u),d.set(m,y)}for(let u of d.values()){let m=u[0],y=u.map(f=>f.alias).sort((f,_)=>f.localeCompare(_)),w=await st(m.package_root);c.push(Xc(w,m,y,e,s,a))}let l=Zc(n.fields),p=l?c.map(u=>ed(u,l)):c;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Ot.filter(u=>u!=="extensions"),packages:p}}var Qc=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 Zc(e){if(e===void 0)return;let t=Ro(e);if(t.length===0)throw new h("Package catalog --fields requires a comma-separated list of field names",g.USAGE);let n=t.filter(o=>!Qc.has(o));if(n.length>0)throw new h(`Unknown package catalog --fields value(s): ${n.join(", ")}`,g.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function ed(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]="8994c8e2-8e3a-5e00-a3ca-7bd553c045d7")}catch{}})();var Tn=od(td),jt="@unbrained/pm-cli",sd={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},En;async function Wr(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let o=S.resolve(t);for(;;){let r=S.join(o,"node_modules",...n.split("/")),i=S.join(r,"package.json");if(await x(i))try{let s=JSON.parse(await P.readFile(i,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:r}}catch{return null}let a=S.dirname(o);if(a===o)return null;o=a}}function $n(e,t,n){let o=e.split("/").map(d=>d.trim()).filter(d=>d.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 cd(e,t,n){let o=e.slice(4).trim();if(o.length===0)throw new h('npm package source must include a package spec after "npm:".',g.USAGE);if(t)throw new h('Options "--gh/--github" cannot be combined with npm: package sources.',g.USAGE);if(n)throw new h('Option "--ref" cannot be combined with npm: package sources.',g.USAGE);return{kind:"npm",input:e,spec:o}}function Ft(e,t={}){let n=e.trim();if(n.length===0)throw new h("Extension source is required for --install.",g.USAGE);let o=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return cd(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 $n(s,n,o)}catch{return null}})();if(r)return r;let i=n.startsWith("github.com/")?n.slice(11):null;if(i){let a=$n(i,n,o);if(!a)throw new h(`Invalid GitHub source "${n}".`,g.USAGE);return a}if(t.forceGithub){let a=$n(n,n,o);if(!a)throw new h(`Invalid GitHub shorthand "${n}".`,g.USAGE);return a}if(/^https?:\/\//i.test(n))throw new h(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,g.USAGE);return{kind:"local",input:n,absolute_path:S.resolve(process.cwd(),n)}}async function Dt(e,t=Tn,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 h(`Git command failed: git ${e.join(" ")}
|
|
24
|
+
${i}`,g.GENERIC_FAILURE)}}function dd(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function ld(e=process.platform){return e==="win32"}async function Hr(e,t,n=Tn,o=process.platform){let r=dd(o);try{return((await n(r,e,{cwd:t,encoding:"utf8",shell:ld(o)})).stdout??"").trim()}catch(i){let a=typeof i=="object"&&i!==null&&"stderr"in i?String(i.stderr):"",s=a.trim().length>0?a.trim():i instanceof Error?i.message:String(i);throw new h(`npm command failed: ${r} ${e.join(" ")}
|
|
25
|
+
${s}`,g.GENERIC_FAILURE)}}function pd(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 ud(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 md(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return ud(e)||n.includes("not found")}function fd(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function hd(e){let t=pd(e),n=fd(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 gd(e,t){if(!md(t))return null;let n=hd(e);return new h(n.message,g.NOT_FOUND,n.context)}async function Kr(e){if(S.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=S.resolve(process.cwd(),e);return await x(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=nd(t);return await x(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=S.resolve(process.cwd(),e);if(await x(t))return t}return null}async function yd(e){let t=await Kr(e);if(t)return t;let n=_d(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function _d(e,t=process.cwd()){let n="@file:",o=e.lastIndexOf(n);if(o<=0)return e;let r=e.slice(0,o),i=e.slice(o+n.length);if(r.trim().length===0||i.trim().length===0||i.startsWith("//")&&!i.startsWith("///"))return e;if(!i.startsWith("/"))return`${r}@${S.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 wd(e,t){try{let o=JSON.parse(e),r=Array.isArray(o)?o[0]:void 0;if(r&&typeof r.filename=="string"&&r.filename.trim().length>0)return{tarball:S.resolve(t,r.filename),package:typeof r.name=="string"?r.name:void 0,version:typeof r.version=="string"?r.version:void 0}}catch{}let n=e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0).at(-1);if(!n)throw new h("npm pack did not report a tarball filename.",g.GENERIC_FAILURE);return{tarball:S.resolve(t,n)}}async function vd(e){return bd(e,Hr)}async function bd(e,t){let n=await Kr(e.spec);if(n){if((await P.stat(n)).isFile()&&Vr(n))return Yr(n);let s=S.join(n,"package.json"),c=await x(s)?JSON.parse(await P.readFile(s,"utf8")):{};return{directory:await ut(n,e.input),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{}}}let o=await P.mkdtemp(S.join(An.tmpdir(),"pm-npm-package-source-")),r=S.join(o,"pack"),i=S.join(o,"extract");await P.mkdir(r,{recursive:!0}),await P.mkdir(i,{recursive:!0});try{let a=await yd(e.spec),s=await t(["pack",a,"--json","--pack-destination",r]),c=wd(s,r);await Tn("tar",["-xzf",c.tarball,"-C",i],{encoding:"utf8"});let d=S.join(i,"package");return await Xr(d),{directory:await ut(d,e.input),package:c.package,version:c.version,cleanup:async()=>{await P.rm(o,{recursive:!0,force:!0})}}}catch(a){await P.rm(o,{recursive:!0,force:!0});let s=gd(e.spec,a);throw s||a}}function Vr(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ve(e){throw new h(e,g.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 kd(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&ve(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let o=e.path,r=o.split("/");(o.includes("\\")||o.startsWith("/")||/^[A-Za-z]:/u.test(o)||r.some(i=>i===".."))&&ve(`Local package archive contains an escaping path: "${o}".`),r[0]!=="package"&&ve(`Local package archive entry "${o}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ve(`Local package archive link "${o}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ve(`Local package archive entry "${o}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ve(`Local package archive entry "${o}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&ve(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),o==="package/package.json"&&(n.packageJsonEntries+=1)}async function Yr(e,t=sd){(await P.stat(e)).size>t.maxArchiveBytes&&ve(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let o=await P.mkdtemp(S.join(An.tmpdir(),"pm-local-package-archive-")),r=S.join(o,"extract");await P.mkdir(r,{recursive:!0});let i={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await ad({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(a===void 0)try{kd(l,t,i)}catch(p){a=p}}}),a!==void 0)throw a;i.packageJsonEntries!==1&&ve(`Local package archive must contain exactly one package/package.json entry; found ${i.packageJsonEntries}.`),await id({file:e,cwd:r,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=S.join(r,"package"),c=S.join(s,"package.json"),d=JSON.parse(await P.readFile(c,"utf8"));return await Xr(s),{directory:await ut(s,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await P.rm(o,{recursive:!0,force:!0})}}}catch(s){throw await P.rm(o,{recursive:!0,force:!0}),s}}async function Xr(e,t=Hr){let n=S.join(e,"package.json");if(!await x(n))return;let o;try{o=JSON.parse(await P.readFile(n,"utf8"))}catch{return}if(typeof o!="object"||o===null)return;let r=o,i=Td(r),a=xd(r);if(i.length===0&&!a)return;let s={...o};delete s.devDependencies;let c={...s};Sd(c),await P.writeFile(n,`${JSON.stringify(c,null,2)}
|
|
26
|
+
`,"utf8");try{await Promise.all([P.rm(S.join(e,"package-lock.json"),{force:!0}),P.rm(S.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 Ed(e)}finally{await P.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
27
|
+
`,"utf8")}}function xd(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&jt in t)return!0;return!1}function Sd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let o={...n};delete o[jt],Object.keys(o).length===0?delete e[t]:e[t]=o}}async function Ed(e){let t=ce(import.meta.url,["../../.."]),[n,o]=jt.split("/"),r=S.join(e,"node_modules",n),i=S.join(r,o);await P.mkdir(r,{recursive:!0}),await P.rm(i,{recursive:!0,force:!0}),await P.symlink(t,i,$d(process.platform))}function $d(e){return e==="win32"?"junction":"dir"}function Ad(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{rd.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 Td(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===jt||typeof r!="string"||r.trim().length===0||t.has(o))continue;let i=r.trim();t.set(o,Ad(o,i))}return[...t.values()]}async function ut(e,t){let n=await Ct(e);if(n.length===1)return n[0];if(n.length>1){let o=n.map(r=>S.relative(e,r).replaceAll(S.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 Id(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(S.posix.join(".agents/pm/extensions",t.subpath)),n.push(S.posix.join(".custom/pm-extensions",t.subpath)),n.push(S.posix.join(".custom/pm-extension",t.subpath)));for(let r of n){let i=S.resolve(e,r);if(Z(e,i)&&await x(S.join(i,"manifest.json")))return{directory:i,resolved_subpath:r}}if(await x(S.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let o=await ut(e,t.input);return{directory:o,resolved_subpath:S.relative(e,o).replaceAll(S.sep,"/")}}function Od(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 Cd(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Od(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?S.resolve(i.trim()):"";En?.key!==a&&(En={key:a,aliases:await Nt()}),o=En.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 Qr(e){if(e.kind==="local"){let o;try{o=await P.stat(e.absolute_path)}catch{throw await Cd(e)}if(o.isFile()&&Vr(e.absolute_path)){let i=await Yr(e.absolute_path);return{source:e,directory:i.directory,source_root:S.dirname(i.directory),resolved_subpath:S.relative(S.dirname(i.directory),i.directory).replaceAll(S.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 vd(e);return{source:e,directory:o.directory,source_root:S.dirname(o.directory),cleanup:o.cleanup,resolved_subpath:S.relative(S.dirname(o.directory),o.directory).replaceAll(S.sep,"/"),npm_package:o.package,npm_version:o.version}}let t=await P.mkdtemp(S.join(An.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Dt(n);let o=await Dt(["-C",t,"rev-parse","HEAD"]),r=await Id(t,e);return{source:e,directory:r.directory,source_root:t,resolved_subpath:r.resolved_subpath,commit:o,cleanup:async()=>{await P.rm(t,{recursive:!0,force:!0})}}}catch(o){throw await P.rm(t,{recursive:!0,force:!0}),o}}async function Zr(e,t){if(!await x(e)||!await x(t))return!1;let[n,o]=await Promise.all([P.realpath(e),P.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]="30dfc6e4-27c5-56c0-981b-94e85b780f1f")}catch{}})();var In=1,Fe="2026.6.24",Rd=">=22.18.0",Pd={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},ei=new Set([...xo.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(ko).map(e=>e.toLowerCase()),"scaffold"]),Nd="^6.0.0",Dd="^22.0.0",oi=["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 ti(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function ri(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 ii(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 jd={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"],ai={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"]},Fd={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"]'},Ld={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."},Md={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."},si="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Ud={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."]},Gd={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."]},zd={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`."]},Jd={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 ci(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 di(e,t){return e==="schema"?zd[t]:e==="profile"?Jd[t]:Gd[t]}function qd(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&&ei.has(r));return`${(ei.has(n)||i?["starter",...t]:t).join(" ")} ping`}function li(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 Bd(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`,d=e.replace(/-/g,""),l=d===s?[]:[d],p=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`;return[...a,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(u)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...a,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...li(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 Wd(e,t,n){let o=n==="hooks",r=n==="search",i=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",p=n==="services",u=Fd[n],m=e,y=`${e}s`,w=`${e.replace(/-/g,"_")}_note`,f=`${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,"});",""]:[],k=r?On(e,t,"search",u):[],T=i?On(e,t,"importers",u):[],R=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 {",...ti(ri({extensionName:e,itemTypeName:m,itemTypeFolder:y,fieldName:w,migrationId:f,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],C=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 {",...ti(ii(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],se=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,"});",""]:[],fe=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],E=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],G=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";',"",...oi,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...v,...k,...T,...R,...C,...se,...fe,...E,...G,`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 Hd(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 Kd={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"},Vd={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 Yd(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 Xd(e,t,n){let o=[],r=[...Yd(e,t,n)],i=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,p=e.replace(/-/g,""),u=p===d?[]:[p],m=`${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(m)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(u)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(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({",...li(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 Qd(e,t,n){let o=Xd(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 On(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`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${o},`," });"],u=m=>[...p," let deactivated = false;"," try {",...m.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 query = await ext.runSearchProvider({",` provider: ${JSON.stringify(r)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings: {} as PmSettings,"," 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: {} as PmSettings, 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: {} as PmSettings },"," });",' 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(ri({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(ii(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 Zd(e,t,n){let o=n==="parser",r=JSON.stringify([...ai[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" };',"",...oi,`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,"});","",...On(e,t,n,r)].join(`
|
|
30
|
+
`)}function el(e,t,n){let o=ci(n,"package"),r=di(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 (${Kd[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`.",si,"- `.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 ${Vd[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 \`${In}\` 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(`
|
|
31
|
+
`)}function tl(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 nl(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 ol(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 rl(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 il(e,t,n,o="commands",r=!1){let i=`pm-${e}`,a=ai[o],s=Hd(e,t,o),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:In,pm_min_version:Fe,trusted:!0,sandbox_profile:"strict",permissions:{...Pd},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
|
|
32
|
+
`,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Bd(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(`
|
|
33
|
+
`),l=`${JSON.stringify(jd,null,2)}
|
|
34
|
+
`,p=Ld[o],u=ci(o,"package"),m=`${JSON.stringify({name:i,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Rd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Fe}`},devDependencies:{"@types/node":Dd,typescript:Nd},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)}
|
|
35
|
+
`,y=Wd(e,t,o),w=Md[o],f=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
36
|
+
`),_=tl(e),k=["```ts",`import { ${nl(o)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...ol(e,t,o,_),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...rl(t,o,_),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],T=[`# ${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,w,si,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...k,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Ud[o],...di(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 \`${In}\` 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(`
|
|
37
|
+
`);return{"package.json":m,"manifest.json":c,"index.ts":r?Qd(e,t,o):d,"index.test.ts":r?Zd(e,t,o):y,"tsconfig.json":l,".gitignore":f,"README.md":r?el(i,t,o):T}}async function pi(e,t="extension",n="commands",o=!1){let r=n.trim().toLowerCase();if(!ni.includes(r))throw new h(`Unknown scaffold capability "${n}". Supported capabilities: ${ni.join(", ")}.`,g.USAGE);let i=r;if(o&&t!=="package")throw new h("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",g.USAGE);let a=o?"declarative":"imperative",s=e.trim(),c=ft.resolve(process.cwd(),s),d=Rt(ft.basename(c)).replace(/^(?:pm-)+/u,""),l=qd(d),p=il(d,l,t,i,o),u=!1;if(await x(c)){if(!(await mt.stat(c)).isDirectory())throw new h(`Scaffold target "${c}" exists and is not a directory.`,g.CONFLICT)}else await mt.mkdir(c,{recursive:!0}),u=!0;for(let[y,w]of Object.entries(p)){let f=ft.join(c,y);if(!await x(f))continue;if(await mt.readFile(f,"utf8")!==w)throw new h(`Scaffold file "${y}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,g.CONFLICT)}let m=[];for(let[y,w]of Object.entries(p)){let f=ft.join(c,y);if(await x(f)){m.push({path:y,status:"unchanged"});continue}await mt.mkdir(ft.dirname(f),{recursive:!0}),await mt.writeFile(f,w,"utf8"),m.push({path:y,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:i,style:a,target_path:c,created_directory:u,files:m}}(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]="48c3e62a-8085-5215-a692-4c03792022ce")}catch{}})();var ui=1,Cn=6,mi=[["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 Rn(e){return"#".repeat(e)}function fi(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 al(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(fi).join(", ")}`}function sl(e,t,n){let o=[`${Rn(t)} ${e}`,""];return n.length===0?(o.push("_None._",""),o):(o.push(...n.map(r=>`- ${fi(r)}`),""),o)}function cl(e,t,n){return e===0&&!n?[]:[`${Rn(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function Pn(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<ui||n>Cn)throw new RangeError(`headingLevel must be an integer in [${ui}, ${Cn}], received ${String(t.headingLevel)}`);let o=Math.min(n+1,Cn),r=t.includeEmpty===!0,i=t.title??"Extension surfaces",a=[`${Rn(n)} ${i}`,""];(r||e.capabilities.length>0)&&a.push(al(e.capabilities),"");for(let[c,d]of mi){let l=e[c]??[];l.length===0&&!r||a.push(...sl(d,o,l))}return a.push(...cl(e.preflight_overrides,o,r)),!(e.preflight_overrides>0||mi.some(([c])=>(e[c]?.length??0)>0))&&!r&&a.push("_This extension registers no surfaces._",""),`${a.join(`
|
|
38
38
|
`).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]="536ed530-7726-50ab-bb2d-ace030818f1d")}catch{}})();function hi(e,t){return`${e}:${b(t)}`}function
|
|
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]="536ed530-7726-50ab-bb2d-ace030818f1d")}catch{}})();function hi(e,t){return`${e}:${b(t)}`}function dl(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(d=>t.has(b(d.name))))continue;let c=s.at(-1);n.push({command:a,surface:o,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((o,r)=>o.command.localeCompare(r.command)||o.surface.localeCompare(r.surface))}function gi(e,t,n){let o=new Set(n.failed.map(d=>hi(d.layer,d.name))),r=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:o.has(hi(d.layer,d.name))?"failed":"ok",surfaces:Ge(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:Ge(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),i=typeof e=="string"?b(e):null,a=i===null?null:new Set(t.loaded.filter(d=>b(d.name)===i||typeof d.source_package=="string"&&b(d.source_package)===i||(d.source_aliases??[]).some(l=>b(l)===i)).map(d=>b(d.name)).concat(i)),s=a===null?r:r.filter(d=>a.has(b(d.name))),c=a===null?{}:{extensionNames:[...a]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Ge(n,c),command_ownership:dl(n,a)}}var ll={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function lg(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
40
|
`).trimEnd()}
|
|
41
|
-
`;for(let r of e.extensions){let i=`${r.name} (${r.layer} v${r.version}, ${
|
|
41
|
+
`;for(let r of e.extensions){let i=`${r.name} (${r.layer} v${r.version}, ${ll[r.activation_status]})`;o.push(Pn(r.surfaces,{title:i,headingLevel:2}))}return e.extensions.length>1&&o.push(Pn(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${o.join(`
|
|
42
42
|
`).trimEnd()}
|
|
43
|
-
`}import
|
|
44
|
-
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let a=o.filter(l=>l.outcome==="pending").length,s=o.filter(l=>l.outcome==="applied").length,c=o.filter(l=>l.outcome==="skipped").length,d=o.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:Dn(e.pmRoot),total:o.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:d,migrations:o}}async function wi(e){let t=await O(e.resolvedRoots.settings_root),n=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),o=await xe(n);e.warnings.push(...n.warnings,...o.warnings);let r=await yl({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)}(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]="39bc7f14-2d32-5b58-97ab-647f9f238273")}catch{}})();async function vi(e,t,n){let o=typeof t=="string"?null:await pt(e),r=o===null?null:e.trim().toLowerCase(),i=r===null?null:await Jr(r),a=Ft(o??e,{forceGithub:typeof t=="string",ref:n}),s=r===null?null:await Wr(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 te 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]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function jn(e){return e.map(({layer:t,name:n,error:o})=>({layer:t,name:n,error:o}))}function Lt(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 _l(e){let t=new Map,n=new Map;for(let o of e.registrations.commands)Lt(t,o.name,o.command),Lt(n,o.name,o.action);for(let o of e.commands.handlers)Lt(t,o.name,o.command);for(let o of e.commands.overrides)Lt(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 wl(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 Mt(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}=_l(n);return e.map(c=>{let d=b(c.name),l=bi(a.get(d)),p=bi(s.get(d)),u={...l?{command_paths:l}:{},...p?{action_paths:p}:{}},m=wl({enabled:c.enabled,normalizedName:d,loadedNames:o,loadFailedNames:r,activationFailedNames:i});return{...c,...m,...u}})}function vl(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 Si=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 bl(e){return Si.has(Oi(e))}function ki(e){return e==="project"||e==="global"}function Ei(e){let t=e.split(":"),n=t[0];if(!n||!Si.has(n))return null;let o=t.at(-4),r=t.at(-3)?.trim(),i=t.at(-2),a=t.at(-1)?.trim();return!ki(o)||!ki(i)||!r||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:o,name:r},displaced:{layer:i,name:a}}}function kl(e){let t=new Set;for(let n of e){let o=Ei(n);o&&(t.add(o.winner.name),t.add(o.displaced.name))}return[...t].sort((n,o)=>n.localeCompare(o))}function xl(e,t){let n=e.filter(bl);if(n.length===0)return null;let o=kl(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 Sl(e,t,n,o){let r=t.map(p=>Ei(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])),d=new Map;for(let p of r)for(let u of[p.winner.name,p.displaced.name]){let m=b(u);d.set(m,(d.get(m)??0)+1)}let l=[...d.entries()].map(([p,u])=>{let m=c.get(p),y=m?.name??p,w=m?.command_paths??[],f=m?.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:[...f].sort((_,v)=>_.localeCompare(v))}}}).sort((p,u)=>{let m=u.affected_collisions-p.affected_collisions;if(m!==0)return m;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:d.size,next_best_command:s,collisions:r,remediation_candidates:l}}function $i(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 Ai(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 Ti(e,t){let n=[];for(let o of _o(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 El=[{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: ${eo.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 $l(e){let{normalizedWarnings:t,options:n,scope:o,scopeFlag:r,updateCheckFailedTotal:i,policyWarningCount:a,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,p=[],u={options:n,scope:o,scopeFlag:r,updateCheckFailedTotal:i,policyWarningCount:a};if(t.length>0){let m=xl(t,{deactivate:`${U(n,"deactivate")} <name> ${r}`,doctor:`${U(n,"doctor")} ${r} --detail deep --trace`});m&&p.push(m);for(let y of El)y.matches(t,u)&&p.push(y.build(u))}return s?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>).`):c>0&&p.push(`Loaded unmanaged extensions are currently treated as informational. Use ${U(n,"manage")} ${r} --fix-managed-state to adopt them for update checks.`),d>0&&p.push("Non-GitHub managed extensions are skipped by update checks. Use doctor output for non-update diagnostics."),l>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 Ut(e,t,n,o={}){let r=[...new Set(t)].sort((E,G)=>E.localeCompare(G)),i=n.filter(E=>E.managed).length,a=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,c=n.filter(E=>E.update_available===!0).length,d=n.filter(E=>E.managed===!1),l=d.filter(E=>xi(E)).map(E=>E.name).sort((E,G)=>E.localeCompare(G)),p=d.filter(E=>!xi(E)).map(E=>E.name).sort((E,G)=>E.localeCompare(G)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)u[E.update_check_status]+=1;let m=u.failed,y=u.skipped_unmanaged,w=u.skipped_non_github,f=p.length>0,_=f?"partial":"full",v=f?[`extension_update_health_partial_coverage:skipped_unmanaged:${p.length}`]:[],k=[...new Set([...r,...v])].sort((E,G)=>E.localeCompare(G)),T=[...new Set(k.map(E=>Oi(E)))].sort((E,G)=>E.localeCompare(G)),R=vl(k),C=e==="global"?"--global":"--project",se=Sl(e,r,n,o),fe=$l({normalizedWarnings:r,options:o,scope:e,scopeFlag:C,updateCheckFailedTotal:m,policyWarningCount:R.warning_count,updateHealthPartial:f,skippedUnmanagedTotal:y,skippedNonGithubTotal:w,updateAvailableTotal:c});return{status:k.length===0?"ok":"warn",warning_count:k.length,warning_codes:T,warnings:k,policy_warning_count:R.warning_count,policy_violation_count:R.violation_count,policy_blocked_count:R.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:f,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(E=>E.name).sort((E,G)=>E.localeCompare(G)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:u,update_check_failed_total:m,top_warnings:k.slice(0,8),remediation:fe,...se?{collision_plan:se}:{}}}function Ii(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 Oi(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Ci(e){let t=new Set,n=[];for(let o of e){let r=(()=>{let i=lo(o);return i?[i]:po(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 Ri(){return{version:_t.version,capabilities:[..._t.capabilities],legacy_aliases:{..._t.legacy_aliases}}}function xi(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Pi(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(l=>l.active).map(l=>b(l.name)))].sort((l,p)=>l.localeCompare(p)),a=[...new Set(n.filter(l=>l.layer==="project").map(l=>b(l.name)))].sort((l,p)=>l.localeCompare(p)),s=new Set(o.map(l=>b(l.name))),c=i.filter(l=>!a.includes(l)&&!s.has(l)).sort((l,p)=>l.localeCompare(p));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:i.length,loaded_project_count:a.length,active_project_names:i,loaded_project_names:a,missing_active_project_names:c}}}import{randomUUID as Al}from"node:crypto";import M from"node:fs/promises";import Tl from"node:os";import N 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]="263602a2-c000-5df7-80d2-6f095985496f")}catch{}})();var Ni=3,Il=120,Di=250,Ol=12e4,Cl=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),ji=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Fi=e=>Cl.has(String(ji(e))),Gt=(e,t)=>ji(e)===t,Li=e=>new Promise(t=>{setTimeout(t,e)}),Mi=async e=>{let t=N.join(e,"package.json");await x(t)||await M.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
45
|
-
`,"utf8")},Ui=async e=>{let t=ce(import.meta.url,["../../.."]),n=N.join(e,"node_modules","@unbrained"),o=N.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")},
|
|
46
|
-
`,"utf8")}catch(n){throw await M.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Dl=async(e,t,n,o,r)=>{for(let i=1;i<=n;i+=1)try{return await Nl(e,t),!0}catch(a){if(!Gt(a,"EEXIST"))throw a;await Rl(e,r)?i-=1:await Li(o)}return!1},Mn=async(e,t,n,o)=>{let r=N.join(e,"runtime","extension-install-locks"),i=N.join(r,"scope.lock");await M.mkdir(r,{recursive:!0});let{attempts:a=Il,delay_ms:s=Di,stale_ms:c=Ol,heartbeat_ms:d}=o??{};if(![a,s,c,d].filter(_=>_!==void 0).every(Number.isFinite))throw new h("Extension install lock timings must be finite numbers.",g.USAGE);let l=Math.max(1,Math.floor(a)),p=Math.max(0,Math.floor(s)),u=Math.floor(c),m=Math.floor(d??u/3);if(u<=0||m<=0||m>=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:Al(),created_at:A(),destination:t};if(!await Dl(i,y,l,p,u))throw new h(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let f=Pl(i,y.token,m);try{return await n()}finally{await f(),await Ji(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]="4d3c62e9-9116-5cdc-bbda-48bbd2e39476")}catch{}})();var qi=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]="b17dfc10-9e07-5912-b294-c5663133f192")}catch{}})();function Bi(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]="0dc7b063-dc72-595f-8e40-8a06f9db69e1")}catch{}})();function Wi(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=>!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]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var Hi=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=kt(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]="ccb857a5-045d-57a7-91d2-b761225fe53a")}catch{}})();var jl=1e4,Fl=(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"}},Ki=async(e,t=Dt)=>{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,jl);return Fl(r,e.commit,n)}catch(o){return{checked_at:n,available:null,error:o instanceof Error?o.message:String(o)}}};import Le from"node:fs/promises";import Ll from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="98b47a2f-d48a-5c90-8b88-3f33bdd1c826")}catch{}})();var Un=async e=>Le.readFile(e).catch(t=>{if(Gt(t,"ENOENT"))return null;throw t}),Vi=async(e,t,n,o,r)=>{let i=ct(e),a=be(t),[s,c]=await Promise.all([Un(i),Un(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}},Yi=async e=>{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(Ll.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]="8b0fbe09-2221-5b8e-8712-90a83df19306")}catch{}})();var Ml=4,ea=[["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"]],Ul=ea.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Gl={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"},zl="__pm_native_output",Jl=["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"],ta=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],ql=["disabled","require_trusted","require_provenance"],na={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:[]},Bl=e=>{let t=e??na,n={};for(let o of Jl)n[o]=X(t[o]??[]);return n},Wl=(e,t)=>{for(let n of ta)t[n].length>0&&(e[n]=t[n]);return e},Hl=(e,t)=>{for(let n of ql)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Kl=e=>{let t={};for(let n of ta)t[n]=X(e[n]??[]);return t},Vl=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Wl(Hl({name:t},e),Kl(e))},Yl=e=>(e??[]).map(t=>Vl(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Xl=e=>{let t=Object.assign({},na,e??{}),n=Bl(e),o=Yl(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}},oa=async(e,t)=>{let n=[t],o=await qr(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}},ra=(e,t)=>{let n=t.trim(),o=new Set(X(e.extensions.enabled));return new Set(X(e.extensions.disabled)).has(n)?!1:o.size===0?!0:o.has(n)},ia=(e,t)=>{let n=t.trim(),o=new Set(X(e.extensions.enabled)),r=new Set(X(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")},Zl=(e,t)=>{let n=t.trim(),o=new Set(X(e.extensions.enabled)),r=new Set(X(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")},Ql=(e,t)=>{let n=t.trim(),o=new Set(X(e.extensions.enabled)),r=new Set(X(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")},ep=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),o=ea.map(([r,i,a])=>({action:i,flag:a,distance:ro(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},tp=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=ep(e);if(!o)return new h(`One action flag is required. Use one of: ${Ul}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let r=`pm ${n} ${o.flag}`;return io({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(aa),retry_command:r,message_suffix:`. Did you mean "${o.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:r,reason:`nearest lifecycle action for "${e}"`}]})},np=[["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"]],aa={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},op=e=>aa[e]??null,rp=(e,t)=>{let n=[...new Set(np.filter(([o])=>t[o]===!0).map(([,o])=>o))];if(n.length===0){if(e===void 0)return"explore";let o=op(e.trim().toLowerCase());if(o)return o;throw tp(e,t)}if(n.length>1)throw new h("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},ip=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"},ap=[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"}}],sa=e=>{for(let t of ap){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},ca=(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}},sp=(e,t,n,o)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},o),i=o?ra(n,o.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ca({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:i},t,o,sa(o))}},cp=async(e,t,n,o,r,i)=>{let a=te.join(e,t),s=te.join(a,"manifest.json"),c=i.get(b(t));if(!await x(s))return sp(t,n,o,c);let d=Symbol("invalid-extension-manifest-json"),l=await Oe.readFile(s,"utf8").then(m=>JSON.parse(m)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=kn(l);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=r.get(b(p.name))??i.get(b(t));return{summary:ca({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:ra(o,p.name)},n,u,sa(u))}},me=async(e,t,n,o)=>{if(!await x(e))return{extensions:[],warnings:[]};let i=(await Oe.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,p)=>l.localeCompare(p)),a=new Map(o.entries.map(l=>[b(l.name),l])),s=new Map(o.entries.map(l=>[b(l.directory),l])),c=[],d=[];for(let l of i){let p=await cp(e,l,t,n,a,s);p.warning&&c.push(p.warning),p.summary&&d.push(p.summary)}return{extensions:d.sort((l,p)=>l.name.localeCompare(p.name)),warnings:c.sort((l,p)=>l.localeCompare(p))}},dp=go(),lp=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,pp=(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:lp(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"}:{}}},up=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},da=e=>e.map(t=>up(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),la=(e,t,n)=>{let o=b(e);return t.find(r=>(n===void 0||r.layer===n)&&b(r.name)===o)},mp=(e,t,n,o)=>n.find(i=>i.scope===t&&b(i.name)===b(e))?.activation_status??(o?"failed":"unknown"),pa=(e,t,n,o,r)=>dp.enqueue(async()=>{let i=process.env.PM_CLI_PACKAGE_ROOT,a=await Oe.mkdtemp(te.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=ce(import.meta.url,["../.."]);try{let s=await ke({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:r.noExtensions===!0,reload_token:Xt(),cache_bust:!0,module_graph_snapshot_root:a}),c=await xe({...s}),d=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...da(c.failed)],l=Object.fromEntries(s.loaded.map(p=>[b(p.name),mo(Ge(c,{extensionName:p.name}))]));return{installed:Mt(o,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await Oe.rm(a,{recursive:!0,force:!0}),i===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=i}}),zn=async(e,t,n,o)=>{let r=n.filter(c=>!c.managed),i=[...r].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),a=o,s=[];for(let c of i){let d=te.join(e,c.directory),l=await Ye(d),p=A(),u={kind:"local",input:c.name,location:d};a=lt(a,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:p,updated_at:p,source:u}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:u})}return s.length>0&&await je(e,a),{state:a,adopted_entries:s,unmanaged_candidates:i,already_managed_count:n.length-r.length}},fp=(e,t)=>{let n=j(process.cwd(),t.path),o=wt(n,process.cwd()),r=e==="global"?co(process.cwd()):n,i=e==="global"?o.global:o.project;return{pm_root:n,scope:e,settings_root:r,selected_root:i,roots:o}},zt=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]},hp=e=>Gl[e],gp=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=e==="install"?"source":"name",r=`${n} ${o}`,i=hp(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`}]}})},Jt=(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)},yp=(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))},_p=(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",message:"--dry-run is only valid with --migrate."}].find(r=>r.triggered&&!r.allowed);if(o)throw new h(o.message,g.USAGE)},wp=(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},vp=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:vp(e),warnings:[...new Set(e.warnings)].sort((r,i)=>r.localeCompare(i)),details:t};return e.action==="doctor"&&Object.defineProperty(o,zl,{value:!0,enumerable:!1,configurable:!1}),o},Jn=async(e,t,n)=>{let o=rp(e,t);_p(o,t);let r=wp(e,o,t),i=ip(t),a=fp(i,n),c={action:o,normalizedTarget:r,scope:i,resolvedRoots:a,warnings:[],options:t,global:n},l={...c,withResult:(p,u=!0)=>bp(c,p,u)};return await eu(l)},kp=(e,t)=>{let n=t.vocabulary??"extension",o=e.target_path.replace(/\\/g,"/"),r=an(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: ${xt(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`]},xp=async e=>{let{action:t,normalizedTarget:n,options:o,withResult:r}=e;if([zt(o),o.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new h('Action "init" does not accept --gh/--github/--ref options.',g.USAGE);let s=Jt(n,t,o),c=await pi(s,o.vocabulary??"extension",o.capability,o.declarative===!0);return r({scaffolded:c.created_directory||c.files.some(d=>d.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:kp(c,o)})},Sp=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 O(n.settings_root),c=Xt(),d=await ke({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:i.noExtensions,reload_token:c,cache_bust:!0});o.push(...d.warnings);let l=await xe(d);o.push(...l.warnings);let p={reload:{token:c,cache_bust:!0,watch:r.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(u=>({name:u.name,layer:u.layer,version:u.version})),failed_extensions:d.failed.map(u=>({name:u.name,layer:u.layer,error:u.error})),activation_failures:l.failed.map(u=>({name:u.name,layer:u.layer,error:u.error}))};return r.watch===!0&&o.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},Ep=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 Br(n,r,o))},$p=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Ap=e=>({kind:"local",input:e.input,location:e.absolute_path}),Tp=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),Ip=(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}),Op=(e,t,n,o)=>e?$p(e,t):n.kind==="local"?Ap(n):n.kind==="npm"?Tp(n,o):Ip(n,o),Cp=(e,t,n,o)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:o}:Lr(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},Rp=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:r}=e,{validated:i,destinationDirectoryName:a}=t,s=await O(o.settings_root),c=await we(o.selected_root);r.push(...c.warnings);let d=te.join(o.selected_root,a),l=await x(d),p=await Qr(i.directory,d);await Oe.mkdir(o.selected_root,{recursive:!0});let u=await Oe.mkdtemp(te.join(o.selected_root,".pm-extension-install-backup-")),m=te.join(u,"destination");try{let y=await Vi(o.selected_root,o.settings_root,d,l,m),w=Op(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),f=c.state.entries.find(T=>b(T.name)===b(i.manifest.name)),_=Cp(f,i.manifest.version,w,A()),v=lt(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}),k=ia(s,i.manifest.name);try{p||await zi(i.directory,d),await Mi(d),await Ui(d),await je(o.selected_root,v),k&&await Ee(o.settings_root,s,"settings:write")}catch(T){try{await Yi(y)}catch(R){throw new AggregateError([T,R],`Extension install failed: ${String(T)}; rollback failed: ${String(R)}`,{cause:R})}throw T}return{settings:s,managedState:v,sourceRecord:w,destinationDirectory:d,destinationExists:l,installInPlace:p,activationChanged:k}}finally{await Oe.rm(u,{recursive:!0,force:!0}).catch(()=>{})}},Pp=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 it(e.resolvedRoots.pm_root,o,e.warnings,"install:type-folder"),o},Np=(e,t,n,o,r)=>{let i=la(t,n.activation_failures,e.scope),a=mp(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)]}}},Dp=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:r,global:i,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,d=await Rp(e,t),l=await me(o.selected_root,n,d.settings,d.managedState);r.push(...l.warnings);let p=await pa(o.pm_root,te.dirname(o.selected_root),d.settings,l.extensions,i);r.push(...p.warnings);let u=await Pp(e,s.manifest.name,p.item_type_registrations),m=Bi(s.manifest.name,p.installed),y=Np(e,s.manifest.name,p,m,u),w=p.contribution_inventories[b(s.manifest.name)];return w&&(d.managedState=await Mr(o.selected_root,d.managedState,s.manifest.name,w)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:y.activated,settings_changed:d.activationChanged,runtime_activation_status:y.status,command_paths:m.command_paths,action_paths:m.action_paths,contributions:w,command_discovery:pp(s.manifest.name,d.sourceRecord,m,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)},jp=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 c of await Nt()){let d=await pt(c),l=te.resolve(d),p=a.get(l);p===void 0&&(p=await Jn(c,{...t,install:!0},n),a.set(l,p)),i.push({alias:c,result:p})}o.push(...i.flatMap(c=>c.result.warnings));let s=i.every(c=>c.result.ok);return r({installed_all:s,installed_count:i.filter(c=>c.result.ok).length,failed_count:i.filter(c=>!c.result.ok).length,packages:i.map(c=>{let d=c.result.details;return{alias:c.alias,ok:c.result.ok,extension:d.extension,source:d.source,source_resolution:d.source_resolution,destination_path:d.destination_path,activated:d.activated,settings_changed:d.settings_changed,command_paths:d.command_paths,action_paths:d.action_paths,command_discovery:d.command_discovery,verification:d.verification,runtime_activation_status:d.runtime_activation_status,activation_diagnostics:d.activation_diagnostics,warnings:c.result.warnings}})},s)},Fp=async(e,t,n)=>{let{resolvedRoots:o}=e,{bundledAliasName:r,bundledPackageName:i,installSource:a,sourceResolution:s}=await vi(t,n,e.options.ref);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${r}:npm:${d.package}`)}let c=await Zr(a);try{let d=await Ye(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),l=Rt(d.manifest.name);return await Mn(o.settings_root,l,()=>Dp(e,{validated:d,destinationDirectoryName:l,bundledAliasName:r,bundledPackageName:i,sourceResolution:s,installSource:a,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},Lp=async e=>{let t=zt(e.options),n=t??Jt(e.normalizedTarget,e.action,e.options);return[t===void 0,Gr(n)].every(Boolean)?jp(e):Fp(e,n,t)},Mp=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(zt(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 O(o.settings_root),d=await we(o.selected_root);r.push(...d.warnings);let l=await me(o.selected_root,n,c,d.state);r.push(...l.warnings);let p=await zn(o.selected_root,n,l.extensions,d.state),u=await me(o.selected_root,n,c,p.state);r.push(...u.warnings);let m=Ut(n,r,u.extensions,i);r.push(...m.warnings);let y=new Map(u.extensions.map(_=>[`${b(_.name)}:${b(_.directory)}`,_])),w=new Map(u.extensions.map(_=>[b(_.directory),_])),f=p.adopted_entries.map(_=>{let v=b(_.directory),k=y.get(`${b(_.name)}:${v}`)??w.get(v);return{..._,...ua(k)}});return a({adopted_all:f.length>0,adopted_count:f.length,already_managed_count:p.already_managed_count,extensions:f,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},ua=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Up=(e,t,n,o)=>{if(e===void 0)return{kind:"local",input:t,location:n};let r=Ft(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}},Gp=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:r,warnings:i,options:a,withResult:s}=e,c=Jt(n,t,a),d=zt(a),l=await O(r.settings_root),p=await we(r.selected_root);i.push(...p.warnings);let u=await me(r.selected_root,o,l,p.state);i.push(...u.warnings);let m=await oa(u.extensions,c);if(!m)throw new h(`Installed extension "${c}" was not found in ${o} scope.`,g.NOT_FOUND);if(m.managed)return s({adopted:!1,already_managed:!0,extension:{name:m.name,directory:m.directory}});let y=te.join(r.selected_root,m.directory),w=await Ye(y),f=A(),_=Up(d,c,y,a.ref),v=lt(p.state,{name:w.manifest.name,directory:m.directory,scope:o,manifest_version:w.manifest.version,manifest_entry:w.manifest.entry,capabilities:[...w.manifest.capabilities],contributions:w.manifest.contributions,installed_at:f,updated_at:f,source:_});await je(r.selected_root,v);let k=await me(r.selected_root,o,l,v);i.push(...k.warnings);let T=k.extensions.find(R=>b(R.name)===b(w.manifest.name))??k.extensions.find(R=>b(R.directory)===b(m.directory));return s({adopted:!0,extension:{name:w.manifest.name,directory:m.directory,version:w.manifest.version,entry:w.manifest.entry},source:_,...ua(T)})},ma=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:r,warnings:i,options:a}=e,s=Jt(n,t,a),c=await O(r.settings_root),d=await we(r.selected_root);i.push(...d.warnings);let l=await me(r.selected_root,o,c,d.state);i.push(...l.warnings);let p=await oa(l.extensions,s);if(!p)throw new h(`Installed extension "${s}" was not found in ${o} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:p}},zp=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:o,managedStateRead:r,candidate:i}=await ma(e),a=te.join(t.selected_root,i.directory);await Oe.rm(a,{recursive:!0,force:!0});let s={...r.state,updated_at:A(),entries:r.state.entries.filter(d=>b(d.name)!==b(i.name)&&b(d.directory)!==b(i.directory))};await je(t.selected_root,s);let c=Ql(o,i.name);return c&&await Ee(t.settings_root,o,"settings:write"),n({removed:!0,extension:{name:i.name,directory:i.directory},destination_path:a,settings_changed:c})},Xi=async e=>{let{action:t,resolvedRoots:n,warnings:o,global:r,withResult:i}=e,{settings:a,candidate:s}=await ma(e),c=t==="activate"?ia(a,s.name):Zl(a,s.name);c&&await Ee(n.settings_root,a,"settings:write");let d=t==="activate"?await pa(n.pm_root,te.dirname(n.selected_root),a,[s],r).then(l=>(o.push(...l.warnings),la(s.name,l.activation_failures,e.scope))):void 0;return d&&o.push(`extension_activate_failed:${e.scope}:${s.name}`),i({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},d===void 0)},Jp=(e,t,n,o,r,i)=>{let a=o==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=r?.adopted_entries.length??0,d=[[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,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},Gn=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),qp=(e,t,n,o)=>{if(e!=="project"||t||!Gn(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.`},Bp=(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=Ii(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}},Wp=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let o=await zn(e.resolvedRoots.selected_root,e.scope,t,n);return{state:o.state,fix:o}},Hp=(e,t,n,o)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:Gn(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:Gn(o),rerun_command:t?null:i,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},Kp=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:r,options:i,global:a,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=Bp(t,n,i),p=await O(o.settings_root),u=await we(o.selected_root);r.push(...u.warnings);let m=await me(o.selected_root,n,p,u.state);r.push(...m.warnings);let{state:y,fix:w}=await Wp(e,m.extensions,u.state),f=await me(o.selected_root,n,p,y);r.push(...f.warnings);let _=await ke({pmRoot:o.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await xe({..._,loaded:_.loaded});r.push(..._.warnings),r.push(...$i(_.failed)),r.push(...v.warnings),r.push(...Ai(v.failed)),r.push(...Ti(_,v)),r.push(...Wi(v,_)),r.push(...yp(_,v)),r.push(...Hi(v));let k=Mt(f.extensions,_,v),T=Pi(n,k,_.loaded.map(I=>({layer:I.layer,name:I.name})),_.failed.map(I=>({name:I.name})),_.disabled_by_flag);r.push(...T.warnings);let R=k.filter(I=>I.update_check_status==="failed").map(I=>`extension_update_check_failed:${I.name}`);r.push(...R);let C=Ut(n,r,k,i);r.push(...C.warnings);let se=[...C.warnings],fe={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},E=Ci(se),G=Ri(),Xn=C.warning_codes,Va=qp(n,c,i.vocabulary,_),Ya=Jp(C.remediation,_.failed.length,v.failed.length,i.vocabulary,w,Va),Zn=Hp(n,c,i.vocabulary,_),Xa={status:C.status,scope:n,warning_count:C.warning_count,warning_codes:Xn,total_extensions:k.length,managed_total:k.filter(I=>I.managed).length,enabled_total:k.filter(I=>I.enabled).length,active_total:k.filter(I=>I.active).length,unmanaged_loaded_extension_count:C.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:C.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:C.unmanaged_expected_extension_count,runtime_active_total:k.filter(I=>I.runtime_active===!0).length,activation_status_totals:{ok:k.filter(I=>I.activation_status==="ok").length,failed:k.filter(I=>I.activation_status==="failed").length,not_loaded:k.filter(I=>I.activation_status==="not_loaded").length,unknown:k.filter(I=>I.activation_status==="unknown").length},unknown_capability_count:E.length,capability_contract_version:G.version,update_available_total:k.filter(I=>I.update_available===!0).length,update_health_coverage:C.update_health_coverage,update_health_partial:C.update_health_partial,update_check_failed_total:k.filter(I=>I.update_check_status==="failed").length,load_failure_count:_.failed.length,activation_failure_count:v.failed.length,load_failures:jn(_.failed),activation_failures:jn(v.failed),blocking_failure_count:_.failed.length+v.failed.length,has_blocking_failures:_.failed.length+v.failed.length>0,consistency_warning_count:T.warnings.length,trace_enabled:l,isolation:Zn,policy:fe,remediation:Ya},Za=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(I=>I.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:f.extensions.filter(I=>I.managed).length,adopted_extensions:[]},Bt={mode:d,summary:Xa,triage:C,trace_enabled:l,capability_contract:G,capability_guidance:E,managed_state_fix:Za,isolation:Zn,policy:_.policy};if(d==="deep"){let I=l?v.failed:v.failed.map(D=>{let{trace:Du,...Qa}=D;return Qa});Bt.deep={warnings:se,warning_codes:Xn,capability_contract:G,capability_guidance:E,trace_enabled:l,managed_state:{path:u.path,count:y.entries.length,entries:y.entries},installed_extensions:k,load:{roots:_.roots,policy:_.policy,warnings:_.warnings,failed:_.failed,loaded:_.loaded.map(D=>({layer:D.layer,directory:D.directory,name:D.name,version:D.version,entry:D.entry,priority:D.priority}))},activation:{failed:I,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:T.summary},l&&(Bt.deep.trace={activation_failures:v.failed.filter(D=>D.trace!==void 0).map(D=>({layer:D.layer,name:D.name,entry_path:D.entry_path,error:D.error,method:D.trace.method,command:D.trace.command,capability:D.trace.capability,missing_capability:D.trace.missing_capability,registration_index:D.trace.registration_index,expected_schema:D.trace.expected_schema,hint:D.trace.hint,received:D.trace.received}))})}return s(Bt)},Vp=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:r,options:i,global:a,withResult:s}=e,c=await O(o.settings_root),d=await ke({pmRoot:o.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),l=await xe(d);r.push(...d.warnings),r.push(...l.warnings);let p=gi(t,d,l);if(t!==void 0&&p.extensions.length===0){let u=i.vocabulary==="package"?"package":"extension",m=[...new Set(d.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,f)=>w.localeCompare(f)),y=m.length>0?` Loaded ${u} names: ${m.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})},Yp=async(e,t,n)=>{let o=n,r=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await zn(e.resolvedRoots.selected_root,e.scope,t,n),o=r.state),e.action==="manage"){let i=await qi(o.entries,Ml,async a=>{if(a.source.kind!=="github")return a;let s=await Ki(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 je(e.resolvedRoots.selected_root,o)}return{state:o,fix:r}},Xp=async(e,t,n)=>{let o=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await xe({...o,loaded:o.loaded});return e.warnings.push(...o.warnings,...r.warnings),{installed:Mt(n,o,r),failures:da(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}}},Zp=(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},Zi=async e=>{let{action:t,scope:n,resolvedRoots:o,warnings:r,options:i,withResult:a}=e,s=await O(o.settings_root),c=Xl(s.extensions.policy),d=await we(o.selected_root);r.push(...d.warnings);let l=await me(o.selected_root,n,s,d.state);r.push(...l.warnings);let{state:p,fix:u}=await Yp(e,l.extensions,d.state),m=await me(o.selected_root,n,s,p);if(r.push(...m.warnings),t==="manage"){let v=m.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);r.push(...v)}let y=await Xp(e,s,m.extensions),w=y.installed,f=Ut(n,r,w,i);r.push(...f.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:f,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=Zp(u,w)),a(_)},Qi={init:xp,install:Lp,uninstall:zp,explore:Zi,manage:Zi,describe:Vp,reload:Sp,doctor:Kp,catalog:Ep,adopt:Gp,"adopt-all":Mp,activate:Xi,deactivate:Xi,migrate:wi},Qp=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),eu=e=>Qp(e)?Mn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Qi[e.action](e)):Qi[e.action](e);import fa from"node:fs/promises";import ae from"node:path";import ha from"node:readline/promises";import{stdin as ga,stdout as ht}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]="a4403557-1cbf-5bfe-94ab-cf07c32d5147")}catch{}})();var ya=["ask","add","skip","status"],tu=["AGENTS.md","CLAUDE.md"],nu=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],ou=8,Wn=1,ru="<!-- pm-cli:agent-guidance:start:",iu=`<!-- pm-cli:agent-guidance:start:v${Wn} -->`,qn="<!-- pm-cli:agent-guidance:end -->",yt="Add workflow guidance later: pm init --agent-guidance add",By={toPortableRelativePath:Xe,ensureTrailingNewline:Bn,detectLineEnding:wa,findGuidanceBlockRange:Hn,buildAgentGuidanceBlock:va,upsertAgentGuidanceBlock:ba,resolveProjectRoot:ka,resolveTargetGuidancePath:xa,parsePromptChoice:Sa,pushUnique:Ze,promptForGuidanceWrite:Ea,normalizeAgentGuidanceState:Kn,applyAgentGuidanceState:Aa,writeGuidanceFile:Ta,setAgentGuidanceReadlineFactoryForTests:au},_a=()=>ha.createInterface({input:ga,output:ht});function au(e){_a=e??(()=>ha.createInterface({input:ga,output:ht}))}function Xe(e,t){let n=ae.relative(e,t);return n.length===0?ae.basename(t):n.split(ae.sep).join("/")}function Bn(e){return e.endsWith(`
|
|
43
|
+
`}import pl from"node:fs/promises";import ul 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]="56290db9-933c-590d-8b9f-df62ff45e515")}catch{}})();function Nn(e){return ul.join(e,"extension-migrations.json")}function yi(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 _i(e,t){return`${e.layer}:${e.name}:${t}`}async function ml(e){let t=Nn(e);if(!await x(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await pl.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 fl(e,t){let n=await ml(e),o=new Map(n.entries.map(r=>[r.key,r]));return t.forEach((r,i)=>{let a=yi(r,i),s=o.get(_i(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 hl(e){let t=await fl(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),o=[],r=!1,i=e.migrations.map((l,p)=>({migration:l,index:p})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:p}of i){let u=yi(l,p),m=_i(l,u),y=n.get(m),w=String(l.definition.status??"pending").toLowerCase(),f=y?.status??(w==="applied"||w==="failed"?w:"pending");if(f==="applied"){o.push({key:m,layer:l.layer,extension:l.name,id:u,before:f,outcome:"skipped"});continue}if(e.dryRun===!0){o.push({key:m,layer:l.layer,extension:l.name,id:u,before:f,outcome:"pending"});continue}let _=l.runtime_definition?.run??l.definition.run;if(typeof _!="function"){o.push({key:m,layer:l.layer,extension:l.name,id:u,before:f,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(_({id:u,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:f}));let k={key:m,layer:l.layer,extension:l.name,id:u,status:"applied",attempted_at:v};n.set(m,k),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,o.push({key:m,layer:l.layer,extension:l.name,id:u,before:f,outcome:"applied"}),r=!0}catch(k){let T=k instanceof Error?k.message:String(k),R={key:m,layer:l.layer,extension:l.name,id:u,status:"failed",attempted_at:v,error:T};n.set(m,R),l.definition.status="failed",l.definition.reason=T,o.push({key:m,layer:l.layer,extension:l.name,id:u,before:f,outcome:"failed",error:T}),r=!0}}if(r){let l=await O(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((u,m)=>u.key.localeCompare(m.key))};await Me({pmRoot:e.pmRoot,filePath:Nn(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
|
|
44
|
+
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let a=o.filter(l=>l.outcome==="pending").length,s=o.filter(l=>l.outcome==="applied").length,c=o.filter(l=>l.outcome==="skipped").length,d=o.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:Nn(e.pmRoot),total:o.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:d,migrations:o}}async function wi(e){let t=await O(e.resolvedRoots.settings_root),n=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),o=await xe(n);e.warnings.push(...n.warnings,...o.warnings);let r=await hl({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)}(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]="39bc7f14-2d32-5b58-97ab-647f9f238273")}catch{}})();async function vi(e,t,n){let o=typeof t=="string"?null:await pt(e),r=o===null?null:e.trim().toLowerCase(),i=r===null?null:await Jr(r),a=Ft(o??e,{forceGithub:typeof t=="string",ref:n}),s=r===null?null:await Wr(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 te 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]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function Dn(e){return e.map(({layer:t,name:n,error:o})=>({layer:t,name:n,error:o}))}function Lt(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 gl(e){let t=new Map,n=new Map;for(let o of e.registrations.commands)Lt(t,o.name,o.command),Lt(n,o.name,o.action);for(let o of e.commands.handlers)Lt(t,o.name,o.command);for(let o of e.commands.overrides)Lt(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 yl(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 Mt(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}=gl(n);return e.map(c=>{let d=b(c.name),l=bi(a.get(d)),p=bi(s.get(d)),u={...l?{command_paths:l}:{},...p?{action_paths:p}:{}},m=yl({enabled:c.enabled,normalizedName:d,loadedNames:o,loadFailedNames:r,activationFailedNames:i});return{...c,...m,...u}})}function _l(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 Si=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 wl(e){return Si.has(Oi(e))}function ki(e){return e==="project"||e==="global"}function Ei(e){let t=e.split(":"),n=t[0];if(!n||!Si.has(n))return null;let o=t.at(-4),r=t.at(-3)?.trim(),i=t.at(-2),a=t.at(-1)?.trim();return!ki(o)||!ki(i)||!r||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:o,name:r},displaced:{layer:i,name:a}}}function vl(e){let t=new Set;for(let n of e){let o=Ei(n);o&&(t.add(o.winner.name),t.add(o.displaced.name))}return[...t].sort((n,o)=>n.localeCompare(o))}function bl(e,t){let n=e.filter(wl);if(n.length===0)return null;let o=vl(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 kl(e,t,n,o){let r=t.map(p=>Ei(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])),d=new Map;for(let p of r)for(let u of[p.winner.name,p.displaced.name]){let m=b(u);d.set(m,(d.get(m)??0)+1)}let l=[...d.entries()].map(([p,u])=>{let m=c.get(p),y=m?.name??p,w=m?.command_paths??[],f=m?.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:[...f].sort((_,v)=>_.localeCompare(v))}}}).sort((p,u)=>{let m=u.affected_collisions-p.affected_collisions;if(m!==0)return m;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:d.size,next_best_command:s,collisions:r,remediation_candidates:l}}function $i(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 Ai(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 Ti(e,t){let n=[];for(let o of yo(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 xl=[{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: ${Zn.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 Sl(e){let{normalizedWarnings:t,options:n,scope:o,scopeFlag:r,updateCheckFailedTotal:i,policyWarningCount:a,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,p=[],u={options:n,scope:o,scopeFlag:r,updateCheckFailedTotal:i,policyWarningCount:a};if(t.length>0){let m=bl(t,{deactivate:`${U(n,"deactivate")} <name> ${r}`,doctor:`${U(n,"doctor")} ${r} --detail deep --trace`});m&&p.push(m);for(let y of xl)y.matches(t,u)&&p.push(y.build(u))}return s?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>).`):c>0&&p.push(`Loaded unmanaged extensions are currently treated as informational. Use ${U(n,"manage")} ${r} --fix-managed-state to adopt them for update checks.`),d>0&&p.push("Non-GitHub managed extensions are skipped by update checks. Use doctor output for non-update diagnostics."),l>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 Ut(e,t,n,o={}){let r=[...new Set(t)].sort((E,G)=>E.localeCompare(G)),i=n.filter(E=>E.managed).length,a=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,c=n.filter(E=>E.update_available===!0).length,d=n.filter(E=>E.managed===!1),l=d.filter(E=>xi(E)).map(E=>E.name).sort((E,G)=>E.localeCompare(G)),p=d.filter(E=>!xi(E)).map(E=>E.name).sort((E,G)=>E.localeCompare(G)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)u[E.update_check_status]+=1;let m=u.failed,y=u.skipped_unmanaged,w=u.skipped_non_github,f=p.length>0,_=f?"partial":"full",v=f?[`extension_update_health_partial_coverage:skipped_unmanaged:${p.length}`]:[],k=[...new Set([...r,...v])].sort((E,G)=>E.localeCompare(G)),T=[...new Set(k.map(E=>Oi(E)))].sort((E,G)=>E.localeCompare(G)),R=_l(k),C=e==="global"?"--global":"--project",se=kl(e,r,n,o),fe=Sl({normalizedWarnings:r,options:o,scope:e,scopeFlag:C,updateCheckFailedTotal:m,policyWarningCount:R.warning_count,updateHealthPartial:f,skippedUnmanagedTotal:y,skippedNonGithubTotal:w,updateAvailableTotal:c});return{status:k.length===0?"ok":"warn",warning_count:k.length,warning_codes:T,warnings:k,policy_warning_count:R.warning_count,policy_violation_count:R.violation_count,policy_blocked_count:R.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:f,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(E=>E.name).sort((E,G)=>E.localeCompare(G)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:u,update_check_failed_total:m,top_warnings:k.slice(0,8),remediation:fe,...se?{collision_plan:se}:{}}}function Ii(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 Oi(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Ci(e){let t=new Set,n=[];for(let o of e){let r=(()=>{let i=co(o);return i?[i]:lo(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 Ri(){return{version:_t.version,capabilities:[..._t.capabilities],legacy_aliases:{..._t.legacy_aliases}}}function xi(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Pi(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(l=>l.active).map(l=>b(l.name)))].sort((l,p)=>l.localeCompare(p)),a=[...new Set(n.filter(l=>l.layer==="project").map(l=>b(l.name)))].sort((l,p)=>l.localeCompare(p)),s=new Set(o.map(l=>b(l.name))),c=i.filter(l=>!a.includes(l)&&!s.has(l)).sort((l,p)=>l.localeCompare(p));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:i.length,loaded_project_count:a.length,active_project_names:i,loaded_project_names:a,missing_active_project_names:c}}}import{randomUUID as El}from"node:crypto";import M from"node:fs/promises";import $l from"node:os";import N 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]="263602a2-c000-5df7-80d2-6f095985496f")}catch{}})();var Ni=3,Al=120,Di=250,Tl=12e4,Il=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),ji=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Fi=e=>Il.has(String(ji(e))),Gt=(e,t)=>ji(e)===t,Li=e=>new Promise(t=>{setTimeout(t,e)}),Mi=async e=>{let t=N.join(e,"package.json");await x(t)||await M.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
45
|
+
`,"utf8")},Ui=async e=>{let t=ce(import.meta.url,["../../.."]),n=N.join(e,"node_modules","@unbrained"),o=N.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")},jn=async e=>{let t=N.resolve(e),n=N.dirname(t),o=N.parse(n).root,r=await M.realpath(o).catch(()=>o),i=N.relative(o,n),a=i===""?[]:i.split(N.sep);for(let[s,c]of a.entries()){let d=N.join(r,c);try{r=await M.realpath(d)}catch{r=N.join(r,...a.slice(s));break}}return N.join(r,N.basename(t))},Gi=async(e,t,n,o=$l.tmpdir())=>{let r=N.resolve(e),i=await M.realpath(r).catch(()=>r),a=await jn(t);if(i===a)return;if(!Z(i,a)){await n(e,t,{recursive:!0,force:!0});return}let s=u=>{let m=N.resolve(u);if(m!==r&&!Z(r,m))return!1;let y=N.resolve(i,N.relative(r,m));if(y===a||Z(a,y))return!1;let f=N.relative(i,y).split(N.sep);return f.some(_=>_==="node_modules"||_.startsWith(".pm-extension-install-backup-"))?!1:f[0]!==".agents"},c=await M.realpath(N.resolve(o)).catch(()=>jn(o)),d=Z(i,c)?N.dirname(i):c;if(Z(i,d))throw new h(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,g.USAGE,{code:"extension_install_source_contains_destination"});let l=await M.mkdtemp(N.join(d,"pm-extension-copy-")),p=N.join(l,"extension");try{await n(e,p,{recursive:!0,force:!0,filter:s}),await n(p,t,{recursive:!0,force:!0})}finally{await M.rm(l,{recursive:!0,force:!0})}},zi=async(e,t,n=M.cp)=>{for(let o=1;o<=Ni;o+=1)try{await M.rm(t,{recursive:!0,force:!0}),await Gi(e,t,n);return}catch(r){if(!Fi(r)||o===Ni)throw r;await Li(Di)}},Fn=async e=>{let t;try{t=await M.readFile(N.join(e,"owner.json"),"utf8")}catch(r){if(!Qn(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},Ji=async(e,t)=>await Fn(e)!==t?!1:(await M.rm(e,{recursive:!0,force:!0}),!0),Ol=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 Fn(e);return o===null?(await M.rm(e,{recursive:!0,force:!0}),!0):Ji(e,o)},Cl=(e,t,n)=>{let o=Promise.resolve(),r=setInterval(()=>{o=o.then(async()=>{if(await Fn(e)!==t)return;let i=new Date;await M.utimes(e,i,i)}).catch(()=>{})},n);return r.unref(),async()=>{clearInterval(r),await o}},Rl=async(e,t)=>{await M.mkdir(e);try{await M.writeFile(N.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
46
|
+
`,"utf8")}catch(n){throw await M.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Pl=async(e,t,n,o,r)=>{for(let i=1;i<=n;i+=1)try{return await Rl(e,t),!0}catch(a){if(!Gt(a,"EEXIST"))throw a;await Ol(e,r)?i-=1:await Li(o)}return!1},Ln=async(e,t,n,o)=>{let r=N.join(e,"runtime","extension-install-locks"),i=N.join(r,"scope.lock");await M.mkdir(r,{recursive:!0});let{attempts:a=Al,delay_ms:s=Di,stale_ms:c=Tl,heartbeat_ms:d}=o??{};if(![a,s,c,d].filter(_=>_!==void 0).every(Number.isFinite))throw new h("Extension install lock timings must be finite numbers.",g.USAGE);let l=Math.max(1,Math.floor(a)),p=Math.max(0,Math.floor(s)),u=Math.floor(c),m=Math.floor(d??u/3);if(u<=0||m<=0||m>=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:El(),created_at:A(),destination:t};if(!await Pl(i,y,l,p,u))throw new h(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let f=Cl(i,y.token,m);try{return await n()}finally{await f(),await Ji(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]="4d3c62e9-9116-5cdc-bbda-48bbd2e39476")}catch{}})();var qi=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]="b17dfc10-9e07-5912-b294-c5663133f192")}catch{}})();function Bi(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]="0dc7b063-dc72-595f-8e40-8a06f9db69e1")}catch{}})();function Wi(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=>!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]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var Hi=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=xt(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]="ccb857a5-045d-57a7-91d2-b761225fe53a")}catch{}})();var Nl=1e4,Dl=(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"}},Ki=async(e,t=Dt)=>{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,Nl);return Dl(r,e.commit,n)}catch(o){return{checked_at:n,available:null,error:o instanceof Error?o.message:String(o)}}};import Le from"node:fs/promises";import jl 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]="98b47a2f-d48a-5c90-8b88-3f33bdd1c826")}catch{}})();var Mn=async e=>Le.readFile(e).catch(t=>{if(Gt(t,"ENOENT"))return null;throw t}),Vi=async(e,t,n,o,r)=>{let i=ct(e),a=be(t),[s,c]=await Promise.all([Mn(i),Mn(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}},Yi=async e=>{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(jl.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]="8b0fbe09-2221-5b8e-8712-90a83df19306")}catch{}})();var Fl=4,ea=[["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"]],Ll=ea.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Ml={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"},Ul="__pm_native_output",Gl=["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"],ta=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],zl=["disabled","require_trusted","require_provenance"],na={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:[]},Jl=e=>{let t=e??na,n={};for(let o of Gl)n[o]=X(t[o]??[]);return n},ql=(e,t)=>{for(let n of ta)t[n].length>0&&(e[n]=t[n]);return e},Bl=(e,t)=>{for(let n of zl)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Wl=e=>{let t={};for(let n of ta)t[n]=X(e[n]??[]);return t},Hl=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:ql(Bl({name:t},e),Wl(e))},Kl=e=>(e??[]).map(t=>Hl(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Vl=e=>{let t=Object.assign({},na,e??{}),n=Jl(e),o=Kl(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}},oa=async(e,t)=>{let n=[t],o=await qr(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}},ra=(e,t)=>{let n=t.trim(),o=new Set(X(e.extensions.enabled));return new Set(X(e.extensions.disabled)).has(n)?!1:o.size===0?!0:o.has(n)},ia=(e,t)=>{let n=t.trim(),o=new Set(X(e.extensions.enabled)),r=new Set(X(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")},Yl=(e,t)=>{let n=t.trim(),o=new Set(X(e.extensions.enabled)),r=new Set(X(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")},Xl=(e,t)=>{let n=t.trim(),o=new Set(X(e.extensions.enabled)),r=new Set(X(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")},Ql=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),o=ea.map(([r,i,a])=>({action:i,flag:a,distance:oo(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},Zl=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=Ql(e);if(!o)return new h(`One action flag is required. Use one of: ${Ll}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let r=`pm ${n} ${o.flag}`;return ro({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(aa),retry_command:r,message_suffix:`. Did you mean "${o.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:r,reason:`nearest lifecycle action for "${e}"`}]})},ep=[["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"]],aa={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},tp=e=>aa[e]??null,np=(e,t)=>{let n=[...new Set(ep.filter(([o])=>t[o]===!0).map(([,o])=>o))];if(n.length===0){if(e===void 0)return"explore";let o=tp(e.trim().toLowerCase());if(o)return o;throw Zl(e,t)}if(n.length>1)throw new h("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},op=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"},rp=[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"}}],sa=e=>{for(let t of rp){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},ca=(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}},ip=(e,t,n,o)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},o),i=o?ra(n,o.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ca({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:i},t,o,sa(o))}},ap=async(e,t,n,o,r,i)=>{let a=te.join(e,t),s=te.join(a,"manifest.json"),c=i.get(b(t));if(!await x(s))return ip(t,n,o,c);let d=Symbol("invalid-extension-manifest-json"),l=await Oe.readFile(s,"utf8").then(m=>JSON.parse(m)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=bn(l);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=r.get(b(p.name))??i.get(b(t));return{summary:ca({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:ra(o,p.name)},n,u,sa(u))}},me=async(e,t,n,o)=>{if(!await x(e))return{extensions:[],warnings:[]};let i=(await Oe.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,p)=>l.localeCompare(p)),a=new Map(o.entries.map(l=>[b(l.name),l])),s=new Map(o.entries.map(l=>[b(l.directory),l])),c=[],d=[];for(let l of i){let p=await ap(e,l,t,n,a,s);p.warning&&c.push(p.warning),p.summary&&d.push(p.summary)}return{extensions:d.sort((l,p)=>l.name.localeCompare(p.name)),warnings:c.sort((l,p)=>l.localeCompare(p))}},sp=ho(),cp=(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:cp(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"}:{}}},lp=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},da=e=>e.map(t=>lp(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),la=(e,t,n)=>{let o=b(e);return t.find(r=>(n===void 0||r.layer===n)&&b(r.name)===o)},pp=(e,t,n,o)=>n.find(i=>i.scope===t&&b(i.name)===b(e))?.activation_status??(o?"failed":"unknown"),pa=(e,t,n,o,r)=>sp.enqueue(async()=>{let i=process.env.PM_CLI_PACKAGE_ROOT,a=await Oe.mkdtemp(te.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=ce(import.meta.url,["../.."]);try{let s=await ke({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:r.noExtensions===!0,reload_token:Xt(),cache_bust:!0,module_graph_snapshot_root:a}),c=await xe({...s}),d=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...da(c.failed)],l=Object.fromEntries(s.loaded.map(p=>[b(p.name),uo(Ge(c,{extensionName:p.name}))]));return{installed:Mt(o,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await Oe.rm(a,{recursive:!0,force:!0}),i===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=i}}),Gn=async(e,t,n,o)=>{let r=n.filter(c=>!c.managed),i=[...r].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),a=o,s=[];for(let c of i){let d=te.join(e,c.directory),l=await Ye(d),p=A(),u={kind:"local",input:c.name,location:d};a=lt(a,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:p,updated_at:p,source:u}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:u})}return s.length>0&&await je(e,a),{state:a,adopted_entries:s,unmanaged_candidates:i,already_managed_count:n.length-r.length}},up=(e,t)=>{let n=j(process.cwd(),t.path),o=wt(n,process.cwd()),r=e==="global"?so(process.cwd()):n,i=e==="global"?o.global:o.project;return{pm_root:n,scope:e,settings_root:r,selected_root:i,roots:o}},zt=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=>Ml[e],fp=(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`}]}})},Jt=(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 fp(t,n)},hp=(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))},gp=(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",message:"--dry-run is only valid with --migrate."}].find(r=>r.triggered&&!r.allowed);if(o)throw new h(o.message,g.USAGE)},yp=(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},_p=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},wp=(e,t,n)=>{let o={ok:n,action:e.action,scope:e.scope,roots:_p(e),warnings:[...new Set(e.warnings)].sort((r,i)=>r.localeCompare(i)),details:t};return e.action==="doctor"&&Object.defineProperty(o,Ul,{value:!0,enumerable:!1,configurable:!1}),o},zn=async(e,t,n)=>{let o=np(e,t);gp(o,t);let r=yp(e,o,t),i=op(t),a=up(i,n),c={action:o,normalizedTarget:r,scope:i,resolvedRoots:a,warnings:[],options:t,global:n},l={...c,withResult:(p,u=!0)=>wp(c,p,u)};return await Qp(l)},vp=(e,t)=>{let n=t.vocabulary??"extension",o=e.target_path.replace(/\\/g,"/"),r=bo(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: ${kt(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`]},bp=async e=>{let{action:t,normalizedTarget:n,options:o,withResult:r}=e;if([zt(o),o.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new h('Action "init" does not accept --gh/--github/--ref options.',g.USAGE);let s=Jt(n,t,o),c=await pi(s,o.vocabulary??"extension",o.capability,o.declarative===!0);return r({scaffolded:c.created_directory||c.files.some(d=>d.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:vp(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 O(n.settings_root),c=Xt(),d=await ke({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:i.noExtensions,reload_token:c,cache_bust:!0});o.push(...d.warnings);let l=await xe(d);o.push(...l.warnings);let p={reload:{token:c,cache_bust:!0,watch:r.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(u=>({name:u.name,layer:u.layer,version:u.version})),failed_extensions:d.failed.map(u=>({name:u.name,layer:u.layer,error:u.error})),activation_failures:l.failed.map(u=>({name:u.name,layer:u.layer,error:u.error}))};return r.watch===!0&&o.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},xp=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 Br(n,r,o))},Sp=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Ep=e=>({kind:"local",input:e.input,location:e.absolute_path}),$p=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),Ap=(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}),Tp=(e,t,n,o)=>e?Sp(e,t):n.kind==="local"?Ep(n):n.kind==="npm"?$p(n,o):Ap(n,o),Ip=(e,t,n,o)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:o}:Lr(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},Op=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:r}=e,{validated:i,destinationDirectoryName:a}=t,s=await O(o.settings_root),c=await we(o.selected_root);r.push(...c.warnings);let d=te.join(o.selected_root,a),l=await x(d),p=await Zr(i.directory,d);await Oe.mkdir(o.selected_root,{recursive:!0});let u=await Oe.mkdtemp(te.join(o.selected_root,".pm-extension-install-backup-")),m=te.join(u,"destination");try{let y=await Vi(o.selected_root,o.settings_root,d,l,m),w=Tp(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),f=c.state.entries.find(T=>b(T.name)===b(i.manifest.name)),_=Ip(f,i.manifest.version,w,A()),v=lt(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}),k=ia(s,i.manifest.name);try{p||await zi(i.directory,d),await Mi(d),await Ui(d),await je(o.selected_root,v),k&&await Ee(o.settings_root,s,"settings:write")}catch(T){try{await Yi(y)}catch(R){throw new AggregateError([T,R],`Extension install failed: ${String(T)}; rollback failed: ${String(R)}`,{cause:R})}throw T}return{settings:s,managedState:v,sourceRecord:w,destinationDirectory:d,destinationExists:l,installInPlace:p,activationChanged:k}}finally{await Oe.rm(u,{recursive:!0,force:!0}).catch(()=>{})}},Cp=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 it(e.resolvedRoots.pm_root,o,e.warnings,"install:type-folder"),o},Rp=(e,t,n,o,r)=>{let i=la(t,n.activation_failures,e.scope),a=pp(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)]}}},Pp=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:r,global:i,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,d=await Op(e,t),l=await me(o.selected_root,n,d.settings,d.managedState);r.push(...l.warnings);let p=await pa(o.pm_root,te.dirname(o.selected_root),d.settings,l.extensions,i);r.push(...p.warnings);let u=await Cp(e,s.manifest.name,p.item_type_registrations),m=Bi(s.manifest.name,p.installed),y=Rp(e,s.manifest.name,p,m,u),w=p.contribution_inventories[b(s.manifest.name)];return w&&(d.managedState=await Mr(o.selected_root,d.managedState,s.manifest.name,w)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:y.activated,settings_changed:d.activationChanged,runtime_activation_status:y.status,command_paths:m.command_paths,action_paths:m.action_paths,contributions:w,command_discovery:dp(s.manifest.name,d.sourceRecord,m,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)},Np=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 c of await Nt()){let d=await pt(c),l=te.resolve(d),p=a.get(l);p===void 0&&(p=await zn(c,{...t,install:!0},n),a.set(l,p)),i.push({alias:c,result:p})}o.push(...i.flatMap(c=>c.result.warnings));let s=i.every(c=>c.result.ok);return r({installed_all:s,installed_count:i.filter(c=>c.result.ok).length,failed_count:i.filter(c=>!c.result.ok).length,packages:i.map(c=>{let d=c.result.details;return{alias:c.alias,ok:c.result.ok,extension:d.extension,source:d.source,source_resolution:d.source_resolution,destination_path:d.destination_path,activated:d.activated,settings_changed:d.settings_changed,command_paths:d.command_paths,action_paths:d.action_paths,command_discovery:d.command_discovery,verification:d.verification,runtime_activation_status:d.runtime_activation_status,activation_diagnostics:d.activation_diagnostics,warnings:c.result.warnings}})},s)},Dp=async(e,t,n)=>{let{resolvedRoots:o}=e,{bundledAliasName:r,bundledPackageName:i,installSource:a,sourceResolution:s}=await vi(t,n,e.options.ref);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${r}:npm:${d.package}`)}let c=await Qr(a);try{let d=await Ye(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),l=Rt(d.manifest.name);return await Ln(o.settings_root,l,()=>Pp(e,{validated:d,destinationDirectoryName:l,bundledAliasName:r,bundledPackageName:i,sourceResolution:s,installSource:a,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},jp=async e=>{let t=zt(e.options),n=t??Jt(e.normalizedTarget,e.action,e.options);return[t===void 0,Gr(n)].every(Boolean)?Np(e):Dp(e,n,t)},Fp=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(zt(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 O(o.settings_root),d=await we(o.selected_root);r.push(...d.warnings);let l=await me(o.selected_root,n,c,d.state);r.push(...l.warnings);let p=await Gn(o.selected_root,n,l.extensions,d.state),u=await me(o.selected_root,n,c,p.state);r.push(...u.warnings);let m=Ut(n,r,u.extensions,i);r.push(...m.warnings);let y=new Map(u.extensions.map(_=>[`${b(_.name)}:${b(_.directory)}`,_])),w=new Map(u.extensions.map(_=>[b(_.directory),_])),f=p.adopted_entries.map(_=>{let v=b(_.directory),k=y.get(`${b(_.name)}:${v}`)??w.get(v);return{..._,...ua(k)}});return a({adopted_all:f.length>0,adopted_count:f.length,already_managed_count:p.already_managed_count,extensions:f,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},ua=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Lp=(e,t,n,o)=>{if(e===void 0)return{kind:"local",input:t,location:n};let r=Ft(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}},Mp=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:r,warnings:i,options:a,withResult:s}=e,c=Jt(n,t,a),d=zt(a),l=await O(r.settings_root),p=await we(r.selected_root);i.push(...p.warnings);let u=await me(r.selected_root,o,l,p.state);i.push(...u.warnings);let m=await oa(u.extensions,c);if(!m)throw new h(`Installed extension "${c}" was not found in ${o} scope.`,g.NOT_FOUND);if(m.managed)return s({adopted:!1,already_managed:!0,extension:{name:m.name,directory:m.directory}});let y=te.join(r.selected_root,m.directory),w=await Ye(y),f=A(),_=Lp(d,c,y,a.ref),v=lt(p.state,{name:w.manifest.name,directory:m.directory,scope:o,manifest_version:w.manifest.version,manifest_entry:w.manifest.entry,capabilities:[...w.manifest.capabilities],contributions:w.manifest.contributions,installed_at:f,updated_at:f,source:_});await je(r.selected_root,v);let k=await me(r.selected_root,o,l,v);i.push(...k.warnings);let T=k.extensions.find(R=>b(R.name)===b(w.manifest.name))??k.extensions.find(R=>b(R.directory)===b(m.directory));return s({adopted:!0,extension:{name:w.manifest.name,directory:m.directory,version:w.manifest.version,entry:w.manifest.entry},source:_,...ua(T)})},ma=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:r,warnings:i,options:a}=e,s=Jt(n,t,a),c=await O(r.settings_root),d=await we(r.selected_root);i.push(...d.warnings);let l=await me(r.selected_root,o,c,d.state);i.push(...l.warnings);let p=await oa(l.extensions,s);if(!p)throw new h(`Installed extension "${s}" was not found in ${o} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:p}},Up=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:o,managedStateRead:r,candidate:i}=await ma(e),a=te.join(t.selected_root,i.directory);await Oe.rm(a,{recursive:!0,force:!0});let s={...r.state,updated_at:A(),entries:r.state.entries.filter(d=>b(d.name)!==b(i.name)&&b(d.directory)!==b(i.directory))};await je(t.selected_root,s);let c=Xl(o,i.name);return c&&await Ee(t.settings_root,o,"settings:write"),n({removed:!0,extension:{name:i.name,directory:i.directory},destination_path:a,settings_changed:c})},Xi=async e=>{let{action:t,resolvedRoots:n,warnings:o,global:r,withResult:i}=e,{settings:a,candidate:s}=await ma(e),c=t==="activate"?ia(a,s.name):Yl(a,s.name);c&&await Ee(n.settings_root,a,"settings:write");let d=t==="activate"?await pa(n.pm_root,te.dirname(n.selected_root),a,[s],r).then(l=>(o.push(...l.warnings),la(s.name,l.activation_failures,e.scope))):void 0;return d&&o.push(`extension_activate_failed:${e.scope}:${s.name}`),i({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},d===void 0)},Gp=(e,t,n,o,r,i)=>{let a=o==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=r?.adopted_entries.length??0,d=[[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,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},Un=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),zp=(e,t,n,o)=>{if(e!=="project"||t||!Un(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.`},Jp=(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=Ii(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}},qp=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let o=await Gn(e.resolvedRoots.selected_root,e.scope,t,n);return{state:o.state,fix:o}},Bp=(e,t,n,o)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:Un(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:Un(o),rerun_command:t?null:i,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},Wp=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:r,options:i,global:a,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=Jp(t,n,i),p=await O(o.settings_root),u=await we(o.selected_root);r.push(...u.warnings);let m=await me(o.selected_root,n,p,u.state);r.push(...m.warnings);let{state:y,fix:w}=await qp(e,m.extensions,u.state),f=await me(o.selected_root,n,p,y);r.push(...f.warnings);let _=await ke({pmRoot:o.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await xe({..._,loaded:_.loaded});r.push(..._.warnings),r.push(...$i(_.failed)),r.push(...v.warnings),r.push(...Ai(v.failed)),r.push(...Ti(_,v)),r.push(...Wi(v,_)),r.push(...hp(_,v)),r.push(...Hi(v));let k=Mt(f.extensions,_,v),T=Pi(n,k,_.loaded.map(I=>({layer:I.layer,name:I.name})),_.failed.map(I=>({name:I.name})),_.disabled_by_flag);r.push(...T.warnings);let R=k.filter(I=>I.update_check_status==="failed").map(I=>`extension_update_check_failed:${I.name}`);r.push(...R);let C=Ut(n,r,k,i);r.push(...C.warnings);let se=[...C.warnings],fe={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},E=Ci(se),G=Ri(),Yn=C.warning_codes,Va=zp(n,c,i.vocabulary,_),Ya=Gp(C.remediation,_.failed.length,v.failed.length,i.vocabulary,w,Va),Xn=Bp(n,c,i.vocabulary,_),Xa={status:C.status,scope:n,warning_count:C.warning_count,warning_codes:Yn,total_extensions:k.length,managed_total:k.filter(I=>I.managed).length,enabled_total:k.filter(I=>I.enabled).length,active_total:k.filter(I=>I.active).length,unmanaged_loaded_extension_count:C.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:C.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:C.unmanaged_expected_extension_count,runtime_active_total:k.filter(I=>I.runtime_active===!0).length,activation_status_totals:{ok:k.filter(I=>I.activation_status==="ok").length,failed:k.filter(I=>I.activation_status==="failed").length,not_loaded:k.filter(I=>I.activation_status==="not_loaded").length,unknown:k.filter(I=>I.activation_status==="unknown").length},unknown_capability_count:E.length,capability_contract_version:G.version,update_available_total:k.filter(I=>I.update_available===!0).length,update_health_coverage:C.update_health_coverage,update_health_partial:C.update_health_partial,update_check_failed_total:k.filter(I=>I.update_check_status==="failed").length,load_failure_count:_.failed.length,activation_failure_count:v.failed.length,load_failures:Dn(_.failed),activation_failures:Dn(v.failed),blocking_failure_count:_.failed.length+v.failed.length,has_blocking_failures:_.failed.length+v.failed.length>0,consistency_warning_count:T.warnings.length,trace_enabled:l,isolation:Xn,policy:fe,remediation:Ya},Qa=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(I=>I.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:f.extensions.filter(I=>I.managed).length,adopted_extensions:[]},Bt={mode:d,summary:Xa,triage:C,trace_enabled:l,capability_contract:G,capability_guidance:E,managed_state_fix:Qa,isolation:Xn,policy:_.policy};if(d==="deep"){let I=l?v.failed:v.failed.map(D=>{let{trace:Pu,...Za}=D;return Za});Bt.deep={warnings:se,warning_codes:Yn,capability_contract:G,capability_guidance:E,trace_enabled:l,managed_state:{path:u.path,count:y.entries.length,entries:y.entries},installed_extensions:k,load:{roots:_.roots,policy:_.policy,warnings:_.warnings,failed:_.failed,loaded:_.loaded.map(D=>({layer:D.layer,directory:D.directory,name:D.name,version:D.version,entry:D.entry,priority:D.priority}))},activation:{failed:I,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:T.summary},l&&(Bt.deep.trace={activation_failures:v.failed.filter(D=>D.trace!==void 0).map(D=>({layer:D.layer,name:D.name,entry_path:D.entry_path,error:D.error,method:D.trace.method,command:D.trace.command,capability:D.trace.capability,missing_capability:D.trace.missing_capability,registration_index:D.trace.registration_index,expected_schema:D.trace.expected_schema,hint:D.trace.hint,received:D.trace.received}))})}return s(Bt)},Hp=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:r,options:i,global:a,withResult:s}=e,c=await O(o.settings_root),d=await ke({pmRoot:o.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),l=await xe(d);r.push(...d.warnings),r.push(...l.warnings);let p=gi(t,d,l);if(t!==void 0&&p.extensions.length===0){let u=i.vocabulary==="package"?"package":"extension",m=[...new Set(d.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,f)=>w.localeCompare(f)),y=m.length>0?` Loaded ${u} names: ${m.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})},Kp=async(e,t,n)=>{let o=n,r=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await Gn(e.resolvedRoots.selected_root,e.scope,t,n),o=r.state),e.action==="manage"){let i=await qi(o.entries,Fl,async a=>{if(a.source.kind!=="github")return a;let s=await Ki(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 je(e.resolvedRoots.selected_root,o)}return{state:o,fix:r}},Vp=async(e,t,n)=>{let o=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await xe({...o,loaded:o.loaded});return e.warnings.push(...o.warnings,...r.warnings),{installed:Mt(n,o,r),failures:da(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}}},Yp=(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},Qi=async e=>{let{action:t,scope:n,resolvedRoots:o,warnings:r,options:i,withResult:a}=e,s=await O(o.settings_root),c=Vl(s.extensions.policy),d=await we(o.selected_root);r.push(...d.warnings);let l=await me(o.selected_root,n,s,d.state);r.push(...l.warnings);let{state:p,fix:u}=await Kp(e,l.extensions,d.state),m=await me(o.selected_root,n,s,p);if(r.push(...m.warnings),t==="manage"){let v=m.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);r.push(...v)}let y=await Vp(e,s,m.extensions),w=y.installed,f=Ut(n,r,w,i);r.push(...f.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:f,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=Yp(u,w)),a(_)},Zi={init:bp,install:jp,uninstall:Up,explore:Qi,manage:Qi,describe:Hp,reload:kp,doctor:Wp,catalog:xp,adopt:Mp,"adopt-all":Fp,activate:Xi,deactivate:Xi,migrate:wi},Xp=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),Qp=e=>Xp(e)?Ln(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Zi[e.action](e)):Zi[e.action](e);import fa from"node:fs/promises";import ae from"node:path";import ha from"node:readline/promises";import{stdin as ga,stdout as ht}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]="b7c97e30-02c8-547c-b3db-c6c59e662b54")}catch{}})();var ya=["ask","add","skip","status"],Zp=["AGENTS.md","CLAUDE.md"],eu=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],tu=8,Bn=1,nu="<!-- pm-cli:agent-guidance:start:",ou=`<!-- pm-cli:agent-guidance:start:v${Bn} -->`,Jn="<!-- pm-cli:agent-guidance:end -->",yt="Add workflow guidance later: pm init --agent-guidance add",Gy={toPortableRelativePath:Xe,ensureTrailingNewline:qn,detectLineEnding:wa,findGuidanceBlockRange:Wn,buildAgentGuidanceBlock:va,upsertAgentGuidanceBlock:ba,resolveProjectRoot:ka,resolveTargetGuidancePath:xa,parsePromptChoice:Sa,pushUnique:Qe,promptForGuidanceWrite:Ea,normalizeAgentGuidanceState:Hn,applyAgentGuidanceState:Aa,writeGuidanceFile:Ta,setAgentGuidanceReadlineFactoryForTests:ru},_a=()=>ha.createInterface({input:ga,output:ht});function ru(e){_a=e??(()=>ha.createInterface({input:ga,output:ht}))}function Xe(e,t){let n=ae.relative(e,t);return n.length===0?ae.basename(t):n.split(ae.sep).join("/")}function qn(e){return e.endsWith(`
|
|
47
47
|
`)?e:`${e}
|
|
48
48
|
`}function wa(e){return e.includes(`\r
|
|
49
49
|
`)?`\r
|
|
50
50
|
`:`
|
|
51
|
-
`}function
|
|
51
|
+
`}function Wn(e){let t=e.indexOf(nu);if(t===-1)return null;let n=e.indexOf(Jn,t);return n===-1?null:{start_index:t,end_index:n+Jn.length}}function iu(e){return Wn(e)!==null}function va(e){return[ou,"## pm Workflow (Agent Quickstart)","",'- Orient before mutate: `pm context --limit 10`, `pm search "<keywords>" --limit 10`, `pm list --status open --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="node scripts/run-tests.mjs test -- ..."`.','- Verify and close: `pm test <id> --run --progress`, `pm close <id> "<evidence>" --validate-close warn`, `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Jn,""].join(e)}function ba(e){let t=wa(e),n=va(t),o=Wn(e);if(o){let a=e.slice(o.end_index),s=a.startsWith(`\r
|
|
52
52
|
`)?a.slice(2):a.startsWith(`
|
|
53
|
-
`)?a.slice(1):a,c=
|
|
53
|
+
`)?a.slice(1):a,c=qn(`${e.slice(0,o.start_index)}${n}${s}`);return{next_content:c,changed:c!==e}}let r=e.length===0?"":e.endsWith(`
|
|
54
54
|
`)?`
|
|
55
55
|
`:`
|
|
56
56
|
|
|
57
|
-
`,i=
|
|
57
|
+
`,i=qn(`${e}${r}${n}`);return{next_content:i,changed:i!==e}}function ka(e,t){let n=ae.dirname(e);return ae.basename(e)==="pm"&&ae.basename(n)===".agents"?ae.dirname(n):ae.resolve(t,e)}function xa(e,t){let n=e.find(r=>ae.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:ae.join(t,"AGENTS.md")}function Sa(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 Ea(e){let t=_a();try{ht.write(`
|
|
58
58
|
Agent guidance check
|
|
59
59
|
`),ht.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
60
60
|
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return ht.write(`
|
|
61
|
-
`),Sa(n,!0)}finally{t.close()}}function Kn(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:Wn,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 $a(e){let t=[];for(let n of tu){let o=ae.join(e,n),r=await x(o);if(!r){t.push({file_path:o,exists:r,has_guidance:!1,has_marker:!1});continue}let i=await fa.readFile(o,"utf8"),a=i.toLowerCase(),s=nu.filter(d=>a.includes(d)),c=su(i);t.push({file_path:o,exists:r,has_guidance:c||s.length>=ou,has_marker:c})}return t}function Ze(e,t){e.includes(t)||e.push(t)}function Aa(e,t){let n=Kn(e),o=JSON.stringify(n)!==JSON.stringify(t);return o&&(e.agent_guidance=t),{changed:o,state:t}}async function Ta(e){let n=await x(e)?await fa.readFile(e,"utf8"):"",o=ba(n);return o.changed?(await he(e,o.next_content),{changed:!0,warnings:await q({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function cu(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=>Xe(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Xe(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Xe(e.projectRoot,t.file_path))}}async function du(e,t,n){return e?await $a(n):t}function gt(e,t,n){e.state={...e.state,...n,template_version:Wn,last_checked_files:t}}async function Ia(e,t){if(t.presentBefore)return;let n=await Ta(t.targetPath);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function lu(e,t){t||(e.warnings.push("agent_guidance:missing"),Ze(e.nextSteps,yt))}function pu(e,t){e.skipped=!0,gt(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,yt)}async function uu(e,t){await Ia(e,t),gt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function mu(e,t){e.state.declined&>(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function fu(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ze(e.nextSteps,yt)}async function hu(e,t){if(e.prompted=!0,await Ea(t.targetRelativePath)){await Ia(e,t),gt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,gt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ze(e.nextSteps,yt)}function gu(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ze(e.nextSteps,yt)}async function yu(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(lu(n,t.presentBefore),n):t.mode==="skip"?(pu(n,t.checkedFiles),n):t.mode==="add"?(await uu(n,t),n):t.presentBefore?(mu(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(fu(n),n):t.interactive?(await hu(n,t),n):(gu(n),n)}async function Oa(e){let t=ka(e.pm_root,e.cwd),n=await $a(t),o=xa(n,t),r=Xe(t,o),i=n.map(l=>Xe(t,l.file_path)),a=n.some(l=>l.has_guidance),s=await yu(Kn(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:o,targetRelativePath:r,checkedFiles:i,presentBefore:a}),c=Aa(e.settings,s.state);return n=await du(s.applied,n,t),{summary:cu({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 _u from"node:fs/promises";import F from"node:path";import Ra from"node:readline/promises";import{stdin as Pa,stdout as V}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]="75c0d2d2-6a89-508f-b7dd-b43d55978b44")}catch{}})();function h_(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 g_={normalizeInitGovernancePreset:Vn,normalizeInitTypePreset:Da,normalizeOptionalInitAuthor:ja,normalizeInitAgentGuidanceMode:Ma,isPathLikeInitTarget:qt,resolveInitInvocation:Fa,resolveInitPrefixInput:La,parseYesNoChoice:Ua,applyGovernancePreset:Yn,runInitWizard:Wa,setInitReadlineFactoryForTests:wu,summarizeInstalledPackages:Ga,buildInitNextSteps:Ha,registerInitTypePreset:za,assertExplicitTrackerPathIsNotWorkspaceRoot:qa,isLikelyWorkspaceRoot:Ja,installInitMergeFence:Ka},Na=()=>Ra.createInterface({input:Pa,output:V});function wu(e){Na=e??(()=>Ra.createInterface({input:Pa,output:V}))}function vu(){return structuredClone(Ht)}var bu=["minimal","default","strict"];function Vn(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: ${bu.join(", ")}`,g.USAGE)}function Da(e){if(e!==void 0){if(e.trim().length===0)throw new h("--type-preset must not be empty",g.USAGE);try{return At(e)}catch{throw new h(`Invalid --type-preset value "${e}". Allowed: ${ot.join(", ")}`,g.USAGE)}}}function ja(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:F.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function Fa(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 d=F.resolve(e,r),l=F.join(d,".agents","pm");return{pmRoot:l,prefixArg:n,target:{mode:"workspace-path",tracker_root:l,workspace_root:d}}}if(t.path===void 0&&qt(n)){let d=F.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let i=j(e,t.path),a=F.join(F.resolve(e),".agents","pm"),s=F.dirname(F.dirname(i)),c=F.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:F.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function La(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&&Se(e)!==Se(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 ${Se(e)}`,`pm init --id-prefix ${Se(t)}`]});return t}function Ma(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: ${ya.join(", ")}`,g.USAGE)}function Ua(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Yn(e,t){let n=no[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function ku(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ga(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(ku).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function za(e,t,n){let o=W(t.schema),r=ee(e,o.files.types,K.types),a=oe(await z(r)),s=[],c=[];for(let d of rt(n)){let l=Ue(a,d);a=l.file,(l.replaced?c:s).push(l.definition.name)}return await Me({pmRoot:e,filePath:r,raw:de(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 Ja(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",F.join(".agents","pm")];for(let n of t)if(await x(F.join(e,n)))return!0;return!1}async function qa(e,t,n){if(!t||n||await x(F.join(e,"settings.json"))||!await Ja(e))return;let o=F.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 Ba(e,t){let n=[],o=[];for(let r of t){let i=r?F.join(e,r):e,a=await x(i);await _u.mkdir(i,{recursive:!0}),a?o.push(`already_exists:${i}`):n.push(i),o.push(...await q({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:o}}async function Wa(e,t){let n=Na();try{V.write(`pm init setup wizard (agent-optimized)
|
|
61
|
+
`),Sa(n,!0)}finally{t.close()}}function Hn(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:Bn,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 $a(e){let t=[];for(let n of Zp){let o=ae.join(e,n),r=await x(o);if(!r){t.push({file_path:o,exists:r,has_guidance:!1,has_marker:!1});continue}let i=await fa.readFile(o,"utf8"),a=i.toLowerCase(),s=eu.filter(d=>a.includes(d)),c=iu(i);t.push({file_path:o,exists:r,has_guidance:c||s.length>=tu,has_marker:c})}return t}function Qe(e,t){e.includes(t)||e.push(t)}function Aa(e,t){let n=Hn(e),o=JSON.stringify(n)!==JSON.stringify(t);return o&&(e.agent_guidance=t),{changed:o,state:t}}async function Ta(e){let n=await x(e)?await fa.readFile(e,"utf8"):"",o=ba(n);return o.changed?(await he(e,o.next_content),{changed:!0,warnings:await q({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function au(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=>Xe(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Xe(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Xe(e.projectRoot,t.file_path))}}async function su(e,t,n){return e?await $a(n):t}function gt(e,t,n){e.state={...e.state,...n,template_version:Bn,last_checked_files:t}}async function Ia(e,t){if(t.presentBefore)return;let n=await Ta(t.targetPath);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function cu(e,t){t||(e.warnings.push("agent_guidance:missing"),Qe(e.nextSteps,yt))}function du(e,t){e.skipped=!0,gt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Qe(e.nextSteps,yt)}async function lu(e,t){await Ia(e,t),gt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function pu(e,t){e.state.declined&>(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function uu(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Qe(e.nextSteps,yt)}async function mu(e,t){if(e.prompted=!0,await Ea(t.targetRelativePath)){await Ia(e,t),gt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,gt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Qe(e.nextSteps,yt)}function fu(e){e.warnings.push("agent_guidance:missing_non_interactive"),Qe(e.nextSteps,yt)}async function hu(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(cu(n,t.presentBefore),n):t.mode==="skip"?(du(n,t.checkedFiles),n):t.mode==="add"?(await lu(n,t),n):t.presentBefore?(pu(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(uu(n),n):t.interactive?(await mu(n,t),n):(fu(n),n)}async function Oa(e){let t=ka(e.pm_root,e.cwd),n=await $a(t),o=xa(n,t),r=Xe(t,o),i=n.map(l=>Xe(t,l.file_path)),a=n.some(l=>l.has_guidance),s=await hu(Hn(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:o,targetRelativePath:r,checkedFiles:i,presentBefore:a}),c=Aa(e.settings,s.state);return n=await su(s.applied,n,t),{summary:au({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 gu from"node:fs/promises";import F from"node:path";import Ra from"node:readline/promises";import{stdin as Pa,stdout as V}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]="75c0d2d2-6a89-508f-b7dd-b43d55978b44")}catch{}})();function p_(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 u_={normalizeInitGovernancePreset:Kn,normalizeInitTypePreset:Da,normalizeOptionalInitAuthor:ja,normalizeInitAgentGuidanceMode:Ma,isPathLikeInitTarget:qt,resolveInitInvocation:Fa,resolveInitPrefixInput:La,parseYesNoChoice:Ua,applyGovernancePreset:Vn,runInitWizard:Wa,setInitReadlineFactoryForTests:yu,summarizeInstalledPackages:Ga,buildInitNextSteps:Ha,registerInitTypePreset:za,assertExplicitTrackerPathIsNotWorkspaceRoot:qa,isLikelyWorkspaceRoot:Ja,installInitMergeFence:Ka},Na=()=>Ra.createInterface({input:Pa,output:V});function yu(e){Na=e??(()=>Ra.createInterface({input:Pa,output:V}))}function _u(){return structuredClone(Ht)}var wu=["minimal","default","strict"];function Kn(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: ${wu.join(", ")}`,g.USAGE)}function Da(e){if(e!==void 0){if(e.trim().length===0)throw new h("--type-preset must not be empty",g.USAGE);try{return At(e)}catch{throw new h(`Invalid --type-preset value "${e}". Allowed: ${ot.join(", ")}`,g.USAGE)}}}function ja(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:F.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function Fa(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 d=F.resolve(e,r),l=F.join(d,".agents","pm");return{pmRoot:l,prefixArg:n,target:{mode:"workspace-path",tracker_root:l,workspace_root:d}}}if(t.path===void 0&&qt(n)){let d=F.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let i=j(e,t.path),a=F.join(F.resolve(e),".agents","pm"),s=F.dirname(F.dirname(i)),c=F.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:F.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function La(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&&Se(e)!==Se(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 ${Se(e)}`,`pm init --id-prefix ${Se(t)}`]});return t}function Ma(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: ${ya.join(", ")}`,g.USAGE)}function Ua(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Vn(e,t){let n=to[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 Ga(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 za(e,t,n){let o=W(t.schema),r=ee(e,o.files.types,K.types),a=oe(await z(r)),s=[],c=[];for(let d of rt(n)){let l=Ue(a,d);a=l.file,(l.replaced?c:s).push(l.definition.name)}return await Me({pmRoot:e,filePath:r,raw:de(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 Ja(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",F.join(".agents","pm")];for(let n of t)if(await x(F.join(e,n)))return!0;return!1}async function qa(e,t,n){if(!t||n||await x(F.join(e,"settings.json"))||!await Ja(e))return;let o=F.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 Ba(e,t){let n=[],o=[];for(let r of t){let i=r?F.join(e,r):e,a=await x(i);await gu.mkdir(i,{recursive:!0}),a?o.push(`already_exists:${i}`):n.push(i),o.push(...await q({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:o}}async function Wa(e,t){let n=Na();try{V.write(`pm init setup wizard (agent-optimized)
|
|
62
62
|
`),V.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
63
63
|
|
|
64
64
|
`),V.write(`1/3 Item ID prefix
|
|
@@ -68,10 +68,10 @@ Agent guidance check
|
|
|
68
68
|
`),V.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
69
69
|
`),V.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
70
70
|
`),V.write(`strict: ownership blocking, strict create defaults, close validation strict.
|
|
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=
|
|
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=Kn(a)}catch{V.write(`Unrecognized governance preset "${a}"; using minimal.
|
|
72
72
|
`)}V.write(`
|
|
73
73
|
3/3 Project telemetry
|
|
74
74
|
`),V.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
|
|
75
75
|
`);let c=t?"Y/n":"y/N",d=await n.question(`Enable telemetry for this project? [${c}] `),l=Ua(d,t);return V.write(`
|
|
76
|
-
`),{prefix:r,preset:s,telemetry_enabled:l}}finally{n.close()}}function
|
|
77
|
-
//# sourceMappingURL=chunk-
|
|
76
|
+
`),{prefix:r,preset:s,telemetry_enabled:l}}finally{n.close()}}function bu(e){return{presetFromOption:Kn(e.preset),useDefaults:e.defaults===!0,authorFromOption:ja(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:Ma(e.agentGuidance),typePreset:Da(e.typePreset)}}function ku(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 xu(e,t,n,o){if(t.length===0||n)return;let r=o.discovery==="ancestor";throw new h(`${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.`,g.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 Su(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&&(Vn(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 Eu(e){let t=await O(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=ku({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return xu(e.settingsPath,n,e.options.force===!0,e.target),Su({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Ee(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function $u(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 Wa(t,Ht.telemetry.enabled);t=c.prefix,n=c.preset,o=c.telemetry_enabled,r=!0}let i=n??"minimal",a=_u();a.id_prefix=t,Vn(a,i);let s=vo()?.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 Ee(e.pmRoot,a),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:r}}async function Ca(e){return e.settingsExists?await Eu(e):await $u({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function Au(e){let t=await Oa({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await Ee(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function Tu(e,t){let n=[],o=[],r=await wo(e,t.schema);for(let i of r.created_paths)n.push(i),o.push(...await q({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:o}}async function Iu(e){if(e.typePreset===void 0)return;let t=await za(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await q({path:t.file,scope:"project",op:"init:type_preset"})),t}async function Ou(e){let n=J(e.settings,B()).folders.filter(r=>!Wt.includes(r)),o=await Ba(e.pmRoot,n);e.createdDirs.push(...o.createdDirs),e.warnings.push(...o.warnings)}function Cu(e){let t=F.resolve(e.tracker_root),n=F.dirname(t);return F.basename(t)==="pm"&&F.basename(n)===".agents"?F.dirname(n):e.workspace_root}async function Ru(e,t,n,o){if(!e)return;let r=await zn("all",{install:!0,project:!0},{...t,path:n});o.push(...r.warnings);let i=Ga(r),a=i.packages.filter(s=>!s.ok).map(s=>s.alias);if(!i.installed_all||a.length>0)throw new h(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,g.GENERIC_FAILURE);return i}function Ha(e){let t=o=>kt([...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 Ka(e,t,n,o=un){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 h))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 m_(e,t,n={}){let o=process.cwd(),r=Fa(o,t,e,n.workspace),i=r.pmRoot;e=La(r.prefixArg,n.idPrefix);let a=bu(n);await qa(i,r.target.mode==="tracker-path",n.force===!0);let s=[],c=[],d=F.join(i,"settings.json"),l=await x(d),p;l&&(p=await Ca({pmRoot:i,settingsPath:d,settingsExists:l,normalizedPrefix:Se(e),prefixArg:e,options:n,normalizedOptions:a,warnings:c,target:r.target}));let u=await Ba(i,Wt);s.push(...u.createdDirs),c.push(...u.warnings),p??=await Ca({pmRoot:i,settingsPath:d,settingsExists:l,normalizedPrefix:Se(e),prefixArg:e,options:n,normalizedOptions:a,warnings:c,target:r.target});let{settings:m}=p,y=Cu(r.target),w=await dn(y??F.dirname(i)),f=y??w,_=await Au({pmRoot:i,cwd:f??o,agentGuidanceMode:a.agentGuidanceMode,settings:m,warnings:c}),v=await Tu(i,m);s.push(...v.createdDirs),c.push(...v.warnings);let k=await Iu({pmRoot:i,settings:m,typePreset:a.typePreset,warnings:c});if(k&&(m=await O(i)),await Ou({pmRoot:i,settings:m,createdDirs:s,warnings:c}),f&&a.agentGuidanceMode!=="status"){let C=await Wo(f,{pmRoot:i});C.changed&&c.push(`updated:gitignore:${C.path}`)}!l&&n.mergeFence!==!1&&a.agentGuidanceMode!=="status"&&await Ka(i,w,c);let T=await Ru(a.installBundledPackages,t,i,c),R=Ha({installBundledPackages:a.installBundledPackages,registeredTypePreset:k,agentGuidanceNextSteps:_.next_steps,target:r.target});return{ok:!0,path:i,target:r.target,settings:m,created_dirs:s,warnings:c,governance_preset:m.governance.preset,wizard_used:p.wizardUsed,...k?{registered_type_preset:k}:{},...T?{installed_packages:T}:{},next_steps:R,agent_guidance:_}}export{en as a,Go as b,Jo as c,on as d,gs as e,_s as f,Wo as g,Ge as h,vs as i,bs as j,Ko as k,St as l,Qo as m,ze as n,sn as o,$s as p,dn as q,pn as r,or as s,um as t,mm as u,rr as v,fm as w,un as x,mr as y,Be as z,We as A,fr as B,lr as C,Je as D,qe as E,pr as F,pc as G,vr as H,Sr as I,dc as J,lc as K,kf as L,xf as M,Sf as N,it as O,Ef as P,$f as Q,Af as R,Tf as S,If as T,Of as U,Cf as V,Rf as W,Pf as X,Nf as Y,Df as Z,jf as _,Ff as $,Lf as aa,Mf as ba,Uf as ca,Gf as da,zf as ea,Jf as fa,qf as ga,Bf as ha,Wf as ia,Hf as ja,Kf as ka,Vf as la,b as ma,we as na,Ot as oa,Tc as pa,st as qa,Ct as ra,Wr as sa,ni as ta,Pn as ua,gi as va,lg as wa,bl as xa,Ci as ya,Ri as za,Nn as Aa,ml as Ba,fl as Ca,hl as Da,wi as Ea,vi as Fa,zn as Ga,ya as Ha,Gy as Ia,Oa as Ja,p_ as Ka,u_ as La,m_ as Ma};
|
|
77
|
+
//# sourceMappingURL=chunk-YBMRWW4E.js.map
|