@unbrained/pm-cli 2026.8.29 → 2026.8.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/HARNESS_COMPATIBILITY.md +1 -1
- package/.agents/skills/README.md +1 -1
- package/.agents/skills/pm-developer/SKILL.md +1 -1
- package/.agents/skills/pm-developer/references/COMMAND_PLAYBOOK.md +2 -2
- package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +1 -1
- package/.agents/skills/pm-developer/references/TOKEN_BUDGETS.md +1 -1
- package/.agents/skills/pm-extensions/SKILL.md +2 -2
- package/.agents/skills/pm-extensions/references/AUTHORING.md +1 -1
- package/.agents/skills/pm-extensions/references/LIFECYCLE.md +1 -1
- package/.agents/skills/pm-sdk/SKILL.md +1 -1
- package/.agents/skills/pm-user/SKILL.md +2 -2
- package/.agents/skills/pm-user/references/WORKFLOWS.md +2 -2
- package/.claude-plugin/marketplace.json +2 -2
- package/AGENTS.md +1 -1
- package/CHANGELOG.md +24 -0
- package/dist/cli/register-list-query.js +32 -17
- package/dist/cli/register-operations.d.ts +2 -0
- package/dist/cli/register-operations.js +20 -9
- package/dist/cli-bundle/bundle-manifest.json +137 -137
- package/dist/cli-bundle/chunks/chunk-2XVV45NJ.js +35 -0
- package/dist/cli-bundle/chunks/{chunk-N6OR6FAR.js → chunk-3FCSFWZT.js} +12 -12
- package/dist/cli-bundle/chunks/{chunk-WS2GJQVG.js → chunk-52JXYSDW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TGNAA66W.js → chunk-5DH5XCJL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2UETTHY6.js → chunk-IEFJ3ZEB.js} +29 -29
- package/dist/cli-bundle/chunks/{chunk-MTTKAUBX.js → chunk-JIFYOJF7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3TEF3HM5.js → chunk-MWIN6OH2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GNWPTEBW.js → chunk-NW6LV3TU.js} +64 -64
- package/dist/cli-bundle/chunks/{chunk-7SKMLSMX.js → chunk-OUGDA7NR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2MKLQL2E.js → chunk-QZCIBZR3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CMIEDWAY.js → chunk-SXMHPK4V.js} +41 -41
- package/dist/cli-bundle/chunks/{register-list-query-OMKJ5ONN.js → register-list-query-7C7DKZ2U.js} +11 -11
- package/dist/cli-bundle/chunks/{register-mutation-QBSNCOY3.js → register-mutation-OI4BJLUX.js} +2 -2
- package/dist/cli-bundle/chunks/register-operations-IIMA5OKO.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-GLQ5SYV3.js → register-setup-52H36QCB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HVQ22RC4.js → chunk-2FEZ5SKM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-Y3JJXRVK.js → chunk-4O4CJAR6.js} +5 -5
- package/dist/cli-bundle/focused-chunks/{chunk-RKOKG43G.js → chunk-APN4QN6R.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LYFWQMVC.js → chunk-BEVHCEWG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3UMBF26I.js → chunk-BMD42PUG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XXOWRJZ5.js → chunk-BPWJ4QM5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-G6PATS5E.js → chunk-EUTABA4M.js} +15 -15
- package/dist/cli-bundle/focused-chunks/{chunk-73EDXGYE.js → chunk-FOMZ6NG5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JCOOAUHK.js +51 -0
- package/dist/cli-bundle/focused-chunks/chunk-JEFKLWMM.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JZYPPMXF.js → chunk-KB5OFSFD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-AD6ULRAF.js → chunk-QDFJIRKN.js} +4 -4
- package/dist/cli-bundle/focused-chunks/{chunk-THEPQMLX.js → chunk-SVXJYD6G.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3AVAWVZA.js → chunk-UN34D63M.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TDK3OCX3.js → chunk-VJ7EFMFL.js} +2 -2
- package/dist/cli-bundle/main.js +2 -2
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +29 -29
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +33 -33
- 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 +9 -9
- package/dist/core/schema/runtime-schema.d.ts +4 -0
- package/dist/core/schema/runtime-schema.js +60 -48
- package/dist/core/schema/status-defs-file.js +5 -2
- package/dist/mcp/legacy-adapter.d.ts +11 -2
- package/dist/mcp/legacy-adapter.js +26 -12
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +6 -2
- package/dist/sdk/cli-contracts/grammar-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +12 -2
- package/dist/sdk/cli-contracts/runtime-contracts.js +3 -2
- package/dist/sdk/cli-contracts/tool-schema.js +11 -3
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +14 -2
- package/dist/sdk/governance/health.js +17 -6
- package/dist/sdk/governance/status-role-diagnostics.d.ts +27 -0
- package/dist/sdk/governance/status-role-diagnostics.js +36 -0
- package/dist/sdk/governance/validate-normalization.d.ts +6 -0
- package/dist/sdk/governance/validate-normalization.js +37 -0
- package/dist/sdk/governance/validate.d.ts +1 -1
- package/dist/sdk/governance/validate.js +20 -35
- package/dist/sdk/governance/workspace-position.d.ts +69 -0
- package/dist/sdk/governance/workspace-position.js +164 -0
- package/dist/sdk/governance.d.ts +2 -0
- package/dist/sdk/governance.js +4 -2
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +3 -3
- package/dist/sdk/mcp/protocol.d.ts +10 -2
- package/dist/sdk/mcp/protocol.js +15 -4
- package/dist/sdk/query/context.js +11 -14
- package/dist/sdk/query/list.d.ts +2 -0
- package/dist/sdk/query/list.js +33 -12
- package/dist/sdk/runtime-extended-actions.js +8 -4
- package/dist/sdk/schema.js +12 -2
- package/dist/sdk/test/execution.d.ts +15 -0
- package/dist/sdk/test/execution.js +35 -27
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_PROVENANCE_ADR.md +1 -1
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +2 -2
- package/docs/CLAUDE_CODE_PLUGIN.md +3 -3
- package/docs/COMMANDS.md +12 -12
- package/docs/CONFIGURATION.md +1 -1
- package/docs/DEFECT_RECURRENCE.md +2 -0
- package/docs/MCP_2026_07_28.md +28 -8
- package/docs/MCP_2026_07_28_CONFORMANCE.md +1 -0
- package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +4 -2
- package/docs/ONBOARDING.md +1 -1
- package/docs/README.md +2 -1
- package/docs/READ_OUTPUT_CONTRACTS.md +1 -1
- package/docs/RECURRENCE_RECOVERY_CONTRACTS.md +1 -1
- package/docs/SDK.md +3 -3
- package/docs/TESTING.md +23 -14
- package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +113 -0
- package/docs/examples/policy-restricted-extension/README.md +2 -2
- package/docs/examples/starter-extension/README.md +1 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
- package/marketplace.json +2 -2
- package/package.json +4 -4
- 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/sdk/public-surface.json +171 -10
- package/dist/cli-bundle/chunks/chunk-7X6OZEIV.js +0 -34
- package/dist/cli-bundle/chunks/register-operations-UC77FQZC.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AXZ5AJAF.js +0 -50
- package/dist/cli-bundle/focused-chunks/chunk-LLNTHF5X.js +0 -2
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
import{Ac as H,B as
|
|
2
|
-
`)}function ms(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function
|
|
1
|
+
import{Ac as H,B as Yt,Bd as xr,C as g,Cb as ur,Cd as et,Db as mr,E as h,Ed as kt,Ej as jr,Fi as tn,Ge as Er,H as or,He as xt,Jc as W,Lb as fr,Ma as sr,Mb as hr,Mh as Ir,Na as cr,Nh as Oe,Oa as B,Ob as gr,Oh as tt,Ph as Tr,Qh as Or,R as I,Rh as ie,Sh as Ge,Th as Cr,Uh as le,Wa as D,Xa as dr,Ya as lr,Za as pr,ba as ir,bi as ae,c as x,cc as Zt,d as yt,da as ar,dc as yr,e as oe,ea as te,ec as _r,ei as O,f as q,fc as vt,fi as Se,g as he,hc as be,i as tr,ia as de,jc as ke,jh as Q,ki as Rr,l as _t,mc as wr,mf as $r,nh as en,oa as wt,oc as bt,pa as Xt,pc as vr,qa as Qt,qc as br,qh as Me,qi as Pr,s as nr,ue as Sr,uh as xe,vd as A,vf as Ar,vi as Ue,vm as St,w as Vt,wd as Y,wi as Nr,xd as kr,xi as Dr,y as rr,yd as K,zd as ne,ze as V,zi as Ce}from"./chunk-NW6LV3TU.js";import{mkdir as ss,readFile as cs}from"node:fs/promises";import zr 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 nn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},ds="sdk-workspace-transaction",ls=/^[a-zA-Z0-9._-]+$/,ps=30,us=3e3;function Lr(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!ls.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Fr(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 Mr(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function Jr(e,t){return zr.join(e,"transactions","sdk",`${t}.json`)}async function Ee(e,t){t.updatedAt=I();let n=Jr(e,t.transactionId);await ss(zr.dirname(n),{recursive:!0}),await he(n,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`)}function ms(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 fs(e,t){try{let n=JSON.stringify(e,(r,o)=>{if(typeof o=="number"&&!Number.isFinite(o))throw new TypeError(`${t} contains a non-finite number`);if(o===void 0||typeof o=="function"||typeof o=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return o});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function rn(e,t){return e===void 0?void 0:fs(e,t)}function on(e,t,n,r){let o=rn(n,r);o===void 0?delete e[t]:e[t]=o}function Gr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ur(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function hs(e,t){if(!Ur(e.startedStepIds,t)||!Ur(e.completedStepIds,t)||!Gr(e.results)||!Gr(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),o=e.completedStepIds,i=new Set(o);return Object.keys(e.compensationData).some(a=>!r.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&&r.size===0}function gs(e,t,n){let r;try{r=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let o=r,i=o.schemaVersion===1&&o.transactionId===t,a=Array.isArray(o.stepIds)&&o.stepIds.length===n.length&&o.stepIds.every((l,p)=>l===n[p]),s=hs(o,n),c=ms(o),d=["applying","compensating","compensated","committed"].includes(String(o.status));if(!i||!a||!s||!c||!d)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...o,results:Re(o.results),compensationData:Re(o.compensationData)}}async function ys(e,t,n,r,o){let i=o,a=i!==void 0;if(i?.status==="compensating"&&await qr(e,i),i===void 0||i.status==="compensated"){let s=I();i={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(i?.attempt??0)+1,createdAt:i?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:Re(),compensationData:Re()},await Ee(e.pmRoot,i),await ge(e,i,"prepared")}return{journal:i,recovered:a}}async function _s(e,t,n){try{await vs(t,e.steps),await Ee(e.pmRoot,t);let r=new Set(t.completedStepIds),o=new Set(t.startedStepIds);for(let i of e.steps){if(r.has(i.id))continue;let a=await i.inspect(),s=rn(a.result,`Step ${i.id} result`);if(a.state!=="applied"){let c=await i.prepareCompensation?.();on(t.compensationData,i.id,c,`Step ${i.id} compensation data`),o.add(i.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>o.has(l)),await Ee(e.pmRoot,t);let d=await i.apply();s=rn(d,`Step ${i.id} result`)}await ge(e,t,"step_applied",i.id),r.add(i.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),on(t.results,i.id,s,`Step ${i.id} result`),await Ee(e.pmRoot,t),await ge(e,t,"step_recorded",i.id)}return await ge(e,t,"committing"),t.status="committed",await Ee(e.pmRoot,t),await ge(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Re(t.results)}}catch(r){if(r instanceof nn||t.status==="committed")throw r;try{await qr(e,t)}catch(o){throw new AggregateError([r,o],`Workspace transaction failed and compensation failed: ${String(o)}`,{cause:o})}throw r}}async function ws(e,t,n){try{return gs(await cs(Jr(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&oe(r))return;throw r}}async function ge(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function vs(e,t){let n=new Set,r=Re();for(let o of t){let i=await o.inspect();i.state==="applied"&&(n.add(o.id),on(r,o.id,i.result,`Step ${o.id} result`))}e.results=r,e.completedStepIds=t.map(o=>o.id).filter(o=>n.has(o))}async function qr(e,t){t.status="compensating",await Ee(e.pmRoot,t),await ge(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let o of[...e.steps].reverse()){if(!r.has(o.id)&&!n.has(o.id))continue;let i;try{i=r.has(o.id)&&(await o.inspect()).state==="applied"}catch{i=r.has(o.id)}i&&(await ge(e,t,"step_compensating",o.id),await o.compensate(t.compensationData[o.id])),n.delete(o.id),r.delete(o.id),t.completedStepIds=e.steps.map(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>r.has(a)),delete t.results[o.id],delete t.compensationData[o.id],await Ee(e.pmRoot,t),await ge(e,t,"step_compensated",o.id)}t.status="compensated",await Ee(e.pmRoot,t),await ge(e,t,"compensated")}async function Br(e){let t=Fr(e.pmRoot,"Transaction pmRoot"),n=Lr(e.transactionId,"Transaction id"),r=Fr(e.author,"Transaction author"),o=Mr(e.lockTtlSeconds,ps,"Transaction lock TTL"),i=Mr(e.lockWaitMs,us,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(l=>{let p=Lr(l.id,"Transaction step id");if(p!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return p});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:a,lockTtlSeconds:o,lockWaitMs:i},d=await Q(t,ds,o,r,!1,!1,i);try{let l=await ws(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 ys(c,n,r,s,l);return await _s(c,u.journal,p||u.recovered)}finally{await d()}}import{readFile as bs,writeFile as ks}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 Hr="# pm-cli:runtime-cache:start",an="# pm-cli:runtime-cache:end",Kr=".agents/pm",xs=["runtime/","search/","locks/","transactions/","checkpoints/"],Ss=["search/eval-queries.json"];async function Wr(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 Vr(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function sn(e){let t=e.replaceAll("\\","/");return nt.isAbsolute(e)||t===".."||t.startsWith("../")}function Es(e=Kr){let t=Vr(e);return[Hr,...xs.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Ss.map(n=>`!${t}/${n}`),an].join(`
|
|
3
3
|
`)}async function Yr(e,t={}){let n=nt.join(e,".gitignore"),r=Kr;if(t.pmRoot!==void 0){let l=Vr(nt.relative(nt.resolve(e),nt.resolve(t.pmRoot)));if(sn(l))return{path:n,changed:!1};l.length>0&&(r=l)}let o="";try{o=await Wr(()=>bs(n,"utf8"))}catch(l){if(!(l instanceof Error&&"code"in l&&oe(l)))throw l}let i=o.indexOf(Hr),a=o.indexOf(an),c=(i>=0&&a>=i?`${o.slice(0,i)}${o.slice(a+an.length)}`:o).trimEnd(),d=`${c.length>0?`${c}
|
|
4
4
|
|
|
5
5
|
`:""}${Es(r)}
|
|
6
|
-
`;return d===o?{path:n,changed:!1}:(await Wr(()=>ks(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 $s=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function
|
|
7
|
-
`),s=to(to(o,
|
|
6
|
+
`;return d===o?{path:n,changed:!1}:(await Wr(()=>ks(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 $s=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function ze(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(bt(t.extensionName));for(let f of t.extensionNames??[])n.add(bt(f));let r=f=>n.size===0||n.has(bt(f)),o=(f,_)=>Xr(f.filter(v=>r(v.name)).map(_)),i=(f,_)=>Xr(f.filter(v=>r(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=>r(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=o(a.assurance_providers??[],f=>f.definition.id);return{capabilities:vr(e,t),commands:o(a.commands,f=>f.command),command_overrides:o(s.overrides,f=>f.command),command_handlers:o(s.handlers,f=>f.command),hooks:$s.filter(([f])=>u[f].some(_=>r(_.name))).map(([,f])=>f),flag_commands:o(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:o(a.profiles,f=>f.profile.name),importers:o(a.importers,f=>f.importer),exporters:o(a.exporters,f=>f.exporter),search_providers:o(a.search_providers,f=>f.definition.name),vector_store_adapters:o(a.vector_store_adapters,f=>f.definition.name),...w.length>0?{assurance_providers:w}:{},parser_overrides:o(c.overrides,f=>f.command),service_overrides:o(l.overrides,f=>f.service),renderer_overrides:o(p.overrides,f=>f.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:d.overrides.filter(f=>r(f.name)).length,preflight_ownership:d.overrides.filter(f=>r(f.name)).map(f=>({commands:[...f.commands??[]]}))}}function Xr(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 As="PM_SOURCE_CONTEXT_ACCESS",Is="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Qr(e){let t=e[As],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[Is]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}import{readFile as $t,realpath as cn,writeFile as Ts}from"node:fs/promises";import{execFile as Os}from"node:child_process";import L from"node:path";import{promisify as Cs}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]="dea4137f-adbd-5dca-bfc7-b56c99c7aa79")}catch{}})();var ln=Cs(Os),Et="# pm-cli:merge-drivers:start",no="# pm-cli:merge-drivers:end",Je="# pm-cli:merge-drivers:v2:start",dn="# pm-cli:merge-drivers:v2:end",Rs="merge-fence";function Zr(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function ro(){let e=de(import.meta.url,["../../.."]);return`${Zr(process.execPath)} ${Zr(L.join(e,"dist","cli.js"))}`}var oo=[{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 Ps(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),o=Qr(e.environment),i=!!(n&&r),a=t===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(t!==void 0){let s=D(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}return a?{pm_root:L.resolve(r),workspace_start:L.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?D(e.cwd,".agents/pm"):D(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function pn(e){try{let{stdout:t}=await ln("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await cn(t.trim())}catch{return null}}async function io(e){let t=await pn(e);if(t===null)throw new h("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function un(e,t){return L.relative(e,t).replaceAll("\\","/")}function pe(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function eo(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function Ns(e,t){let n=eo(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=eo(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(L.basename(n.value))||L.basename(r.value)!=="cli.js"||L.basename(L.dirname(r.value))!=="dist"||!await x(n.value)||!await x(r.value))return!1;try{let o=L.dirname(L.dirname(r.value)),i=JSON.parse(await $t(L.join(o,"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 mn(e,t){let n=e.length>0?`${e}/`:"",r=[`${pe(`${n}**/*.toon`)} merge=pm-item-toon`,`${pe(`${n}**/*.md`)} merge=pm-item-markdown`];for(let o of t)r.push(`${pe(`${n}${o}/*.toon`)} merge=pm-item-toon`),r.push(`${pe(`${n}${o}/*.md`)} merge=pm-item-markdown`);return r.push(`${pe(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${pe(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${pe(`${n}settings.json`)} merge=pm-json`),r.push(`${pe(`${n}**/*.json`)} merge=pm-json`),r.push(`${pe(`${n}extensions/**`)} -merge`),r.push(`${pe(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function to(e,t,n){let r=e.indexOf(t),o=e.indexOf(n);return r>=0&&o>r?`${e.slice(0,r)}${e.slice(o+n.length)}`:e.replace(t,"").replace(n,"")}async function ao(e,t,n){let r=L.join(e,".gitattributes"),o="";try{o=await $t(r,"utf8")}catch(d){if(!(d instanceof Error&&"code"in d&&oe(d)))throw d}let i=[Je,...t,dn].join(`
|
|
7
|
+
`),s=to(to(o,Je,dn),Et,no).trimEnd(),c=`${s.length>0?`${s}
|
|
8
8
|
|
|
9
9
|
`:""}${i}
|
|
10
|
-
`;return c===o?{path:r,changed:!1}:(n||await Ts(r,c,"utf8"),{path:r,changed:!0})}function so(e){let t=B(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function Om(e,t){let n=L.resolve(e),r=null,o="",i=n;for(let v=0;v<8;v+=1){let
|
|
11
|
-
`).map(v=>v.trim()).filter(v=>v.length>0):[],m=mn(un(r,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 Cm(e){let t=ro(),n=[],r=[];for(let o of oo){let i=`merge.${o.key}.driver`,a=` merge driver ${o.artifact} "%O" "%A" "%B"${o.itemPath===void 0?"":` --item-path ${o.itemPath}`}`,s=`${t}${a}`;try{let{stdout:c}=await ln("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),d=c.trim();d!==s&&!await Ns(d,a)&&r.push(i)}catch{n.push(i)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function co(e){let t;try{t=await io(L.resolve(e))}catch{return{status:"no_git"}}let n=un(t,L.resolve(e)),r=await O(e),o=V(void 0,r.author_default),i=await Q(e,Rs,r.locks.ttl_seconds,o,!1,ae(r).force_required_for_stale_lock,r.locks.wait_ms);try{let a=L.join(t,".gitattributes"),s;try{s=await
|
|
12
|
-
`}function go(e,t){let n=e.fields.find(a=>A(a.key)===t.key),r=n!==void 0,o=e.fields.filter(a=>A(a.key)!==t.key),i={...n,key:t.key,type:t.type,commands:[...t.commands]};return uo(i,"description",t.description),uo(i,"cli_flag",t.cliFlag),t.cliAliases.length>0?i.cli_aliases=[...t.cliAliases]:delete i.cli_aliases,mo(i,"required",t.required),mo(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,o.push(i),o.sort((a,s)=>A(a.key).localeCompare(A(s.key))),{file:{fields:o},definition:i,replaced:r}}function yo(e,t){let n=A(t);if(n.length===0)throw new Error("Field key must not be empty.");let r=[],o=e.fields.filter(i=>A(i.key)===n?(r.push(i),!1):!0);return r.length===0?{file:{fields:o},removed:!1}:{file:{fields:o},removed:!0,definition:r[0]}}function uo(e,t,n){let r=e;n!==void 0&&n.length>0?r[t]=n:delete r[t]}function mo(e,t,n){let r=e;n?r[t]=!0:delete r[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]="
|
|
13
|
-
`}function wo(e,t,n){let r=e.statuses.slice(),o=r.findIndex(s=>A(s.id)===t.id),i=o>=0?r[o]: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),o>=0?r[o]=a:r.push(a),{file:{statuses:r},definition:a,replaced:i!==void 0}}function vo(e,t){let n=A(t);if(n.length===0)throw new Error("Status id must not be empty.");if(
|
|
14
|
-
`}function Io(e,t){if(t.kind==="rename-type"){let r=ie(e).definitions;return{source:r.some(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(o=>o.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=
|
|
15
|
-
`)}function cc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function dc(e){let t=await Nr(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 Dr(t,{schema:e.settings.schema})).document.metadata}function bo(e,t,n){let r=n==="forward"?t.from:t.to,o=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===o.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=o,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===o.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=o,["status"]}let i=e.metadata;if(Object.prototype.hasOwnProperty.call(i,o)&&!Object.prototype.hasOwnProperty.call(i,r))return[];if(!Object.prototype.hasOwnProperty.call(i,r)||Object.prototype.hasOwnProperty.call(i,o))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return i[o]=i[r],delete i[r],[r,o]}function ko(e){return{id:e.id,inspect:async()=>{let t=await
|
|
16
|
-
`)}import kc from"node:path";import{mkdir as xc}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 rt=["agile","ops","research"],_c={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function 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: ${rt.join(", ")}.`)}function ot(e){return _c[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 wc=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function vc(e){let t=wc.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function bc(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Oo(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,o=new Map;for(let a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=vc(s);if(c===void 0)continue;let d=o.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(s),o.set(c,d)}let i=[];for(let[a,s]of o.entries()){if(s.count<n)continue;let c=bc(a);i.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:Ir(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]="6112923d-5e06-5839-b452-a32818c6398d")}catch{}})();var zf=["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"],It="schema-types",Co="schema-statuses",Ro="schema-fields";function Ae(e){return Fe({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 Jf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{o=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(r),a=K(i.schema),s=ne(r,a.files.types,Y.types),c=[],d=V(t.author,i.author_default),l=ae(i),p=await Q(r,It,i.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await q(s),y;try{y=ie(m)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.GENERIC_FAILURE)}try{Tr(o,y);let w=new Map,f=B(i,H());for(let[_,v]of Object.entries(f.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!w.has(x)&&w.set(x,_)}Or(o,y,w)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}u=Me(y,o),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await Ae({pmRoot:r,filePath:s,raw:le(u.file),op:"schema:add-type",author:d,settings:i}),await it(r,[u.definition],c,"schema:add-type-folder"),c.push(...await W({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await Po(r,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:I()}}async function _e(e){await Ge(e)}async function Po(e,t){try{let n=await co(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 Sc(e,t,n,r){let o=B(t,H()),i=r.trim().toLowerCase();return(await Oe(e,t.item_format,o.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===i).length}async function Ec(e,t,n,r){let o=B(t,H()),i=Ze(n),a=A(r);return(await Oe(e,t.item_format,o.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(i.alias_to_id.get(A(d))??A(d))===a}).length}async function $c(e,t,n,r,o){if(o.length===0||Re.has(o))return;let i=await Ec(t,n,r,o);i>0&&e.push(`items_using_status:${i}`);let a=No(r.workflow,o);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function No(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,r])=>r!==void 0&&A(r)===t).map(([r])=>r)}async function qf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o=await O(r),i=K(o.schema),a=ne(r,i.files.types,Y.types),s=[],c=V(t.author,o.author_default),d=ae(o),l=await Q(r,It,o.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms),p;try{let u=await q(a),m;try{m=ie(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=Cr(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 Sc(r,o,i,y);w>0&&s.push(`items_using_type:${w}`)}await Ae({pmRoot:r,filePath:a,raw:le(p.file),op:"schema:remove-type",author:c,settings:o}),s.push(...await W({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return p.removed&&await Po(r,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:I()}}function wn(e,t){return ne(e,t.files.statuses,Y.statuses)}function Tt(e,t){return ne(e,t.files.fields,Y.fields)}function Do(e,t){return ne(e,t.files.types,Y.types)}async function it(e,t,n,r){for(let o of t){let i=cr(o.folder??sr(o.name)),a=kc.join(e,i);await k(a)||(await xc(a,{recursive:!0}),n.push(...await W({path:a,scope:"project",op:r})))}}function vn(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 Ac(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 Ic(e){let t=new Map;for(let n of e){let r=A(n.id);if(r.length!==0){t.set(r,r);for(let o of Array.isArray(n.aliases)?n.aliases:[]){let i=A(o);i.length>0&&!t.has(i)&&t.set(i,r)}}}return t}async function Bf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{o=_o({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(r),a=K(i.schema),s=wn(r,a),c=Ze(a);try{hn(o,c.alias_to_id)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}let d=Ac(c.by_id.get(o.id)),l=[],p=V(t.author,i.author_default),u=ae(i),m=await Q(r,Co,i.locks.ttl_seconds,p,!!t.force,u.force_required_for_stale_lock,i.locks.wait_ms),y;try{let w=await q(s),f;try{f=Be(w)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let _=Ic(f.statuses);try{hn(o,_)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.USAGE)}y=wo(f,o,d),await Ae({pmRoot:r,filePath:s,raw:We(y.file),op:"schema:add-status",author:p,settings:i}),l.push(...await W({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:I()}}async function Wf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o=await O(r),i=K(o.schema),a=wn(r,i),s=[],c=V(t.author,o.author_default),d=ae(o),l=await Q(r,Co,o.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms),p;try{let u=await q(a),m;try{m=Be(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=vo(m,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=A(p.definition?.id??e);await $c(s,r,o,i,y),await Ae({pmRoot:r,filePath:a,raw:We(p.file),op:"schema:remove-status",author:c,settings:o}),s.push(...await W({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:I()}}function jo(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 Tc(e,t,n){return{...jo(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 Lo(e){return{id:e.id,source:Re.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Fo(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function Oc(){let e=new Map,t=H();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let o of r){if(typeof o!="object"||o===null||Array.isArray(o))continue;let i=o.name;typeof i=="string"&&i.trim().length>0&&e.set(i.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function Cc(e){let t=Ze(e),n=[],r=[];for(let o of t.definitions){let i=Lo(o);i.source==="builtin"?n.push(i):r.push(i)}return{builtin:n,custom:r}}async function at(e){let t=D(process.cwd(),e.path);await _e(t);let n=await O(t),r=K(n.schema),o=ne(t,r.files.types,Y.types),i=wn(t,r),a=B(n,H()),s=Oc(),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:o,statusesPath:i,byType:a.by_type,customNames:c,extensionProvenance:s,schema:r}}async function Hf(e){let t=await at(e),n=[],r=[],o=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Fo(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=jo(s);c==="extension"?o.push(d):c==="custom"?r.push(d):n.push(d)}let i=Cc(t.schema),a=bt(t.schema).definitions.map(vn);return{action:"list",builtin:n,custom:r,extension:o,counts:{builtin:n.length,custom:r.length,extension:o.length,total:n.length+r.length+o.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:I()}}async function Kf(e,t){let n=(e??"").trim();if(n.length===0)throw new h("Type name must not be empty.",g.USAGE);let r=await at(t),o=Object.values(r.byType).find(i=>i.name.toLowerCase()===n.toLowerCase()||i.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!o)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:Tc(o,Fo(o.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(o.name.toLowerCase())),file:{path:r.typesPath},generated_at:I()}}async function Vf(e,t){let n=A(e);if(n.length===0)throw new h("Status id must not be empty.",g.USAGE);let r=await at(t),o=Ze(r.schema),i=o.alias_to_id.get(n)??n,a=o.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:Lo(a),file:{path:r.statusesPath},generated_at:I()}}async function Yf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{o=ho({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(r),a=K(i.schema),s=Tt(r,a),c=[],d=xt(o.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=V(t.author,i.author_default),p=ae(i),u=await Q(r,Ro,i.locks.ttl_seconds,l,!!t.force,p.force_required_for_stale_lock,i.locks.wait_ms),m;try{let y=await q(s),w;try{w=Je(y)}catch(f){throw new h(f instanceof Error?f.message:String(f),g.GENERIC_FAILURE)}m=go(w,o),await Ae({pmRoot:r,filePath:s,raw:qe(m.file),op:"schema:add-field",author:l,settings:i}),c.push(...await W({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:I()}}async function Rc(e,t,n,r){let o=B(t,H());return(await Oe(e,t.item_format,o.type_to_folder,[],n)).filter(a=>{let s=a[r];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function Xf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o=await O(r),i=K(o.schema),a=Tt(r,i),s=[],c=V(t.author,o.author_default),d=ae(o),l=await Q(r,Ro,o.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms),p;try{let u=await q(a),m;try{m=Je(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=yo(m,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=A(p.definition?.key??e),w=A(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(w.length>0){let f=await Rc(r,o,i,w);f>0&&s.push(`items_using_field:${f}`)}await Ae({pmRoot:r,filePath:a,raw:qe(p.file),op:"schema:remove-field",author:c,settings:o}),s.push(...await W({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:I()}}async function Qf(e){let t=await at(e),n=bt(t.schema).definitions.map(vn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Tt(t.pmRoot,t.schema)},generated_at:I()}}async function Zf(e,t){let n=A(e);if(n.length===0)throw new h("Field key must not be empty.",g.USAGE);let r=await at(t),o=bt(r.schema).by_key.get(n);if(!o)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:vn(o),file:{path:Tt(r.pmRoot,r.schema)},generated_at:I()}}async function eh(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{let w=At(e);if(w===void 0)throw new Error(`Type preset name is required. Allowed: ${rt.join(", ")}.`);o=w}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}let i=await O(r),a=K(i.schema),s=Do(r,a),c=[],d=V(t.author,i.author_default),l=ae(i),p=[],u=[],m,y=await Q(r,It,i.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms);try{let w=await q(s),f;try{f=ie(w)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let _=f;for(let v of ot(o)){let x=Me(_,v);_=x.file,(x.replaced?u:p).push(x.definition.name)}m=_.definitions.length,await Ae({pmRoot:r,filePath:s,raw:le(_),op:"schema:apply-preset",author:d,settings:i}),await it(r,ot(o),c,"schema:apply-preset-folder"),c.push(...await W({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:o,registered:p,replaced:u,file:{path:s,definitions:m},warnings:Ie(c),generated_at:I()}}function Pc(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 th(e,t){let n=D(process.cwd(),t.path);await _e(n);let r=await O(n),o=K(r.schema),i=Do(n,o),a=Pc(e.minCount),s=B(r,H()),d=(await Oe(n,r.item_format,s.type_to_folder,[],o)).map(x=>typeof x.title=="string"?x.title:""),l=Oo(d,{minCount:a}),p=[],u=[],m=[],y=[],w;if(!e.apply){let x;try{x=ie(await q(i))}catch(S){throw new h(S instanceof Error?S.message:String(S),g.GENERIC_FAILURE)}return w=x.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:I()}}let f=V(e.author,r.author_default),_=ae(r),v=await Q(n,It,r.locks.ttl_seconds,f,!!e.force,_.force_required_for_stale_lock,r.locks.wait_ms);try{let x=await q(i),S;try{S=ie(x)}catch(M){throw new h(M instanceof Error?M.message:String(M),g.GENERIC_FAILURE)}let C=S;for(let M of l){if(M.shadows_builtin){y.push({name:M.name,reason:"shadows_builtin"});continue}let G;try{G=tt({name:M.name})}catch{y.push({name:M.name,reason:"invalid_type_token"});continue}let ce=Me(C,G);C=ce.file,(ce.replaced?m:u).push(ce.definition.name)}w=C.definitions.length,await Ae({pmRoot:n,filePath:i,raw:le(C),op:"schema:infer-types",author:f,settings:r}),await it(n,C.definitions.filter(M=>u.includes(M.name)||m.includes(M.name)),p,"schema:infer-types-folder"),p.push(...await W({path:i,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:l,registered:u,replaced:m,skipped:y,file:{path:i,definitions:w},warnings:Ie(p),generated_at:I()}}function nh(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 rh(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 oh(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",r=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${r} in ${e.file.path}.`}function ih(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 ah(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,r]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])r.length!==0&&t.push(`${n}: ${r.map(o=>o.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,r]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])r.length!==0&&t.push(`${n}: ${r.map(o=>o.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(`
|
|
10
|
+
`;return c===o?{path:r,changed:!1}:(n||await Ts(r,c,"utf8"),{path:r,changed:!0})}function so(e){let t=B(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function Om(e,t){let n=L.resolve(e),r=null,o="",i=n;for(let v=0;v<8;v+=1){let k=L.join(i,".gitattributes");try{let C=await $t(k,"utf8");if(C.includes(Je)||C.includes(Et)){r=i,o=C;break}}catch{}let S=L.dirname(i);if(S===i)break;i=S}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let a=L.join(r,".gitattributes"),s=o.includes(Je),c=s?Je:Et,d=s?dn:no,l=o.indexOf(c),p=o.indexOf(d),u=p>l?o.slice(l+c.length,p).split(`
|
|
11
|
+
`).map(v=>v.trim()).filter(v=>v.length>0):[],m=mn(un(r,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 Cm(e){let t=ro(),n=[],r=[];for(let o of oo){let i=`merge.${o.key}.driver`,a=` merge driver ${o.artifact} "%O" "%A" "%B"${o.itemPath===void 0?"":` --item-path ${o.itemPath}`}`,s=`${t}${a}`;try{let{stdout:c}=await ln("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),d=c.trim();d!==s&&!await Ns(d,a)&&r.push(i)}catch{n.push(i)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function co(e){let t;try{t=await io(L.resolve(e))}catch{return{status:"no_git"}}let n=un(t,L.resolve(e)),r=await O(e),o=V(void 0,r.author_default),i=await Q(e,Rs,r.locks.ttl_seconds,o,!1,ae(r).force_required_for_stale_lock,r.locks.wait_ms);try{let a=L.join(t,".gitattributes"),s;try{s=await $t(a,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&oe(p))return{status:"not_installed",path:a};throw p}if(!s.includes(Je)&&!s.includes(Et))return{status:"not_installed",path:a};let c=await O(e),d=so(c),l=await ao(t,mn(n,d),!1);return{status:l.changed?"refreshed":"unchanged",path:l.path}}finally{await i()}}async function Rm(e,t){let n=Ps({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await Ue(r);let o=await io(n.workspace_start);return fn({pmRoot:r,workspaceRoot:o,dryRun:e.dryRun===!0})}async function fn(e){let t=L.resolve(e.pmRoot),n=L.resolve(e.workspaceRoot),r=e.dryRun===!0,o,i;try{[o,i]=await Promise.all([cn(t),cn(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=un(i,o);if(sn(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(o),c=so(s),d=mn(a,c),l=[],p=ro();for(let m of oo)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(!r)try{for(let m of l)await ln("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 ao(i,d,r);return{ok:!0,dry_run:r,workspace_root:i,pm_root:o,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:I()}}import{createHash as xo}from"node:crypto";import Ne from"node:fs/promises";import Ve 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 Ds=new Set(Xt),js=new Set(Qt),lo=new Set([...nr.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"]),Ls=["create","update"];function fo(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function po(e){return e.replaceAll("_","-")}function Fs(e,t){let n=new Set;for(let r of e){let o=fo(r);o.length>0&&o!==t&&n.add(o)}return[...n].sort((r,o)=>r.localeCompare(o))}function Ms(e){let t=new Set;for(let n of e??[]){let r=n.trim();r.length>0&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function Gs(e){let t=new Set,n=[];for(let r of e??[]){let o=r.trim().toLowerCase();if(o.length!==0){if(!js.has(o))throw new Error(`Invalid field command "${r}". Allowed: ${Qt.join(", ")}.`);t.has(o)||(t.add(o),n.push(o))}}return e===void 0||n.length===0?[...Ls]:n}function ho(e){let t=A(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(lo.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: ${[...lo].sort((l,p)=>l.localeCompare(p)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!Ds.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${Xt.join(", ")}.`);let r=n,o=Gs(e.commands),i=fo(e.cliFlag),a=i.length>0&&i!==po(t)?i:void 0,s=a??po(t),c=Fs(e.aliases??[],s),d=e.description?.trim();return{key:t,type:r,commands:o,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:Ms(e.requiredTypes)}}function Us(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 zs(e){let t=Us(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r;typeof o.key!="string"||o.key.trim().length===0||n.push(o)}return n}function qe(e){if(e==null||e.trim().length===0)return{fields:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/fields.json contains invalid JSON.")}return{fields:zs(t)}}function Be(e){return`${JSON.stringify({fields:e.fields},null,2)}
|
|
12
|
+
`}function go(e,t){let n=e.fields.find(a=>A(a.key)===t.key),r=n!==void 0,o=e.fields.filter(a=>A(a.key)!==t.key),i={...n,key:t.key,type:t.type,commands:[...t.commands]};return uo(i,"description",t.description),uo(i,"cli_flag",t.cliFlag),t.cliAliases.length>0?i.cli_aliases=[...t.cliAliases]:delete i.cli_aliases,mo(i,"required",t.required),mo(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,o.push(i),o.sort((a,s)=>A(a.key).localeCompare(A(s.key))),{file:{fields:o},definition:i,replaced:r}}function yo(e,t){let n=A(t);if(n.length===0)throw new Error("Field key must not be empty.");let r=[],o=e.fields.filter(i=>A(i.key)===n?(r.push(i),!1):!0);return r.length===0?{file:{fields:o},removed:!1}:{file:{fields:o},removed:!0,definition:r[0]}}function uo(e,t,n){let r=e;n!==void 0&&n.length>0?r[t]=n:delete r[t]}function mo(e,t,n){let r=e;n?r[t]=!0:delete r[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]="ec456832-5120-5171-93fd-861ea4125acb")}catch{}})();var Js=new Set(wt),Pe=new Set(kr.map(e=>A(e.id)).filter(e=>e.length>0));function qs(e){let t=new Set;for(let n of e){let r=A(n);r.length>0&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function _o(e){let t=A(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: ${wt.join(", ")}.`);a.has(c)||(a.add(c),n.push(c))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${wt.join(", ")}.`)}let r=e.aliases===void 0?void 0:qs(e.aliases).filter(a=>a!==t),o=e.description?.trim(),i=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:r,description:o&&o.length>0?o:void 0,order:i}}function Bs(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 Ws(e){let t=Bs(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r;typeof o.id!="string"||o.id.trim().length===0||n.push(o)}return n}function We(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:Ws(t)}}function He(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
|
|
13
|
+
`}function wo(e,t,n){let r=e.statuses.slice(),o=r.findIndex(s=>A(s.id)===t.id),i=o>=0?r[o]: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),o>=0?r[o]=a:r.push(a),{file:{statuses:r},definition:a,replaced:i!==void 0}}function vo(e,t){let n=A(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 r=e.statuses.slice(),o=r.findIndex(a=>A(a.id)===n);if(o<0)return{file:{statuses:r},removed:!1};let[i]=r.splice(o,1);return{file:{statuses:r},removed:!0,definition:i}}function hn(e,t){let n=[e.id,...e.aliases??[]];for(let r of n){let o=A(r);if(o.length===0)continue;let i=t.get(o);if(i!==void 0&&i!==e.id)throw new Error(`Status token "${o}" 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]="60738c1f-3b44-5f8a-82c9-99d2b2de1e51")}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 So(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 Eo(e,t){let n=yn(e),r=ye(t,"migrationScope");return`auto-${xo("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function yn(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:A(ye(e.from,"source")),to:A(ye(e.to,"target")),...e.type===void 0?{}:{type:ye(e.type,"type")}}:{kind:e.kind,from:A(ye(e.from,"source")),to:A(ye(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Hs(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Ks(e,t,n){let r=K(t.schema),o=Hs(n);return ne(e,r.files[o],Y[o])}function $o(e,t){return Ve.join(e,"transactions","schema",`${t}-plan.json`)}function At(e){return e.length===0?null:JSON.parse(e)}async function Ke(e){let t=await q(e);return{exists:t!==null,raw:t??""}}async function Ao(e,t){t.exists?await he(e,t.raw):await Ne.rm(e,{force:!0})}function Vs(e,t,n){let r=ie(e),o=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),i=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(i>=0)return le(r);if(o<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[o],name:t.to})}else o>=0&&r.definitions.splice(o,1);return le(r)}function Ys(e,t,n){let r=qe(e),o=r.fields.findIndex(a=>a.key===t.from),i=r.fields.findIndex(a=>a.key===t.to);if(n==="stage"){if(i>=0)return Be(r);if(o<0)throw new TypeError(`Unknown custom field "${t.from}".`);let a=r.fields[o];r.fields.push({...a,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else o>=0&&r.fields.splice(o,1);return Be(r)}function Xs(e,t,n){let r=We(e),o=r.statuses.findIndex(a=>a.id===t.from),i=r.statuses.findIndex(a=>a.id===t.to);if(n==="stage"){if(i>=0)return He(r);if(o<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[o],id:t.to})}else o>=0&&r.statuses.splice(o,1);return He(r)}function Qs(e,t,n){return t.kind==="rename-type"?Vs(e,t,n):t.kind==="rename-field"?Ys(e,t,n):Xs(e,t,n)}function $e(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function _n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Ye(e){return Array.isArray(e)?e.map(t=>_n(t)).filter(t=>t!==void 0):[]}function Zs(e,t){for(let n of Ye(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>$e(r,t)));for(let n of Ye(e.type_workflows))n.type=$e(n.type,t)}function ec(e,t){for(let r of Ye(e.definitions))r.default_status=$e(r.default_status,t);let n=_n(e.workflow);if(n)for(let[r,o]of Object.entries(n))n[r]=$e(o,t);for(let r of Ye(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(o=>Array.isArray(o)?o.map(i=>$e(i,t)):o))}function tc(e,t){for(let n of Ye(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(o=>$e(o,t)));for(let r of["options","command_option_policies"])for(let o of Ye(n[r])){let i=r==="options"?"key":"option";o[i]=$e(o[i],t)}}}function nc(e,t){let n=_n(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=$e(n[r],t)}function gn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?Zs(r,t):t.kind==="rename-field"?tc(r,t):ec(r,t),nc(r,t),`${JSON.stringify(r,null,2)}
|
|
14
|
+
`}function Io(e,t){if(t.kind==="rename-type"){let r=ie(e).definitions;return{source:r.some(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(o=>o.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=qe(e).fields;return{source:r.some(o=>o.key===t.from),target:r.some(o=>o.key===t.to)}}let n=We(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function rc(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 oc(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 To(e,t){let n=yn(t.request),r=t.migrationId===void 0?Eo(n,t.migrationScope??"plan"):So(t.migrationId),o=e.map(c=>oc(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),i=xo("sha256").update(JSON.stringify({migrationId:r,request:n,items:o})).digest("hex"),a=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=o.filter(c=>!a.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:i,affected_item_count:o.length,pending_item_count:s.length,skipped_completed_count:o.length-s.length,items:Object.freeze(s)})}async function ic(e){let t=B(e.settings,H()),n=[...new Set(Object.values(t.type_to_folder))],r=await Pr(e.pmRoot,n),o=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=r?await Rr({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:o}):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 ac(e,t){let n=await q($o(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new h(`Stored schema migration plan "${t}" is invalid: ${or(r)}`,g.GENERIC_FAILURE)}}async function sc(e,t){let n=$o(e,t.migration_id);await Ne.mkdir(Ve.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await he(n,`${JSON.stringify(r,null,2)}
|
|
15
|
+
`)}function cc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function dc(e){let t=await Nr(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 Dr(t,{schema:e.settings.schema})).document.metadata}function bo(e,t,n){let r=n==="forward"?t.from:t.to,o=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===o.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=o,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===o.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=o,["status"]}let i=e.metadata;if(Object.prototype.hasOwnProperty.call(i,o)&&!Object.prototype.hasOwnProperty.call(i,r))return[];if(!Object.prototype.hasOwnProperty.call(i,r)||Object.prototype.hasOwnProperty.call(i,o))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return i[o]=i[r],delete i[r],[r,o]}function ko(e){return{id:e.id,inspect:async()=>{let t=await Ke(e.filePath),n=Io(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Ke(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ke(e.filePath);return await he(e.filePath,Qs(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 Ao(e.filePath,{exists:t.exists,raw:t.raw})}}}function lc(e){return{id:e.stepId,inspect:async()=>{let t=await Ke(e.filePath);return{state:gn(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Ke(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ke(e.filePath);return await he(e.filePath,gn(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 Ao(e.filePath,{exists:t.exists,raw:t.raw})}}}function pc(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await O(e.pmRoot),n=B(t,H()).type_to_folder,r=await dc({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),o=rc(r,e.request).length===0;return{state:o?"applied":"pending",...o?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await O(e.pmRoot),n=B(t,H()).type_to_folder,r=await tn({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(o){return{changedFields:bo(o,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await O(e.pmRoot),n=B(t,H()).type_to_folder;await tn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:bo(r,e.request,"reverse")}}})}}}async function uc(e){let t=await ac(e.pmRoot,e.migrationId);if(t){if(!cc(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 ic({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...To(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function mc(e){let t=Io(await q(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 sc(e.pmRoot,e.plan)}async function fc(e){let t=K(e.settings.schema),n=[...new Set([["types",Y.types],["fields",Y.fields],["workflows",Y.workflows]].map(([o,i])=>ne(e.pmRoot,t.files[o],i)).filter(o=>o!==e.schemaPath))];try{let o=Ve.join(e.pmRoot,"templates"),i=await Ne.readdir(o,{withFileTypes:!0});n.push(...i.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>Ve.join(o,a.name)))}catch(o){if(typeof o!="object"||o===null||!("code"in o)||!oe(o))throw o}n.sort((o,i)=>o.localeCompare(i));let r=[];for(let o of n){let i=await q(o);i!==null&&gn(i,e.request)!==i&&r.push({filePath:o,beforeRaw:i})}return{paths:n,snapshots:r}}async function hc(e){for(let t of e.snapshots){let n=await Ne.readFile(t.filePath,"utf8"),r=Ve.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await en({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:At(t.beforeRaw),after:At(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function gc(e,t,n){let r=yn(e),o=D(process.cwd(),n.path);await Ue(o);let i=t.migrationId===void 0?Eo(r,await Ne.realpath(o)):So(t.migrationId),a=await O(o),s=V(t.author,a.author_default),c=await uc({pmRoot:o,settings:a,migrationId:i,request:r}),d=c.plan;if(t.dryRun===!0)return{...d,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Ks(o,a,r),p=await Ne.readFile(l,"utf8");c.stored||await mc({pmRoot:o,schemaPath:l,request:r,plan:d});let u=await fc({pmRoot:o,schemaPath:l,settings:a,request:r}),m=[ko({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...u.paths.map((_,v)=>lc({filePath:_,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(_=>pc({pmRoot:o,id:_.id,request:r,author:s,force:t.force===!0})),ko({id:"retire-source",filePath:l,request:r,phase:"retire"})],y=await Br({pmRoot:o,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 en({pmRoot:o,author:s,documentPath:Ve.relative(o,l).replaceAll("\\","/"),before:At(p),after:At(w),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await hc({pmRoot:o,author:s,settings:a,request:r,plan:d,snapshots:u.snapshots}),{...d,action:r.kind,applied:!0,recovered:y.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:f}}function yc(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 kc from"node:path";import{mkdir as xc}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 rt=["agile","ops","research"],_c={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function It(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${rt.join(", ")}.`)}function ot(e){return _c[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 wc=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function vc(e){let t=wc.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function bc(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Oo(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,o=new Map;for(let a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=vc(s);if(c===void 0)continue;let d=o.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(s),o.set(c,d)}let i=[];for(let[a,s]of o.entries()){if(s.count<n)continue;let c=bc(a);i.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:Ir(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]="264088a5-09d1-52ed-8b12-af00392e1a5f")}catch{}})();var zf=["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",Co="schema-statuses",Ro="schema-fields";function Ae(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 Jf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{o=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(r),a=K(i.schema),s=ne(r,a.files.types,Y.types),c=[],d=V(t.author,i.author_default),l=ae(i),p=await Q(r,Tt,i.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await q(s),y;try{y=ie(m)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.GENERIC_FAILURE)}try{Tr(o,y);let w=new Map,f=B(i,H());for(let[_,v]of Object.entries(f.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!w.has(k)&&w.set(k,_)}Or(o,y,w)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}u=Ge(y,o),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await Ae({pmRoot:r,filePath:s,raw:le(u.file),op:"schema:add-type",author:d,settings:i}),await it(r,[u.definition],c,"schema:add-type-folder"),c.push(...await W({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await Po(r,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:I()}}async function _e(e){await Ue(e)}async function Po(e,t){try{let n=await co(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 Sc(e,t,n,r){let o=B(t,H()),i=r.trim().toLowerCase();return(await Ce(e,t.item_format,o.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===i).length}async function Ec(e,t,n,r){let o=B(t,H()),i=et(n),a=A(r);return(await Ce(e,t.item_format,o.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(i.alias_to_id.get(A(d))??A(d))===a}).length}async function $c(e,t,n,r,o){if(o.length===0||Pe.has(o))return;let i=await Ec(t,n,r,o);i>0&&e.push(`items_using_status:${i}`);let a=No(r.workflow,o);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function No(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,r])=>r!==void 0&&A(r)===t).map(([r])=>r)}async function qf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o=await O(r),i=K(o.schema),a=ne(r,i.files.types,Y.types),s=[],c=V(t.author,o.author_default),d=ae(o),l=await Q(r,Tt,o.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms),p;try{let u=await q(a),m;try{m=ie(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=Cr(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 Sc(r,o,i,y);w>0&&s.push(`items_using_type:${w}`)}await Ae({pmRoot:r,filePath:a,raw:le(p.file),op:"schema:remove-type",author:c,settings:o}),s.push(...await W({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return p.removed&&await Po(r,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:I()}}function wn(e,t){return ne(e,t.files.statuses,Y.statuses)}function Ot(e,t){return ne(e,t.files.fields,Y.fields)}function Do(e,t){return ne(e,t.files.types,Y.types)}async function it(e,t,n,r){for(let o of t){let i=cr(o.folder??sr(o.name)),a=kc.join(e,i);await x(a)||(await xc(a,{recursive:!0}),n.push(...await W({path:a,scope:"project",op:r})))}}function vn(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 Ac(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 Ic(e){let t=new Map;for(let n of e){let r=A(n.id);if(r.length!==0){t.set(r,r);for(let o of Array.isArray(n.aliases)?n.aliases:[]){let i=A(o);i.length>0&&!t.has(i)&&t.set(i,r)}}}return t}async function Bf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{o=_o({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(f){throw new h(f instanceof Error?f.message:String(f),g.USAGE)}let i=await O(r),a=K(i.schema),s=wn(r,a),c=et(a);try{hn(o,c.alias_to_id)}catch(f){throw new h(f instanceof Error?f.message:String(f),g.USAGE)}let d=Ac(c.by_id.get(o.id));if((o.roles??d?.roles??[]).length===0)throw new h(`Status "${o.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,g.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Oe(o.id)}" --role active`,`pm schema add-status "${Oe(o.id)}" --role blocked`]});let p=[],u=V(t.author,i.author_default),m=ae(i),y=await Q(r,Co,i.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,i.locks.wait_ms),w;try{let f=await q(s),_;try{_=We(f)}catch(k){throw new h(k instanceof Error?k.message:String(k),g.GENERIC_FAILURE)}let v=Ic(_.statuses);try{hn(o,v)}catch(k){throw new h(k instanceof Error?k.message:String(k),g.USAGE)}w=wo(_,o,d),await Ae({pmRoot:r,filePath:s,raw:He(w.file),op:"schema:add-status",author:u,settings:i}),p.push(...await W({path:s,scope:"project",op:"schema:add-status"}))}finally{await y()}return{action:"add-status",registered:!0,replaced:w.replaced,status:w.definition,file:{path:s,statuses:w.file.statuses.length},warnings:Ie(p),generated_at:I()}}async function Wf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o=await O(r),i=K(o.schema),a=wn(r,i),s=[],c=V(t.author,o.author_default),d=ae(o),l=await Q(r,Co,o.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms),p;try{let u=await q(a),m;try{m=We(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=vo(m,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=A(p.definition?.id??e);await $c(s,r,o,i,y),await Ae({pmRoot:r,filePath:a,raw:He(p.file),op:"schema:remove-status",author:c,settings:o}),s.push(...await W({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:I()}}function jo(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 Tc(e,t,n){return{...jo(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 Lo(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 Fo(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function Oc(){let e=new Map,t=H();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let o of r){if(typeof o!="object"||o===null||Array.isArray(o))continue;let i=o.name;typeof i=="string"&&i.trim().length>0&&e.set(i.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function Cc(e){let t=et(e),n=[],r=[];for(let o of t.definitions){let i=Lo(o);i.source==="builtin"?n.push(i):r.push(i)}return{builtin:n,custom:r}}async function at(e){let t=D(process.cwd(),e.path);await _e(t);let n=await O(t),r=K(n.schema),o=ne(t,r.files.types,Y.types),i=wn(t,r),a=B(n,H()),s=Oc(),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:o,statusesPath:i,byType:a.by_type,customNames:c,extensionProvenance:s,schema:r}}async function Hf(e){let t=await at(e),n=[],r=[],o=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Fo(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=jo(s);c==="extension"?o.push(d):c==="custom"?r.push(d):n.push(d)}let i=Cc(t.schema),a=kt(t.schema).definitions.map(vn);return{action:"list",builtin:n,custom:r,extension:o,counts:{builtin:n.length,custom:r.length,extension:o.length,total:n.length+r.length+o.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:I()}}async function Kf(e,t){let n=(e??"").trim();if(n.length===0)throw new h("Type name must not be empty.",g.USAGE);let r=await at(t),o=Object.values(r.byType).find(i=>i.name.toLowerCase()===n.toLowerCase()||i.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!o)throw new h(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Oe(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Tc(o,Fo(o.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(o.name.toLowerCase())),file:{path:r.typesPath},generated_at:I()}}async function Vf(e,t){let n=A(e);if(n.length===0)throw new h("Status id must not be empty.",g.USAGE);let r=await at(t),o=et(r.schema),i=o.alias_to_id.get(n)??n,a=o.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 "${Oe(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Lo(a),file:{path:r.statusesPath},generated_at:I()}}async function Yf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{o=ho({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(r),a=K(i.schema),s=Ot(r,a),c=[],d=St(o.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=V(t.author,i.author_default),p=ae(i),u=await Q(r,Ro,i.locks.ttl_seconds,l,!!t.force,p.force_required_for_stale_lock,i.locks.wait_ms),m;try{let y=await q(s),w;try{w=qe(y)}catch(f){throw new h(f instanceof Error?f.message:String(f),g.GENERIC_FAILURE)}m=go(w,o),await Ae({pmRoot:r,filePath:s,raw:Be(m.file),op:"schema:add-field",author:l,settings:i}),c.push(...await W({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:I()}}async function Rc(e,t,n,r){let o=B(t,H());return(await Ce(e,t.item_format,o.type_to_folder,[],n)).filter(a=>{let s=a[r];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function Xf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o=await O(r),i=K(o.schema),a=Ot(r,i),s=[],c=V(t.author,o.author_default),d=ae(o),l=await Q(r,Ro,o.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms),p;try{let u=await q(a),m;try{m=qe(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=yo(m,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=A(p.definition?.key??e),w=A(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(w.length>0){let f=await Rc(r,o,i,w);f>0&&s.push(`items_using_field:${f}`)}await Ae({pmRoot:r,filePath:a,raw:Be(p.file),op:"schema:remove-field",author:c,settings:o}),s.push(...await W({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:I()}}async function Qf(e){let t=await at(e),n=kt(t.schema).definitions.map(vn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Ot(t.pmRoot,t.schema)},generated_at:I()}}async function Zf(e,t){let n=A(e);if(n.length===0)throw new h("Field key must not be empty.",g.USAGE);let r=await at(t),o=kt(r.schema).by_key.get(n);if(!o)throw new h(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Oe(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:vn(o),file:{path:Ot(r.pmRoot,r.schema)},generated_at:I()}}async function eh(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{let w=It(e);if(w===void 0)throw new Error(`Type preset name is required. Allowed: ${rt.join(", ")}.`);o=w}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}let i=await O(r),a=K(i.schema),s=Do(r,a),c=[],d=V(t.author,i.author_default),l=ae(i),p=[],u=[],m,y=await Q(r,Tt,i.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms);try{let w=await q(s),f;try{f=ie(w)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let _=f;for(let v of ot(o)){let k=Ge(_,v);_=k.file,(k.replaced?u:p).push(k.definition.name)}m=_.definitions.length,await Ae({pmRoot:r,filePath:s,raw:le(_),op:"schema:apply-preset",author:d,settings:i}),await it(r,ot(o),c,"schema:apply-preset-folder"),c.push(...await W({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:o,registered:p,replaced:u,file:{path:s,definitions:m},warnings:Ie(c),generated_at:I()}}function Pc(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 th(e,t){let n=D(process.cwd(),t.path);await _e(n);let r=await O(n),o=K(r.schema),i=Do(n,o),a=Pc(e.minCount),s=B(r,H()),d=(await Ce(n,r.item_format,s.type_to_folder,[],o)).map(k=>typeof k.title=="string"?k.title:""),l=Oo(d,{minCount:a}),p=[],u=[],m=[],y=[],w;if(!e.apply){let k;try{k=ie(await q(i))}catch(S){throw new h(S instanceof Error?S.message:String(S),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:I()}}let f=V(e.author,r.author_default),_=ae(r),v=await Q(n,Tt,r.locks.ttl_seconds,f,!!e.force,_.force_required_for_stale_lock,r.locks.wait_ms);try{let k=await q(i),S;try{S=ie(k)}catch(M){throw new h(M instanceof Error?M.message:String(M),g.GENERIC_FAILURE)}let C=S;for(let M of l){if(M.shadows_builtin){y.push({name:M.name,reason:"shadows_builtin"});continue}let G;try{G=tt({name:M.name})}catch{y.push({name:M.name,reason:"invalid_type_token"});continue}let ce=Ge(C,G);C=ce.file,(ce.replaced?m:u).push(ce.definition.name)}w=C.definitions.length,await Ae({pmRoot:n,filePath:i,raw:le(C),op:"schema:infer-types",author:f,settings:r}),await it(n,C.definitions.filter(M=>u.includes(M.name)||m.includes(M.name)),p,"schema:infer-types-folder"),p.push(...await W({path:i,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:l,registered:u,replaced:m,skipped:y,file:{path:i,definitions:w},warnings:Ie(p),generated_at:I()}}function nh(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 "${Oe(e.type.name)}" "<title>"`}function rh(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 oh(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",r=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${r} in ${e.file.path}.`}function ih(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 ah(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,r]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])r.length!==0&&t.push(`${n}: ${r.map(o=>o.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,r]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])r.length!==0&&t.push(`${n}: ${r.map(o=>o.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
17
|
`)}function sh(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
18
|
`)}function ch(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
19
|
`)}function Nc(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 dh(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 lh(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 ph(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${Nc(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
|
|
20
20
|
`)}function uh(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
21
|
`)}function mh(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",r=[t,n].filter(o=>o.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${r.length>0?` (${r})`:""}.`}function fh(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;let t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(let n of e.candidates){let r=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${r}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
|
|
22
|
-
`)}var hh={workflowSlotsReferencing:No};import Uo from"node:fs/promises";import Ne from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6fc24a7c-a359-51fd-a432-4c8037d10e9e")}catch{}})();var Ot=["extensions","docs","examples","assets","prompts"],Dc=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 jc(e){return Ot.includes(e)}function Lc(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],r=[];for(let o of n){if(typeof o!="string"||o.trim().length===0)throw new h(`Package manifest field pm.${e} must contain string paths.`,g.USAGE);r.push(o.trim())}return[...new Set(r)].sort((o,i)=>o.localeCompare(i))}function Fc(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[r,o]of Object.entries(n)){if(!jc(r))continue;let i=Lc(r,o);i.length>0&&(t[r]=i)}return t}function ue(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function bn(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,r)=>n.localeCompare(r)):void 0}function Mo(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 Mc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:ue(t,"docs"),npm:ue(t,"npm"),repository:ue(t,"repository"),report:ue(t,"report")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function Gc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:ue(t,"image"),video:ue(t,"video")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function Uc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:ue(t,"display_name")??ue(t,"displayName"),category:ue(t,"category"),summary:ue(t,"summary"),links:Mc(t.links),media:Gc(t.media),tags:bn(t.tags)};return Object.values(n).some(r=>r!==void 0)?n:void 0}async function st(e){let t=Ne.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await Uo.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 r=n,o=r.pm,i=o!=null,a=typeof o=="object"&&o!==null&&!Array.isArray(o)?o:{};return{source:i?"pm":"convention",package_json_path:t,package_name:typeof r.name=="string"?r.name:void 0,package_version:typeof r.version=="string"?r.version:void 0,package_private:r.private===!0,package_description:typeof r.description=="string"?r.description:void 0,package_keywords:bn(r.keywords),package_homepage:typeof r.homepage=="string"?r.homepage:void 0,package_repository_url:Mo(r.repository),package_bugs_url:Mo(r.bugs),aliases:bn(a.aliases),resources:Fc(o),catalog:Uc(a.catalog)}}async function Go(e){if(!await k(e))return[];let t=await Uo.readdir(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let o=Ne.join(e,r.name);await k(Ne.join(o,"manifest.json"))&&n.push(o)}return n.sort((r,o)=>r.localeCompare(o))}async function Ct(e){if(await k(Ne.join(e,"manifest.json")))return[e];let n=(await st(e)).resources.extensions??[],r=new Set;for(let o of n){if(o.includes("*")||o.startsWith("!"))throw new h(`Package extension entry "${o}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,g.USAGE);let i=Ne.resolve(e,o);if(!te(e,i))throw new h(`Package extension entry "${o}" resolves outside package root.`,g.USAGE);if(await k(Ne.join(i,"manifest.json"))){r.add(i);continue}for(let a of await Go(i))r.add(a)}if(n.length===0)for(let o of Dc.extensions)for(let i of await Go(Ne.join(e,o)))r.add(i);return[...r].sort((o,i)=>o.localeCompare(i))}import{execFile as cd}from"node:child_process";import R from"node:fs/promises";import On from"node:os";import E from"node:path";import{fileURLToPath as dd}from"node:url";import{promisify as ld}from"node:util";import pd from"npm-package-arg";import{extract as ud,list as md}from"tar";import Qc from"node:fs/promises";import se from"node:path";import zo from"node:fs/promises";import kn 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 Z(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function b(e){return e.trim().toLowerCase()}function Rt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let o=t.slice(n,r);if(o.length===0)throw new h("Extension manifest name must resolve to a non-empty directory name.",g.USAGE);if(o==="."||o==="..")throw new h('Extension manifest name must not resolve to "." or "..".',g.USAGE);return o}function xn(e){return yr(e)}async function zc(e){try{let t=JSON.parse(await zo.readFile(kn.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(r=>typeof t.scripts?.[r]=="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 r=await zc(n.source_root),o=r.package_name?`pm install npm:${r.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${r.has_build_script?", and this package declares a build or publish script":""}. ${o?`Try "${o}" 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:o?[o,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:o?[`Retry with ${o}.`,"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],...o?{next_best_command:o}:{}}})}async function Ye(e,t={}){let n=kn.join(e,"manifest.json");if(!await k(n))throw new h(`Extension manifest is missing at "${n}".`,g.USAGE);let r;try{r=JSON.parse(await zo.readFile(n,"utf8"))}catch(a){throw new h(`Failed to parse extension manifest at "${n}": ${qc(a)}`,g.USAGE)}let o=xn(r);if(!o)throw new h(`Extension manifest at "${n}" is invalid.`,g.USAGE);let i=kn.resolve(e,o.entry);if(!te(e,i))throw new h(`Extension entry "${o.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await k(i))throw await Jc(o,i,t);if(!await _r(e,i))throw new h(`Extension entry "${o.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:i,manifest:o}}function qc(e){return e instanceof Error?e.message:String(e)}import Sn from"node:fs/promises";import Bc 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 Wc=".managed-extensions.json",Pt=1;function ct(e){return Bc.join(e,Wc)}function Hc(){return{version:Pt,updated_at:I(),entries:[]}}function dt(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.name.localeCompare(n.name);return o!==0?o:t.directory.localeCompare(n.directory)})}function Jo(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 ee(e){return typeof e=="string"?e:void 0}function Kc(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 Vc(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:ee(t.name),package:ee(t.package),version:ee(t.version),repository:ee(t.repository),owner:ee(t.owner),repo:ee(t.repo),ref:ee(t.ref),subpath:ee(t.subpath),commit:ee(t.commit)}}function Yc(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Kc(t))return null;let n=Vc(t.source);if(!n)return null;let r=fr(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Z(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:ee(t.last_update_check_at),last_update_remote_commit:ee(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:ee(t.update_error)}}function Xc(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 r of t.entries){let o=Yc(r);o&&n.push(o)}return{version:Pt,updated_at:ee(t.updated_at)??I(),entries:dt(n)}}async function we(e){let t=ct(e),n=Hc();try{let r=await Sn.readFile(t,"utf8"),o=JSON.parse(r),i=Xc(o);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(r){if(r instanceof h)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&oe(r))return{path:t,state:n,warnings:[]};throw new h(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE)}}async function De(e,t){let n=ct(e),r={version:Pt,updated_at:I(),entries:dt(t.entries)};await Sn.mkdir(e,{recursive:!0}),await Sn.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
23
|
-
`,"utf8")}function lt(e,t){let n=e.entries.filter(r=>b(r.name)!==b(t.name)&&b(r.directory)!==b(t.directory));return n.push(t),{...e,updated_at:I(),entries:dt(n)}}async function qo(e,t,n,r){let o=t.entries.find(a=>b(a.name)===b(n));if(!o)return t;let i=lt(t,{...o,contributions:r});return await
|
|
22
|
+
`)}var hh={workflowSlotsReferencing:No};import Uo 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 Ct=["extensions","docs","examples","assets","prompts"],Dc=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 jc(e){return Ct.includes(e)}function Lc(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],r=[];for(let o of n){if(typeof o!="string"||o.trim().length===0)throw new h(`Package manifest field pm.${e} must contain string paths.`,g.USAGE);r.push(o.trim())}return[...new Set(r)].sort((o,i)=>o.localeCompare(i))}function Fc(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[r,o]of Object.entries(n)){if(!jc(r))continue;let i=Lc(r,o);i.length>0&&(t[r]=i)}return t}function ue(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function bn(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,r)=>n.localeCompare(r)):void 0}function Mo(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 Mc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:ue(t,"docs"),npm:ue(t,"npm"),repository:ue(t,"repository"),report:ue(t,"report")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function Gc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:ue(t,"image"),video:ue(t,"video")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function Uc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:ue(t,"display_name")??ue(t,"displayName"),category:ue(t,"category"),summary:ue(t,"summary"),links:Mc(t.links),media:Gc(t.media),tags:bn(t.tags)};return Object.values(n).some(r=>r!==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 Uo.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 r=n,o=r.pm,i=o!=null,a=typeof o=="object"&&o!==null&&!Array.isArray(o)?o:{};return{source:i?"pm":"convention",package_json_path:t,package_name:typeof r.name=="string"?r.name:void 0,package_version:typeof r.version=="string"?r.version:void 0,package_private:r.private===!0,package_description:typeof r.description=="string"?r.description:void 0,package_keywords:bn(r.keywords),package_homepage:typeof r.homepage=="string"?r.homepage:void 0,package_repository_url:Mo(r.repository),package_bugs_url:Mo(r.bugs),aliases:bn(a.aliases),resources:Fc(o),catalog:Uc(a.catalog)}}async function Go(e){if(!await x(e))return[];let t=await Uo.readdir(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let o=De.join(e,r.name);await x(De.join(o,"manifest.json"))&&n.push(o)}return n.sort((r,o)=>r.localeCompare(o))}async function Rt(e){if(await x(De.join(e,"manifest.json")))return[e];let n=(await st(e)).resources.extensions??[],r=new Set;for(let o of n){if(o.includes("*")||o.startsWith("!"))throw new h(`Package extension entry "${o}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,g.USAGE);let i=De.resolve(e,o);if(!te(e,i))throw new h(`Package extension entry "${o}" resolves outside package root.`,g.USAGE);if(await x(De.join(i,"manifest.json"))){r.add(i);continue}for(let a of await Go(i))r.add(a)}if(n.length===0)for(let o of Dc.extensions)for(let i of await Go(De.join(e,o)))r.add(i);return[...r].sort((o,i)=>o.localeCompare(i))}import{execFile as cd}from"node:child_process";import R from"node:fs/promises";import On from"node:os";import E from"node:path";import{fileURLToPath as dd}from"node:url";import{promisify as ld}from"node:util";import pd from"npm-package-arg";import{extract as ud,list as md}from"tar";import Qc from"node:fs/promises";import se from"node:path";import zo from"node:fs/promises";import kn 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 Z(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function b(e){return e.trim().toLowerCase()}function Pt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let o=t.slice(n,r);if(o.length===0)throw new h("Extension manifest name must resolve to a non-empty directory name.",g.USAGE);if(o==="."||o==="..")throw new h('Extension manifest name must not resolve to "." or "..".',g.USAGE);return o}function xn(e){return yr(e)}async function zc(e){try{let t=JSON.parse(await zo.readFile(kn.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(r=>typeof t.scripts?.[r]=="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 r=await zc(n.source_root),o=r.package_name?`pm install npm:${r.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${r.has_build_script?", and this package declares a build or publish script":""}. ${o?`Try "${o}" 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:o?[o,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:o?[`Retry with ${o}.`,"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],...o?{next_best_command:o}:{}}})}async function Xe(e,t={}){let n=kn.join(e,"manifest.json");if(!await x(n))throw new h(`Extension manifest is missing at "${n}".`,g.USAGE);let r;try{r=JSON.parse(await zo.readFile(n,"utf8"))}catch(a){throw new h(`Failed to parse extension manifest at "${n}": ${qc(a)}`,g.USAGE)}let o=xn(r);if(!o)throw new h(`Extension manifest at "${n}" is invalid.`,g.USAGE);let i=kn.resolve(e,o.entry);if(!te(e,i))throw new h(`Extension entry "${o.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await x(i))throw await Jc(o,i,t);if(!await _r(e,i))throw new h(`Extension entry "${o.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:i,manifest:o}}function qc(e){return e instanceof Error?e.message:String(e)}import Sn from"node:fs/promises";import Bc 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 Wc=".managed-extensions.json",Nt=1;function ct(e){return Bc.join(e,Wc)}function Hc(){return{version:Nt,updated_at:I(),entries:[]}}function dt(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.name.localeCompare(n.name);return o!==0?o:t.directory.localeCompare(n.directory)})}function Jo(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 ee(e){return typeof e=="string"?e:void 0}function Kc(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 Vc(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:ee(t.name),package:ee(t.package),version:ee(t.version),repository:ee(t.repository),owner:ee(t.owner),repo:ee(t.repo),ref:ee(t.ref),subpath:ee(t.subpath),commit:ee(t.commit)}}function Yc(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Kc(t))return null;let n=Vc(t.source);if(!n)return null;let r=fr(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Z(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:ee(t.last_update_check_at),last_update_remote_commit:ee(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:ee(t.update_error)}}function Xc(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Nt||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let o=Yc(r);o&&n.push(o)}return{version:Nt,updated_at:ee(t.updated_at)??I(),entries:dt(n)}}async function we(e){let t=ct(e),n=Hc();try{let r=await Sn.readFile(t,"utf8"),o=JSON.parse(r),i=Xc(o);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(r){if(r instanceof h)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&oe(r))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),r={version:Nt,updated_at:I(),entries:dt(t.entries)};await Sn.mkdir(e,{recursive:!0}),await Sn.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
23
|
+
`,"utf8")}function lt(e,t){let n=e.entries.filter(r=>b(r.name)!==b(t.name)&&b(r.directory)!==b(t.directory));return n.push(t),{...e,updated_at:I(),entries:dt(n)}}async function qo(e,t,n,r){let o=t.entries.find(a=>b(a.name)===b(n));if(!o)return t;let i=lt(t,{...o,contributions:r});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 Zc="PM_CLI_PACKAGE_ROOT",Bo={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},ed=new Set(["*","all"]);function En(){let e=[],t=process.env[Zc];return typeof t=="string"&&t.trim().length>0&&e.push(se.resolve(t.trim())),e.push(de(import.meta.url,["../../.."])),[...new Set(e)]}async function pt(e){let t=e.trim().toLowerCase(),n=await Ho(t);if(n)return n;let r=Bo[t];if(!r)return null;for(let o of En()){let i=se.join(o,".agents","pm","extensions",r.legacy_extension_directory);if(await x(se.join(i,"manifest.json")))return i}return null}function Wo(e){return ed.has(e.trim().toLowerCase())}function td(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function nd(e,t){let n=await Qc.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let o=se.join(e,r.name);if(!await x(se.join(o,"package.json")))continue;let i=await st(o),a=i.aliases&&i.aliases.length>0?i.aliases:[td(r.name)];for(let s of a){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:o,package_name:i.package_name??null})}}}async function $n(){let e=new Map;for(let t of En()){let n=se.join(t,"packages");await x(n)&&await nd(n,e)}for(let[t,n]of Object.entries(Bo))if(!e.has(t))for(let r of En()){let o=se.join(r,"packages",n.package_directory);if(await x(se.join(o,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:o,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Dt(){return(await $n()).map(e=>e.alias)}async function Ho(e){let t=e.trim().toLowerCase();return(await $n()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function Ko(e){let t=await Ho(e);return t?(await st(t)).package_name??null:null}async function Vo(e){let t=await pt(e);if(!t)return null;try{let n=await Rt(t);return n.length!==1?null:(await Xe(n[0])).manifest.name}catch{return null}}function rd(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 od(e,t,n,r,o,i){let a=r==="global"?"--global":"--project",s=Object.fromEntries(Ct.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=>o.has(c))||i.has(se.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${a}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:rd(e),media:e.catalog?.media}}}async function Yo(e,t,n={}){let r=vt(D(process.cwd(),t.path),process.cwd()),o=e==="global"?r.global:r.project,i=await we(o),a=new Set(i.state.entries.filter(u=>u.scope===e).filter(u=>u.source.kind!=="builtin").map(u=>se.resolve(u.source.location))),s=new Set(i.state.entries.filter(u=>u.scope===e&&u.source.kind==="builtin").flatMap(u=>[u.source.name,u.source.input,u.source.location]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toLowerCase())),c=[],d=new Map;for(let u of await $n()){let m=se.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(od(w,m,y,e,s,a))}let l=ad(n.fields),p=l?c.map(u=>sd(u,l)):c;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Ct.filter(u=>u!=="extensions"),packages:p}}var id=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 ad(e){if(e===void 0)return;let t=jr(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(r=>!id.has(r));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 sd(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;return n}(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]="05f56edb-c08d-570c-b8b5-641fc694331e")}catch{}})();var Qo=ld(cd),Lt="@unbrained/pm-cli",fd={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},An;async function Zo(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=E.resolve(t);for(;;){let o=E.join(r,"node_modules",...n.split("/")),i=E.join(o,"package.json");if(await x(i))try{let s=JSON.parse(await R.readFile(i,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:o}}catch{return null}let a=E.dirname(r);if(a===r)return null;r=a}}function In(e,t,n){let r=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(r.length<2)return null;let o=r[0],i=r[1].replace(/\.git$/i,"");if(o.length===0||i.length===0)return null;let a=r.slice(2),s,c;return a[0]==="tree"&&a.length>=2?(s=a[1],c=a.slice(2).join("/")):a.length>0&&(c=a.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:o,repo:i,repository:`https://github.com/${o}/${i}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function hd(e,t,n){let r=e.slice(4).trim();if(r.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:r}}function Ft(e,t={}){let n=e.trim();if(n.length===0)throw new h("Extension source is required for --install.",g.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return hd(n,t.forceGithub===!0,r);let o=(()=>{try{let a=new URL(n);if(a.hostname!=="github.com")return null;let s=a.pathname.replace(/^\/+/,"");return In(s,n,r)}catch{return null}})();if(o)return o;let i=n.startsWith("github.com/")?n.slice(11):null;if(i){let a=In(i,n,r);if(!a)throw new h(`Invalid GitHub source "${n}".`,g.USAGE);return a}if(t.forceGithub){let a=In(n,n,r);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:E.resolve(process.cwd(),n)}}async function jt(e,t=Qo,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let o=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",i=o.trim().length>0?o.trim():r instanceof Error?r.message:String(r);throw new h(`Git command failed: git ${e.join(" ")}
|
|
24
24
|
${i}`,g.GENERIC_FAILURE)}}function gd(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function yd(e=process.platform){return e==="win32"}async function ei(e,t,n=Qo,r=process.platform,o=process.env){let i=gd(r),a=Object.fromEntries(Object.entries(o).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(i,e,{cwd:t,encoding:"utf8",env:a,shell:yd(r)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",d=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new h(`npm command failed: ${i} ${e.join(" ")}
|
|
25
|
-
${d}`,g.GENERIC_FAILURE)}}function ti(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 ni(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function _d(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 wd(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return _d(e)||n.includes("not found")}function vd(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function bd(e){let t=ti(e),n=vd(t),r=t.replace(/^.*\//,""),o=n?`github.com/unbraind/${r}`:void 0,i=o?`pm install --project ${o}`: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}`],...o&&i?{fallback_candidates:[{source:o,command:i,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:i}:{}}}}}function kd(e,t){if(!wd(t))return null;let n=bd(e);return new h(n.message,g.NOT_FOUND,n.context)}async function ri(e){if(E.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=E.resolve(process.cwd(),e);return await
|
|
25
|
+
${d}`,g.GENERIC_FAILURE)}}function ti(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 ni(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function _d(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 wd(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return _d(e)||n.includes("not found")}function vd(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function bd(e){let t=ti(e),n=vd(t),r=t.replace(/^.*\//,""),o=n?`github.com/unbraind/${r}`:void 0,i=o?`pm install --project ${o}`: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}`],...o&&i?{fallback_candidates:[{source:o,command:i,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:i}:{}}}}}function kd(e,t){if(!wd(t))return null;let n=bd(e);return new h(n.message,g.NOT_FOUND,n.context)}async function ri(e){if(E.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=E.resolve(process.cwd(),e);return await x(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=dd(t);return await x(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=E.resolve(process.cwd(),e);if(await x(t))return t}return null}async function xd(e){let t=await ri(e);if(t)return t;let n=Sd(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Sd(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!ni(e))return e;let o=e.slice(0,r),i=e.slice(r+n.length);if(i.startsWith("//")&&!i.startsWith("///"))return e;if(!i.startsWith("/"))return`${o}@${E.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`${o}@${s}`}function Xo(e,t){let n=E.resolve(e,t),r=E.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${E.sep}`)||E.isAbsolute(r))throw new h("npm pack reported a package archive outside its isolated destination.",g.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function Ed(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function $d(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]).flatMap(({key:n,value:r})=>{let o=Ed(r,n);return o?[o]:[]})}function Ad(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(a=>{let s=a.name?.trim().toLowerCase();return s!==void 0?s===n:a.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let o=e[0],i=o.name??o.key;return n&&i!==void 0&&i.trim().toLowerCase()!==n?void 0:o}function Id(e,t,n){let r;try{r=JSON.parse(e)}catch{let a=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!a)throw new h("npm pack did not report a tarball filename.",g.GENERIC_FAILURE);return{tarball:Xo(t,a)}}let o=$d(r),i=Ad(o,n);if(!i)throw new h("npm pack --json returned an unsupported or ambiguous package receipt.",g.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${o.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Xo(t,i.filename),package:i.name??i.key,version:i.version}}async function Td(e){return Od(e,ei)}async function Od(e,t){let n=await ri(e.spec);if(n){if((await R.stat(n)).isFile()&&oi(n))return Tn(n);let a=E.join(n,"package.json"),s=await x(a)?JSON.parse(await R.readFile(a,"utf8")):{};return{directory:await Mt(n,e.input),package:typeof s.name=="string"?s.name:void 0,version:typeof s.version=="string"?s.version:void 0,cleanup:async()=>{}}}let r=await R.mkdtemp(E.join(On.tmpdir(),"pm-npm-package-source-")),o=E.join(r,"pack");await R.mkdir(o,{recursive:!0});try{let i=await xd(e.spec),a=await t(["pack",i,"--json","--pack-destination",o]),s=Id(a,o,ni(e.spec)?void 0:ti(e.spec));if(!await x(s.tarball))throw new h("npm pack did not create its reported package archive.",g.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await Tn(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await R.rm(r,{recursive:!0,force:!0})}}}}catch(i){await R.rm(r,{recursive:!0,force:!0});let a=kd(e.spec,i);throw a||i}}function oi(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 Cd(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 r=e.path,o=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||o.some(i=>i===".."))&&ve(`Local package archive contains an escaping path: "${r}".`),o[0]!=="package"&&ve(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ve(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ve(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ve(`Local package archive entry "${r}" 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.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function Tn(e,t=fd){(await R.stat(e)).size>t.maxArchiveBytes&&ve(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await R.mkdtemp(E.join(On.tmpdir(),"pm-local-package-archive-")),o=E.join(r,"extract");await R.mkdir(o,{recursive:!0});let i={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await md({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(a===void 0)try{Cd(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 ud({file:e,cwd:o,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=E.join(o,"package"),c=E.join(s,"package.json"),d=JSON.parse(await R.readFile(c,"utf8"));return await Rd(s),{directory:await Mt(s,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await R.rm(r,{recursive:!0,force:!0})}}}catch(s){throw await R.rm(r,{recursive:!0,force:!0}),s}}async function Rd(e,t=ei){let n=E.join(e,"package.json");if(!await x(n))return;let r;try{r=JSON.parse(await R.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let o=r,i=Fd(o),a=Pd(o);if(i.length===0&&!a)return;let s={...r};delete s.devDependencies;let c={...s};Nd(c),await R.writeFile(n,`${JSON.stringify(c,null,2)}
|
|
26
26
|
`,"utf8");try{await Promise.all([R.rm(E.join(e,"package-lock.json"),{force:!0}),R.rm(E.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 Dd(e)}finally{await R.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
27
|
-
`,"utf8")}}function Pd(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 Nd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[jt],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function Dd(e){let t=de(import.meta.url,["../../.."]),[n,r]=jt.split("/"),o=E.join(e,"node_modules",n),i=E.join(o,r);await R.mkdir(o,{recursive:!0}),await R.rm(i,{recursive:!0,force:!0}),await R.symlink(t,i,jd(process.platform))}function jd(e){return e==="win32"?"junction":"dir"}function Ld(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(r=>{let o=r.charCodeAt(0);return o<=31||o===127||"&|;()`\"'".includes(r)}))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{pd.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 Fd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,o]of Object.entries(n)){if(r===jt||typeof o!="string"||o.trim().length===0||t.has(r))continue;let i=o.trim();t.set(r,Ld(r,i))}return[...t.values()]}async function Ft(e,t){let n=await Ct(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(o=>E.relative(e,o).replaceAll(E.sep,"/")).sort((o,i)=>o.localeCompare(i));throw new h(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.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 Md(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(E.posix.join(".agents/pm/extensions",t.subpath)),n.push(E.posix.join(".custom/pm-extensions",t.subpath)),n.push(E.posix.join(".custom/pm-extension",t.subpath)));for(let o of n){let i=E.resolve(e,o);if(te(e,i)&&await k(E.join(i,"manifest.json")))return{directory:i,resolved_subpath:o}}if(await k(E.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await Ft(e,t.input);return{directory:r,resolved_subpath:E.relative(e,r).replaceAll(E.sep,"/")}}function Gd(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 Ud(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Gd(n))return new h(t,g.NOT_FOUND);let r=[];try{let i=process.env.PM_CLI_PACKAGE_ROOT,a=typeof i=="string"&&i.trim().length>0?E.resolve(i.trim()):"";An?.key!==a&&(An={key:a,aliases:await Nt()}),r=An.aliases}catch{}let o=[`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): ${r.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:o,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function ii(e){if(e.kind==="local"){let r;try{r=await R.stat(e.absolute_path)}catch{throw await Ud(e)}if(r.isFile()&&oi(e.absolute_path)){let i=await Tn(e.absolute_path);return{source:e,directory:i.directory,source_root:E.dirname(i.directory),resolved_subpath:E.relative(E.dirname(i.directory),i.directory).replaceAll(E.sep,"/"),npm_package:i.package,npm_version:i.version,cleanup:i.cleanup}}if(!r.isDirectory())throw new h(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,g.USAGE);let o=await Ft(e.absolute_path,e.input);return{source:e,directory:o,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await Td(e);return{source:e,directory:r.directory,source_root:E.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:E.relative(E.dirname(r.directory),r.directory).replaceAll(E.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await R.mkdtemp(E.join(On.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 r=await Dt(["-C",t,"rev-parse","HEAD"]),o=await Md(t,e);return{source:e,directory:o.directory,source_root:t,resolved_subpath:o.resolved_subpath,commit:r,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await R.rm(t,{recursive:!0,force:!0}),r}}async function ai(e,t){if(!await k(e)||!await k(t))return!1;let[n,r]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===r}import ut from"node:fs/promises";import mt 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]="5321d574-4de4-5f94-99db-0c49639673fc")}catch{}})();var Cn=1,je="2026.6.24",zd=">=22.18.0",Jd={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},si=new Set([...Ar.map(e=>e.split("-")[0].toLowerCase()),...Object.keys($r).map(e=>e.toLowerCase()),"scaffold"]),qd="^6.0.0",Bd="^22.0.0",li=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],me=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function ci(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function pi(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 ui(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 Wd={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},di=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],mi={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"]},Hd={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"]'},Kd={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."},Vd={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."},fi="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Yd={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."]},Xd={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`."]},Zd={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 hi(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 gi(e,t){return e==="schema"?Qd[t]:e==="profile"?Zd[t]:Xd[t]}function el(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let o=t[r]?.toLowerCase(),i=r>0&&(r===t.length||o!==void 0&&si.has(o));return`${(si.has(n)||i?["starter",...t]:t).join(" ")} ping`}function yi(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),o=r===t?[]:[r],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(o)},`,` 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 tl(e,t,n){let r=`${e}-search`,o=`${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(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(o)},`,' 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({",...yi(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 nl(e,t,n){let r=n==="hooks",o=n==="search",i=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",p=n==="services",u=Hd[n],m=e,y=`${e}s`,w=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`,_=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],x=o?Rn(e,t,"search",u):[],S=i?Rn(e,t,"importers",u):[],C=a?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...ci(pi({extensionName:e,itemTypeName:m,itemTypeFolder:y,fieldName:w,migrationId:f,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],M=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 {",...ci(ui(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],G=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;",...me,"});",""]:[],ce=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;",...me,"});",""]:[],$=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;",...me,"});",""]:[],J=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;",...me,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",..._,'} from "@unbrained/pm-cli/sdk/testing";',...o?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...li,`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;",...me,"});","",...v,...x,...S,...C,...M,...G,...ce,...$,...J,`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(`
|
|
27
|
+
`,"utf8")}}function Pd(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Lt in t)return!0;return!1}function Nd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Lt],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function Dd(e){let t=de(import.meta.url,["../../.."]),[n,r]=Lt.split("/"),o=E.join(e,"node_modules",n),i=E.join(o,r);await R.mkdir(o,{recursive:!0}),await R.rm(i,{recursive:!0,force:!0}),await R.symlink(t,i,jd(process.platform))}function jd(e){return e==="win32"?"junction":"dir"}function Ld(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(r=>{let o=r.charCodeAt(0);return o<=31||o===127||"&|;()`\"'".includes(r)}))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{pd.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 Fd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,o]of Object.entries(n)){if(r===Lt||typeof o!="string"||o.trim().length===0||t.has(r))continue;let i=o.trim();t.set(r,Ld(r,i))}return[...t.values()]}async function Mt(e,t){let n=await Rt(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(o=>E.relative(e,o).replaceAll(E.sep,"/")).sort((o,i)=>o.localeCompare(i));throw new h(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.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 Md(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(E.posix.join(".agents/pm/extensions",t.subpath)),n.push(E.posix.join(".custom/pm-extensions",t.subpath)),n.push(E.posix.join(".custom/pm-extension",t.subpath)));for(let o of n){let i=E.resolve(e,o);if(te(e,i)&&await x(E.join(i,"manifest.json")))return{directory:i,resolved_subpath:o}}if(await x(E.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await Mt(e,t.input);return{directory:r,resolved_subpath:E.relative(e,r).replaceAll(E.sep,"/")}}function Gd(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 Ud(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Gd(n))return new h(t,g.NOT_FOUND);let r=[];try{let i=process.env.PM_CLI_PACKAGE_ROOT,a=typeof i=="string"&&i.trim().length>0?E.resolve(i.trim()):"";An?.key!==a&&(An={key:a,aliases:await Dt()}),r=An.aliases}catch{}let o=[`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): ${r.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:o,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function ii(e){if(e.kind==="local"){let r;try{r=await R.stat(e.absolute_path)}catch{throw await Ud(e)}if(r.isFile()&&oi(e.absolute_path)){let i=await Tn(e.absolute_path);return{source:e,directory:i.directory,source_root:E.dirname(i.directory),resolved_subpath:E.relative(E.dirname(i.directory),i.directory).replaceAll(E.sep,"/"),npm_package:i.package,npm_version:i.version,cleanup:i.cleanup}}if(!r.isDirectory())throw new h(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,g.USAGE);let o=await Mt(e.absolute_path,e.input);return{source:e,directory:o,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await Td(e);return{source:e,directory:r.directory,source_root:E.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:E.relative(E.dirname(r.directory),r.directory).replaceAll(E.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await R.mkdtemp(E.join(On.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await jt(n);let r=await jt(["-C",t,"rev-parse","HEAD"]),o=await Md(t,e);return{source:e,directory:o.directory,source_root:t,resolved_subpath:o.resolved_subpath,commit:r,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await R.rm(t,{recursive:!0,force:!0}),r}}async function ai(e,t){if(!await x(e)||!await x(t))return!1;let[n,r]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===r}import ut from"node:fs/promises";import mt 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]="5321d574-4de4-5f94-99db-0c49639673fc")}catch{}})();var Cn=1,Le="2026.6.24",zd=">=22.18.0",Jd={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},si=new Set([...Ar.map(e=>e.split("-")[0].toLowerCase()),...Object.keys($r).map(e=>e.toLowerCase()),"scaffold"]),qd="^6.0.0",Bd="^22.0.0",li=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],me=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function ci(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function pi(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 ui(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 Wd={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},di=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],mi={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"]},Hd={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"]'},Kd={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."},Vd={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."},fi="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Yd={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."]},Xd={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`."]},Zd={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 hi(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 gi(e,t){return e==="schema"?Qd[t]:e==="profile"?Zd[t]:Xd[t]}function el(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let o=t[r]?.toLowerCase(),i=r>0&&(r===t.length||o!==void 0&&si.has(o));return`${(si.has(n)||i?["starter",...t]:t).join(" ")} ping`}function yi(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),o=r===t?[]:[r],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(o)},`,` 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 tl(e,t,n){let r=`${e}-search`,o=`${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(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(o)},`,' 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({",...yi(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 nl(e,t,n){let r=n==="hooks",o=n==="search",i=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",p=n==="services",u=Hd[n],m=e,y=`${e}s`,w=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`,_=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],k=o?Rn(e,t,"search",u):[],S=i?Rn(e,t,"importers",u):[],C=a?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...ci(pi({extensionName:e,itemTypeName:m,itemTypeFolder:y,fieldName:w,migrationId:f,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],M=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 {",...ci(ui(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],G=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;",...me,"});",""]:[],ce=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;",...me,"});",""]:[],$=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;",...me,"});",""]:[],J=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;",...me,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",..._,'} from "@unbrained/pm-cli/sdk/testing";',...o?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...li,`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;",...me,"});","",...v,...k,...S,...C,...M,...G,...ce,...$,...J,`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
28
|
`)}function rl(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var ol={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"},il={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 al(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function sl(e,t,n){let r=[],o=[...al(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":r.push("defineAfterCommandHook"),o.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":r.push("defineSearchProvider","defineVectorStoreAdapter"),o.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":r.push("defineExporter","defineImporter"),o.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":r.push("defineItemField","defineItemType","defineMigration"),o.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":r.push("defineProjectProfile"),o.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({",...yi(e),"});"),i.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),o.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":r.push("defineParserOverride"),o.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":r.push("definePreflightOverride"),o.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":r.push("defineServiceOverride"),o.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:r,definitions:o,blueprintFields:i}}function cl(e,t,n){let r=sl(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((i,a)=>i.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
|
|
29
|
-
`)}function Rn(e,t,n,r){if(n==="commands")return[];let o=`${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: ${r},`," });"],u=m=>[...p," let deactivated = false;"," try {",...m.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...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(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(o)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(o)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(i)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...u([` ext.assertImporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(a)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...u(pi({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(ui(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 dl(e,t,n){let r=n==="parser",o=JSON.stringify([...mi[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" };',"",...li,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(je)},`," },",` target: { pmVersion: ${JSON.stringify(je)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${o});`,` assert.deepEqual(report.manifest?.capabilities, ${o});`,"});","",`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: ${o},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});","",...Rn(e,t,n,o)].join(`
|
|
30
|
-
`)}function ll(e,t,n){let r=hi(n,"package"),o=gi(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${ol[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`.",fi,"- `.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 ${il[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.",...o,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Cn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${
|
|
31
|
-
`)}function pl(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 ul(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 ml(e,t,n,r){let o=["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"&&o.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&o.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&o.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"&&o.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&o.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&o.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&o.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&o.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"&&o.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),o}function fl(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function hl(e,t,n,r="commands",o=!1){let i=`pm-${e}`,a=mi[r],s=rl(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Cn,pm_min_version:
|
|
29
|
+
`)}function Rn(e,t,n,r){if(n==="commands")return[];let o=`${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: ${r},`," });"],u=m=>[...p," let deactivated = false;"," try {",...m.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...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(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(o)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(o)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(i)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...u([` ext.assertImporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(a)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...u(pi({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(ui(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 dl(e,t,n){let r=n==="parser",o=JSON.stringify([...mi[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" };',"",...li,`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(Le)},`," },",` target: { pmVersion: ${JSON.stringify(Le)} },`," });"," // 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, ${o});`,` assert.deepEqual(report.manifest?.capabilities, ${o});`,"});","",`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: ${o},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});","",...Rn(e,t,n,o)].join(`
|
|
30
|
+
`)}function ll(e,t,n){let r=hi(n,"package"),o=gi(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${ol[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`.",fi,"- `.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 ${il[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.",...o,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Cn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Le}\`. 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 pl(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 ul(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 ml(e,t,n,r){let o=["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"&&o.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&o.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&o.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"&&o.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&o.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&o.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&o.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&o.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"&&o.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),o}function fl(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function hl(e,t,n,r="commands",o=!1){let i=`pm-${e}`,a=mi[r],s=rl(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Cn,pm_min_version:Le,trusted:!0,sandbox_profile:"strict",permissions:{...Jd},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
|
|
32
32
|
`,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...tl(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
|
|
33
33
|
`),l=`${JSON.stringify(Wd,null,2)}
|
|
34
|
-
`,p=Kd[r],u=hi(r,"package"),m=`${JSON.stringify({name:i,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:zd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${
|
|
34
|
+
`,p=Kd[r],u=hi(r,"package"),m=`${JSON.stringify({name:i,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:zd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Le}`},devDependencies:{"@types/node":Bd,typescript:qd},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
35
|
`,y=nl(e,t,r),w=Vd[r],f=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
36
|
-
`),_=pl(e),
|
|
37
|
-
`);return{"package.json":m,"manifest.json":c,"index.ts":o?cl(e,t,r):d,"index.test.ts":o?dl(e,t,r):y,"tsconfig.json":l,".gitignore":f,"README.md":o?ll(i,t,r):S}}async function _i(e,t="extension",n="commands",r=!1){let o=n.trim().toLowerCase();if(!di.includes(o))throw new h(`Unknown scaffold capability "${n}". Supported capabilities: ${di.join(", ")}.`,g.USAGE);let i=o;if(r&&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=r?"declarative":"imperative",s=e.trim(),c=mt.resolve(process.cwd(),s),d=
|
|
36
|
+
`),_=pl(e),k=["```ts",`import { ${ul(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...ml(e,t,r,_),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...fl(t,r,_),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],S=[`# ${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,fi,"- `.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`.",...Yd[r],...gi(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Le}\`. 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 \`${Cn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Le}\`. 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":o?cl(e,t,r):d,"index.test.ts":o?dl(e,t,r):y,"tsconfig.json":l,".gitignore":f,"README.md":o?ll(i,t,r):S}}async function _i(e,t="extension",n="commands",r=!1){let o=n.trim().toLowerCase();if(!di.includes(o))throw new h(`Unknown scaffold capability "${n}". Supported capabilities: ${di.join(", ")}.`,g.USAGE);let i=o;if(r&&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=r?"declarative":"imperative",s=e.trim(),c=mt.resolve(process.cwd(),s),d=Pt(mt.basename(c)).replace(/^(?:pm-)+/u,""),l=el(d),p=hl(d,l,t,i,r),u=!1;if(await x(c)){if(!(await ut.stat(c)).isDirectory())throw new h(`Scaffold target "${c}" exists and is not a directory.`,g.CONFLICT)}else await ut.mkdir(c,{recursive:!0}),u=!0;for(let[y,w]of Object.entries(p)){let f=mt.join(c,y);if(!await x(f))continue;if(await ut.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=mt.join(c,y);if(await x(f)){m.push({path:y,status:"unchanged"});continue}await ut.mkdir(mt.dirname(f),{recursive:!0}),await ut.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 wi=1,Pn=6,vi=[["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 Nn(e){return"#".repeat(e)}function bi(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let i of e)n=i==="`"?n+1:0,t=Math.max(t,n);let r="`".repeat(t+1),o=e.startsWith("`")||e.endsWith("`")?" ":"";return`${r}${o}${e}${o}${r}`}function gl(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(bi).join(", ")}`}function yl(e,t,n){let r=[`${Nn(t)} ${e}`,""];return n.length===0?(r.push("_None._",""),r):(r.push(...n.map(o=>`- ${bi(o)}`),""),r)}function _l(e,t,n){return e===0&&!n?[]:[`${Nn(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function Dn(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<wi||n>Pn)throw new RangeError(`headingLevel must be an integer in [${wi}, ${Pn}], received ${String(t.headingLevel)}`);let r=Math.min(n+1,Pn),o=t.includeEmpty===!0,i=t.title??"Extension surfaces",a=[`${Nn(n)} ${i}`,""];(o||e.capabilities.length>0)&&a.push(gl(e.capabilities),"");for(let[c,d]of vi){let l=e[c]??[];l.length===0&&!o||a.push(...yl(d,r,l))}return a.push(..._l(e.preflight_overrides,r,o)),!(e.preflight_overrides>0||vi.some(([c])=>(e[c]?.length??0)>0))&&!o&&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 ki(e,t){return`${e}:${b(t)}`}function wl(e,t){let n=[];for(let[r,o]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let i=new Map;for(let a of o){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:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((r,o)=>r.command.localeCompare(o.command)||r.surface.localeCompare(o.surface))}function xi(e,t,n){let r=new Set(n.failed.map(d=>ki(d.layer,d.name))),o=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(ki(d.layer,d.name))?"failed":"ok",surfaces:
|
|
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 ki(e,t){return`${e}:${b(t)}`}function wl(e,t){let n=[];for(let[r,o]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let i=new Map;for(let a of o){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:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((r,o)=>r.command.localeCompare(o.command)||r.surface.localeCompare(o.surface))}function xi(e,t,n){let r=new Set(n.failed.map(d=>ki(d.layer,d.name))),o=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(ki(d.layer,d.name))?"failed":"ok",surfaces:ze(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:ze(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?o:o.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:ze(n,c),command_ownership:wl(n,a)}}var vl={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function Og(e,t){let r=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(r.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),r.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){r.push("## Command ownership","");for(let o of e.command_ownership){let i=o.claimants.find(s=>s.winner),a=o.claimants.map(s=>`${s.layer}:${s.name}`).join(", ");r.push(`- \`${o.command}\` (${o.surface}): ${i.layer}:${i.name}; policy=${o.policy}; collision=${String(o.collision)}; claimants=${a}`)}r.push("")}if(e.extensions.length===0)return r.push(`_No ${t}s are loaded._`,""),`${r.join(`
|
|
40
40
|
`).trimEnd()}
|
|
41
41
|
`;for(let o of e.extensions){let i=`${o.name} (${o.layer} v${o.version}, ${vl[o.activation_status]})`;r.push(Dn(o.surfaces,{title:i,headingLevel:2}))}return e.extensions.length>1&&r.push(Dn(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${r.join(`
|
|
42
42
|
`).trimEnd()}
|
|
43
|
-
`}import bl from"node:fs/promises";import kl 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 jn(e){return kl.join(e,"extension-migrations.json")}function Si(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 Ei(e,t){return`${e.layer}:${e.name}:${t}`}async function xl(e){let t=jn(e);if(!await
|
|
44
|
-
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let a=r.filter(l=>l.outcome==="pending").length,s=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:jn(e.pmRoot),total:r.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function $i(e){let t=await O(e.resolvedRoots.settings_root),n=await be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await ke(n);e.warnings.push(...n.warnings,...r.warnings);let o=await El({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:o,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},o.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 Ai(e,t,n){let r=typeof t=="string"?null:await pt(e),o=r===null?null:e.trim().toLowerCase(),i=o===null?null:await Ko(o),a=Lt(r??e,{forceGithub:typeof t=="string",ref:n}),s=o===null?null:await Zo(e);return{bundledAliasName:o,bundledPackageName:i,installSource:a,sourceResolution:{requested:e,selected:{kind:o===null?a.kind:"builtin",input:o??a.input,...i===null?{}:{package:i}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...o===null?[]:[{kind:"builtin",input:o,...i===null?{}:{package:i},command:`pm install ${o}`}],...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 Te from"node:fs/promises";import re 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 Ln(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function Mt(e,t,n){let r=b(t),o=n.trim();if(r.length===0||o.length===0)return;let i=e.get(r)??new Set;i.add(o),e.set(r,i)}function $l(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)Mt(t,r.name,r.command),Mt(n,r.name,r.action);for(let r of e.commands.handlers)Mt(t,r.name,r.command);for(let r of e.commands.overrides)Mt(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Ii(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Al(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:o,activationFailedNames:i}=e;return t?o.has(n)||i.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function Gt(e,t,n){let r=new Set(t.loaded.map(c=>b(c.name))),o=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=Ii(a.get(d)),p=Ii(s.get(d)),u={...l?{command_paths:l}:{},...p?{action_paths:p}:{}},m=Al({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:o,activationFailedNames:i});return{...c,...m,...u}})}function Il(e){let t=0,n=0,r=0;for(let o of e)if(o.startsWith("extension_policy_")){if(t+=1,o.startsWith("extension_policy_violation_")){n+=1;continue}o.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function U(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Ci=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 Tl(e){return Ci.has(Li(e))}function Ti(e){return e==="project"||e==="global"}function Ri(e){let t=e.split(":"),n=t[0];if(!n||!Ci.has(n))return null;let r=t.at(-4),o=t.at(-3)?.trim(),i=t.at(-2),a=t.at(-1)?.trim();return!Ti(r)||!Ti(i)||!o||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:o},displaced:{layer:i,name:a}}}function Ol(e){let t=new Set;for(let n of e){let r=Ri(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Cl(e,t){let n=e.filter(Tl);if(n.length===0)return null;let r=Ol(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function Rl(e,t,n,r){let o=t.map(p=>Ri(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(o.length===0)return;let i=e==="global"?"--global":"--project",a=U(r,"deactivate"),s=`${U(r,"doctor")} ${i} --detail deep --trace`,c=new Map(n.map(p=>[b(p.name),p])),d=new Map;for(let p of o)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:o.length,extension_count:d.size,next_best_command:s,collisions:o,remediation_candidates:l}}function Pi(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function Ni(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let o=r.trace?.missing_capability??r.trace?.capability;typeof o=="string"&&o.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${o.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function Di(e,t){let n=[];for(let r of br(e.loaded,t))for(let o of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${o}`);return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}var Pl=[{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: ${tr.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 Nl(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:o,updateCheckFailedTotal:i,policyWarningCount:a,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,p=[],u={options:n,scope:r,scopeFlag:o,updateCheckFailedTotal:i,policyWarningCount:a};if(t.length>0){let m=Cl(t,{deactivate:`${U(n,"deactivate")} <name> ${o}`,doctor:`${U(n,"doctor")} ${o} --detail deep --trace`});m&&p.push(m);for(let y of Pl)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")} ${o} --fix-managed-state (or ${U(n,"adopt-all")} ${o}, ${U(n,"adopt")} <name> ${o}, or reinstall via ${U(n,"install")} ${o} <source>).`):c>0&&p.push(`Loaded unmanaged extensions are currently treated as informational. Use ${U(n,"manage")} ${o} --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")} ${o} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${U(n,"manage")} ${o} after extension changes.`),p}function Ut(e,t,n,r={}){let o=[...new Set(t)].sort(($,J)=>$.localeCompare(J)),i=n.filter($=>$.managed).length,a=n.filter($=>$.enabled).length,s=n.filter($=>$.active).length,c=n.filter($=>$.update_available===!0).length,d=n.filter($=>$.managed===!1),l=d.filter($=>Oi($)).map($=>$.name).sort(($,J)=>$.localeCompare(J)),p=d.filter($=>!Oi($)).map($=>$.name).sort(($,J)=>$.localeCompare(J)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let $ of n)u[$.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}`]:[],x=[...new Set([...o,...v])].sort(($,J)=>$.localeCompare(J)),S=[...new Set(x.map($=>Li($)))].sort(($,J)=>$.localeCompare(J)),C=Il(x),M=e==="global"?"--global":"--project",G=Rl(e,o,n,r),ce=Nl({normalizedWarnings:o,options:r,scope:e,scopeFlag:M,updateCheckFailedTotal:m,policyWarningCount:C.warning_count,updateHealthPartial:f,skippedUnmanagedTotal:y,skippedNonGithubTotal:w,updateAvailableTotal:c});return{status:x.length===0?"ok":"warn",warning_count:x.length,warning_codes:S,warnings:x,policy_warning_count:C.warning_count,policy_violation_count:C.violation_count,policy_blocked_count:C.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($=>$.name).sort(($,J)=>$.localeCompare(J)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:u,update_check_failed_total:m,top_warnings:x.slice(0,8),remediation:ce,...G?{collision_plan:G}:{}}}function ji(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 Li(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Fi(e){let t=new Set,n=[];for(let r of e){let o=(()=>{let i=ur(r);return i?[i]:mr(r)})();for(let i of o){let a=`${i.layer}:${i.name}:${i.capability}`;t.has(a)||(t.add(a),n.push(i))}}return n}function Mi(){return{version:_t.version,capabilities:[..._t.capabilities],legacy_aliases:{..._t.legacy_aliases}}}function Oi(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Gi(e,t,n,r,o){if(e!=="project"||o)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(r.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 Dl}from"node:crypto";import F from"node:fs/promises";import jl from"node:os";import P 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 Ui=3,Ll=120,zi=250,Fl=12e4,Ml=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Ji=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,qi=e=>Ml.has(String(Ji(e))),zt=(e,t)=>Ji(e)===t,Bi=e=>new Promise(t=>{setTimeout(t,e)}),Wi=async e=>{let t=P.join(e,"package.json");await k(t)||await F.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
43
|
+
`}import bl from"node:fs/promises";import kl 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 jn(e){return kl.join(e,"extension-migrations.json")}function Si(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 Ei(e,t){return`${e.layer}:${e.name}:${t}`}async function xl(e){let t=jn(e);if(!await x(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await bl.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function Sl(e,t){let n=await xl(e),r=new Map(n.entries.map(o=>[o.key,o]));return t.forEach((o,i)=>{let a=Si(o,i),s=r.get(Ei(o,a));s&&(o.definition.status=s.status,s.status==="failed"?o.definition.reason=s.error:(delete o.definition.reason,delete o.definition.error,delete o.definition.message))}),n}async function El(e){let t=await Sl(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),r=[],o=!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=Si(l,p),m=Ei(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"){r.push({key:m,layer:l.layer,extension:l.name,id:u,before:f,outcome:"skipped"});continue}if(e.dryRun===!0){r.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"){r.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,r.push({key:m,layer:l.layer,extension:l.name,id:u,before:f,outcome:"applied"}),o=!0}catch(k){let S=k instanceof Error?k.message:String(k),C={key:m,layer:l.layer,extension:l.name,id:u,status:"failed",attempted_at:v,error:S};n.set(m,C),l.definition.status="failed",l.definition.reason=S,r.push({key:m,layer:l.layer,extension:l.name,id:u,before:f,outcome:"failed",error:S}),o=!0}}if(o){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:jn(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=r.filter(l=>l.outcome==="pending").length,s=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:jn(e.pmRoot),total:r.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function $i(e){let t=await O(e.resolvedRoots.settings_root),n=await be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await ke(n);e.warnings.push(...n.warnings,...r.warnings);let o=await El({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:o,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},o.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 Ai(e,t,n){let r=typeof t=="string"?null:await pt(e),o=r===null?null:e.trim().toLowerCase(),i=o===null?null:await Ko(o),a=Ft(r??e,{forceGithub:typeof t=="string",ref:n}),s=o===null?null:await Zo(e);return{bundledAliasName:o,bundledPackageName:i,installSource:a,sourceResolution:{requested:e,selected:{kind:o===null?a.kind:"builtin",input:o??a.input,...i===null?{}:{package:i}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...o===null?[]:[{kind:"builtin",input:o,...i===null?{}:{package:i},command:`pm install ${o}`}],...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 Te from"node:fs/promises";import re 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 Ln(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function Gt(e,t,n){let r=b(t),o=n.trim();if(r.length===0||o.length===0)return;let i=e.get(r)??new Set;i.add(o),e.set(r,i)}function $l(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)Gt(t,r.name,r.command),Gt(n,r.name,r.action);for(let r of e.commands.handlers)Gt(t,r.name,r.command);for(let r of e.commands.overrides)Gt(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Ii(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Al(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:o,activationFailedNames:i}=e;return t?o.has(n)||i.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function Ut(e,t,n){let r=new Set(t.loaded.map(c=>b(c.name))),o=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=Ii(a.get(d)),p=Ii(s.get(d)),u={...l?{command_paths:l}:{},...p?{action_paths:p}:{}},m=Al({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:o,activationFailedNames:i});return{...c,...m,...u}})}function Il(e){let t=0,n=0,r=0;for(let o of e)if(o.startsWith("extension_policy_")){if(t+=1,o.startsWith("extension_policy_violation_")){n+=1;continue}o.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function U(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Ci=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 Tl(e){return Ci.has(Li(e))}function Ti(e){return e==="project"||e==="global"}function Ri(e){let t=e.split(":"),n=t[0];if(!n||!Ci.has(n))return null;let r=t.at(-4),o=t.at(-3)?.trim(),i=t.at(-2),a=t.at(-1)?.trim();return!Ti(r)||!Ti(i)||!o||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:o},displaced:{layer:i,name:a}}}function Ol(e){let t=new Set;for(let n of e){let r=Ri(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Cl(e,t){let n=e.filter(Tl);if(n.length===0)return null;let r=Ol(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function Rl(e,t,n,r){let o=t.map(p=>Ri(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(o.length===0)return;let i=e==="global"?"--global":"--project",a=U(r,"deactivate"),s=`${U(r,"doctor")} ${i} --detail deep --trace`,c=new Map(n.map(p=>[b(p.name),p])),d=new Map;for(let p of o)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:o.length,extension_count:d.size,next_best_command:s,collisions:o,remediation_candidates:l}}function Pi(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function Ni(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let o=r.trace?.missing_capability??r.trace?.capability;typeof o=="string"&&o.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${o.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function Di(e,t){let n=[];for(let r of br(e.loaded,t))for(let o of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${o}`);return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}var Pl=[{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: ${tr.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 Nl(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:o,updateCheckFailedTotal:i,policyWarningCount:a,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,p=[],u={options:n,scope:r,scopeFlag:o,updateCheckFailedTotal:i,policyWarningCount:a};if(t.length>0){let m=Cl(t,{deactivate:`${U(n,"deactivate")} <name> ${o}`,doctor:`${U(n,"doctor")} ${o} --detail deep --trace`});m&&p.push(m);for(let y of Pl)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")} ${o} --fix-managed-state (or ${U(n,"adopt-all")} ${o}, ${U(n,"adopt")} <name> ${o}, or reinstall via ${U(n,"install")} ${o} <source>).`):c>0&&p.push(`Loaded unmanaged extensions are currently treated as informational. Use ${U(n,"manage")} ${o} --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")} ${o} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${U(n,"manage")} ${o} after extension changes.`),p}function zt(e,t,n,r={}){let o=[...new Set(t)].sort(($,J)=>$.localeCompare(J)),i=n.filter($=>$.managed).length,a=n.filter($=>$.enabled).length,s=n.filter($=>$.active).length,c=n.filter($=>$.update_available===!0).length,d=n.filter($=>$.managed===!1),l=d.filter($=>Oi($)).map($=>$.name).sort(($,J)=>$.localeCompare(J)),p=d.filter($=>!Oi($)).map($=>$.name).sort(($,J)=>$.localeCompare(J)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let $ of n)u[$.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([...o,...v])].sort(($,J)=>$.localeCompare(J)),S=[...new Set(k.map($=>Li($)))].sort(($,J)=>$.localeCompare(J)),C=Il(k),M=e==="global"?"--global":"--project",G=Rl(e,o,n,r),ce=Nl({normalizedWarnings:o,options:r,scope:e,scopeFlag:M,updateCheckFailedTotal:m,policyWarningCount:C.warning_count,updateHealthPartial:f,skippedUnmanagedTotal:y,skippedNonGithubTotal:w,updateAvailableTotal:c});return{status:k.length===0?"ok":"warn",warning_count:k.length,warning_codes:S,warnings:k,policy_warning_count:C.warning_count,policy_violation_count:C.violation_count,policy_blocked_count:C.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($=>$.name).sort(($,J)=>$.localeCompare(J)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:u,update_check_failed_total:m,top_warnings:k.slice(0,8),remediation:ce,...G?{collision_plan:G}:{}}}function ji(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 Li(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Fi(e){let t=new Set,n=[];for(let r of e){let o=(()=>{let i=ur(r);return i?[i]:mr(r)})();for(let i of o){let a=`${i.layer}:${i.name}:${i.capability}`;t.has(a)||(t.add(a),n.push(i))}}return n}function Mi(){return{version:_t.version,capabilities:[..._t.capabilities],legacy_aliases:{..._t.legacy_aliases}}}function Oi(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Gi(e,t,n,r,o){if(e!=="project"||o)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(r.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 Dl}from"node:crypto";import F from"node:fs/promises";import jl from"node:os";import P 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 Ui=3,Ll=120,zi=250,Fl=12e4,Ml=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Ji=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,qi=e=>Ml.has(String(Ji(e))),Jt=(e,t)=>Ji(e)===t,Bi=e=>new Promise(t=>{setTimeout(t,e)}),Wi=async e=>{let t=P.join(e,"package.json");await x(t)||await F.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
45
45
|
`,"utf8")},Hi=async e=>{let t=de(import.meta.url,["../../.."]),n=P.join(e,"node_modules","@unbrained"),r=P.join(n,"pm-cli");await F.mkdir(n,{recursive:!0}),await F.rm(r,{recursive:!0,force:!0}),await F.symlink(t,r,process.platform==="win32"?"junction":"dir")},Fn=async e=>{let t=P.resolve(e),n=P.dirname(t),r=P.parse(n).root,o=await F.realpath(r).catch(()=>r),i=P.relative(r,n),a=i===""?[]:i.split(P.sep);for(let[s,c]of a.entries()){let d=P.join(o,c);try{o=await F.realpath(d)}catch{o=P.join(o,...a.slice(s));break}}return P.join(o,P.basename(t))},Ki=async(e,t,n,r=jl.tmpdir())=>{let o=P.resolve(e),i=await F.realpath(o).catch(()=>o),a=await Fn(t);if(i===a)return;if(!te(i,a)){await n(e,t,{recursive:!0,force:!0});return}let s=u=>{let m=P.resolve(u);if(m!==o&&!te(o,m))return!1;let y=P.resolve(i,P.relative(o,m));if(y===a||te(a,y))return!1;let f=P.relative(i,y).split(P.sep);return f.some(_=>_==="node_modules"||_.startsWith(".pm-extension-install-backup-"))?!1:f[0]!==".agents"},c=await F.realpath(P.resolve(r)).catch(()=>Fn(r)),d=te(i,c)?P.dirname(i):c;if(te(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 F.mkdtemp(P.join(d,"pm-extension-copy-")),p=P.join(l,"extension");try{await n(e,p,{recursive:!0,force:!0,filter:s}),await n(p,t,{recursive:!0,force:!0})}finally{await F.rm(l,{recursive:!0,force:!0})}},Vi=async(e,t,n=F.cp)=>{for(let r=1;r<=Ui;r+=1)try{await F.rm(t,{recursive:!0,force:!0}),await Ki(e,t,n);return}catch(o){if(!qi(o)||r===Ui)throw o;await Bi(zi)}},Mn=async e=>{let t;try{t=await F.readFile(P.join(e,"owner.json"),"utf8")}catch(o){if(!yt(o))throw o;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},Yi=async(e,t)=>await Mn(e)!==t?!1:(await F.rm(e,{recursive:!0,force:!0}),!0),Gl=async(e,t)=>{let n;try{n=await F.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await Mn(e);return r===null?(await F.rm(e,{recursive:!0,force:!0}),!0):Yi(e,r)},Ul=(e,t,n)=>{let r=Promise.resolve(),o=setInterval(()=>{r=r.then(async()=>{if(await Mn(e)!==t)return;let i=new Date;await F.utimes(e,i,i)}).catch(()=>{})},n);return o.unref(),async()=>{clearInterval(o),await r}},zl=async(e,t)=>{await F.mkdir(e);try{await F.writeFile(P.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
46
|
-
`,"utf8")}catch(n){throw await F.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Jl=async(e,t,n,r,o)=>{for(let i=1;i<=n;i+=1)try{return await zl(e,t),!0}catch(a){if(!zt(a,"EEXIST"))throw a;await Gl(e,o)?i-=1:await Bi(r)}return!1},Gn=async(e,t,n,r)=>{let o=P.join(e,"runtime","extension-install-locks"),i=P.join(o,"scope.lock");await F.mkdir(o,{recursive:!0});let{attempts:a=Ll,delay_ms:s=zi,stale_ms:c=Fl,heartbeat_ms:d}=r??{};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:Dl(),created_at:I(),destination:t};if(!await Jl(i,y,l,p,u))throw new h(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let f=Ul(i,y.token,m);try{return await n()}finally{await f(),await Yi(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 Xi=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;o<e.length;){let a=o;o+=1,r[a]=await n(e[a])}});return await Promise.all(i),r};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b17dfc10-9e07-5912-b294-c5663133f192")}catch{}})();function Qi(e,t){let n=b(e),r=t.find(o=>b(o.name)===n);return{command_paths:[...r?.command_paths??[]].sort((o,i)=>o.localeCompare(i)),action_paths:[...r?.action_paths??[]].sort((o,i)=>o.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]="e5a4cea9-ac5d-5bda-9f7c-6cf8cf9e9998")}catch{}})();function Zi(e,t){let n=new Set((t?.loaded??[]).flatMap(i=>(i.activation?.commands?.length??0)>0?[`${i.layer}:${b(i.name)}`]:[])),r=e.services.overrides.filter(i=>i.service==="output_format").filter(i=>i.passThrough!==!0).filter(i=>!n.has(`${i.layer}:${b(i.name)}`)).map(i=>`extension_output_service_override_global:${i.service}:${i.layer}:${i.name}`),o=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([...r,...o])].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 ea=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,r)=>r.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 ql=1e4,Bl=(e,t,n)=>{let r=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),o=r.find(a=>a.ref.endsWith("^{}"))??r[0];if(!o)return{checked_at:n,available:null,error:"no_remote_reference_found"};let i=t?.trim();return i?{checked_at:n,remote_commit:o.commit,available:o.commit!==i}:{checked_at:n,remote_commit:o.commit,available:null,error:"missing_installed_commit"}},ta=async(e,t=Dt)=>{let n=I();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let r=[e.ref?.trim(),"HEAD"].find(Boolean),o=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,ql);return Bl(o,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import Wl from"node:fs/promises";import Hl 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]="5755dee7-d2df-5ced-8a94-aeb51762edb7")}catch{}})();function Kl(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Vl(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function Yl(e){let t=Hl.join(e,"manifest.json"),n;try{n=await Wl.readFile(t,"utf8")}catch(s){if(yt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let o=r,i=gr(o),a=Kl(o);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:i.findings,warnings:i.findings.map(s=>Vl(a,s)),remediation:i.findings.map(s=>s.message)}}function na(e){return Yl(dr(e))}import Le from"node:fs/promises";import Xl 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(zt(t,"ENOENT"))return null;throw t}),ra=async(e,t,n,r,o)=>{let i=ct(e),a=pr(t),[s,c]=await Promise.all([Un(i),Un(a)]);return r&&await Le.cp(n,o,{recursive:!0,force:!0}),{backupDirectory:o,destinationDirectory:n,destinationExists:r,managedStatePath:i,managedStateContents:s,settingsPath:a,settingsContents:c}},oa=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(Xl.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]="8d5ed026-8d61-5083-956c-9281caa0168b")}catch{}})();var Ql=4,ca=[["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"]],Zl=ca.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),ep={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"},tp="__pm_native_output",np=["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"],da=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],rp=["disabled","require_trusted","require_provenance"],la={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:[]},op=e=>{let t=e??la,n={};for(let r of np)n[r]=Z(t[r]??[]);return n},ip=(e,t)=>{for(let n of da)t[n].length>0&&(e[n]=t[n]);return e},ap=(e,t)=>{for(let n of rp)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},sp=e=>{let t={};for(let n of da)t[n]=Z(e[n]??[]);return t},cp=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:ip(ap({name:t},e),sp(e))},dp=e=>(e??[]).map(t=>cp(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),lp=e=>{let t=Object.assign({},la,e??{}),n=op(e),r=dp(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},pa=async(e,t)=>{let n=[t],r=await Vo(t);r&&n.push(r);let o=[...new Set(n.map(i=>b(i)).filter(i=>i.length>0))];for(let i of o){let a=e.find(c=>b(c.name)===i);if(a)return a;let s=e.find(c=>b(c.directory)===i);if(s)return s}},ua=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled));return new Set(Z(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},ma=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled)),o=new Set(Z(e.extensions.disabled)),i=[...r],a=[...o];return o.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},pp=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled)),o=new Set(Z(e.extensions.disabled)),i=[...r],a=[...o];return r.delete(n),o.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},up=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled)),o=new Set(Z(e.extensions.disabled)),i=[...r],a=[...o];return r.delete(n),o.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},mp=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=ca.map(([o,i,a])=>({action:i,flag:a,distance:ir(t,o,n)})).filter(o=>o.distance!==null).sort((o,i)=>o.distance-i.distance)[0];return r?{action:r.action,flag:r.flag}:null},fp=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=mp(e);if(!r)return new h(`One action flag is required. Use one of: ${Zl}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let o=`pm ${n} ${r.flag}`;return ar({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(fa),retry_command:o,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:o,reason:`nearest lifecycle action for "${e}"`}]})},hp=[["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"]],fa={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},gp=e=>fa[e]??null,yp=(e,t)=>{let n=[...new Set(hp.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=gp(e.trim().toLowerCase());if(r)return r;throw fp(e,t)}if(n.length>1)throw new h("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},_p=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"},wp=[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"}}],ha=e=>{for(let t of wp){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},ga=(e,t,n,r)=>{let o=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:o.contributions,managed:!!n,source:o.source,update_available:o.update_available,last_update_check_at:o.last_update_check_at,last_update_remote_commit:o.last_update_remote_commit,update_error:o.update_error,update_check_status:r.status,update_check_reason:r.reason}},vp=(e,t,n,r)=>{let o=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),i=r?ua(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ga({name:o.name,directory:e,version:o.manifest_version,entry:o.manifest_entry,enabled:i},t,r,ha(r))}},bp=async(e,t,n,r,o,i)=>{let a=re.join(e,t),s=re.join(a,"manifest.json"),c=i.get(b(t));if(!await k(s))return vp(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await Te.readFile(s,"utf8").then(m=>JSON.parse(m)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=xn(l);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=o.get(b(p.name))??i.get(b(t));return{summary:ga({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:ua(r,p.name)},n,u,ha(u))}},fe=async(e,t,n,r)=>{if(!await k(e))return{extensions:[],warnings:[]};let i=(await Te.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,p)=>l.localeCompare(p)),a=new Map(r.entries.map(l=>[b(l.name),l])),s=new Map(r.entries.map(l=>[b(l.directory),l])),c=[],d=[];for(let l of i){let p=await bp(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))}},kp=wr(),xp=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Sp=(e,t,n,r)=>{let o=n.command_paths.map(s=>`pm ${s} --help`),i=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...o]:["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:xp(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:o,next_steps:a,...i?{sdk_dependency_status:"missing"}:{}}},Ep=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},ya=e=>e.map(t=>Ep(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),_a=(e,t,n)=>{let r=b(e);return t.find(o=>(n===void 0||o.layer===n)&&b(o.name)===r)},$p=(e,t,n,r)=>n.find(i=>i.scope===t&&b(i.name)===b(e))?.activation_status??(r?"failed":"unknown"),wa=(e,t,n,r,o)=>kp.enqueue(async()=>{let i=process.env.PM_CLI_PACKAGE_ROOT,a=await Te.mkdtemp(re.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=de(import.meta.url,["../.."]);try{let s=await be({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:o.noExtensions===!0,reload_token:Zt(),cache_bust:!0,module_graph_snapshot_root:a}),c=await ke({...s}),d=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...ya(c.failed)],l=Object.fromEntries(s.loaded.map(p=>[b(p.name),hr(Ue(c,{extensionName:p.name}))]));return{installed:Gt(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await Te.rm(a,{recursive:!0,force:!0}),i===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=i}}),Jn=async(e,t,n,r)=>{let o=n.filter(c=>!c.managed),i=[...o].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),a=r,s=[];for(let c of i){let d=re.join(e,c.directory),l=await Ye(d),p=I(),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 De(e,a),{state:a,adopted_entries:s,unmanaged_candidates:i,already_managed_count:n.length-o.length}},Ap=(e,t)=>{let n=D(process.cwd(),t.path),r=wt(n,process.cwd()),o=e==="global"?lr(process.cwd()):n,i=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:o,selected_root:i,roots:r}},Jt=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new h('Options "--gh" and "--github" must match when both are provided.',g.USAGE);return n[0]},Ip=e=>ep[e],Tp=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",o=`${n} ${r}`,i=Ip(e),a=`<${r}>`,s=`pm ${n} ${i} ${a}`;throw new h(`Action "${e}" requires ${o} input.`,g.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},qt=(e,t,n={})=>{let r=e?.trim();if(r)return r;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 Tp(t,n)},Op=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${b(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${b(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,o,i)=>i.indexOf(r)===o).sort((r,o)=>r.localeCompare(o))},Cp=(e,t)=>{let r=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate",message:"--dry-run is only valid with --migrate."}].find(o=>o.triggered&&!o.allowed);if(r)throw new h(r.message,g.USAGE)},Rp=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),o=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:o?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},Pp=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},Np=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:Pp(e),warnings:[...new Set(e.warnings)].sort((o,i)=>o.localeCompare(i)),details:t};return e.action==="doctor"&&Object.defineProperty(r,tp,{value:!0,enumerable:!1,configurable:!1}),r},qn=async(e,t,n)=>{let r=yp(e,t);Cp(r,t);let o=Rp(e,r,t),i=_p(t),a=Ap(i,n),c={action:r,normalizedTarget:o,scope:i,resolvedRoots:a,warnings:[],options:t,global:n},l={...c,withResult:(p,u=!0)=>Np(c,p,u)};return await mu(l)},Dp=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),o=Er(r),i={package:`Install dependencies: cd ${o}, then run "npm install"`,extension:`Install type-check dependencies: cd ${o}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},a={package:`Validate the package: cd ${o}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${o}, 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",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},jp=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:o}=e;if([Jt(r),r.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=qt(n,t,r),c=await _i(s,r.vocabulary??"extension",r.capability,r.declarative===!0);return o({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:Dp(c,r)})},Lp=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:o,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=Zt(),d=await be({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:i.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await ke(d);r.push(...l.warnings);let p={reload:{token:c,cache_bust:!0,watch:o.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 o.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},Fp=async e=>{let{normalizedTarget:t,scope:n,options:r,global:o,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 Yo(n,o,r))},Mp=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Gp=e=>({kind:"local",input:e.input,location:e.absolute_path}),Up=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),zp=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),Jp=(e,t,n,r)=>e?Mp(e,t):n.kind==="local"?Gp(n):n.kind==="npm"?Up(n,r):zp(n,r),qp=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:Jo(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},Bp=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:o}=e,{validated:i,destinationDirectoryName:a}=t,s=await O(r.settings_root),c=await we(r.selected_root);o.push(...c.warnings);let d=re.join(r.selected_root,a),l=await k(d),p=await ai(i.directory,d);await Te.mkdir(r.selected_root,{recursive:!0});let u=await Te.mkdtemp(re.join(r.selected_root,".pm-extension-install-backup-")),m=re.join(u,"destination");try{let y=await ra(r.selected_root,r.settings_root,d,l,m),w=Jp(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),f=c.state.entries.find(S=>b(S.name)===b(i.manifest.name)),_=qp(f,i.manifest.version,w,I()),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}),x=ma(s,i.manifest.name);try{p||await Vi(i.directory,d),await Wi(d),await Hi(d),await De(r.selected_root,v),x&&await Se(r.settings_root,s,"settings:write")}catch(S){try{await oa(y)}catch(C){throw new AggregateError([S,C],`Extension install failed: ${String(S)}; rollback failed: ${String(C)}`,{cause:C})}throw S}return{settings:s,managedState:v,sourceRecord:w,destinationDirectory:d,destinationExists:l,installInPlace:p,activationChanged:x}}finally{await Te.rm(u,{recursive:!0,force:!0}).catch(()=>{})}},Wp=async(e,t,n)=>{let r=n.filter(o=>b(o.name)===b(t)).flatMap(o=>o.types.map(i=>({name:i.name,folder:i.folder})));return e.scope==="project"&&r.length>0&&await it(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},Hp=(e,t,n,r,o)=>{let i=_a(t,n.activation_failures,e.scope),a=$p(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:r.command_paths,registered_actions:r.action_paths,registered_item_types:o,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},Kp=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:o,global:i,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,d=await Bp(e,t),l=await fe(r.selected_root,n,d.settings,d.managedState);o.push(...l.warnings);let p=await wa(r.pm_root,re.dirname(r.selected_root),d.settings,l.extensions,i);o.push(...p.warnings);let u=await Wp(e,s.manifest.name,p.item_type_registrations),m=Qi(s.manifest.name,p.installed),y=Hp(e,s.manifest.name,p,m,u),w=p.contribution_inventories[b(s.manifest.name)];return w&&(d.managedState=await qo(r.selected_root,d.managedState,s.manifest.name,w)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,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:Sp(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)},Vp=async e=>{let{options:t,global:n,warnings:r,withResult:o}=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=re.resolve(d),p=a.get(l);p===void 0&&(p=await qn(c,{...t,install:!0},n),a.set(l,p)),i.push({alias:c,result:p})}r.push(...i.flatMap(c=>c.result.warnings));let s=i.every(c=>c.result.ok);return o({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)},Yp=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:o,bundledPackageName:i,installSource:a,sourceResolution:s}=await Ai(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:${o}:npm:${d.package}`)}let c=await ii(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 Gn(r.settings_root,l,()=>Kp(e,{validated:d,destinationDirectoryName:l,bundledAliasName:o,bundledPackageName:i,sourceResolution:s,installSource:a,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},Xp=async e=>{let t=Jt(e.options),n=t??qt(e.normalizedTarget,e.action,e.options);return[t===void 0,Wo(n)].every(Boolean)?Vp(e):Yp(e,n,t)},Qp=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:o,options:i,withResult:a}=e;if(t!==void 0)throw new h('Action "adopt-all" does not accept a target argument.',g.USAGE);if(Jt(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(r.settings_root),d=await we(r.selected_root);o.push(...d.warnings);let l=await fe(r.selected_root,n,c,d.state);o.push(...l.warnings);let p=await Jn(r.selected_root,n,l.extensions,d.state),u=await fe(r.selected_root,n,c,p.state);o.push(...u.warnings);let m=Ut(n,o,u.extensions,i);o.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),x=y.get(`${b(_.name)}:${v}`)??w.get(v);return{..._,...va(x)}});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})},va=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Zp=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let o=Lt(e,{forceGithub:!0,ref:r});if(o.kind!=="github")throw new h(`Invalid GitHub shorthand "${e}".`,g.USAGE);return{kind:"github",input:o.input,location:o.subpath??".",repository:o.repository,owner:o.owner,repo:o.repo,ref:o.ref,subpath:o.subpath}},eu=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:o,warnings:i,options:a,withResult:s}=e,c=qt(n,t,a),d=Jt(a),l=await O(o.settings_root),p=await we(o.selected_root);i.push(...p.warnings);let u=await fe(o.selected_root,r,l,p.state);i.push(...u.warnings);let m=await pa(u.extensions,c);if(!m)throw new h(`Installed extension "${c}" was not found in ${r} scope.`,g.NOT_FOUND);if(m.managed)return s({adopted:!1,already_managed:!0,extension:{name:m.name,directory:m.directory}});let y=re.join(o.selected_root,m.directory),w=await Ye(y),f=I(),_=Zp(d,c,y,a.ref),v=lt(p.state,{name:w.manifest.name,directory:m.directory,scope:r,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 De(o.selected_root,v);let x=await fe(o.selected_root,r,l,v);i.push(...x.warnings);let S=x.extensions.find(C=>b(C.name)===b(w.manifest.name))??x.extensions.find(C=>b(C.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:_,...va(S)})},ba=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:o,warnings:i,options:a}=e,s=qt(n,t,a),c=await O(o.settings_root),d=await we(o.selected_root);i.push(...d.warnings);let l=await fe(o.selected_root,r,c,d.state);i.push(...l.warnings);let p=await pa(l.extensions,s);if(!p)throw new h(`Installed extension "${s}" was not found in ${r} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:p}},tu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:o,candidate:i}=await ba(e),a=re.join(t.selected_root,i.directory);await Te.rm(a,{recursive:!0,force:!0});let s={...o.state,updated_at:I(),entries:o.state.entries.filter(d=>b(d.name)!==b(i.name)&&b(d.directory)!==b(i.directory))};await De(t.selected_root,s);let c=up(r,i.name);return c&&await Se(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:i.name,directory:i.directory},destination_path:a,settings_changed:c})},ia=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:o,withResult:i}=e,{settings:a,candidate:s}=await ba(e),c=t==="activate"?ma(a,s.name):pp(a,s.name);c&&await Se(n.settings_root,a,"settings:write");let d=t==="activate"?await wa(n.pm_root,re.dirname(n.selected_root),a,[s],o).then(l=>(r.push(...l.warnings),_a(s.name,l.activation_failures,e.scope))):void 0;return d&&r.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)},nu=(e,t,n,r,o,i)=>{let a=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=o?.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))]},zn=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),ru=(e,t,n,r)=>{if(e!=="project"||t||!zn(r))return null;let o=n==="package"?"package":"extension";return`Global ${o} registrations are included in project diagnostics. For hermetic ${o} smoke tests, rerun pm ${o} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},ou=(e,t,n)=>{if(String(e??"").trim().length>0)throw new h('Action "doctor" does not accept a target argument.',g.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new h("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",g.USAGE);let o=ji(n.detail),i=n.trace===!0;if([i,o!=="deep"].every(Boolean))throw new h("--trace requires --detail deep with --doctor.",g.USAGE);return{isolated:r,detailMode:o,includeTrace:i}},iu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await Jn(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},au=(e,t,n,r)=>{let o=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:zn(r),rerun_command:null,pm_global_path_recipe:null};let i=`pm ${o} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:zn(r),rerun_command:t?null:i,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${o} doctor --project --detail deep --trace`}},su=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:o,options:i,global:a,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=ou(t,n,i),p=await O(r.settings_root),u=await we(r.selected_root);o.push(...u.warnings);let m=await fe(r.selected_root,n,p,u.state);o.push(...m.warnings);let{state:y,fix:w}=await iu(e,m.extensions,u.state),f=await fe(r.selected_root,n,p,y);o.push(...f.warnings);let _=await be({pmRoot:r.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await ke({..._,loaded:_.loaded}),x=await na(r.pm_root);o.push(...x.warnings,..._.warnings),o.push(...Pi(_.failed)),o.push(...v.warnings),o.push(...Ni(v.failed)),o.push(...Di(_,v)),o.push(...Zi(v,_)),o.push(...Op(_,v)),o.push(...ea(v));let S=Gt(f.extensions,_,v),C=Gi(n,S,_.loaded.map(T=>({layer:T.layer,name:T.name})),_.failed.map(T=>({name:T.name})),_.disabled_by_flag);o.push(...C.warnings);let M=S.filter(T=>T.update_check_status==="failed").map(T=>`extension_update_check_failed:${T.name}`);o.push(...M);let G=Ut(n,o,S,i);o.push(...G.warnings);let ce=[...G.warnings],$={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},J=Fi(ce),Wt=Mi(),Zn=G.warning_codes,ns=ru(n,c,i.vocabulary,_),rs=nu(G.remediation,_.failed.length,v.failed.length,i.vocabulary,w,ns),er=au(n,c,i.vocabulary,_),os={status:G.status,scope:n,warning_count:G.warning_count,warning_codes:Zn,total_extensions:S.length,managed_total:S.filter(T=>T.managed).length,enabled_total:S.filter(T=>T.enabled).length,active_total:S.filter(T=>T.active).length,unmanaged_loaded_extension_count:G.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:G.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:G.unmanaged_expected_extension_count,runtime_active_total:S.filter(T=>T.runtime_active===!0).length,activation_status_totals:{ok:S.filter(T=>T.activation_status==="ok").length,failed:S.filter(T=>T.activation_status==="failed").length,not_loaded:S.filter(T=>T.activation_status==="not_loaded").length,unknown:S.filter(T=>T.activation_status==="unknown").length},unknown_capability_count:J.length,capability_contract_version:Wt.version,update_available_total:S.filter(T=>T.update_available===!0).length,update_health_coverage:G.update_health_coverage,update_health_partial:G.update_health_partial,update_check_failed_total:S.filter(T=>T.update_check_status==="failed").length,load_failure_count:_.failed.length,activation_failure_count:v.failed.length,load_failures:Ln(_.failed),activation_failures:Ln(v.failed),blocking_failure_count:_.failed.length+v.failed.length,has_blocking_failures:_.failed.length+v.failed.length>0,consistency_warning_count:C.warnings.length,trace_enabled:l,isolation:er,policy:$,remediation:rs},is=w?{requested:!0,applied:w.adopted_entries.length>0,adopted_count:w.adopted_entries.length,already_managed_count:w.already_managed_count,adopted_extensions:w.adopted_entries.map(T=>T.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:f.extensions.filter(T=>T.managed).length,adopted_extensions:[]},Ht={mode:d,summary:os,triage:G,trace_enabled:l,capability_contract:Wt,capability_guidance:J,managed_state_fix:is,author_manifest:x,isolation:er,policy:_.policy};if(d==="deep"){let T=l?v.failed:v.failed.map(N=>{let{trace:Yu,...as}=N;return as});Ht.deep={warnings:ce,warning_codes:Zn,capability_contract:Wt,capability_guidance:J,trace_enabled:l,managed_state:{path:u.path,count:y.entries.length,entries:y.entries},installed_extensions:S,load:{roots:_.roots,policy:_.policy,warnings:_.warnings,failed:_.failed,loaded:_.loaded.map(N=>({layer:N.layer,directory:N.directory,name:N.name,version:N.version,entry:N.entry,priority:N.priority}))},activation:{failed:T,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:C.summary},l&&(Ht.deep.trace={activation_failures:v.failed.filter(N=>N.trace!==void 0).map(N=>({layer:N.layer,name:N.name,entry_path:N.entry_path,error:N.error,method:N.trace.method,command:N.trace.command,capability:N.trace.capability,missing_capability:N.trace.missing_capability,registration_index:N.trace.registration_index,expected_schema:N.trace.expected_schema,hint:N.trace.hint,received:N.trace.received}))})}return s(Ht)},cu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:o,options:i,global:a,withResult:s}=e,c=await O(r.settings_root),d=await be({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),l=await ke(d);o.push(...d.warnings),o.push(...l.warnings);let p=xi(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})},du=async(e,t,n)=>{let r=n,o=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(o=await Jn(e.resolvedRoots.selected_root,e.scope,t,n),r=o.state),e.action==="manage"){let i=await Xi(r.entries,Ql,async a=>{if(a.source.kind!=="github")return a;let s=await ta(a.source);return{...a,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});r={...r,updated_at:I(),entries:dt(i)},await De(e.resolvedRoots.selected_root,r)}return{state:r,fix:o}},lu=async(e,t,n)=>{let r=await be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),o=await ke({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...o.warnings),{installed:Gt(n,r,o),failures:ya(o.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:o.failed.length,warning_count:[...new Set([...r.warnings,...o.warnings])].length,policy:r.policy}}},pu=(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},aa=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:o,options:i,withResult:a}=e,s=await O(r.settings_root),c=lp(s.extensions.policy),d=await we(r.selected_root);o.push(...d.warnings);let l=await fe(r.selected_root,n,s,d.state);o.push(...l.warnings);let{state:p,fix:u}=await du(e,l.extensions,d.state),m=await fe(r.selected_root,n,s,p);if(o.push(...m.warnings),t==="manage"){let v=m.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);o.push(...v)}let y=await lu(e,s,m.extensions),w=y.installed,f=Ut(n,o,w,i);o.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=pu(u,w)),a(_)},sa={init:jp,install:Xp,uninstall:tu,explore:aa,manage:aa,describe:cu,reload:Lp,doctor:su,catalog:Fp,adopt:eu,"adopt-all":Qp,activate:ia,deactivate:ia,migrate:$i},uu=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),mu=e=>uu(e)?Gn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>sa[e.action](e)):sa[e.action](e);import Hn from"node:fs/promises";import z from"node:path";import ka from"node:readline/promises";import{stdin as xa,stdout as ft}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]="e404796d-439b-5f4c-9330-5b12ff41d7b2")}catch{}})();var Sa=["ask","add","skip","status"],fu=["AGENTS.md","CLAUDE.md"],hu=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],gu=8,Kn=1,yu="<!-- pm-cli:agent-guidance:start:",_u=`<!-- pm-cli:agent-guidance:start:v${Kn} -->`,Bn="<!-- pm-cli:agent-guidance:end -->",gt="Add workflow guidance later: pm init --agent-guidance add",f_={toPortableRelativePath:Xe,ensureTrailingNewline:Wn,detectLineEnding:$a,findGuidanceBlockRange:Vn,buildAgentGuidanceBlock:Aa,upsertAgentGuidanceBlock:Ia,resolveProjectRoot:Ta,resolveTargetGuidancePath:Oa,parsePromptChoice:Ca,pushUnique:Qe,promptForGuidanceWrite:Ra,normalizeAgentGuidanceState:Yn,applyAgentGuidanceState:Na,writeGuidanceFile:Da,setAgentGuidanceReadlineFactoryForTests:wu},Ea=()=>ka.createInterface({input:xa,output:ft});function wu(e){Ea=e??(()=>ka.createInterface({input:xa,output:ft}))}function Xe(e,t){let n=z.relative(e,t);return n.length===0?z.basename(t):n.split(z.sep).join("/")}function Wn(e){return e.endsWith(`
|
|
46
|
+
`,"utf8")}catch(n){throw await F.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Jl=async(e,t,n,r,o)=>{for(let i=1;i<=n;i+=1)try{return await zl(e,t),!0}catch(a){if(!Jt(a,"EEXIST"))throw a;await Gl(e,o)?i-=1:await Bi(r)}return!1},Gn=async(e,t,n,r)=>{let o=P.join(e,"runtime","extension-install-locks"),i=P.join(o,"scope.lock");await F.mkdir(o,{recursive:!0});let{attempts:a=Ll,delay_ms:s=zi,stale_ms:c=Fl,heartbeat_ms:d}=r??{};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:Dl(),created_at:I(),destination:t};if(!await Jl(i,y,l,p,u))throw new h(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let f=Ul(i,y.token,m);try{return await n()}finally{await f(),await Yi(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 Xi=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;o<e.length;){let a=o;o+=1,r[a]=await n(e[a])}});return await Promise.all(i),r};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b17dfc10-9e07-5912-b294-c5663133f192")}catch{}})();function Qi(e,t){let n=b(e),r=t.find(o=>b(o.name)===n);return{command_paths:[...r?.command_paths??[]].sort((o,i)=>o.localeCompare(i)),action_paths:[...r?.action_paths??[]].sort((o,i)=>o.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]="e5a4cea9-ac5d-5bda-9f7c-6cf8cf9e9998")}catch{}})();function Zi(e,t){let n=new Set((t?.loaded??[]).flatMap(i=>(i.activation?.commands?.length??0)>0?[`${i.layer}:${b(i.name)}`]:[])),r=e.services.overrides.filter(i=>i.service==="output_format").filter(i=>i.passThrough!==!0).filter(i=>!n.has(`${i.layer}:${b(i.name)}`)).map(i=>`extension_output_service_override_global:${i.service}:${i.layer}:${i.name}`),o=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([...r,...o])].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 ea=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=St(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));(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 ql=1e4,Bl=(e,t,n)=>{let r=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),o=r.find(a=>a.ref.endsWith("^{}"))??r[0];if(!o)return{checked_at:n,available:null,error:"no_remote_reference_found"};let i=t?.trim();return i?{checked_at:n,remote_commit:o.commit,available:o.commit!==i}:{checked_at:n,remote_commit:o.commit,available:null,error:"missing_installed_commit"}},ta=async(e,t=jt)=>{let n=I();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let r=[e.ref?.trim(),"HEAD"].find(Boolean),o=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,ql);return Bl(o,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import Wl from"node:fs/promises";import Hl 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]="5755dee7-d2df-5ced-8a94-aeb51762edb7")}catch{}})();function Kl(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Vl(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function Yl(e){let t=Hl.join(e,"manifest.json"),n;try{n=await Wl.readFile(t,"utf8")}catch(s){if(yt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let o=r,i=gr(o),a=Kl(o);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:i.findings,warnings:i.findings.map(s=>Vl(a,s)),remediation:i.findings.map(s=>s.message)}}function na(e){return Yl(dr(e))}import Fe from"node:fs/promises";import Xl 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=>Fe.readFile(e).catch(t=>{if(Jt(t,"ENOENT"))return null;throw t}),ra=async(e,t,n,r,o)=>{let i=ct(e),a=pr(t),[s,c]=await Promise.all([Un(i),Un(a)]);return r&&await Fe.cp(n,o,{recursive:!0,force:!0}),{backupDirectory:o,destinationDirectory:n,destinationExists:r,managedStatePath:i,managedStateContents:s,settingsPath:a,settingsContents:c}},oa=async e=>{await Fe.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Fe.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 Fe.rm(t,{force:!0}):(await Fe.mkdir(Xl.dirname(t),{recursive:!0}),await Fe.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]="8d5ed026-8d61-5083-956c-9281caa0168b")}catch{}})();var Ql=4,ca=[["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"]],Zl=ca.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),ep={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"},tp="__pm_native_output",np=["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"],da=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],rp=["disabled","require_trusted","require_provenance"],la={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:[]},op=e=>{let t=e??la,n={};for(let r of np)n[r]=Z(t[r]??[]);return n},ip=(e,t)=>{for(let n of da)t[n].length>0&&(e[n]=t[n]);return e},ap=(e,t)=>{for(let n of rp)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},sp=e=>{let t={};for(let n of da)t[n]=Z(e[n]??[]);return t},cp=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:ip(ap({name:t},e),sp(e))},dp=e=>(e??[]).map(t=>cp(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),lp=e=>{let t=Object.assign({},la,e??{}),n=op(e),r=dp(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},pa=async(e,t)=>{let n=[t],r=await Vo(t);r&&n.push(r);let o=[...new Set(n.map(i=>b(i)).filter(i=>i.length>0))];for(let i of o){let a=e.find(c=>b(c.name)===i);if(a)return a;let s=e.find(c=>b(c.directory)===i);if(s)return s}},ua=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled));return new Set(Z(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},ma=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled)),o=new Set(Z(e.extensions.disabled)),i=[...r],a=[...o];return o.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},pp=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled)),o=new Set(Z(e.extensions.disabled)),i=[...r],a=[...o];return r.delete(n),o.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},up=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled)),o=new Set(Z(e.extensions.disabled)),i=[...r],a=[...o];return r.delete(n),o.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},mp=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=ca.map(([o,i,a])=>({action:i,flag:a,distance:ir(t,o,n)})).filter(o=>o.distance!==null).sort((o,i)=>o.distance-i.distance)[0];return r?{action:r.action,flag:r.flag}:null},fp=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=mp(e);if(!r)return new h(`One action flag is required. Use one of: ${Zl}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let o=`pm ${n} ${r.flag}`;return ar({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(fa),retry_command:o,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:o,reason:`nearest lifecycle action for "${e}"`}]})},hp=[["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"]],fa={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},gp=e=>fa[e]??null,yp=(e,t)=>{let n=[...new Set(hp.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=gp(e.trim().toLowerCase());if(r)return r;throw fp(e,t)}if(n.length>1)throw new h("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},_p=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"},wp=[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"}}],ha=e=>{for(let t of wp){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},ga=(e,t,n,r)=>{let o=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:o.contributions,managed:!!n,source:o.source,update_available:o.update_available,last_update_check_at:o.last_update_check_at,last_update_remote_commit:o.last_update_remote_commit,update_error:o.update_error,update_check_status:r.status,update_check_reason:r.reason}},vp=(e,t,n,r)=>{let o=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),i=r?ua(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ga({name:o.name,directory:e,version:o.manifest_version,entry:o.manifest_entry,enabled:i},t,r,ha(r))}},bp=async(e,t,n,r,o,i)=>{let a=re.join(e,t),s=re.join(a,"manifest.json"),c=i.get(b(t));if(!await x(s))return vp(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await Te.readFile(s,"utf8").then(m=>JSON.parse(m)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=xn(l);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=o.get(b(p.name))??i.get(b(t));return{summary:ga({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:ua(r,p.name)},n,u,ha(u))}},fe=async(e,t,n,r)=>{if(!await x(e))return{extensions:[],warnings:[]};let i=(await Te.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,p)=>l.localeCompare(p)),a=new Map(r.entries.map(l=>[b(l.name),l])),s=new Map(r.entries.map(l=>[b(l.directory),l])),c=[],d=[];for(let l of i){let p=await bp(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))}},kp=wr(),xp=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Sp=(e,t,n,r)=>{let o=n.command_paths.map(s=>`pm ${s} --help`),i=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...o]:["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:xp(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:o,next_steps:a,...i?{sdk_dependency_status:"missing"}:{}}},Ep=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},ya=e=>e.map(t=>Ep(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),_a=(e,t,n)=>{let r=b(e);return t.find(o=>(n===void 0||o.layer===n)&&b(o.name)===r)},$p=(e,t,n,r)=>n.find(i=>i.scope===t&&b(i.name)===b(e))?.activation_status??(r?"failed":"unknown"),wa=(e,t,n,r,o)=>kp.enqueue(async()=>{let i=process.env.PM_CLI_PACKAGE_ROOT,a=await Te.mkdtemp(re.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=de(import.meta.url,["../.."]);try{let s=await be({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:o.noExtensions===!0,reload_token:Zt(),cache_bust:!0,module_graph_snapshot_root:a}),c=await ke({...s}),d=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...ya(c.failed)],l=Object.fromEntries(s.loaded.map(p=>[b(p.name),hr(ze(c,{extensionName:p.name}))]));return{installed:Ut(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await Te.rm(a,{recursive:!0,force:!0}),i===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=i}}),Jn=async(e,t,n,r)=>{let o=n.filter(c=>!c.managed),i=[...o].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),a=r,s=[];for(let c of i){let d=re.join(e,c.directory),l=await Xe(d),p=I(),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-o.length}},Ap=(e,t)=>{let n=D(process.cwd(),t.path),r=vt(n,process.cwd()),o=e==="global"?lr(process.cwd()):n,i=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:o,selected_root:i,roots:r}},qt=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new h('Options "--gh" and "--github" must match when both are provided.',g.USAGE);return n[0]},Ip=e=>ep[e],Tp=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",o=`${n} ${r}`,i=Ip(e),a=`<${r}>`,s=`pm ${n} ${i} ${a}`;throw new h(`Action "${e}" requires ${o} input.`,g.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},Bt=(e,t,n={})=>{let r=e?.trim();if(r)return r;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 Tp(t,n)},Op=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${b(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${b(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,o,i)=>i.indexOf(r)===o).sort((r,o)=>r.localeCompare(o))},Cp=(e,t)=>{let r=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate",message:"--dry-run is only valid with --migrate."}].find(o=>o.triggered&&!o.allowed);if(r)throw new h(r.message,g.USAGE)},Rp=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),o=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:o?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},Pp=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},Np=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:Pp(e),warnings:[...new Set(e.warnings)].sort((o,i)=>o.localeCompare(i)),details:t};return e.action==="doctor"&&Object.defineProperty(r,tp,{value:!0,enumerable:!1,configurable:!1}),r},qn=async(e,t,n)=>{let r=yp(e,t);Cp(r,t);let o=Rp(e,r,t),i=_p(t),a=Ap(i,n),c={action:r,normalizedTarget:o,scope:i,resolvedRoots:a,warnings:[],options:t,global:n},l={...c,withResult:(p,u=!0)=>Np(c,p,u)};return await mu(l)},Dp=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),o=Er(r),i={package:`Install dependencies: cd ${o}, then run "npm install"`,extension:`Install type-check dependencies: cd ${o}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},a={package:`Validate the package: cd ${o}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${o}, 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",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},jp=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:o}=e;if([qt(r),r.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=Bt(n,t,r),c=await _i(s,r.vocabulary??"extension",r.capability,r.declarative===!0);return o({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:Dp(c,r)})},Lp=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:o,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=Zt(),d=await be({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:i.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await ke(d);r.push(...l.warnings);let p={reload:{token:c,cache_bust:!0,watch:o.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 o.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},Fp=async e=>{let{normalizedTarget:t,scope:n,options:r,global:o,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 Yo(n,o,r))},Mp=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Gp=e=>({kind:"local",input:e.input,location:e.absolute_path}),Up=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),zp=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),Jp=(e,t,n,r)=>e?Mp(e,t):n.kind==="local"?Gp(n):n.kind==="npm"?Up(n,r):zp(n,r),qp=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:Jo(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},Bp=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:o}=e,{validated:i,destinationDirectoryName:a}=t,s=await O(r.settings_root),c=await we(r.selected_root);o.push(...c.warnings);let d=re.join(r.selected_root,a),l=await x(d),p=await ai(i.directory,d);await Te.mkdir(r.selected_root,{recursive:!0});let u=await Te.mkdtemp(re.join(r.selected_root,".pm-extension-install-backup-")),m=re.join(u,"destination");try{let y=await ra(r.selected_root,r.settings_root,d,l,m),w=Jp(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),f=c.state.entries.find(S=>b(S.name)===b(i.manifest.name)),_=qp(f,i.manifest.version,w,I()),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=ma(s,i.manifest.name);try{p||await Vi(i.directory,d),await Wi(d),await Hi(d),await je(r.selected_root,v),k&&await Se(r.settings_root,s,"settings:write")}catch(S){try{await oa(y)}catch(C){throw new AggregateError([S,C],`Extension install failed: ${String(S)}; rollback failed: ${String(C)}`,{cause:C})}throw S}return{settings:s,managedState:v,sourceRecord:w,destinationDirectory:d,destinationExists:l,installInPlace:p,activationChanged:k}}finally{await Te.rm(u,{recursive:!0,force:!0}).catch(()=>{})}},Wp=async(e,t,n)=>{let r=n.filter(o=>b(o.name)===b(t)).flatMap(o=>o.types.map(i=>({name:i.name,folder:i.folder})));return e.scope==="project"&&r.length>0&&await it(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},Hp=(e,t,n,r,o)=>{let i=_a(t,n.activation_failures,e.scope),a=$p(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:r.command_paths,registered_actions:r.action_paths,registered_item_types:o,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},Kp=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:o,global:i,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,d=await Bp(e,t),l=await fe(r.selected_root,n,d.settings,d.managedState);o.push(...l.warnings);let p=await wa(r.pm_root,re.dirname(r.selected_root),d.settings,l.extensions,i);o.push(...p.warnings);let u=await Wp(e,s.manifest.name,p.item_type_registrations),m=Qi(s.manifest.name,p.installed),y=Hp(e,s.manifest.name,p,m,u),w=p.contribution_inventories[b(s.manifest.name)];return w&&(d.managedState=await qo(r.selected_root,d.managedState,s.manifest.name,w)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,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:Sp(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)},Vp=async e=>{let{options:t,global:n,warnings:r,withResult:o}=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 Dt()){let d=await pt(c),l=re.resolve(d),p=a.get(l);p===void 0&&(p=await qn(c,{...t,install:!0},n),a.set(l,p)),i.push({alias:c,result:p})}r.push(...i.flatMap(c=>c.result.warnings));let s=i.every(c=>c.result.ok);return o({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)},Yp=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:o,bundledPackageName:i,installSource:a,sourceResolution:s}=await Ai(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:${o}:npm:${d.package}`)}let c=await ii(a);try{let d=await Xe(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),l=Pt(d.manifest.name);return await Gn(r.settings_root,l,()=>Kp(e,{validated:d,destinationDirectoryName:l,bundledAliasName:o,bundledPackageName:i,sourceResolution:s,installSource:a,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},Xp=async e=>{let t=qt(e.options),n=t??Bt(e.normalizedTarget,e.action,e.options);return[t===void 0,Wo(n)].every(Boolean)?Vp(e):Yp(e,n,t)},Qp=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:o,options:i,withResult:a}=e;if(t!==void 0)throw new h('Action "adopt-all" does not accept a target argument.',g.USAGE);if(qt(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(r.settings_root),d=await we(r.selected_root);o.push(...d.warnings);let l=await fe(r.selected_root,n,c,d.state);o.push(...l.warnings);let p=await Jn(r.selected_root,n,l.extensions,d.state),u=await fe(r.selected_root,n,c,p.state);o.push(...u.warnings);let m=zt(n,o,u.extensions,i);o.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{..._,...va(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})},va=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Zp=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let o=Ft(e,{forceGithub:!0,ref:r});if(o.kind!=="github")throw new h(`Invalid GitHub shorthand "${e}".`,g.USAGE);return{kind:"github",input:o.input,location:o.subpath??".",repository:o.repository,owner:o.owner,repo:o.repo,ref:o.ref,subpath:o.subpath}},eu=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:o,warnings:i,options:a,withResult:s}=e,c=Bt(n,t,a),d=qt(a),l=await O(o.settings_root),p=await we(o.selected_root);i.push(...p.warnings);let u=await fe(o.selected_root,r,l,p.state);i.push(...u.warnings);let m=await pa(u.extensions,c);if(!m)throw new h(`Installed extension "${c}" was not found in ${r} scope.`,g.NOT_FOUND);if(m.managed)return s({adopted:!1,already_managed:!0,extension:{name:m.name,directory:m.directory}});let y=re.join(o.selected_root,m.directory),w=await Xe(y),f=I(),_=Zp(d,c,y,a.ref),v=lt(p.state,{name:w.manifest.name,directory:m.directory,scope:r,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(o.selected_root,v);let k=await fe(o.selected_root,r,l,v);i.push(...k.warnings);let S=k.extensions.find(C=>b(C.name)===b(w.manifest.name))??k.extensions.find(C=>b(C.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:_,...va(S)})},ba=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:o,warnings:i,options:a}=e,s=Bt(n,t,a),c=await O(o.settings_root),d=await we(o.selected_root);i.push(...d.warnings);let l=await fe(o.selected_root,r,c,d.state);i.push(...l.warnings);let p=await pa(l.extensions,s);if(!p)throw new h(`Installed extension "${s}" was not found in ${r} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:p}},tu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:o,candidate:i}=await ba(e),a=re.join(t.selected_root,i.directory);await Te.rm(a,{recursive:!0,force:!0});let s={...o.state,updated_at:I(),entries:o.state.entries.filter(d=>b(d.name)!==b(i.name)&&b(d.directory)!==b(i.directory))};await je(t.selected_root,s);let c=up(r,i.name);return c&&await Se(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:i.name,directory:i.directory},destination_path:a,settings_changed:c})},ia=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:o,withResult:i}=e,{settings:a,candidate:s}=await ba(e),c=t==="activate"?ma(a,s.name):pp(a,s.name);c&&await Se(n.settings_root,a,"settings:write");let d=t==="activate"?await wa(n.pm_root,re.dirname(n.selected_root),a,[s],o).then(l=>(r.push(...l.warnings),_a(s.name,l.activation_failures,e.scope))):void 0;return d&&r.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)},nu=(e,t,n,r,o,i)=>{let a=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=o?.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))]},zn=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),ru=(e,t,n,r)=>{if(e!=="project"||t||!zn(r))return null;let o=n==="package"?"package":"extension";return`Global ${o} registrations are included in project diagnostics. For hermetic ${o} smoke tests, rerun pm ${o} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},ou=(e,t,n)=>{if(String(e??"").trim().length>0)throw new h('Action "doctor" does not accept a target argument.',g.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new h("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",g.USAGE);let o=ji(n.detail),i=n.trace===!0;if([i,o!=="deep"].every(Boolean))throw new h("--trace requires --detail deep with --doctor.",g.USAGE);return{isolated:r,detailMode:o,includeTrace:i}},iu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await Jn(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},au=(e,t,n,r)=>{let o=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:zn(r),rerun_command:null,pm_global_path_recipe:null};let i=`pm ${o} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:zn(r),rerun_command:t?null:i,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${o} doctor --project --detail deep --trace`}},su=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:o,options:i,global:a,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=ou(t,n,i),p=await O(r.settings_root),u=await we(r.selected_root);o.push(...u.warnings);let m=await fe(r.selected_root,n,p,u.state);o.push(...m.warnings);let{state:y,fix:w}=await iu(e,m.extensions,u.state),f=await fe(r.selected_root,n,p,y);o.push(...f.warnings);let _=await be({pmRoot:r.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await ke({..._,loaded:_.loaded}),k=await na(r.pm_root);o.push(...k.warnings,..._.warnings),o.push(...Pi(_.failed)),o.push(...v.warnings),o.push(...Ni(v.failed)),o.push(...Di(_,v)),o.push(...Zi(v,_)),o.push(...Op(_,v)),o.push(...ea(v));let S=Ut(f.extensions,_,v),C=Gi(n,S,_.loaded.map(T=>({layer:T.layer,name:T.name})),_.failed.map(T=>({name:T.name})),_.disabled_by_flag);o.push(...C.warnings);let M=S.filter(T=>T.update_check_status==="failed").map(T=>`extension_update_check_failed:${T.name}`);o.push(...M);let G=zt(n,o,S,i);o.push(...G.warnings);let ce=[...G.warnings],$={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},J=Fi(ce),Ht=Mi(),Zn=G.warning_codes,ns=ru(n,c,i.vocabulary,_),rs=nu(G.remediation,_.failed.length,v.failed.length,i.vocabulary,w,ns),er=au(n,c,i.vocabulary,_),os={status:G.status,scope:n,warning_count:G.warning_count,warning_codes:Zn,total_extensions:S.length,managed_total:S.filter(T=>T.managed).length,enabled_total:S.filter(T=>T.enabled).length,active_total:S.filter(T=>T.active).length,unmanaged_loaded_extension_count:G.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:G.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:G.unmanaged_expected_extension_count,runtime_active_total:S.filter(T=>T.runtime_active===!0).length,activation_status_totals:{ok:S.filter(T=>T.activation_status==="ok").length,failed:S.filter(T=>T.activation_status==="failed").length,not_loaded:S.filter(T=>T.activation_status==="not_loaded").length,unknown:S.filter(T=>T.activation_status==="unknown").length},unknown_capability_count:J.length,capability_contract_version:Ht.version,update_available_total:S.filter(T=>T.update_available===!0).length,update_health_coverage:G.update_health_coverage,update_health_partial:G.update_health_partial,update_check_failed_total:S.filter(T=>T.update_check_status==="failed").length,load_failure_count:_.failed.length,activation_failure_count:v.failed.length,load_failures:Ln(_.failed),activation_failures:Ln(v.failed),blocking_failure_count:_.failed.length+v.failed.length,has_blocking_failures:_.failed.length+v.failed.length>0,consistency_warning_count:C.warnings.length,trace_enabled:l,isolation:er,policy:$,remediation:rs},is=w?{requested:!0,applied:w.adopted_entries.length>0,adopted_count:w.adopted_entries.length,already_managed_count:w.already_managed_count,adopted_extensions:w.adopted_entries.map(T=>T.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:f.extensions.filter(T=>T.managed).length,adopted_extensions:[]},Kt={mode:d,summary:os,triage:G,trace_enabled:l,capability_contract:Ht,capability_guidance:J,managed_state_fix:is,author_manifest:k,isolation:er,policy:_.policy};if(d==="deep"){let T=l?v.failed:v.failed.map(N=>{let{trace:Yu,...as}=N;return as});Kt.deep={warnings:ce,warning_codes:Zn,capability_contract:Ht,capability_guidance:J,trace_enabled:l,managed_state:{path:u.path,count:y.entries.length,entries:y.entries},installed_extensions:S,load:{roots:_.roots,policy:_.policy,warnings:_.warnings,failed:_.failed,loaded:_.loaded.map(N=>({layer:N.layer,directory:N.directory,name:N.name,version:N.version,entry:N.entry,priority:N.priority}))},activation:{failed:T,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:C.summary},l&&(Kt.deep.trace={activation_failures:v.failed.filter(N=>N.trace!==void 0).map(N=>({layer:N.layer,name:N.name,entry_path:N.entry_path,error:N.error,method:N.trace.method,command:N.trace.command,capability:N.trace.capability,missing_capability:N.trace.missing_capability,registration_index:N.trace.registration_index,expected_schema:N.trace.expected_schema,hint:N.trace.hint,received:N.trace.received}))})}return s(Kt)},cu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:o,options:i,global:a,withResult:s}=e,c=await O(r.settings_root),d=await be({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),l=await ke(d);o.push(...d.warnings),o.push(...l.warnings);let p=xi(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})},du=async(e,t,n)=>{let r=n,o=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(o=await Jn(e.resolvedRoots.selected_root,e.scope,t,n),r=o.state),e.action==="manage"){let i=await Xi(r.entries,Ql,async a=>{if(a.source.kind!=="github")return a;let s=await ta(a.source);return{...a,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});r={...r,updated_at:I(),entries:dt(i)},await je(e.resolvedRoots.selected_root,r)}return{state:r,fix:o}},lu=async(e,t,n)=>{let r=await be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),o=await ke({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...o.warnings),{installed:Ut(n,r,o),failures:ya(o.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:o.failed.length,warning_count:[...new Set([...r.warnings,...o.warnings])].length,policy:r.policy}}},pu=(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},aa=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:o,options:i,withResult:a}=e,s=await O(r.settings_root),c=lp(s.extensions.policy),d=await we(r.selected_root);o.push(...d.warnings);let l=await fe(r.selected_root,n,s,d.state);o.push(...l.warnings);let{state:p,fix:u}=await du(e,l.extensions,d.state),m=await fe(r.selected_root,n,s,p);if(o.push(...m.warnings),t==="manage"){let v=m.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);o.push(...v)}let y=await lu(e,s,m.extensions),w=y.installed,f=zt(n,o,w,i);o.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=pu(u,w)),a(_)},sa={init:jp,install:Xp,uninstall:tu,explore:aa,manage:aa,describe:cu,reload:Lp,doctor:su,catalog:Fp,adopt:eu,"adopt-all":Qp,activate:ia,deactivate:ia,migrate:$i},uu=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),mu=e=>uu(e)?Gn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>sa[e.action](e)):sa[e.action](e);import Hn from"node:fs/promises";import z from"node:path";import ka from"node:readline/promises";import{stdin as xa,stdout as ft}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]="e404796d-439b-5f4c-9330-5b12ff41d7b2")}catch{}})();var Sa=["ask","add","skip","status"],fu=["AGENTS.md","CLAUDE.md"],hu=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],gu=8,Kn=1,yu="<!-- pm-cli:agent-guidance:start:",_u=`<!-- pm-cli:agent-guidance:start:v${Kn} -->`,Bn="<!-- pm-cli:agent-guidance:end -->",gt="Add workflow guidance later: pm init --agent-guidance add",f_={toPortableRelativePath:Qe,ensureTrailingNewline:Wn,detectLineEnding:$a,findGuidanceBlockRange:Vn,buildAgentGuidanceBlock:Aa,upsertAgentGuidanceBlock:Ia,resolveProjectRoot:Ta,resolveTargetGuidancePath:Oa,parsePromptChoice:Ca,pushUnique:Ze,promptForGuidanceWrite:Ra,normalizeAgentGuidanceState:Yn,applyAgentGuidanceState:Na,writeGuidanceFile:Da,setAgentGuidanceReadlineFactoryForTests:wu},Ea=()=>ka.createInterface({input:xa,output:ft});function wu(e){Ea=e??(()=>ka.createInterface({input:xa,output:ft}))}function Qe(e,t){let n=z.relative(e,t);return n.length===0?z.basename(t):n.split(z.sep).join("/")}function Wn(e){return e.endsWith(`
|
|
47
47
|
`)?e:`${e}
|
|
48
48
|
`}function $a(e){return e.includes(`\r
|
|
49
49
|
`)?`\r
|
|
@@ -54,11 +54,11 @@ ${d}`,g.GENERIC_FAILURE)}}function ti(e){let t=e.trim(),n=t.includes("@file:")?t
|
|
|
54
54
|
`)?`
|
|
55
55
|
`:`
|
|
56
56
|
|
|
57
|
-
`,a=Wn(`${e}${i}${r}`);return{next_content:a,changed:a!==e}}async function bu(e){if(await
|
|
57
|
+
`,a=Wn(`${e}${i}${r}`);return{next_content:a,changed:a!==e}}async function bu(e){if(await x(z.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Hn.readFile(z.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=ku(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await x(z.join(e,"pnpm-lock.yaml"))?"pnpm test":await x(z.join(e,"bun.lock"))||await x(z.join(e,"bun.lockb"))?"bun run test":await x(z.join(e,"yarn.lock"))?"yarn test":"npm test"}function ku(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function Ta(e,t){let n=z.dirname(e);return z.basename(e)==="pm"&&z.basename(n)===".agents"?z.dirname(n):z.resolve(t,e)}function Oa(e,t){let n=e.find(o=>z.basename(o.file_path)==="AGENTS.md"&&o.exists);if(n)return n.file_path;let r=e.find(o=>o.exists);return r?r.file_path:z.join(t,"AGENTS.md")}function Ca(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 Ra(e){let t=Ea();try{ft.write(`
|
|
58
58
|
Agent guidance check
|
|
59
59
|
`),ft.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 ft.write(`
|
|
61
|
-
`),Ca(n,!0)}finally{t.close()}}function Yn(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:Kn,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function Pa(e){let t=[];for(let n of fu){let r=z.join(e,n),o=await k(r);if(!o){t.push({file_path:r,exists:o,has_guidance:!1,has_marker:!1});continue}let i=await Hn.readFile(r,"utf8"),a=i.toLowerCase(),s=hu.filter(d=>a.includes(d)),c=vu(i);t.push({file_path:r,exists:o,has_guidance:c||s.length>=gu,has_marker:c})}return t}function Qe(e,t){e.includes(t)||e.push(t)}function Na(e,t){let n=Yn(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function Da(e,t=z.dirname(e)){let r=await k(e)?await Hn.readFile(e,"utf8"):"",o=Ia(r,await bu(t));return o.changed?(await he(e,o.next_content),{changed:!0,warnings:await W({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function xu(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 Pa(n):t}function ht(e,t,n){e.state={...e.state,...n,template_version:Kn,last_checked_files:t}}async function ja(e,t){if(t.presentBefore)return;let n=await Da(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Eu(e,t){t||(e.warnings.push("agent_guidance:missing"),Qe(e.nextSteps,gt))}function $u(e,t){e.skipped=!0,ht(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,gt)}async function Au(e,t){await ja(e,t),ht(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Iu(e,t){e.state.declined&&ht(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Tu(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Qe(e.nextSteps,gt)}async function Ou(e,t){if(e.prompted=!0,await Ra(t.targetRelativePath)){await ja(e,t),ht(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,ht(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Qe(e.nextSteps,gt)}function Cu(e){e.warnings.push("agent_guidance:missing_non_interactive"),Qe(e.nextSteps,gt)}async function Ru(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Eu(n,t.presentBefore),n):t.mode==="skip"?($u(n,t.checkedFiles),n):t.mode==="add"?(await Au(n,t),n):t.presentBefore?(Iu(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Tu(n),n):t.interactive?(await Ou(n,t),n):(Cu(n),n)}async function La(e){let t=Ta(e.pm_root,e.cwd),n=await Pa(t),r=Oa(n,t),o=Xe(t,r),i=n.map(l=>Xe(t,l.file_path)),a=n.some(l=>l.has_guidance),s=await Ru(Yn(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:o,checkedFiles:i,presentBefore:a,projectRoot:t}),c=Na(e.settings,s.state);return n=await Su(s.applied,n,t),{summary:xu({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:o,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import Pu from"node:fs/promises";import j from"node:path";import Ma from"node:readline/promises";import{stdin as Ga,stdout as X}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="75c0d2d2-6a89-508f-b7dd-b43d55978b44")}catch{}})();function F_(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 M_={normalizeInitGovernancePreset:Xn,normalizeInitTypePreset:za,normalizeOptionalInitAuthor:Ja,normalizeInitAgentGuidanceMode:Wa,isPathLikeInitTarget:Bt,resolveInitInvocation:qa,resolveInitPrefixInput:Ba,parseYesNoChoice:Ha,applyGovernancePreset:Qn,runInitWizard:Za,setInitReadlineFactoryForTests:Nu,summarizeInstalledPackages:Ka,buildInitNextSteps:es,registerInitTypePreset:Va,assertExplicitTrackerPathIsNotWorkspaceRoot:Xa,isLikelyWorkspaceRoot:Ya,installInitMergeFence:ts},Ua=()=>Ma.createInterface({input:Ga,output:X});function Nu(e){Ua=e??(()=>Ma.createInterface({input:Ga,output:X}))}function Du(){return structuredClone(Vt)}var ju=["minimal","default","strict"];function Xn(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: ${ju.join(", ")}`,g.USAGE)}function za(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: ${rt.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 Bt(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:j.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function qa(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new h("--workspace must not be empty",g.USAGE);if(o!==void 0){if(t.path!==void 0||Bt(n))throw new h("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",g.USAGE);let d=j.resolve(e,o),l=j.join(d,".agents","pm");return{pmRoot:l,prefixArg:n,target:{mode:"workspace-path",tracker_root:l,workspace_root:d}}}if(t.path===void 0&&Bt(n)){let d=j.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let i=D(e,t.path),a=j.join(j.resolve(e),".agents","pm"),s=j.dirname(j.dirname(i)),c=j.resolve(i)===a?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:c,requested_cwd:j.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function Ba(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(Bt(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&&xe(e)!==xe(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 ${xe(e)}`,`pm init --id-prefix ${xe(t)}`]});return t}function Wa(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: ${Sa.join(", ")}`,g.USAGE)}function Ha(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Qn(e,t){let n=rr[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function Lu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ka(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(Lu).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Va(e,t,n){let r=K(t.schema),o=ne(e,r.files.types,Y.types),a=ie(await q(o)),s=[],c=[];for(let d of ot(n)){let l=Me(a,d);a=l.file,(l.replaced?c:s).push(l.definition.name)}return await Fe({pmRoot:e,filePath:o,raw:le(a),op:"init:type-preset",author:V(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:s,updated:c,file:o}}async function Ya(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",j.join(".agents","pm")];for(let n of t)if(await k(j.join(e,n)))return!0;return!1}async function Xa(e,t,n){if(!t||n||await k(j.join(e,"settings.json"))||!await Ya(e))return;let r=j.join(e,".agents","pm");throw new h(`Refusing to initialize tracker files directly in workspace root "${e}".`,g.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function Qa(e,t){let n=[],r=[];for(let o of t){let i=o?j.join(e,o):e,a=await k(i);await Pu.mkdir(i,{recursive:!0}),a?r.push(`already_exists:${i}`):n.push(i),r.push(...await W({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function Za(e,t){let n=Ua();try{X.write(`pm init setup wizard (agent-optimized)
|
|
61
|
+
`),Ca(n,!0)}finally{t.close()}}function Yn(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:Kn,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function Pa(e){let t=[];for(let n of fu){let r=z.join(e,n),o=await x(r);if(!o){t.push({file_path:r,exists:o,has_guidance:!1,has_marker:!1});continue}let i=await Hn.readFile(r,"utf8"),a=i.toLowerCase(),s=hu.filter(d=>a.includes(d)),c=vu(i);t.push({file_path:r,exists:o,has_guidance:c||s.length>=gu,has_marker:c})}return t}function Ze(e,t){e.includes(t)||e.push(t)}function Na(e,t){let n=Yn(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function Da(e,t=z.dirname(e)){let r=await x(e)?await Hn.readFile(e,"utf8"):"",o=Ia(r,await bu(t));return o.changed?(await he(e,o.next_content),{changed:!0,warnings:await W({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function xu(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Qe(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Qe(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Qe(e.projectRoot,t.file_path))}}async function Su(e,t,n){return e?await Pa(n):t}function ht(e,t,n){e.state={...e.state,...n,template_version:Kn,last_checked_files:t}}async function ja(e,t){if(t.presentBefore)return;let n=await Da(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Eu(e,t){t||(e.warnings.push("agent_guidance:missing"),Ze(e.nextSteps,gt))}function $u(e,t){e.skipped=!0,ht(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,gt)}async function Au(e,t){await ja(e,t),ht(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Iu(e,t){e.state.declined&&ht(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Tu(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ze(e.nextSteps,gt)}async function Ou(e,t){if(e.prompted=!0,await Ra(t.targetRelativePath)){await ja(e,t),ht(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,ht(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ze(e.nextSteps,gt)}function Cu(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ze(e.nextSteps,gt)}async function Ru(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Eu(n,t.presentBefore),n):t.mode==="skip"?($u(n,t.checkedFiles),n):t.mode==="add"?(await Au(n,t),n):t.presentBefore?(Iu(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Tu(n),n):t.interactive?(await Ou(n,t),n):(Cu(n),n)}async function La(e){let t=Ta(e.pm_root,e.cwd),n=await Pa(t),r=Oa(n,t),o=Qe(t,r),i=n.map(l=>Qe(t,l.file_path)),a=n.some(l=>l.has_guidance),s=await Ru(Yn(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:o,checkedFiles:i,presentBefore:a,projectRoot:t}),c=Na(e.settings,s.state);return n=await Su(s.applied,n,t),{summary:xu({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:o,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import Pu from"node:fs/promises";import j from"node:path";import Ma from"node:readline/promises";import{stdin as Ga,stdout as X}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="75c0d2d2-6a89-508f-b7dd-b43d55978b44")}catch{}})();function F_(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 M_={normalizeInitGovernancePreset:Xn,normalizeInitTypePreset:za,normalizeOptionalInitAuthor:Ja,normalizeInitAgentGuidanceMode:Wa,isPathLikeInitTarget:Wt,resolveInitInvocation:qa,resolveInitPrefixInput:Ba,parseYesNoChoice:Ha,applyGovernancePreset:Qn,runInitWizard:Za,setInitReadlineFactoryForTests:Nu,summarizeInstalledPackages:Ka,buildInitNextSteps:es,registerInitTypePreset:Va,assertExplicitTrackerPathIsNotWorkspaceRoot:Xa,isLikelyWorkspaceRoot:Ya,installInitMergeFence:ts},Ua=()=>Ma.createInterface({input:Ga,output:X});function Nu(e){Ua=e??(()=>Ma.createInterface({input:Ga,output:X}))}function Du(){return structuredClone(Yt)}var ju=["minimal","default","strict"];function Xn(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: ${ju.join(", ")}`,g.USAGE)}function za(e){if(e!==void 0){if(e.trim().length===0)throw new h("--type-preset must not be empty",g.USAGE);try{return It(e)}catch{throw new h(`Invalid --type-preset value "${e}". Allowed: ${rt.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 Wt(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:j.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function qa(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new h("--workspace must not be empty",g.USAGE);if(o!==void 0){if(t.path!==void 0||Wt(n))throw new h("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",g.USAGE);let d=j.resolve(e,o),l=j.join(d,".agents","pm");return{pmRoot:l,prefixArg:n,target:{mode:"workspace-path",tracker_root:l,workspace_root:d}}}if(t.path===void 0&&Wt(n)){let d=j.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let i=D(e,t.path),a=j.join(j.resolve(e),".agents","pm"),s=j.dirname(j.dirname(i)),c=j.resolve(i)===a?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:c,requested_cwd:j.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function Ba(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(Wt(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&&xe(e)!==xe(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 ${xe(e)}`,`pm init --id-prefix ${xe(t)}`]});return t}function Wa(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: ${Sa.join(", ")}`,g.USAGE)}function Ha(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Qn(e,t){let n=rr[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function Lu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ka(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(Lu).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Va(e,t,n){let r=K(t.schema),o=ne(e,r.files.types,Y.types),a=ie(await q(o)),s=[],c=[];for(let d of ot(n)){let l=Ge(a,d);a=l.file,(l.replaced?c:s).push(l.definition.name)}return await Me({pmRoot:e,filePath:o,raw:le(a),op:"init:type-preset",author:V(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:s,updated:c,file:o}}async function Ya(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",j.join(".agents","pm")];for(let n of t)if(await x(j.join(e,n)))return!0;return!1}async function Xa(e,t,n){if(!t||n||await x(j.join(e,"settings.json"))||!await Ya(e))return;let r=j.join(e,".agents","pm");throw new h(`Refusing to initialize tracker files directly in workspace root "${e}".`,g.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function Qa(e,t){let n=[],r=[];for(let o of t){let i=o?j.join(e,o):e,a=await x(i);await Pu.mkdir(i,{recursive:!0}),a?r.push(`already_exists:${i}`):n.push(i),r.push(...await W({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function Za(e,t){let n=Ua();try{X.write(`pm init setup wizard (agent-optimized)
|
|
62
62
|
`),X.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
63
63
|
|
|
64
64
|
`),X.write(`1/3 Item ID prefix
|
|
@@ -73,5 +73,5 @@ Agent guidance check
|
|
|
73
73
|
3/3 Project telemetry
|
|
74
74
|
`),X.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=Ha(d,t);return X.write(`
|
|
76
|
-
`),{prefix:o,preset:s,telemetry_enabled:l}}finally{n.close()}}function Fu(e){return{presetFromOption:Xn(e.preset),useDefaults:e.defaults===!0,authorFromOption:Ja(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:Wa(e.agentGuidance),typePreset:za(e.typePreset)}}function Mu(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 Gu(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new h(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,g.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['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 Uu(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&&(Qn(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 zu(e){let t=await O(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=Mu({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return Gu(e.settingsPath,n,e.options.force===!0,e.target),Uu({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Se(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function Ju(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await Za(t,
|
|
77
|
-
//# sourceMappingURL=chunk-
|
|
76
|
+
`),{prefix:o,preset:s,telemetry_enabled:l}}finally{n.close()}}function Fu(e){return{presetFromOption:Xn(e.preset),useDefaults:e.defaults===!0,authorFromOption:Ja(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:Wa(e.agentGuidance),typePreset:za(e.typePreset)}}function Mu(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 Gu(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new h(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,g.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['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 Uu(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&&(Qn(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 zu(e){let t=await O(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=Mu({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return Gu(e.settingsPath,n,e.options.force===!0,e.target),Uu({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Se(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function Ju(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await Za(t,Yt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let i=n??"minimal",a=Du();a.id_prefix=t,Qn(a,i);let s=Sr()?.trim()||void 0;return a.author_default=e.normalizedOptions.authorFromOption??s??"",r!==void 0&&(a.telemetry.enabled=r,a.telemetry.first_run_prompt_completed=!0),await Se(e.pmRoot,a),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function Fa(e){return e.settingsExists?await zu(e):await Ju({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function qu(e){let t=await La({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 Se(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function Bu(e,t){let n=[],r=[],o=await xr(e,t.schema);for(let i of o.created_paths)n.push(i),r.push(...await W({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function Wu(e){if(e.typePreset===void 0)return;let t=await Va(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await W({path:t.file,scope:"project",op:"init:type_preset"})),t}async function Hu(e){let n=B(e.settings,H()).folders.filter(o=>!Vt.includes(o)),r=await Qa(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function Ku(e){let t=j.resolve(e.tracker_root),n=j.dirname(t);return j.basename(t)==="pm"&&j.basename(n)===".agents"?j.dirname(n):e.workspace_root}async function Vu(e,t,n,r){if(!e)return;let o=await qn("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let i=Ka(o),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 es(e){let t=r=>xt([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function ts(e,t,n,r=fn){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 o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof h))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function G_(e,t,n={}){let r=process.cwd(),o=qa(r,t,e,n.workspace),i=o.pmRoot;e=Ba(o.prefixArg,n.idPrefix);let a=Fu(n);await Xa(i,o.target.mode==="tracker-path",n.force===!0);let s=[],c=[],d=j.join(i,"settings.json"),l=await x(d),p;l&&(p=await Fa({pmRoot:i,settingsPath:d,settingsExists:l,normalizedPrefix:xe(e),prefixArg:e,options:n,normalizedOptions:a,warnings:c,target:o.target}));let u=await Qa(i,Vt);s.push(...u.createdDirs),c.push(...u.warnings),p??=await Fa({pmRoot:i,settingsPath:d,settingsExists:l,normalizedPrefix:xe(e),prefixArg:e,options:n,normalizedOptions:a,warnings:c,target:o.target});let{settings:m}=p,y=Ku(o.target),w=await pn(y??j.dirname(i)),f=y??w,_=await qu({pmRoot:i,cwd:f??r,agentGuidanceMode:a.agentGuidanceMode,settings:m,warnings:c}),v=await Bu(i,m);s.push(...v.createdDirs),c.push(...v.warnings);let k=await Wu({pmRoot:i,settings:m,typePreset:a.typePreset,warnings:c});if(k&&(m=await O(i)),await Hu({pmRoot:i,settings:m,createdDirs:s,warnings:c}),f&&a.agentGuidanceMode!=="status"){let M=await Yr(f,{pmRoot:i});M.changed&&c.push(`updated:gitignore:${M.path}`)}!l&&n.mergeFence!==!1&&a.agentGuidanceMode!=="status"&&await ts(i,w,c);let S=await Vu(a.installBundledPackages,t,i,c),C=es({installBundledPackages:a.installBundledPackages,registeredTypePreset:k,agentGuidanceNextSteps:_.next_steps,target:o.target});return{ok:!0,path:i,target:o.target,settings:m,created_dirs:s,warnings:c,governance_preset:m.governance.preset,wizard_used:p.wizardUsed,...k?{registered_type_preset:k}:{},...S?{installed_packages:S}:{},next_steps:C,agent_guidance:_}}export{nn as a,Br as b,Hr as c,an as d,xs as e,Es as f,Yr as g,ze as h,As as i,Is as j,Qr as k,Et as l,no as m,Je as n,dn as o,Ps as p,pn as q,mn as r,so as s,Om as t,Cm as u,co as v,Rm as w,fn as x,_o as y,We as z,He as A,wo as B,ho as C,qe as D,Be as E,go as F,_c as G,Eo as H,To as I,gc as J,yc as K,zf as L,Jf as M,qf as N,it as O,Bf as P,Wf as Q,Hf as R,Kf as S,Vf as T,Yf as U,Xf as V,Qf as W,Zf as X,eh as Y,th as Z,nh as _,rh as $,oh as aa,ih as ba,ah as ca,sh as da,ch as ea,dh as fa,lh as ga,ph as ha,uh as ia,mh as ja,fh as ka,hh as la,b as ma,we as na,Ct as oa,Dc as pa,st as qa,Rt as ra,Zo as sa,di as ta,Dn as ua,xi as va,Og as wa,Cl as xa,Fi as ya,Mi as za,Xi as Aa,jn as Ba,xl as Ca,Sl as Da,El as Ea,$i as Fa,Yl as Ga,Ai as Ha,qn as Ia,Sa as Ja,f_ as Ka,La,F_ as Ma,M_ as Na,G_ as Oa};
|
|
77
|
+
//# sourceMappingURL=chunk-IEFJ3ZEB.js.map
|