@unbrained/pm-cli 2026.8.17 → 2026.8.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/AGENTS.md +4 -3
- package/CHANGELOG.md +35 -3
- package/README.md +3 -3
- package/dist/cli/error-guidance.js +7 -4
- package/dist/cli/register-list-query.js +132 -51
- package/dist/cli-bundle/bundle-manifest.json +146 -146
- package/dist/cli-bundle/chunks/chunk-5UZZAJKR.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-YM2YAMF7.js → chunk-ALDJGKAK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HBJAS566.js → chunk-BSK2IN3C.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-DY4DMUMC.js +197 -0
- package/dist/cli-bundle/chunks/{chunk-JOKATURE.js → chunk-GNFAFIJI.js} +9 -9
- package/dist/cli-bundle/chunks/chunk-L5Q2CLPE.js +35 -0
- package/dist/cli-bundle/chunks/{chunk-TPXZIBIV.js → chunk-PVRUN5ZS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7IBRGCHX.js → chunk-RZQTVMRQ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-SARFF5H5.js +3 -0
- package/dist/cli-bundle/chunks/chunk-UYCLQVL2.js +13 -0
- package/dist/cli-bundle/chunks/{chunk-3UEGXBMR.js → chunk-YRGOLZA7.js} +58 -54
- package/dist/cli-bundle/chunks/register-list-query-I23LALEE.js +11 -0
- package/dist/cli-bundle/chunks/{register-mutation-4WBRPXLV.js → register-mutation-6YGU3GPH.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-SSENDH5B.js → register-operations-4HTFC6J7.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-DOSFBGKE.js → register-setup-PPPEF3SN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2PN4TJXH.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZQPGZZWQ.js → chunk-3TKWMNKF.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-5AF3ZBNB.js +155 -0
- package/dist/cli-bundle/focused-chunks/chunk-C5IW2NDA.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SYZENPIT.js → chunk-EUEGXZ2A.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XKAMP5OU.js → chunk-EX6MKP2X.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-CYFK5UPB.js → chunk-K43KKAFS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ATEY76SX.js → chunk-M62NO7EI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SALH6B6K.js → chunk-ODOVCP45.js} +5 -5
- package/dist/cli-bundle/focused-chunks/chunk-RNDNMARJ.js +16 -0
- package/dist/cli-bundle/focused-chunks/chunk-TN4AE665.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-TVV2DONO.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-UI6AJ5TD.js +4 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MHPIL773.js → chunk-V5XTGLK7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KP2VQQVQ.js → chunk-WGHQVU6P.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XYNBXTDQ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Z56ECT7I.js +2 -0
- package/dist/cli-bundle/main.js +7 -7
- 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 +31 -31
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +32 -32
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +4 -4
- package/dist/core/config/nested-settings.js +8 -2
- package/dist/core/extensions/exporter-output-contract.d.ts +12 -0
- package/dist/core/extensions/exporter-output-contract.js +67 -0
- package/dist/core/extensions/extension-types.d.ts +36 -1
- package/dist/core/extensions/extension-types.js +2 -2
- package/dist/core/extensions/loader.js +35 -44
- package/dist/core/history/event-index.d.ts +5 -0
- package/dist/core/history/event-index.js +133 -27
- package/dist/core/sentry/helpers.js +3 -3
- package/dist/core/shared/constants.js +5 -2
- package/dist/core/store/settings-validator.d.ts +4 -0
- package/dist/core/store/settings-validator.js +3 -2
- package/dist/core/store/settings.js +8 -2
- package/dist/mcp/tool-definitions.js +12 -7
- package/dist/sdk/agent/refusal-reachability.js +4 -4
- package/dist/sdk/authoring.d.ts +1 -1
- package/dist/sdk/authoring.js +2 -2
- package/dist/sdk/cli-bootstrap.d.ts +2 -2
- package/dist/sdk/cli-bootstrap.js +4 -4
- package/dist/sdk/cli-contracts/command-aliases.d.ts +34 -2
- package/dist/sdk/cli-contracts/command-aliases.js +64 -13
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +4 -0
- package/dist/sdk/cli-contracts/enum-contracts.js +9 -2
- package/dist/sdk/cli-contracts/flag-contracts.js +11 -7
- package/dist/sdk/cli-contracts/grammar-contracts.d.ts +70 -0
- package/dist/sdk/cli-contracts/grammar-contracts.js +345 -0
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +19 -2
- package/dist/sdk/cli-contracts/runtime-contracts.js +61 -14
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +7 -2
- package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
- package/dist/sdk/cli-contracts/tool-schema.js +20 -11
- package/dist/sdk/cli-contracts.d.ts +2 -2
- package/dist/sdk/cli-contracts.js +4 -4
- package/dist/sdk/completion.js +13 -15
- package/dist/sdk/compose.d.ts +3 -3
- package/dist/sdk/compose.js +2 -2
- package/dist/sdk/contracts.d.ts +1 -0
- package/dist/sdk/contracts.js +3 -2
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +3 -3
- package/dist/sdk/environment/host-environment-errors.js +3 -3
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +54 -14
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +50 -14
- package/dist/sdk/guide-topics.js +5 -5
- package/dist/sdk/index.d.ts +4 -3
- package/dist/sdk/index.js +6 -5
- package/dist/sdk/init-agent-guidance.js +3 -3
- package/dist/sdk/mutation-events.d.ts +18 -2
- package/dist/sdk/mutation-events.js +59 -16
- package/dist/sdk/output.d.ts +44 -0
- package/dist/sdk/output.js +28 -2
- package/dist/sdk/query/complete-list.d.ts +94 -0
- package/dist/sdk/query/complete-list.js +173 -0
- package/dist/sdk/query/list.js +5 -2
- package/dist/sdk/query.d.ts +1 -0
- package/dist/sdk/query.js +3 -2
- package/dist/sdk/read-output-contracts.d.ts +2 -2
- package/dist/sdk/read-output-contracts.js +36 -9
- package/dist/sdk/runtime-extended-actions.js +10 -2
- package/dist/sdk/runtime.d.ts +8 -2
- package/dist/sdk/runtime.js +11 -8
- package/dist/types.d.ts +5 -0
- package/dist/types.js +2 -2
- package/docs/AGENT_GUIDE.md +25 -9
- package/docs/CLI_GRAMMAR.md +106 -0
- package/docs/COMMANDS.md +23 -23
- package/docs/ONBOARDING.md +4 -4
- package/docs/QUICKSTART.md +1 -1
- package/docs/README.md +2 -0
- package/docs/RELEASING.md +30 -6
- package/docs/SDK.md +36 -2
- package/docs/SDK_ARTIFACT_OUTPUT.md +72 -0
- package/docs/SDK_CONTEXT_COORDINATION.md +46 -12
- package/docs/agent-task-token-baseline.json +5 -5
- package/marketplace.json +2 -2
- package/package.json +3 -2
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/sdk/public-surface.json +652 -31
- package/dist/cli-bundle/chunks/chunk-2QLOXC3V.js +0 -3
- package/dist/cli-bundle/chunks/chunk-4JPYF536.js +0 -35
- package/dist/cli-bundle/chunks/chunk-6VDLG2FC.js +0 -13
- package/dist/cli-bundle/chunks/chunk-ION3E43Q.js +0 -197
- package/dist/cli-bundle/chunks/chunk-OAC5NIV4.js +0 -3
- package/dist/cli-bundle/chunks/register-list-query-Q7KII4G5.js +0 -10
- package/dist/cli-bundle/focused-chunks/chunk-267MUUS6.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-2NNFLLNG.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2QSAKMIH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-BUCG4ZI2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-EHXIKD6K.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-KGEXTMPG.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-POEEAD2V.js +0 -4
- package/dist/cli-bundle/focused-chunks/chunk-XPIC53VA.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-ZT2DJS27.js +0 -155
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{a as ki,c as Wn,d as Bn,e as Qo,g as es,h as Si,i as ts,j as At,k as Rt,l as ns,m as rs,n as Ei,o as is,p as It,q as Ct,r as as,s as os,t as Ai}from"./chunk-SYZENPIT.js";import{a as ds,f as Xn,g as Ri}from"./chunk-KGEXTMPG.js";import{B as Kn,a as Jo,g as bi,i as Vo}from"./chunk-2NNFLLNG.js";import{Z as Ys,l as Vs,n as Ks}from"./chunk-MHPIL773.js";import{$ as Us,Aa as Hs,Ba as Js,Da as Di,I as lr,J as Os,K as $i,L as an,N as Ti,R as Ds,S as Ps,T as Ns,U as Ms,V as dr,X as Ls,Y as Fs,Z as js,_ as ht,aa as Nt,ba as zs,ca as Oi,da as Mt,e as Rs,ea as qs,f as Is,fa as Gs,g as Cs,t as nn,u as $s,ua as Ws,v as rn,va as ur,w as Ts,za as Bs}from"./chunk-ZQPGZZWQ.js";import{a as Ko,b as Hn,c as xi,d as Yo,e as Xo,f as We,g as Jn,h as Zo,i as it}from"./chunk-XKAMP5OU.js";import{$a as I,Aa as _s,Ma as ys,Ra as ue,Sa as nr,Ta as ws,U as Y,Ua as Ci,V as $,Va as rr,Wa as ir,Xa as ar,Ya as vs,Za as Te,_ as de,_a as bs,ab as or,b as ms,cb as ks,d as ps,ea as hs,fa as Qn,hb as xs,ia as er,ib as Ss,ja as gs,l as z,ma as $t,nb as sr,o as re,oa as Tt,pb as Es,q as He,qb as Ot,r as fs,ra as tr,rb as Dt,s as Zn,sb as Pt,tb as Je,ub as cr,xb as ft,ya as Ii,zb as As}from"./chunk-ZT2DJS27.js";import{Ba as vi,Ca as Bo,Da as Ho,E as Lo,Ea as Et,F as Fo,G as q,Ga as Ne,Ia as Me,Ka as se,L as tn,La as Ae,M as L,N as pt,Na as we,O as qn,Oa as Le,P as K,R as jo,S as Gn,Sa as Be,Ua as Vn,W as Z,Ya as Yn,Z as Uo,Za as cs,_a as ls,a as Co,ba as zo,d as $o,e as To,ea as _i,ga as yi,h as St,p as gi,q as A,r as zn,s as j,sa as qo,t as X,ta as Go,u as le,x as ye,y as Ee,z as Mo}from"./chunk-POEEAD2V.js";import{b as us}from"./chunk-KP2VQQVQ.js";import{N as Oo,P as Do,R as Po,U as No,V as Un,Y as _,Z as y,a as Fn,aa as oe,ba as Wo,ca as wi,d as jn,ka as ss,t as hi}from"./chunk-EHXIKD6K.js";(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]="d2d5135a-8110-527e-8530-653b25b792a4")}catch{}})();var N=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},ve=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Fe=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function Lt(e){try{return await e()}catch(t){throw t instanceof N?new y(t.message,_.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Xs(e){try{return await e()}catch(t){throw t instanceof ve?new y(t.message,_.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as kp}from"node:crypto";import xp 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]="b911b43d-d14d-5e4f-a35e-5020b1a84542")}catch{}})();var Ft=1e3;(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]="2bf52d6d-7e4f-5ec5-86bd-3e817ef521bb")}catch{}})();var Qs=1,gt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],Pi=["items","dependency_kind","graph","validate","health","history","links","provider","derived"],Sp=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Ep=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,mr=30,pr=5e3,ec=4,Ap=50;function Ve(e,t){if(!Ep.test(e))throw new N(`${t} must be a stable lowercase id`)}function Rp(e,t){if(!Number.isFinite(e)||e<0)throw new N(`${t} must be a finite non-negative number`)}function on(e){let t=Sp.filter(i=>e[i]!==void 0);if(t.length!==1)throw new N(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function Ni(e,t){return oe(e)===oe(t)}function tc(e,t){if(t.polarity==="equals")return Ni(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function nc(e){let t=on(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>tc(r.observed,t)===(r.expected==="pass"))}function Ip(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!Ni(e.value,t.value)}function Cp(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||oe(e.scope)!==oe(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Ip(on(e),on(t))||n[t.enforcement]<n[e.enforcement]||r}function $p(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new N("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new N("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new N("items source equals/state requires field")}function Mi(e){Ve(e.id,"measurement.id"),e.max_cost!==void 0&&Rp(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new N(`measurement.source.kind must be one of ${Pi.join(", ")}`);let n=Reflect.get(t,"kind");if(!Pi.includes(n))throw new N(`measurement.source.kind must be one of ${Pi.join(", ")}`);let r=t;if(r.kind==="items"&&$p(r),r.kind==="dependency_kind"&&(typeof r.dependency_kind!="string"||r.dependency_kind.trim().length===0))throw new N("dependency_kind source requires dependency_kind");if((r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new N(`${r.kind} source requires field`);return r.kind==="provider"&&(Ve(r.provider,"provider source provider"),Ve(r.key,"provider source key")),e}function Li(e){if(Ve(e.id,"assertion.id"),Ve(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new N("assertion.owner_item_id is required");let t=on(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new N(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new N("retired assertion requires retire_reason");e.scope.kind==="filter"&&Ve(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new N("assertion negative control requires pass and fail cases");if(!nc(e))throw new N(`assertion ${e.id} negative control does not prove its bound`);return e}function Tp(e){if(!Array.isArray(e.allowed_providers))throw new N("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)Ve(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new N("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!gt.includes(t))throw new N(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new N(`gate provider policy trigger ${t} is invalid`)}}function rc(e){if(Ve(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new N("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new N("gate requires at least one assertion");for(let t of e.assertion_ids)Ve(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new N(`gate.triggers is required and must be an array of ${gt.join(", ")}`);if(e.triggers.length===0)throw new N("gate requires at least one trigger");for(let t of e.triggers)if(!gt.includes(t))throw new N(`gate trigger must be one of ${gt.join(", ")}`);return e.provider_policy&&Tp(e.provider_policy),e}function jt(e){if(e.version!==Qs)throw new N(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Mi(r),t.has(`measurement:${r.id}`))throw new N(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(Li(r),t.has(`assertion:${r.id}`))throw new N(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){rc(r);let i=r.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(i.length>0)throw new N(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new N(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of ic(e))if(!n.has(r))throw new N(`${i.join(", ")} references missing measurement ${r}`);return e}function Fi(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)Fi(n,t)}function ic(e){let t=new Map,n=(r,i)=>{let a=t.get(r)??[];a.push(i),t.set(r,a)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];Fi(r.source.expression,i);for(let a of i)n(a,`derived measurement ${r.id}`)}return t}function Op(e,t){let n=e.assertion_ids.flatMap(a=>{let o=t.assertions.find(s=>s.id===a);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let a=n.pop();if(r.has(a))continue;r.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?i.add(o.source.provider):o.source.kind==="derived"&&Fi(o.source.expression,n)}return i}function sn(){return{version:Qs,measurements:[],assertions:[],gates:[]}}function Dp(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let a=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?a:!a}return Ni(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Pp(e,t){let n=[],r=yi(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let a of i.dependencies??[])(yi(a.kind)??a.kind.trim().toLowerCase())===r&&n.push(`${i.id}->${a.id}`);return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Np(e,t){return{value:t.history.filter(r=>(e.op===void 0||r.op===e.op)&&(e.author===void 0||r.author===e.author)&&(e.harness===void 0||r.agent_harness===e.harness)&&(e.model===void 0||r.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function Mp(e,t){let n=t.items.filter(r=>{let i=r[e.link],a=Array.isArray(i)&&i.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Lp(e,t){let n=e.source;return n.kind==="items"?Dp(n,t):n.kind==="dependency_kind"?Pp(n,t):n.kind==="history"?Np(n,t):n.kind==="links"?Mp(n,t):null}function ac(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function Fp(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function oc(e,t,n){let r=new Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o],o)}});return await Promise.all(a),r}async function sc(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(l=>l.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await cc(o,t,n,r,i);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=i.charged.has(o.id)?[]:[s.cost];return i.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await oc(e.operands,ec,o=>sc(o,t,n,r,i));return{value:Fp(e.operator,a.map(o=>o.value)),costs:a.flatMap(o=>o.costs),population_size:Math.max(0,...a.map(o=>o.population_size)),contributors:[...new Set(a.flatMap(o=>o.contributors))]}}async function jp(e,t,n,r,i){Mi(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await sc(e.source.expression,t,n,[...r,e.id],i);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Lp(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let l={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-a},d=ac([...s,l],Date.now()-a);if(e.max_cost!==void 0&&d.units>e.max_cost)throw new ve(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${d.units}`);return{id:e.id,definition_fingerprint:`sha256:${kp("sha256").update(oe(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:d,contributors:o.contributors??[]}}function cc(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let a=i.cache.get(e.id);if(a)return a;let o=jp(e,t,n,r,i).catch(s=>{if(s instanceof Fe&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},l=new Fe(s.message,c);throw l.cause=s,l}throw s});return i.cache.set(e.id,o),o}async function ji(e,t,n=[e]){return cc(e,t,n,[],{cache:new Map,charged:new Set})}function Up(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity==="monotone_nondecreasing",e-t.value)}function zp(e,t,n={}){Li(e);let r=on(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:Up(t.value,r),verdict:i?"retired":tc(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:nc(e),cost:t.cost,contributors:t.contributors}}function qp(e,t,n,r){let i=Op(e,t);if(i.size===0)return;let a=e.provider_policy,o=a?.triggers[r];if(!a||!o)throw new ve(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let l of i){if(!s.has(l))throw new ve(`assurance gate ${e.id} refuses provider ${l}`);let d=n.provider_capabilities?.[l];if(!d)throw new ve(`assurance provider ${l} has no declared capabilities`);if(c[d.cost_class]>c[o.max_cost_class])throw new ve(`assurance gate ${e.id} refuses ${d.cost_class}-cost provider ${l} at trigger ${r}`);if(d.network&&!o.allow_network)throw new ve(`assurance gate ${e.id} refuses network provider ${l} at trigger ${r}`)}}async function Zs(e,t,n,r,i){try{return await ji(n,r,i)}catch(a){if(a instanceof Fe){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new ve(`assurance gate ${e} assertion ${t} measurement ${s} source ${a.source_kind}${o} field ${a.field} could not resolve: ${a.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}});throw c.cause=a,c}throw a}}async function lc(e,t,n,r){jt(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new ve(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new ve(`assurance gate ${e} does not declare trigger ${r.trigger}`);qp(i,t,n,r.trigger);let a=await oc(i.assertion_ids,ec,async c=>{let l=t.assertions.find(f=>f.id===c),d=t.measurements.find(f=>f.id===l.measurement_id),u=n;if(l.scope.kind==="active"){let f=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(g=>!f.has(g.status))}}else if(l.scope.kind==="filter"){let f=l.scope.measurement_id,g=t.measurements.find(v=>v.id===f),h=await Zs(i.id,l.id,g,n,t.measurements),w=new Set(h.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(f=>f.id===l.owner_item_id),p=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return zp(l,await Zs(i.id,l.id,d,u,t.measurements),{owner_terminal:p})}),o=a.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=a.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":s?"warn":"pass",exit_code:o?1:0,assertions:a,assertions_total:a.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:ac(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function fr(e){return xp.join(e,"assurance.json")}async function dc(e){let t=await X(fr(e));return t===null?sn():hr(t)}function hr(e){try{return jt(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",_.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function gr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Gp(e,t){e==="measurement"?Mi(t):e==="assertion"?Li(t):rc(t)}async function cn(e,t){let n=structuredClone(gr(await dc(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Ui(e,t,n){let r=gr(await dc(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function _r(e,t,n,r={}){Gp(t,n);let i=await I(e),a=Y(r.author,i.author_default),o=await ir({pmRoot:e,filePath:fr(e),op:`assurance:${t}:put`,author:a,message:r.message,lockTtlSeconds:mr,lockWaitMs:pr,mutate:s=>{let c=s===null?sn():hr(s),l=gr(c,t),d=l.findIndex(m=>m.id===n.id),u=d<0?"created":"updated";if(t==="assertion"&&d>=0&&Cp(l[d],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new N(`loosening assertion ${n.id} requires a verified authorization_decision`)}return d<0?l.push(structuredClone(n)):l[d]=structuredClone(n),jt(c),{raw:`${JSON.stringify(c,null,2)}
|
|
1
|
+
import{a as ki,c as Wn,d as Bn,e as Qo,g as es,h as Si,i as ts,j as At,k as Rt,l as ns,m as rs,n as Ei,o as is,p as It,q as Ct,r as as,s as os,t as Ai}from"./chunk-EUEGXZ2A.js";import{e as Xn,f as Ri}from"./chunk-XYNBXTDQ.js";import{B as Kn,a as Jo,g as bi,i as Vo}from"./chunk-C5IW2NDA.js";import{Z as Ys,l as Vs,n as Ks}from"./chunk-V5XTGLK7.js";import{$ as Us,Aa as Hs,Ba as Js,Da as Di,I as lr,J as Os,K as $i,L as an,N as Ti,R as Ds,S as Ps,T as Ns,U as Ms,V as dr,X as Ls,Y as Fs,Z as js,_ as ht,aa as Nt,ba as zs,ca as Oi,da as Mt,e as Rs,ea as qs,f as Is,fa as Gs,g as Cs,t as nn,u as $s,ua as Ws,v as rn,va as ur,w as Ts,za as Bs}from"./chunk-3TKWMNKF.js";import{a as Ko,b as Hn,c as xi,d as Yo,e as Xo,f as We,g as Jn,h as Zo,i as it}from"./chunk-EX6MKP2X.js";import{$a as bs,Ab as As,Ba as _s,Na as ys,Sa as ue,Ta as nr,U as Y,Ua as ws,V as $,Va as Ci,Wa as rr,Xa as ir,Ya as ar,Za as vs,_ as de,_a as Te,ab as I,b as ms,bb as or,d as ps,db as ks,ea as hs,fa as Qn,ia as er,ib as xs,ja as gs,jb as Ss,l as z,ma as $t,o as re,oa as Tt,ob as sr,q as He,qb as Es,r as fs,ra as tr,rb as Ot,s as Zn,sb as Dt,tb as Pt,ub as Je,vb as cr,yb as ft,za as Ii}from"./chunk-5AF3ZBNB.js";import{Ba as vi,Ca as Bo,Da as Ho,E as Lo,Ea as Et,F as Fo,G as q,Ga as Ne,Ia as Me,Ka as se,L as tn,La as Ae,M as L,N as pt,Na as we,O as qn,Oa as Le,P as K,R as jo,S as Gn,Sa as Be,Ua as Vn,W as Z,Ya as Yn,Z as Uo,Za as ls,_a as ds,a as Co,ba as zo,d as $o,e as To,ea as _i,ga as yi,h as St,p as gi,q as A,r as zn,s as j,sa as qo,t as X,ta as Go,u as le,x as ye,y as Ee,z as Mo}from"./chunk-UI6AJ5TD.js";import{b as us}from"./chunk-WGHQVU6P.js";import{N as Oo,P as Do,R as Po,U as No,V as Un,Y as _,Z as y,a as Fn,aa as oe,ba as Wo,ca as wi,d as jn,fa as ss,oa as cs,t as hi}from"./chunk-2PN4TJXH.js";(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]="d2d5135a-8110-527e-8530-653b25b792a4")}catch{}})();var N=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},ve=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Fe=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function Lt(e){try{return await e()}catch(t){throw t instanceof N?new y(t.message,_.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Xs(e){try{return await e()}catch(t){throw t instanceof ve?new y(t.message,_.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as kp}from"node:crypto";import xp 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]="b911b43d-d14d-5e4f-a35e-5020b1a84542")}catch{}})();var Ft=1e3;(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]="2bf52d6d-7e4f-5ec5-86bd-3e817ef521bb")}catch{}})();var Qs=1,gt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],Pi=["items","dependency_kind","graph","validate","health","history","links","provider","derived"],Sp=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Ep=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,mr=30,pr=5e3,ec=4,Ap=50;function Ve(e,t){if(!Ep.test(e))throw new N(`${t} must be a stable lowercase id`)}function Rp(e,t){if(!Number.isFinite(e)||e<0)throw new N(`${t} must be a finite non-negative number`)}function on(e){let t=Sp.filter(i=>e[i]!==void 0);if(t.length!==1)throw new N(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function Ni(e,t){return oe(e)===oe(t)}function tc(e,t){if(t.polarity==="equals")return Ni(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function nc(e){let t=on(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>tc(r.observed,t)===(r.expected==="pass"))}function Ip(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!Ni(e.value,t.value)}function Cp(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||oe(e.scope)!==oe(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Ip(on(e),on(t))||n[t.enforcement]<n[e.enforcement]||r}function $p(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new N("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new N("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new N("items source equals/state requires field")}function Mi(e){Ve(e.id,"measurement.id"),e.max_cost!==void 0&&Rp(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new N(`measurement.source.kind must be one of ${Pi.join(", ")}`);let n=Reflect.get(t,"kind");if(!Pi.includes(n))throw new N(`measurement.source.kind must be one of ${Pi.join(", ")}`);let r=t;if(r.kind==="items"&&$p(r),r.kind==="dependency_kind"&&(typeof r.dependency_kind!="string"||r.dependency_kind.trim().length===0))throw new N("dependency_kind source requires dependency_kind");if((r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new N(`${r.kind} source requires field`);return r.kind==="provider"&&(Ve(r.provider,"provider source provider"),Ve(r.key,"provider source key")),e}function Li(e){if(Ve(e.id,"assertion.id"),Ve(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new N("assertion.owner_item_id is required");let t=on(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new N(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new N("retired assertion requires retire_reason");e.scope.kind==="filter"&&Ve(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new N("assertion negative control requires pass and fail cases");if(!nc(e))throw new N(`assertion ${e.id} negative control does not prove its bound`);return e}function Tp(e){if(!Array.isArray(e.allowed_providers))throw new N("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)Ve(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new N("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!gt.includes(t))throw new N(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new N(`gate provider policy trigger ${t} is invalid`)}}function rc(e){if(Ve(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new N("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new N("gate requires at least one assertion");for(let t of e.assertion_ids)Ve(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new N(`gate.triggers is required and must be an array of ${gt.join(", ")}`);if(e.triggers.length===0)throw new N("gate requires at least one trigger");for(let t of e.triggers)if(!gt.includes(t))throw new N(`gate trigger must be one of ${gt.join(", ")}`);return e.provider_policy&&Tp(e.provider_policy),e}function jt(e){if(e.version!==Qs)throw new N(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Mi(r),t.has(`measurement:${r.id}`))throw new N(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(Li(r),t.has(`assertion:${r.id}`))throw new N(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){rc(r);let i=r.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(i.length>0)throw new N(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new N(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of ic(e))if(!n.has(r))throw new N(`${i.join(", ")} references missing measurement ${r}`);return e}function Fi(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)Fi(n,t)}function ic(e){let t=new Map,n=(r,i)=>{let a=t.get(r)??[];a.push(i),t.set(r,a)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];Fi(r.source.expression,i);for(let a of i)n(a,`derived measurement ${r.id}`)}return t}function Op(e,t){let n=e.assertion_ids.flatMap(a=>{let o=t.assertions.find(s=>s.id===a);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let a=n.pop();if(r.has(a))continue;r.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?i.add(o.source.provider):o.source.kind==="derived"&&Fi(o.source.expression,n)}return i}function sn(){return{version:Qs,measurements:[],assertions:[],gates:[]}}function Dp(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let a=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?a:!a}return Ni(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Pp(e,t){let n=[],r=yi(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let a of i.dependencies??[])(yi(a.kind)??a.kind.trim().toLowerCase())===r&&n.push(`${i.id}->${a.id}`);return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Np(e,t){return{value:t.history.filter(r=>(e.op===void 0||r.op===e.op)&&(e.author===void 0||r.author===e.author)&&(e.harness===void 0||r.agent_harness===e.harness)&&(e.model===void 0||r.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function Mp(e,t){let n=t.items.filter(r=>{let i=r[e.link],a=Array.isArray(i)&&i.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Lp(e,t){let n=e.source;return n.kind==="items"?Dp(n,t):n.kind==="dependency_kind"?Pp(n,t):n.kind==="history"?Np(n,t):n.kind==="links"?Mp(n,t):null}function ac(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function Fp(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function oc(e,t,n){let r=new Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o],o)}});return await Promise.all(a),r}async function sc(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(l=>l.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await cc(o,t,n,r,i);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=i.charged.has(o.id)?[]:[s.cost];return i.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await oc(e.operands,ec,o=>sc(o,t,n,r,i));return{value:Fp(e.operator,a.map(o=>o.value)),costs:a.flatMap(o=>o.costs),population_size:Math.max(0,...a.map(o=>o.population_size)),contributors:[...new Set(a.flatMap(o=>o.contributors))]}}async function jp(e,t,n,r,i){Mi(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await sc(e.source.expression,t,n,[...r,e.id],i);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Lp(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let l={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-a},d=ac([...s,l],Date.now()-a);if(e.max_cost!==void 0&&d.units>e.max_cost)throw new ve(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${d.units}`);return{id:e.id,definition_fingerprint:`sha256:${kp("sha256").update(oe(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:d,contributors:o.contributors??[]}}function cc(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let a=i.cache.get(e.id);if(a)return a;let o=jp(e,t,n,r,i).catch(s=>{if(s instanceof Fe&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},l=new Fe(s.message,c);throw l.cause=s,l}throw s});return i.cache.set(e.id,o),o}async function ji(e,t,n=[e]){return cc(e,t,n,[],{cache:new Map,charged:new Set})}function Up(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity==="monotone_nondecreasing",e-t.value)}function zp(e,t,n={}){Li(e);let r=on(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:Up(t.value,r),verdict:i?"retired":tc(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:nc(e),cost:t.cost,contributors:t.contributors}}function qp(e,t,n,r){let i=Op(e,t);if(i.size===0)return;let a=e.provider_policy,o=a?.triggers[r];if(!a||!o)throw new ve(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let l of i){if(!s.has(l))throw new ve(`assurance gate ${e.id} refuses provider ${l}`);let d=n.provider_capabilities?.[l];if(!d)throw new ve(`assurance provider ${l} has no declared capabilities`);if(c[d.cost_class]>c[o.max_cost_class])throw new ve(`assurance gate ${e.id} refuses ${d.cost_class}-cost provider ${l} at trigger ${r}`);if(d.network&&!o.allow_network)throw new ve(`assurance gate ${e.id} refuses network provider ${l} at trigger ${r}`)}}async function Zs(e,t,n,r,i){try{return await ji(n,r,i)}catch(a){if(a instanceof Fe){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new ve(`assurance gate ${e} assertion ${t} measurement ${s} source ${a.source_kind}${o} field ${a.field} could not resolve: ${a.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}});throw c.cause=a,c}throw a}}async function lc(e,t,n,r){jt(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new ve(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new ve(`assurance gate ${e} does not declare trigger ${r.trigger}`);qp(i,t,n,r.trigger);let a=await oc(i.assertion_ids,ec,async c=>{let l=t.assertions.find(f=>f.id===c),d=t.measurements.find(f=>f.id===l.measurement_id),u=n;if(l.scope.kind==="active"){let f=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(g=>!f.has(g.status))}}else if(l.scope.kind==="filter"){let f=l.scope.measurement_id,g=t.measurements.find(v=>v.id===f),h=await Zs(i.id,l.id,g,n,t.measurements),w=new Set(h.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(f=>f.id===l.owner_item_id),p=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return zp(l,await Zs(i.id,l.id,d,u,t.measurements),{owner_terminal:p})}),o=a.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=a.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":s?"warn":"pass",exit_code:o?1:0,assertions:a,assertions_total:a.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:ac(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function fr(e){return xp.join(e,"assurance.json")}async function dc(e){let t=await X(fr(e));return t===null?sn():hr(t)}function hr(e){try{return jt(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",_.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function gr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Gp(e,t){e==="measurement"?Mi(t):e==="assertion"?Li(t):rc(t)}async function cn(e,t){let n=structuredClone(gr(await dc(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Ui(e,t,n){let r=gr(await dc(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function _r(e,t,n,r={}){Gp(t,n);let i=await I(e),a=Y(r.author,i.author_default),o=await ir({pmRoot:e,filePath:fr(e),op:`assurance:${t}:put`,author:a,message:r.message,lockTtlSeconds:mr,lockWaitMs:pr,mutate:s=>{let c=s===null?sn():hr(s),l=gr(c,t),d=l.findIndex(m=>m.id===n.id),u=d<0?"created":"updated";if(t==="assertion"&&d>=0&&Cp(l[d],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new N(`loosening assertion ${n.id} requires a verified authorization_decision`)}return d<0?l.push(structuredClone(n)):l[d]=structuredClone(n),jt(c),{raw:`${JSON.stringify(c,null,2)}
|
|
2
2
|
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function zi(e,t,n={}){let r=sn();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),jt(r);let i=await I(e),a=Y(n.author,i.author_default),o=await ir({pmRoot:e,filePath:fr(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:mr,lockWaitMs:pr,mutate:s=>{let c=s===null?sn():hr(s),l=[],d=[],u=(m,p,f)=>{for(let g of p){let h=m.find(w=>w.id===g.id);if(!h){m.push(structuredClone(g)),l.push(`${f}:${g.id}`);continue}if(oe(h)!==oe(g))throw new N(`assurance bundle refuses to replace divergent ${f} ${g.id}`);d.push(`${f}:${g.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),jt(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
3
|
`,result:{changed:l.length>0,created_ids:l,unchanged_ids:d}}}});return{...o.result,changed:o.changed}}async function uc(e,t,n,r={}){let i=await I(e),a=Y(r.author,i.author_default),o=await ir({pmRoot:e,filePath:fr(e),op:`assurance:${t}:remove`,author:a,message:r.message,lockTtlSeconds:mr,lockWaitMs:pr,mutate:s=>{let c=s===null?sn():hr(s);if(t==="measurement"){let u=ic(c).get(n);if(u&&u.length>0)throw new N(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new N(`assurance assertion ${n} is referenced by gate`);let l=gr(c,t),d=l.findIndex(u=>u.id===n);if(d<0)throw new N(`assurance ${t} ${n} not found`);return l.splice(d,1),jt(c),{raw:`${JSON.stringify(c,null,2)}
|
|
4
4
|
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function mc(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await I(e);await rr({pmRoot:e,op:"assurance:gate:verdict",author:Y(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:mr,lockWaitMs:pr})}async function pc(e,t={}){let n=t.limit??Ap;if(!Number.isInteger(n)||n<1||n>Ft)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${Ft}`);return(await tr(nr(e),ue)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,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]="05c29627-6763-5aee-8579-71e563a98780")}catch{}})();var wr=["software-delivery","research","agent-evaluation","operations"];function fc(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function yr(e,t,n,r,i){let a=`preset-${e}`,o=i.map(c=>({id:`${a}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),s=o.map(c=>fc(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:s,gates:[{id:`${a}-readiness`,description:n,assertion_ids:s.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function vr(e,t){return e==="software-delivery"?yr(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?yr(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?yr(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):yr(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function hc(e,t,n,r={}){return zi(e,vr(t,n).declarations,r)}async function gc(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(a=>!n.has(a.status))};return await Promise.all(["files","tests","docs"].map(async a=>{let o={id:`derived-active-missing-${a}`,description:`Observed active items missing ${a} evidence.`,source:{kind:"links",link:a,state:"missing"}},c=(await ji(o,r)).value,l=fc(`${o.id}-ceiling`,o.id,t,c,"observe"),d=`active-missing-${a}`;return{id:d,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[o],assertions:[l],gates:[{id:`derived-${d}`,description:`Observe the accepted ${a} evidence baseline.`,assertion_ids:[l.id],triggers:["ci","scheduled"]}]}}}))}function _c(e,t,n={}){return zi(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function yc(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return _r(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import bc from"node:fs/promises";import{createRequire as Wp}from"node:module";import be 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]="c21b1a94-1d80-57c0-b090-c4831fc505a2")}catch{}})();function wc(e,t){let n=be.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${be.sep}`)&&!be.isAbsolute(n))return n.split(be.sep).join("/");let r=be.resolve(e),i=0xcbf29ce484222325n;for(let o=0;o<r.length;o+=1)i^=BigInt(r.charCodeAt(o)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${be.basename(be.dirname(e))}/package.json`}function Bp(e){return e.includes(`${be.sep}.pnpm${be.sep}`)?"pnpm":e.includes(`${be.sep}node_modules${be.sep}`)?"npm":"other"}async function vc(e){try{let t=JSON.parse(await bc.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function qi(e){try{return await bc.realpath(e)}catch{return be.resolve(e)}}async function kc(e,t,n=Ee(import.meta.url,["../../.."])){let r=await qi(t),i=await qi(be.join(n,"package.json")),a=await vc(i),o=new Map;a!==void 0&&o.set(i,{version:a,path:wc(i,r),layout:"host",consumers:["pm-cli-host"]});for(let l of e)try{let d=Wp(l.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await qi(d),m=await vc(u);if(m===void 0)continue;let p=u,f=o.get(p);if(f){f.consumers.includes(l.name)||(f.consumers.push(l.name),f.consumers.sort((g,h)=>g.localeCompare(h)));continue}o.set(p,{version:m,path:wc(u,r),layout:Bp(u),consumers:[l.name]})}catch{}let s=[...o.values()].sort((l,d)=>l.path.localeCompare(d.path)),c=a===void 0?[]:s.filter(l=>l.version!==a);return{host_version:a??null,copies:s,mismatches:c,warnings:c.map(l=>`extension_host_pm_cli_version_skew:${a}:${l.version}:${l.consumers.join("+")}`)}}import{createHash as $c}from"node:crypto";import dn from"node:fs/promises";import un from"node:path";import{Option as gE}from"commander";(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]="8d60b13c-c58a-506f-adc9-2414dd69edef")}catch{}})();function Hp(e,t){let n=[],r=new Set;for(let i of t.keys){if(!Object.hasOwn(e,i))continue;let a=e[i];if(a!=null){if(typeof a=="string"){n.push(a);continue}if(!Array.isArray(a)||!a.every(o=>typeof o=="string"))return;r.has(a)||(r.add(a),n.push(...a))}}return n.length>0?n.join("; "):void 0}function br(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function P(e,t){return e[t]===!0?!0:void 0}function Ke(e,t){return e[t]===!1?!0:void 0}function xc(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Sc(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function Ec(e){let t=i=>bi(e,br(Xn,i)),n=i=>Vo(e,br(Ri,i)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:Hp(e,br(Ri,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),allowUnresolvedDeps:xc(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:P(e,"replaceDeps"),replaceTests:P(e,"replaceTests"),replaceFiles:P(e,"replaceFiles"),replaceDocs:P(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:P(e,"clearDeps"),clearComments:P(e,"clearComments"),clearNotes:P(e,"clearNotes"),clearLearnings:P(e,"clearLearnings"),clearFiles:P(e,"clearFiles"),clearTests:P(e,"clearTests"),clearDocs:P(e,"clearDocs"),clearReminders:P(e,"clearReminders"),clearEvents:P(e,"clearEvents"),clearTypeOptions:P(e,"clearTypeOptions")};return Sc(r,e),r}function Q(e,t){let n=br(Jo,t),r=bi(e,n);if(r!==void 0)return r;for(let i of n.keys){let a=e[i];if(Array.isArray(a)){let o=a.filter(s=>typeof s=="string");if(o.length>0)return o.join(",")}if(t==="ids"&&typeof a=="string")return a;if(typeof a=="number"&&Number.isFinite(a))return String(a)}}function Jp(e){let t=P(e,"filterFilesMissing"),n=P(e,"filterDocsMissing");return{filterReviewerMissing:P(e,"filterReviewerMissing"),filterRiskMissing:P(e,"filterRiskMissing"),filterConfidenceMissing:P(e,"filterConfidenceMissing"),filterSprintMissing:P(e,"filterSprintMissing"),filterReleaseMissing:P(e,"filterReleaseMissing"),hasNotes:P(e,"hasNotes"),hasLearnings:P(e,"hasLearnings"),hasFiles:P(e,"hasFiles"),hasDocs:P(e,"hasDocs"),hasTests:P(e,"hasTests"),hasComments:P(e,"hasComments"),hasDeps:P(e,"hasDeps"),hasBody:P(e,"hasBody"),hasLinkedCommand:P(e,"hasLinkedCommand"),noNotes:Ke(e,"notes"),noLearnings:Ke(e,"learnings"),noFiles:Ke(e,"files")??t,filterFilesMissing:t,noDocs:Ke(e,"docs")??n,filterDocsMissing:n,noTests:Ke(e,"tests"),noComments:Ke(e,"comments"),noDeps:Ke(e,"deps"),emptyBody:P(e,"emptyBody"),noLinkedCommand:Ke(e,"linkedCommand")}}function Gi(e){let t={status:Q(e,"status"),type:Q(e,"type"),tag:Q(e,"tag"),priority:Q(e,"priority"),deadlineBefore:Q(e,"deadlineBefore"),deadlineAfter:Q(e,"deadlineAfter"),updatedAfter:Q(e,"updatedAfter"),updatedBefore:Q(e,"updatedBefore"),createdAfter:Q(e,"createdAfter"),createdBefore:Q(e,"createdBefore"),today:P(e,"today"),recent:P(e,"recent"),ids:Q(e,"ids"),assignee:Q(e,"assignee"),assigneeFilter:Q(e,"assigneeFilter"),parent:Q(e,"parent"),sprint:Q(e,"sprint"),release:Q(e,"release"),limit:Q(e,"limit"),offset:Q(e,"offset"),noTruncate:Ke(e,"truncate"),includeBody:P(e,"includeBody"),strictRead:P(e,"strictRead"),compact:P(e,"compact"),brief:P(e,"brief"),full:P(e,"full"),fields:Q(e,"fields"),sort:Q(e,"sort"),order:Q(e,"order"),tree:P(e,"tree"),treeDepth:Q(e,"treeDepth"),filterAcMissing:P(e,"filterAcMissing"),filterEstimatesMissing:xc(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:P(e,"filterResolutionMissing"),filterMetadataMissing:P(e,"filterMetadataMissing"),...Jp(e)};return Sc(t,e),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]="0e153ece-4fc0-5134-97f0-c2315aff0031")}catch{}})();function C(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function ee(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Vp(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Hi(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new y(`${t} must be a finite integer.`,_.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new y(`${t} must be a finite integer.`,_.USAGE);return n}}function EE(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:C(e,"limit")??C(t,"limit")}function AE(e){let t=C(e,"outputFormat");return{json:!0,quiet:!0,author:C(e,"author"),path:C(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:C(e,"outputInclude"),outputLimit:ee(e,"outputLimit"),outputBudget:ee(e,"outputBudget"),outputSession:C(e,"outputSession"),outputCursor:C(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Kp=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Yp=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),Xp=new Set(["files","files-discover","docs","test","test-all"]),Zp=new Set(["claim","release","start-task","pause-task","close-task"]),Qp={list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt"],append:["body"]},ef=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Rc(e,t){let n={},r=t!==void 0&&Xp.has(t),i=t==="files"||t==="files-discover"||t==="docs";for(let[a,o]of Object.entries(e)){if(Array.isArray(o)&&Kp.has(a)){n[a]=o.join(",");continue}if(a==="note"&&i){n[a]=o;continue}if(typeof o=="string"&&Yp.has(a)){n[a]=[o];continue}if(typeof o=="string"&&r&&(a==="add"||a==="remove")){n[a]=[o];continue}n[a]=o}return n}function RE(e,t){let n=zo(e.options),r={},i=c=>{n[c]!==void 0||e[c]===void 0||(r[c]=e[c])};for(let c of Qp[t??""]??[])i(c);for(let c of ef)i(c);let a=Rc({...r,...n},t),o=C(e,"author"),s=t!==void 0&&Zp.has(t)?C(e,"assignee")??C(a,"assignee"):void 0;return o&&a.author===void 0?{...a,author:o}:s&&a.author===void 0?{...a,author:s}:a}function IE(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function CE(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function $E(e){let t=[],n=!0;for(let r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function TE(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function Ji(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function OE(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[a,o]of Object.entries(e))n.has(a)||(r[a]=o);let i={...r,...t};return delete i.args,i}function DE(e,t){return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:{...t}}}function Bi(e){return{type:ee(e,"filterType"),tag:ee(e,"filterTag"),priority:ee(e,"filterPriority"),deadlineBefore:ee(e,"filterDeadlineBefore"),deadlineAfter:ee(e,"filterDeadlineAfter"),updatedAfter:ee(e,"filterUpdatedAfter"),updatedBefore:ee(e,"filterUpdatedBefore"),createdAfter:ee(e,"filterCreatedAfter"),createdBefore:ee(e,"filterCreatedBefore"),ids:Vp(e,"ids"),assignee:ee(e,"filterAssignee"),assigneeFilter:ee(e,"filterAssigneeFilter")??ee(e,"filterAssignee_filter"),parent:ee(e,"filterParent"),sprint:ee(e,"filterSprint"),release:ee(e,"filterRelease"),limit:ee(e,"limit"),offset:ee(e,"offset")}}function Wi(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return Ji(e)}function kr(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function PE(e){let t=Wi(e.kind),n=Wi(e.exemptIsolate),r=Wi(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:kr(e.maxDepth),limit:kr(e.limit),after:C(e,"after"),direction:C(e,"direction"),maxPaths:kr(e.maxPaths),sample:kr(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function NE(e){return{status:C(e,"filterStatus"),list:ln(e.list)?Gi(e.list):Bi(e),reason:C(e,"reason"),resolution:C(e,"resolution"),expectedResult:C(e,"expectedResult")??C(e,"expected_result")??C(e,"expected"),actualResult:C(e,"actualResult")??C(e,"actual_result")??C(e,"actual"),validateClose:C(e,"validateClose")??C(e,"validate_close"),author:C(e,"author"),message:C(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:C(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var tf=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function Ac(e){let t={};for(let[n,r]of Object.entries(e))tf.has(n)||(t[n]=r);return Ic(t)}function Ic(e){let t=Rc(e,"update-many");for(let n of Xn)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return Ec(t)}function ME(e){if(ln(e.list)||ln(e.update)){let t=ln(e.update)?e.update:Ac(e);return{status:ee(e,"filterStatus"),list:ln(e.list)?Gi(e.list):Bi(e),update:Ic(t),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:C(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:ee(e,"filterStatus"),list:Bi(e),update:Ac(e),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:C(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 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]="b389e521-f689-5895-a5f4-08c3866b3ea3")}catch{}})();function Re(e,t){throw new y(e,_.USAGE,t)}var nf="2026-07-15T06:22:12.276Z",rf=Date.parse(nf),af=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Cc=e=>typeof e=="string"?e:"",Tc=e=>{let t=e??{},n=Cc(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Cc(t.ts))>=rf);return af[r][i]};function Oc(e,t,n=20,r=new Set,i=!1){let a=[],o=[],s={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,p]of t.split(/\r?\n/).entries()){let f;try{f=JSON.parse(p)}catch{continue}l+=1;let g=Tc(f);if(g!=="attributed"){if(d+=1,g==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}s[g]+=1,i&&g==="actionable_unknown"&&o.push({item_id:e,line:m+1}),a.length<c&&a.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:s.legacy_unknown,actionable_unknown_event_count:s.actionable_unknown,acknowledged_actionable_event_count:u,samples:a,samples_truncated:s.legacy_unknown+s.actionable_unknown>a.length,actionable_events:o}}var HE=(e,t,n=20,r=new Set)=>Oc(e,t,n,r);function Dc(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let a=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof a!="object"||a===null||!Array.isArray(a.events)))for(let o of a.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var mn=async(e,t=20,n=!1)=>{let r=un.join(e,"history"),i;try{i=(await dn.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let a=new Set,o=[],s=[],c=0,l=0,d=0,u=0,m=0,p=0,f="_workspace.jsonl",g=new Set;if(i.includes(f))try{g=Dc(await dn.readFile(un.join(r,f),"utf8"))}catch{g=new Set}for(let w of i){let v;try{v=await dn.readFile(un.join(r,w),"utf8")}catch{continue}let b=w.slice(0,-6),x=Oc(b,v,t-o.length,g,n);c+=1,l+=x.checked_events,d+=x.unknown_event_count,u+=x.legacy_unknown_event_count,m+=x.actionable_unknown_event_count,p+=x.acknowledged_actionable_event_count,x.unknown_event_count>0&&a.add(b),o.push(...x.samples),n&&s.push(...x.actionable_events)}let h=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:p,affected_item_ids:[...a].sort((w,v)=>w.localeCompare(v)),samples:o,samples_truncated:h>o.length,...n?{actionable_events:s}:{}}};function of(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function sf(e){try{return Dc(await dn.readFile(un.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function cf(e){return(e.item_id===ue||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function lf(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Re(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Tc(i)!=="actionable_unknown"&&Re(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:$c("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Pc(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Re("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Re("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Re("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let a=of(t.all_actionable===!0?(await mn(e,0,!0)).actionable_events:r),o=await sf(e),s=new Map;for(let m of a)if(cf(m)||Re(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!s.has(m.item_id))try{s.set(m.item_id,(await dn.readFile(un.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Re(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=a.map(m=>lf(m,o,s.get(m.item_id))),l=t.all_actionable===!0?"all_actionable":"events",d=$c("sha256").update(JSON.stringify({version:1,selection:l,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:l},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:d},completeCoordinates:c}}async function JE(e,t,n=50){return(await Pc(e,t,n)).plan}function df(e,t){let n=e.length>0;return n&&t&&Re("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&Re("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:uf(e),all_actionable:t}}function uf(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),a=r===ue||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!a||!Number.isSafeInteger(i)||i<1)&&Re(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function VE(e,t){let n=df(Ji(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return mf(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:C(t,"planFingerprint")??C(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:C(t,"attributedAuthor")??C(t,"attributed_author")??void 0,reviewer:C(t,"reviewer"),reason:C(t,"reason")})}async function mf(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",a=await Pc(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:_.SUCCESS,plan:a.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Re("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Re("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==a.plan.plan_fingerprint)throw new y("Author acknowledgment selection changed after preview; no history was mutated.",_.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let s=a.completeCoordinates.filter(({disposition:u})=>a.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:m})=>({item_id:u,line:m}));if(s.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:_.NO_EFFECT,plan:a.plan};let c=await I(e),l=await rr({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:s,attributed_author:r}},message:i,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),d=a.plan.actionable_count>0&&a.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:_.PARTIAL_EFFECT}:{outcome:"effect",exit_code:_.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:s.length,...d,plan:a.plan,history_path:l.historyPath}}import Vi from"node:fs/promises";import Ki 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]="6efed404-acd2-5c3a-a008-856df67c8b77")}catch{}})();var pf=8388608,ff=new Set(["resolved","failed"]),hf=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yi(e){return hf.find(t=>t.matches(e))?.kind}function ZE(e){let t=new Map,n=0,r=0;return{entries:e.map(a=>{let o=je(a.agent_provenance)?a.agent_provenance:void 0;if(o===void 0)return a;let s={},c=!1;for(let[d,u]of Object.entries(o)){let m=je(u)?Yi(u.value):void 0;if(m===void 0){s[d]=u;continue}c=!0,r+=1;let p=a.agent_harness??"unknown",f=`${p}\0${d}\0${m}`,g=t.get(f)??{harness:p,dimension:d,kind:m,count:0};g.count+=1,t.set(f,g)}if(!c)return a;n+=1;let l={...a};return Object.keys(s).length===0?delete l.agent_provenance:l.agent_provenance=s,l}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((a,o)=>a.harness.localeCompare(o.harness)||a.dimension.localeCompare(o.dimension)||a.kind.localeCompare(o.kind))}}}async function QE(e){let t=[];for(let n of await Nc(e))try{let r=await Vi.readFile(Ki.join(e,"history",n),"utf8");for(let i of r.split(`
|
|
5
5
|
`)){if(i.trim().length===0)continue;let a=Mc(i);if(a===null||!je(a.agent_provenance))continue;if(Object.values(a.agent_provenance).some(s=>je(s)&&Yi(s.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Nc(e){try{return(await Vi.readdir(Ki.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function gf(e,t,n){let r;try{r=await Vi.open(Ki.join(e,"history",t),"r");let i=(await r.stat()).size,a=Math.min(i,Math.max(0,n)),o=Buffer.alloc(a),{bytesRead:s}=await r.read(o,0,a,0),c=o.subarray(0,s).toString("utf8"),l=s>=i,d=c.lastIndexOf(`
|
|
6
6
|
`),u=c;return l||(u=d===-1?"":c.slice(0,d+1)),{content:u,bytesRead:s,complete:l}}catch{return null}finally{await r?.close()}}function Mc(e){try{let t=JSON.parse(e);return je(t)?t:null}catch{return null}}function _f(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=je(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([o,s])=>{if(!je(s))return;let c=Yi(s.value);if(!c)return;let l=`${r}\0${o}\0${c}`,d=n.get(l)??{harness:r,dimension:o,kind:c,count:0};d.count+=1,n.set(l,d)}),!je(e.context))return;let a=e.context.agent_provenance_outcomes;je(a)&&Object.entries(a).forEach(([o,s])=>{if(!je(s)||typeof s.resolver!="string"||!ff.has(String(s.status)))return;let c=`${r}\0${o}\0${s.resolver}`,l=t.get(c)??{harness:r,dimension:o,resolver:s.resolver,attempts:0,successes:0};l.attempts+=1,s.status==="resolved"&&(l.successes+=1),t.set(c,l)})}function yf(e,t,n,r,i){let a=i;for(let o of e.split(`
|
|
7
|
-
`)){if(o.trim().length===0)continue;if(a>=r)return{eventsRead:a,truncated:!0};a+=1;let s=Mc(o);s&&_f(s,t,n)}return{eventsRead:a,truncated:!1}}async function Lc(e,t=1e4){let n=new Map,r=new Map,i=0,a=0,o=!1;for(let l of await Nc(e)){let d=await gf(e,l,Math.max(0,pf-a));if(d===null)continue;a+=d.bytesRead;let u=yf(d.content,n,r,t,i);if(i=u.eventsRead,u.truncated){o=!0;break}if(!d.complete){o=!0;break}}let s=[...n.values()].sort((l,d)=>l.harness.localeCompare(d.harness)||l.dimension.localeCompare(d.dimension)||l.resolver.localeCompare(d.resolver)),c=[...r.values()].sort((l,d)=>l.harness.localeCompare(d.harness)||l.dimension.localeCompare(d.dimension)||l.kind.localeCompare(d.kind));return{outcomes:s,invalid_values:c,warnings:o?[]:[...s.filter(l=>l.attempts>0&&l.successes===0).map(l=>`provenance_resolver_zero_success:${l.harness}:${l.dimension}:${l.resolver}:${String(l.attempts)}`),...c.map(l=>`provenance_value_domain_invalid:${l.harness}:${l.dimension}:${l.kind}:${String(l.count)}`)],events_read:i,truncated:o}}import tt from"node:fs/promises";import fe from"node:path";import Ut from"node:fs/promises";import{createHash as wf}from"node:crypto";import jc 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]="32538934-2cbb-50fe-b721-ad9197cef7d8")}catch{}})();var Uc=4,vf="history-drift-cache.json";function zc(e){return jc.join(e,"runtime",vf)}async function bf(e){try{let t=await Ut.readFile(zc(e),"utf8"),n=JSON.parse(t);return n.version!==Uc||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}async function kf(e,t,n,r,i){let a=nr(e),o;try{o=await Ut.stat(a)}catch(l){return j(l)||i.unreadableStreams.push(ue),!1}let s=i.missingStreams.length,c=await Gc({itemId:ue,historyPath:a,stat:o,cached:t[ue],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.chainOk||i.chainMismatches.push(ue),n[ue]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(i.missingStreams.splice(s),c.cacheDirty)}function qc(e){return wf("sha256").update(e).digest("hex")}async function xf(e){let t=await Ut.readFile(e,"utf8");return qc(t)}async function Sf(e){let t=await Ut.readFile(e,"utf8"),n=qc(t);if(t.trim().length===0)return null;let r=[],i=null;for(let o of t.split(/\r?\n/)){let s=o.trim();if(s.length===0)continue;let c=JSON.parse(s);if(typeof c.after_hash!="string"||c.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(c),i=c.after_hash}if(!i)return null;let a=ys(r);return{latestAfterHash:i,chainOk:a.ok,contentHash:n,itemHashVersion:a.item_hash_version??Ii}}function Ef(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Fc(e,t,n){try{let r=await Sf(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Gc(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Ef(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Fc(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await xf(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else r=t;return!e.verifyCacheHitByContent||r===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:r,itemHashVersion:e.cached.item_hash_version??Ii},cacheDirty:!1}:{verification:await Fc(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function Af(e,t,n,r){let i=Gn(e,t.id),a;try{a=await Ut.stat(i)}catch(d){return(j(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let o=await Gc({itemId:t.id,historyPath:i,stat:a,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!o.verification)return o.cacheDirty;o.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:o.verification.contentHash,latest_after_hash:o.verification.latestAfterHash,chain_ok:o.verification.chainOk,item_hash_version:o.verification.itemHashVersion};let{body:s,...c}=t;return _s({metadata:c,body:s},o.verification.itemHashVersion)!==o.verification.latestAfterHash&&r.hashMismatches.push(t.id),o.cacheDirty}async function Rf(e,t){if(!(t.unreadableStreams.includes(ue)||t.chainMismatches.includes(ue)))try{let n=await ws(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(ue)}}async function xr(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},a=(await bf(e))?.entries??{},o={},s=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:a,nextEntries:o,verifyCacheHitByContent:c};for(let m of t)await Af(e,m,l,r)&&(s=!0);let d=await kf(e,a,o,c,r);if(s||=d,await Rf(e,r),s||Object.keys(a).length!==Object.keys(o).length){let m=zc(e);try{await Ut.mkdir(jc.dirname(m),{recursive:!0}),await le(m,JSON.stringify({version:Uc,entries:o}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[ue]:[]])].sort((m,p)=>m.localeCompare(p));return{...r,driftedItems:u}}import pn from"node:fs/promises";import Sr 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]="79f9ccbd-48d1-5eb3-82ae-3dd62427041c")}catch{}})();function If(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:a,ttl_seconds:o}=n;return typeof r!="string"||typeof i!="string"||typeof a!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:r,owner:i,created_at:a,ttl_seconds:o}}function Wc(e,t,n){let r=If(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let a=n-i,o=Math.floor(a/1e3),s=a>r.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:o,stale:s,reason:s?"expired":"active"}}}async function Bc(e,t){let n=t??Date.now(),r=Sr.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},a;try{a=(await pn.readdir(r)).filter(s=>s.endsWith(".lock")).sort()}catch(o){if(j(o))return i;throw o}for(let o of a){let s;try{s=await pn.readFile(Sr.join(r,o),"utf8")}catch(l){if(j(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=Wc(o,s,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function Hc(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Sr.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await pn.readdir(a)).filter(l=>l.endsWith(".lock")).sort()}catch(c){if(j(c))return o;throw c}for(let c of s){o.scanned+=1;let l=Sr.join(a,c),d=`locks/${c}`;if(r?.onRead){let p=await r.onRead(l);o.warnings.push(...p)}let u;try{u=await pn.readFile(l,"utf8")}catch(p){if(j(p)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${c}`),o.retained.push(d),o.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=Wc(c,u,i);if(m.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}if(m.detail==="active"){o.retained.push(d),o.entries.push(m.entry);continue}if(!n){try{await pn.unlink(l)}catch(p){if(!j(p)){o.warnings.push(`lock_remove_failed:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}}if(r?.onWrite){let p=await r.onWrite(l);o.warnings.push(...p)}}o.removed.push(d),o.entries.push(m.entry)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bc9e5edf-c275-5172-8900-fafee9b4a2db")}catch{}})();var Cf=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Xi(e){if(typeof e!="string")return;let t=e.trim();for(let n of Cf)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Zi(e){let t={};for(let n of e){let r=Xi(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Jc(e){return Object.values(Zi(e))}import lt from"node:fs/promises";import Ie 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]="2c514907-377f-59f9-bfdd-a184abf7ffb7")}catch{}})();var $f=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function zt(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Yn(t.extensionName));for(let h of t.extensionNames??[])n.add(Yn(h));let r=h=>n.size===0||n.has(Yn(h)),i=(h,w)=>Vc(h.filter(v=>r(v.name)).map(w)),a=(h,w)=>Vc(h.filter(v=>r(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:c,preflight:l,services:d,renderers:u,hooks:m}=e,p=a(o.relationship_kinds??[],h=>h.definitions.map(w=>w.kind)),f=u.overrides.filter(h=>r(h.name)&&((h.commands?.length??0)>0||h.resultDiscriminator!==void 0)).map(h=>({format:h.format,commands:[...h.commands??[]],result_discriminator:h.resultDiscriminator!==void 0})).sort((h,w)=>h.format.localeCompare(w.format)),g=i(o.assurance_providers??[],h=>h.definition.id);return{capabilities:cs(e,t),commands:i(o.commands,h=>h.command),command_overrides:i(s.overrides,h=>h.command),command_handlers:i(s.handlers,h=>h.command),hooks:$f.filter(([h])=>m[h].some(w=>r(w.name))).map(([,h])=>h),flag_commands:i(o.flags,h=>h.target_command),item_types:a(o.item_types,h=>h.types.map(w=>w.name)),item_fields:a(o.item_fields,h=>h.fields.map(w=>w.name)),...p.length>0?{relationship_kinds:p}:{},migrations:a(o.migrations,h=>typeof h.definition.id=="string"?[h.definition.id]:[]),profiles:i(o.profiles,h=>h.profile.name),importers:i(o.importers,h=>h.importer),exporters:i(o.exporters,h=>h.exporter),search_providers:i(o.search_providers,h=>h.definition.name),vector_store_adapters:i(o.vector_store_adapters,h=>h.definition.name),...g.length>0?{assurance_providers:g}:{},parser_overrides:i(c.overrides,h=>h.command),service_overrides:i(d.overrides,h=>h.service),renderer_overrides:i(u.overrides,h=>h.format),...f.length>0?{renderer_ownership:f}:{},preflight_overrides:l.overrides.filter(h=>r(h.name)).length,preflight_ownership:l.overrides.filter(h=>r(h.name)).map(h=>({commands:[...h.commands??[]]}))}}function Vc(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]="288a7da9-888b-527d-88fb-4711917cec5b")}catch{}})();var Tf=e=>{let t='"',n=0;for(let r of e){if(r==="\\"){n+=1;continue}t+="\\".repeat(r==='"'?n*2+1:n),t+=r,n=0}return`${t}${"\\".repeat(n*2)}"`},Qi=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?Tf(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,Kc=(e,t=process.platform)=>{let n=e.map(r=>Qi(r,t)).join(" ");return n.length>0?`pm ${n}`:"pm"};import Oh from"node:path";import{mkdir as Dh}from"node:fs/promises";import{readFile as Ar,realpath as ra,writeFile as Ff}from"node:fs/promises";import{execFile as jf}from"node:child_process";import te from"node:path";import{promisify as Uf}from"node:util";import{readFile as Of,writeFile as Df}from"node:fs/promises";import fn 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 Xc="# pm-cli:runtime-cache:start",ea="# pm-cli:runtime-cache:end",Zc=".agents/pm",ta=["runtime/","search/","locks/","transactions/","checkpoints/"],Pf=["search/eval-queries.json"];async function Yc(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 y("The workspace .gitignore is not writable.",_.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 Qc(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function na(e){let t=e.replaceAll("\\","/");return fn.isAbsolute(e)||t===".."||t.startsWith("../")}function Nf(e=Zc){let t=Qc(e);return[Xc,...ta.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Pf.map(n=>`!${t}/${n}`),ea].join(`
|
|
7
|
+
`)){if(o.trim().length===0)continue;if(a>=r)return{eventsRead:a,truncated:!0};a+=1;let s=Mc(o);s&&_f(s,t,n)}return{eventsRead:a,truncated:!1}}async function Lc(e,t=1e4){let n=new Map,r=new Map,i=0,a=0,o=!1;for(let l of await Nc(e)){let d=await gf(e,l,Math.max(0,pf-a));if(d===null)continue;a+=d.bytesRead;let u=yf(d.content,n,r,t,i);if(i=u.eventsRead,u.truncated){o=!0;break}if(!d.complete){o=!0;break}}let s=[...n.values()].sort((l,d)=>l.harness.localeCompare(d.harness)||l.dimension.localeCompare(d.dimension)||l.resolver.localeCompare(d.resolver)),c=[...r.values()].sort((l,d)=>l.harness.localeCompare(d.harness)||l.dimension.localeCompare(d.dimension)||l.kind.localeCompare(d.kind));return{outcomes:s,invalid_values:c,warnings:o?[]:[...s.filter(l=>l.attempts>0&&l.successes===0).map(l=>`provenance_resolver_zero_success:${l.harness}:${l.dimension}:${l.resolver}:${String(l.attempts)}`),...c.map(l=>`provenance_value_domain_invalid:${l.harness}:${l.dimension}:${l.kind}:${String(l.count)}`)],events_read:i,truncated:o}}import tt from"node:fs/promises";import fe from"node:path";import Ut from"node:fs/promises";import{createHash as wf}from"node:crypto";import jc 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]="32538934-2cbb-50fe-b721-ad9197cef7d8")}catch{}})();var Uc=4,vf="history-drift-cache.json";function zc(e){return jc.join(e,"runtime",vf)}async function bf(e){try{let t=await Ut.readFile(zc(e),"utf8"),n=JSON.parse(t);return n.version!==Uc||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}async function kf(e,t,n,r,i){let a=nr(e),o;try{o=await Ut.stat(a)}catch(l){return j(l)||i.unreadableStreams.push(ue),!1}let s=i.missingStreams.length,c=await Gc({itemId:ue,historyPath:a,stat:o,cached:t[ue],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.chainOk||i.chainMismatches.push(ue),n[ue]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(i.missingStreams.splice(s),c.cacheDirty)}function qc(e){return wf("sha256").update(e).digest("hex")}async function xf(e){let t=await Ut.readFile(e,"utf8");return qc(t)}async function Sf(e){let t=await Ut.readFile(e,"utf8"),n=qc(t);if(t.trim().length===0)return null;let r=[],i=null;for(let o of t.split(/\r?\n/)){let s=o.trim();if(s.length===0)continue;let c=JSON.parse(s);if(typeof c.after_hash!="string"||c.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(c),i=c.after_hash}if(!i)return null;let a=ys(r);return{latestAfterHash:i,chainOk:a.ok,contentHash:n,itemHashVersion:a.item_hash_version??Ii}}function Ef(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Fc(e,t,n){try{let r=await Sf(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Gc(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Ef(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Fc(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await xf(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else r=t;return!e.verifyCacheHitByContent||r===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:r,itemHashVersion:e.cached.item_hash_version??Ii},cacheDirty:!1}:{verification:await Fc(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function Af(e,t,n,r){let i=Gn(e,t.id),a;try{a=await Ut.stat(i)}catch(d){return(j(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let o=await Gc({itemId:t.id,historyPath:i,stat:a,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!o.verification)return o.cacheDirty;o.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:o.verification.contentHash,latest_after_hash:o.verification.latestAfterHash,chain_ok:o.verification.chainOk,item_hash_version:o.verification.itemHashVersion};let{body:s,...c}=t;return _s({metadata:c,body:s},o.verification.itemHashVersion)!==o.verification.latestAfterHash&&r.hashMismatches.push(t.id),o.cacheDirty}async function Rf(e,t){if(!(t.unreadableStreams.includes(ue)||t.chainMismatches.includes(ue)))try{let n=await ws(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(ue)}}async function xr(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},a=(await bf(e))?.entries??{},o={},s=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:a,nextEntries:o,verifyCacheHitByContent:c};for(let m of t)await Af(e,m,l,r)&&(s=!0);let d=await kf(e,a,o,c,r);if(s||=d,await Rf(e,r),s||Object.keys(a).length!==Object.keys(o).length){let m=zc(e);try{await Ut.mkdir(jc.dirname(m),{recursive:!0}),await le(m,JSON.stringify({version:Uc,entries:o}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[ue]:[]])].sort((m,p)=>m.localeCompare(p));return{...r,driftedItems:u}}import pn from"node:fs/promises";import Sr 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]="79f9ccbd-48d1-5eb3-82ae-3dd62427041c")}catch{}})();function If(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:a,ttl_seconds:o}=n;return typeof r!="string"||typeof i!="string"||typeof a!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:r,owner:i,created_at:a,ttl_seconds:o}}function Wc(e,t,n){let r=If(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let a=n-i,o=Math.floor(a/1e3),s=a>r.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:o,stale:s,reason:s?"expired":"active"}}}async function Bc(e,t){let n=t??Date.now(),r=Sr.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},a;try{a=(await pn.readdir(r)).filter(s=>s.endsWith(".lock")).sort()}catch(o){if(j(o))return i;throw o}for(let o of a){let s;try{s=await pn.readFile(Sr.join(r,o),"utf8")}catch(l){if(j(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=Wc(o,s,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function Hc(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Sr.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await pn.readdir(a)).filter(l=>l.endsWith(".lock")).sort()}catch(c){if(j(c))return o;throw c}for(let c of s){o.scanned+=1;let l=Sr.join(a,c),d=`locks/${c}`;if(r?.onRead){let p=await r.onRead(l);o.warnings.push(...p)}let u;try{u=await pn.readFile(l,"utf8")}catch(p){if(j(p)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${c}`),o.retained.push(d),o.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=Wc(c,u,i);if(m.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}if(m.detail==="active"){o.retained.push(d),o.entries.push(m.entry);continue}if(!n){try{await pn.unlink(l)}catch(p){if(!j(p)){o.warnings.push(`lock_remove_failed:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}}if(r?.onWrite){let p=await r.onWrite(l);o.warnings.push(...p)}}o.removed.push(d),o.entries.push(m.entry)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bc9e5edf-c275-5172-8900-fafee9b4a2db")}catch{}})();var Cf=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Xi(e){if(typeof e!="string")return;let t=e.trim();for(let n of Cf)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Zi(e){let t={};for(let n of e){let r=Xi(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Jc(e){return Object.values(Zi(e))}import lt from"node:fs/promises";import Ie 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]="2c514907-377f-59f9-bfdd-a184abf7ffb7")}catch{}})();var $f=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function zt(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Yn(t.extensionName));for(let h of t.extensionNames??[])n.add(Yn(h));let r=h=>n.size===0||n.has(Yn(h)),i=(h,w)=>Vc(h.filter(v=>r(v.name)).map(w)),a=(h,w)=>Vc(h.filter(v=>r(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:c,preflight:l,services:d,renderers:u,hooks:m}=e,p=a(o.relationship_kinds??[],h=>h.definitions.map(w=>w.kind)),f=u.overrides.filter(h=>r(h.name)&&((h.commands?.length??0)>0||h.resultDiscriminator!==void 0)).map(h=>({format:h.format,commands:[...h.commands??[]],result_discriminator:h.resultDiscriminator!==void 0})).sort((h,w)=>h.format.localeCompare(w.format)),g=i(o.assurance_providers??[],h=>h.definition.id);return{capabilities:ls(e,t),commands:i(o.commands,h=>h.command),command_overrides:i(s.overrides,h=>h.command),command_handlers:i(s.handlers,h=>h.command),hooks:$f.filter(([h])=>m[h].some(w=>r(w.name))).map(([,h])=>h),flag_commands:i(o.flags,h=>h.target_command),item_types:a(o.item_types,h=>h.types.map(w=>w.name)),item_fields:a(o.item_fields,h=>h.fields.map(w=>w.name)),...p.length>0?{relationship_kinds:p}:{},migrations:a(o.migrations,h=>typeof h.definition.id=="string"?[h.definition.id]:[]),profiles:i(o.profiles,h=>h.profile.name),importers:i(o.importers,h=>h.importer),exporters:i(o.exporters,h=>h.exporter),search_providers:i(o.search_providers,h=>h.definition.name),vector_store_adapters:i(o.vector_store_adapters,h=>h.definition.name),...g.length>0?{assurance_providers:g}:{},parser_overrides:i(c.overrides,h=>h.command),service_overrides:i(d.overrides,h=>h.service),renderer_overrides:i(u.overrides,h=>h.format),...f.length>0?{renderer_ownership:f}:{},preflight_overrides:l.overrides.filter(h=>r(h.name)).length,preflight_ownership:l.overrides.filter(h=>r(h.name)).map(h=>({commands:[...h.commands??[]]}))}}function Vc(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]="288a7da9-888b-527d-88fb-4711917cec5b")}catch{}})();var Tf=e=>{let t='"',n=0;for(let r of e){if(r==="\\"){n+=1;continue}t+="\\".repeat(r==='"'?n*2+1:n),t+=r,n=0}return`${t}${"\\".repeat(n*2)}"`},Qi=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?Tf(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,Kc=(e,t=process.platform)=>{let n=e.map(r=>Qi(r,t)).join(" ");return n.length>0?`pm ${n}`:"pm"};import Oh from"node:path";import{mkdir as Dh}from"node:fs/promises";import{readFile as Ar,realpath as ra,writeFile as Ff}from"node:fs/promises";import{execFile as jf}from"node:child_process";import te from"node:path";import{promisify as Uf}from"node:util";import{readFile as Of,writeFile as Df}from"node:fs/promises";import fn 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 Xc="# pm-cli:runtime-cache:start",ea="# pm-cli:runtime-cache:end",Zc=".agents/pm",ta=["runtime/","search/","locks/","transactions/","checkpoints/"],Pf=["search/eval-queries.json"];async function Yc(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 y("The workspace .gitignore is not writable.",_.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 Qc(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function na(e){let t=e.replaceAll("\\","/");return fn.isAbsolute(e)||t===".."||t.startsWith("../")}function Nf(e=Zc){let t=Qc(e);return[Xc,...ta.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Pf.map(n=>`!${t}/${n}`),ea].join(`
|
|
8
8
|
`)}async function xA(e,t={}){let n=fn.join(e,".gitignore"),r=Zc;if(t.pmRoot!==void 0){let d=Qc(fn.relative(fn.resolve(e),fn.resolve(t.pmRoot)));if(na(d))return{path:n,changed:!1};d.length>0&&(r=d)}let i="";try{i=await Yc(()=>Of(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&j(d)))throw d}let a=i.indexOf(Xc),o=i.indexOf(ea),c=(a>=0&&o>=a?`${i.slice(0,a)}${i.slice(o+ea.length)}`:i).trimEnd(),l=`${c.length>0?`${c}
|
|
9
9
|
|
|
10
10
|
`:""}${Nf(r)}
|
|
@@ -21,7 +21,7 @@ import{a as ki,c as Wn,d as Bn,e as Qo,g as es,h as Si,i as ts,j as At,k as Rt,l
|
|
|
21
21
|
${a}`,_.GENERIC_FAILURE)}}function wg(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function vg(e=process.platform){return e==="win32"}async function Jl(e,t,n=Sa,r=process.platform){let i=wg(r);try{return((await n(i,e,{cwd:t,encoding:"utf8",shell:vg(r)})).stdout??"").trim()}catch(a){let o=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr):"",s=o.trim().length>0?o.trim():a instanceof Error?a.message:String(a);throw new y(`npm command failed: ${i} ${e.join(" ")}
|
|
22
22
|
${s}`,_.GENERIC_FAILURE)}}function bg(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 kg(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 xg(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return kg(e)||n.includes("not found")}function Sg(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Eg(e){let t=bg(e),n=Sg(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,a=i?`pm install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:a?[a,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:a?[`Try ${a} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&a?{fallback_candidates:[{source:i,command:a,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:a}:{}}}}}function Ag(e,t){if(!xg(t))return null;let n=Eg(e);return new y(n.message,_.NOT_FOUND,n.context)}async function Vl(e){if(O.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=O.resolve(process.cwd(),e);return await A(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=mg(t);return await A(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=O.resolve(process.cwd(),e);if(await A(t))return t}return null}async function Rg(e){let t=await Vl(e);if(t)return t;let n=Ig(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Ig(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(r<=0)return e;let i=e.slice(0,r),a=e.slice(r+n.length);if(i.trim().length===0||a.trim().length===0||a.startsWith("//")&&!a.startsWith("///"))return e;if(!a.startsWith("/"))return`${i}@${O.resolve(t,a)}`;let o;try{o=decodeURIComponent(new URL(`file:${a}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${i}@${s}`}function Cg(e,t){try{let r=JSON.parse(e),i=Array.isArray(r)?r[0]:void 0;if(i&&typeof i.filename=="string"&&i.filename.trim().length>0)return{tarball:O.resolve(t,i.filename),package:typeof i.name=="string"?i.name:void 0,version:typeof i.version=="string"?i.version:void 0}}catch{}let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).at(-1);if(!n)throw new y("npm pack did not report a tarball filename.",_.GENERIC_FAILURE);return{tarball:O.resolve(t,n)}}async function $g(e){return Tg(e,Jl)}async function Tg(e,t){let n=await Vl(e.spec);if(n){if((await G.stat(n)).isFile()&&Kl(n))return Yl(n);let s=O.join(n,"package.json"),c=await A(s)?JSON.parse(await G.readFile(s,"utf8")):{};return{directory:await bn(n,e.input),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{}}}let r=await G.mkdtemp(O.join(xa.tmpdir(),"pm-npm-package-source-")),i=O.join(r,"pack"),a=O.join(r,"extract");await G.mkdir(i,{recursive:!0}),await G.mkdir(a,{recursive:!0});try{let o=await Rg(e.spec),s=await t(["pack",o,"--json","--pack-destination",i]),c=Cg(s,i);await Sa("tar",["-xzf",c.tarball,"-C",a],{encoding:"utf8"});let l=O.join(a,"package");return await Xl(l),{directory:await bn(l,e.input),package:c.package,version:c.version,cleanup:async()=>{await G.rm(r,{recursive:!0,force:!0})}}}catch(o){await G.rm(r,{recursive:!0,force:!0});let s=Ag(e.spec,o);throw s||o}}function Kl(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function Qe(e){throw new y(e,_.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 Og(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&Qe(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,i=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||i.some(a=>a===".."))&&Qe(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&Qe(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&Qe(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&Qe(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&Qe(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&Qe(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function Yl(e,t=_g){(await G.stat(e)).size>t.maxArchiveBytes&&Qe(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await G.mkdtemp(O.join(xa.tmpdir(),"pm-local-package-archive-")),i=O.join(r,"extract");await G.mkdir(i,{recursive:!0});let a={entries:0,expandedBytes:0,packageJsonEntries:0},o;try{if(await gg({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(o===void 0)try{Og(d,t,a)}catch(u){o=u}}}),o!==void 0)throw o;a.packageJsonEntries!==1&&Qe(`Local package archive must contain exactly one package/package.json entry; found ${a.packageJsonEntries}.`),await hg({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=O.join(i,"package"),c=O.join(s,"package.json"),l=JSON.parse(await G.readFile(c,"utf8"));return await Xl(s),{directory:await bn(s,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.version:void 0,cleanup:async()=>{await G.rm(r,{recursive:!0,force:!0})}}}catch(s){throw await G.rm(r,{recursive:!0,force:!0}),s}}async function Xl(e,t=Jl){let n=O.join(e,"package.json");if(!await A(n))return;let r;try{r=JSON.parse(await G.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,a=Fg(i),o=Dg(i);if(a.length===0&&!o)return;let s={...r};delete s.devDependencies;let c={...s};Pg(c),await G.writeFile(n,`${JSON.stringify(c,null,2)}
|
|
23
23
|
`,"utf8");try{await Promise.all([G.rm(O.join(e,"package-lock.json"),{force:!0}),G.rm(O.join(e,"npm-shrinkwrap.json"),{force:!0})]),a.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await Ng(e)}finally{await G.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
24
|
-
`,"utf8")}}function Dg(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Mr in t)return!0;return!1}function Pg(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Mr],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function Ng(e){let t=Ee(import.meta.url,["../../.."]),[n,r]=Mr.split("/"),i=O.join(e,"node_modules",n),a=O.join(i,r);await G.mkdir(i,{recursive:!0}),await G.rm(a,{recursive:!0,force:!0}),await G.symlink(t,a,Mg(process.platform))}function Mg(e){return e==="win32"?"junction":"dir"}function Lg(e,t){if(e.startsWith("-"))throw new y(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,_.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(r=>{let i=r.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(r)}))throw new y(`Extension runtime dependency "${e}" has an unsafe version specifier.`,_.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{fg.resolve(e,t)}catch{throw new y(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,_.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 Fg(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===Mr||typeof i!="string"||i.trim().length===0||t.has(r))continue;let a=i.trim();t.set(r,Lg(r,a))}return[...t.values()]}async function bn(e,t){let n=await Bn(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>O.relative(e,i).replaceAll(O.sep,"/")).sort((i,a)=>i.localeCompare(a));throw new y(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,_.USAGE)}throw new y(`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.`,_.USAGE)}async function jg(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(O.posix.join(".agents/pm/extensions",t.subpath)),n.push(O.posix.join(".custom/pm-extensions",t.subpath)),n.push(O.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let a=O.resolve(e,i);if(ye(e,a)&&await A(O.join(a,"manifest.json")))return{directory:a,resolved_subpath:i}}if(await A(O.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await bn(e,t.input);return{directory:r,resolved_subpath:O.relative(e,r).replaceAll(O.sep,"/")}}function Ug(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 zg(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Ug(n))return new y(t,_.NOT_FOUND);let r=[];try{let a=process.env.PM_CLI_PACKAGE_ROOT,o=typeof a=="string"&&a.trim().length>0?O.resolve(a.trim()):"";ba?.key!==o&&(ba={key:o,aliases:await Pr()}),r=ba.aliases}catch{}let i=[`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 y(`${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}".`,_.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:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Zl(e){if(e.kind==="local"){let r;try{r=await G.stat(e.absolute_path)}catch{throw await zg(e)}if(r.isFile()&&Kl(e.absolute_path)){let a=await Yl(e.absolute_path);return{source:e,directory:a.directory,source_root:O.dirname(a.directory),resolved_subpath:O.relative(O.dirname(a.directory),a.directory).replaceAll(O.sep,"/"),npm_package:a.package,npm_version:a.version,cleanup:a.cleanup}}if(!r.isDirectory())throw new y(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,_.USAGE);let i=await bn(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await $g(e);return{source:e,directory:r.directory,source_root:O.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:O.relative(O.dirname(r.directory),r.directory).replaceAll(O.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await G.mkdtemp(O.join(xa.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Nr(n);let r=await Nr(["-C",t,"rev-parse","HEAD"]),i=await jg(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await G.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await G.rm(t,{recursive:!0,force:!0}),r}}async function Ql(e,t){if(!await A(e)||!await A(t))return!1;let[n,r]=await Promise.all([G.realpath(e),G.realpath(t)]);return n===r}import kn from"node:fs/promises";import xn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="30dfc6e4-27c5-56c0-981b-94e85b780f1f")}catch{}})();var Ea=1,bt="2026.6.24",qg=">=22.18.0",Gg={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},ed=new Set([...ss.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(ds).map(e=>e.toLowerCase()),"scaffold"]),Wg="^6.0.0",Bg="^22.0.0",rd=["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."," }"," }","}",""],ze=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function td(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function id(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 ad(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 Hg={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},nd=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],od={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"]},Jg={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"]'},Vg={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."},Kg={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."},sd="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Yg={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."]},Xg={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."]},Zg={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`."]},Qg={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 cd(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 ld(e,t){return e==="schema"?Zg[t]:e==="profile"?Qg[t]:Xg[t]}function e_(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),a=r>0&&(r===t.length||i!==void 0&&ed.has(i));return`${(ed.has(n)||a?["starter",...t]:t).join(" ")} ping`}function dd(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],a=`${e.replace(/-/g,"_")}_owner`,o="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(a)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function t_(e,t,n){let r=`${e}-search`,i=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,o=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,l=e.replace(/-/g,""),d=l===s?[]:[l],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...dd(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(a)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(a)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...o,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...o,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function n_(e,t,n){let r=n==="hooks",i=n==="search",a=n==="importers",o=n==="schema",s=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",u=n==="services",m=Jg[n],p=e,f=`${e}s`,g=`${e.replace(/-/g,"_")}_note`,h=`${e}-0001-init`,w=[" 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: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],b=i?Aa(e,t,"search",m):[],x=a?Aa(e,t,"importers",m):[],R=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...td(id({extensionName:e,itemTypeName:p,itemTypeFolder:f,fieldName:g,migrationId:h,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],k=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...td(ad(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],F=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],T=l?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],E=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],U=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...rd,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...l?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});","",...v,...b,...x,...R,...k,...F,...T,...E,...U,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
24
|
+
`,"utf8")}}function Dg(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Mr in t)return!0;return!1}function Pg(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Mr],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function Ng(e){let t=Ee(import.meta.url,["../../.."]),[n,r]=Mr.split("/"),i=O.join(e,"node_modules",n),a=O.join(i,r);await G.mkdir(i,{recursive:!0}),await G.rm(a,{recursive:!0,force:!0}),await G.symlink(t,a,Mg(process.platform))}function Mg(e){return e==="win32"?"junction":"dir"}function Lg(e,t){if(e.startsWith("-"))throw new y(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,_.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(r=>{let i=r.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(r)}))throw new y(`Extension runtime dependency "${e}" has an unsafe version specifier.`,_.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{fg.resolve(e,t)}catch{throw new y(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,_.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 Fg(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===Mr||typeof i!="string"||i.trim().length===0||t.has(r))continue;let a=i.trim();t.set(r,Lg(r,a))}return[...t.values()]}async function bn(e,t){let n=await Bn(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>O.relative(e,i).replaceAll(O.sep,"/")).sort((i,a)=>i.localeCompare(a));throw new y(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,_.USAGE)}throw new y(`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.`,_.USAGE)}async function jg(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(O.posix.join(".agents/pm/extensions",t.subpath)),n.push(O.posix.join(".custom/pm-extensions",t.subpath)),n.push(O.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let a=O.resolve(e,i);if(ye(e,a)&&await A(O.join(a,"manifest.json")))return{directory:a,resolved_subpath:i}}if(await A(O.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await bn(e,t.input);return{directory:r,resolved_subpath:O.relative(e,r).replaceAll(O.sep,"/")}}function Ug(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 zg(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Ug(n))return new y(t,_.NOT_FOUND);let r=[];try{let a=process.env.PM_CLI_PACKAGE_ROOT,o=typeof a=="string"&&a.trim().length>0?O.resolve(a.trim()):"";ba?.key!==o&&(ba={key:o,aliases:await Pr()}),r=ba.aliases}catch{}let i=[`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 y(`${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}".`,_.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:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Zl(e){if(e.kind==="local"){let r;try{r=await G.stat(e.absolute_path)}catch{throw await zg(e)}if(r.isFile()&&Kl(e.absolute_path)){let a=await Yl(e.absolute_path);return{source:e,directory:a.directory,source_root:O.dirname(a.directory),resolved_subpath:O.relative(O.dirname(a.directory),a.directory).replaceAll(O.sep,"/"),npm_package:a.package,npm_version:a.version,cleanup:a.cleanup}}if(!r.isDirectory())throw new y(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,_.USAGE);let i=await bn(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await $g(e);return{source:e,directory:r.directory,source_root:O.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:O.relative(O.dirname(r.directory),r.directory).replaceAll(O.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await G.mkdtemp(O.join(xa.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Nr(n);let r=await Nr(["-C",t,"rev-parse","HEAD"]),i=await jg(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await G.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await G.rm(t,{recursive:!0,force:!0}),r}}async function Ql(e,t){if(!await A(e)||!await A(t))return!1;let[n,r]=await Promise.all([G.realpath(e),G.realpath(t)]);return n===r}import kn from"node:fs/promises";import xn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="30dfc6e4-27c5-56c0-981b-94e85b780f1f")}catch{}})();var Ea=1,bt="2026.6.24",qg=">=22.18.0",Gg={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},ed=new Set([...cs.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(ss).map(e=>e.toLowerCase()),"scaffold"]),Wg="^6.0.0",Bg="^22.0.0",rd=["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."," }"," }","}",""],ze=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function td(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function id(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 ad(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 Hg={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},nd=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],od={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"]},Jg={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"]'},Vg={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."},Kg={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."},sd="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Yg={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."]},Xg={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."]},Zg={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`."]},Qg={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 cd(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 ld(e,t){return e==="schema"?Zg[t]:e==="profile"?Qg[t]:Xg[t]}function e_(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),a=r>0&&(r===t.length||i!==void 0&&ed.has(i));return`${(ed.has(n)||a?["starter",...t]:t).join(" ")} ping`}function dd(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],a=`${e.replace(/-/g,"_")}_owner`,o="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(a)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function t_(e,t,n){let r=`${e}-search`,i=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,o=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,l=e.replace(/-/g,""),d=l===s?[]:[l],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...dd(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(a)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(a)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...o,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...o,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function n_(e,t,n){let r=n==="hooks",i=n==="search",a=n==="importers",o=n==="schema",s=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",u=n==="services",m=Jg[n],p=e,f=`${e}s`,g=`${e.replace(/-/g,"_")}_note`,h=`${e}-0001-init`,w=[" 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: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],b=i?Aa(e,t,"search",m):[],x=a?Aa(e,t,"importers",m):[],R=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...td(id({extensionName:e,itemTypeName:p,itemTypeFolder:f,fieldName:g,migrationId:h,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],k=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...td(ad(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],F=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],T=l?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],E=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],U=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...rd,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...l?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});","",...v,...b,...x,...R,...k,...F,...T,...E,...U,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
25
25
|
`)}function r_(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 i_={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"},a_={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 o_(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 s_(e,t,n){let r=[],i=[...o_(e,t,n)],a=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,l=e,d=`${e}s`,u=e.replace(/-/g,""),m=u===l?[]:[u],p=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),a.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),a.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),a.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(l)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(f)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),a.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...dd(e),"});"),a.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),a.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),a.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),a.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),a.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:a}}function c_(e,t,n){let r=s_(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((a,o)=>a.localeCompare(o)).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(`
|
|
26
26
|
`)}function Aa(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,a=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,l=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],m=p=>[...u," let deactivated = false;"," try {",...p.map(f=>f===""?f:` ${f}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings: {} as PmSettings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings: {} as PmSettings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(a)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings: {} as PmSettings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(id({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:l,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(ad(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function l_(e,t,n){let r=n==="parser",i=JSON.stringify([...od[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" };',"",...rd,`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(bt)},`," },",` target: { pmVersion: ${JSON.stringify(bt)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});","",...Aa(e,t,n,i)].join(`
|
|
27
27
|
`)}function d_(e,t,n){let r=cd(n,"package"),i=ld(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 (${i_[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`.",sd,"- `.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 ${a_[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Ea}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${bt}\`. 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,7 +31,7 @@ ${s}`,_.GENERIC_FAILURE)}}function bg(e){let t=e.trim(),n=t.includes("@file:")?t
|
|
|
31
31
|
`,u=Vg[r],m=cd(r,"package"),p=`${JSON.stringify({name:a,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:qg},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${bt}`},devDependencies:{"@types/node":Bg,typescript:Wg},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)}
|
|
32
32
|
`,f=n_(e,t,r),g=Kg[r],h=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
33
33
|
`),w=u_(e),b=["```ts",`import { ${m_(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...p_(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...f_(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],x=[`# ${a}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,g,sd,"- `.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:",...b,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Yg[r],...ld(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${bt}\`. 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 \`${Ea}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${bt}\`. 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(`
|
|
34
|
-
`);return{"package.json":p,"manifest.json":c,"index.ts":i?c_(e,t,r):l,"index.test.ts":i?l_(e,t,r):f,"tsconfig.json":d,".gitignore":h,"README.md":i?d_(a,t,r):x}}async function ud(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!nd.includes(i))throw new y(`Unknown scaffold capability "${n}". Supported capabilities: ${nd.join(", ")}.`,_.USAGE);let a=i;if(r&&t!=="package")throw new y("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",_.USAGE);let o=r?"declarative":"imperative",s=e.trim(),c=xn.resolve(process.cwd(),s),l=Or(xn.basename(c)).replace(/^(?:pm-)+/u,""),d=e_(l),u=h_(l,d,t,a,r),m=!1;if(await A(c)){if(!(await kn.stat(c)).isDirectory())throw new y(`Scaffold target "${c}" exists and is not a directory.`,_.CONFLICT)}else await kn.mkdir(c,{recursive:!0}),m=!0;for(let[f,g]of Object.entries(u)){let h=xn.join(c,f);if(!await A(h))continue;if(await kn.readFile(h,"utf8")!==g)throw new y(`Scaffold file "${f}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,_.CONFLICT)}let p=[];for(let[f,g]of Object.entries(u)){let h=xn.join(c,f);if(await A(h)){p.push({path:f,status:"unchanged"});continue}await kn.mkdir(xn.dirname(h),{recursive:!0}),await kn.writeFile(h,g,"utf8"),p.push({path:f,status:"created"})}return{extension_name:l,package_name:`pm-${l}`,command_name:d,invocation_command:`pm ${d}`,capability:a,style:o,target_path:c,created_directory:m,files:p}}(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 md(e,t){return`${e}:${S(t)}`}function g_(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let a=new Map;for(let o of i){let s=a.get(o.command)??[];a.set(o.command,[...s,o])}for(let[o,s]of a){if(t!==null&&!s.some(l=>t.has(S(l.name))))continue;let c=s.at(-1);n.push({command:o,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(l=>({name:l.name,layer:l.layer,winner:l===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function pd(e,t,n){let r=new Set(n.failed.map(l=>md(l.layer,l.name))),i=[...t.loaded.map(l=>({name:l.name,layer:l.layer,version:l.version,activation_status:r.has(md(l.layer,l.name))?"failed":"ok",surfaces:zt(n,{extensionName:l.name})})),...t.failed.map(l=>({name:l.name,layer:l.layer,version:"unknown",activation_status:"not_loaded",surfaces:zt(n,{extensionName:l.name})}))].sort((l,d)=>l.name.localeCompare(d.name)||l.layer.localeCompare(d.layer)),a=typeof e=="string"?S(e):null,o=a===null?null:new Set(t.loaded.filter(l=>S(l.name)===a||typeof l.source_package=="string"&&S(l.source_package)===a||(l.source_aliases??[]).some(d=>S(d)===a)).map(l=>S(l.name)).concat(a)),s=o===null?i:i.filter(l=>o.has(S(l.name))),c=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:zt(n,c),command_ownership:g_(n,o)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function Ra(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function Fr(e,t,n){let r=S(t),i=n.trim();if(r.length===0||i.length===0)return;let a=e.get(r)??new Set;a.add(i),e.set(r,a)}function __(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)Fr(t,r.name,r.command),Fr(n,r.name,r.action);for(let r of e.commands.handlers)Fr(t,r.name,r.command);for(let r of e.commands.overrides)Fr(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function fd(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function y_(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:a}=e;return t?i.has(n)||a.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 jr(e,t,n){let r=new Set(t.loaded.map(c=>S(c.name))),i=new Set(t.failed.map(c=>S(c.name))),a=new Set(n.failed.map(c=>S(c.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=__(n);return e.map(c=>{let l=S(c.name),d=fd(o.get(l)),u=fd(s.get(l)),m={...d?{command_paths:d}:{},...u?{action_paths:u}:{}},p=y_({enabled:c.enabled,normalizedName:l,loadedNames:r,loadFailedNames:i,activationFailedNames:a});return{...c,...p,...m}})}function w_(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function ce(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var _d=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 v_(e){return _d.has(xd(e))}function hd(e){return e==="project"||e==="global"}function yd(e){let t=e.split(":"),n=t[0];if(!n||!_d.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!hd(r)||!hd(a)||!i||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:a,name:o}}}function b_(e){let t=new Set;for(let n of e){let r=yd(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Ia(e,t){let n=e.filter(v_);if(n.length===0)return null;let r=b_(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 k_(e,t,n,r){let i=t.map(u=>yd(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let a=e==="global"?"--global":"--project",o=ce(r,"deactivate"),s=`${ce(r,"doctor")} ${a} --detail deep --trace`,c=new Map(n.map(u=>[S(u.name),u])),l=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let p=S(m);l.set(p,(l.get(p)??0)+1)}let d=[...l.entries()].map(([u,m])=>{let p=c.get(u),f=p?.name??u,g=p?.command_paths??[],h=p?.action_paths??[];return{action:"deactivate",extension:f,command:`${o} ${f} ${a}`,affected_collisions:m,feature_loss:{command_paths:[...g].sort((w,v)=>w.localeCompare(v)),action_paths:[...h].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let p=m.affected_collisions-u.affected_collisions;if(p!==0)return p;let f=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,g=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return f!==g?f-g:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:l.size,next_best_command:s,collisions:i,remediation_candidates:d}}function wd(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 vd(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function bd(e,t){let n=[];for(let r of ls(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var x_=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${ce(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: ${Fn.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 ${ce(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 ${ce(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 ${ce(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 ${ce(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 ${ce(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${ce(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 S_(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,u=[],m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o};if(t.length>0){let p=Ia(t,{deactivate:`${ce(n,"deactivate")} <name> ${i}`,doctor:`${ce(n,"doctor")} ${i} --detail deep --trace`});p&&u.push(p);for(let f of x_)f.matches(t,m)&&u.push(f.build(m))}return s?u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${ce(n,"manage")} ${i} --fix-managed-state (or ${ce(n,"adopt-all")} ${i}, ${ce(n,"adopt")} <name> ${i}, or reinstall via ${ce(n,"install")} ${i} <source>).`):c>0&&u.push(`Loaded unmanaged extensions are currently treated as informational. Use ${ce(n,"manage")} ${i} --fix-managed-state to adopt them for update checks.`),l>0&&u.push("Non-GitHub managed extensions are skipped by update checks. Use doctor output for non-update diagnostics."),d>0&&u.push(`Update available managed extensions via ${ce(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${ce(n,"manage")} ${i} after extension changes.`),u}function Ur(e,t,n,r={}){let i=[...new Set(t)].sort((E,U)=>E.localeCompare(U)),a=n.filter(E=>E.managed).length,o=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,c=n.filter(E=>E.update_available===!0).length,l=n.filter(E=>E.managed===!1),d=l.filter(E=>gd(E)).map(E=>E.name).sort((E,U)=>E.localeCompare(U)),u=l.filter(E=>!gd(E)).map(E=>E.name).sort((E,U)=>E.localeCompare(U)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)m[E.update_check_status]+=1;let p=m.failed,f=m.skipped_unmanaged,g=m.skipped_non_github,h=u.length>0,w=h?"partial":"full",v=h?[`extension_update_health_partial_coverage:skipped_unmanaged:${u.length}`]:[],b=[...new Set([...i,...v])].sort((E,U)=>E.localeCompare(U)),x=[...new Set(b.map(E=>xd(E)))].sort((E,U)=>E.localeCompare(U)),R=w_(b),k=e==="global"?"--global":"--project",F=k_(e,i,n,r),T=S_({normalizedWarnings:i,options:r,scope:e,scopeFlag:k,updateCheckFailedTotal:p,policyWarningCount:R.warning_count,updateHealthPartial:h,skippedUnmanagedTotal:f,skippedNonGithubTotal:g,updateAvailableTotal:c});return{status:b.length===0?"ok":"warn",warning_count:b.length,warning_codes:x,warnings:b,policy_warning_count:R.warning_count,policy_violation_count:R.violation_count,policy_blocked_count:R.blocked_count,total_extensions:n.length,managed_total:a,enabled_total:o,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:h,unmanaged_loaded_extension_count:l.length,unmanaged_loaded_extensions:l.map(E=>E.name).sort((E,U)=>E.localeCompare(U)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:p,top_warnings:b.slice(0,8),remediation:T,...F?{collision_plan:F}:{}}}function kd(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new y(`Invalid --detail value "${e}". Expected summary or deep.`,_.USAGE)}function xd(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Sn(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let a=$o(r);return a?[a]:To(r)})();for(let a of i){let o=`${a.layer}:${a.name}:${a.capability}`;t.has(o)||(t.add(o),n.push(a))}}return n}function En(){return{version:jn.version,capabilities:[...jn.capabilities],legacy_aliases:{...jn.legacy_aliases}}}function gd(e){let t=S(e.name),n=S(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Sd(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let a=[...new Set(t.filter(d=>d.active).map(d=>S(d.name)))].sort((d,u)=>d.localeCompare(u)),o=[...new Set(n.filter(d=>d.layer==="project").map(d=>S(d.name)))].sort((d,u)=>d.localeCompare(u)),s=new Set(r.map(d=>S(d.name))),c=a.filter(d=>!o.includes(d)&&!s.has(d)).sort((d,u)=>d.localeCompare(u));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:a.length,loaded_project_count:o.length,active_project_names:a,loaded_project_names:o,missing_active_project_names:c}}}import{randomUUID as E_}from"node:crypto";import ne from"node:fs/promises";import A_ from"node:os";import J from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="263602a2-c000-5df7-80d2-6f095985496f")}catch{}})();var Ed=3,R_=120,Ad=250,I_=12e4,C_=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Rd=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Id=e=>C_.has(String(Rd(e))),zr=(e,t)=>Rd(e)===t,Cd=e=>new Promise(t=>{setTimeout(t,e)}),$d=async e=>{let t=J.join(e,"package.json");await A(t)||await ne.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
34
|
+
`);return{"package.json":p,"manifest.json":c,"index.ts":i?c_(e,t,r):l,"index.test.ts":i?l_(e,t,r):f,"tsconfig.json":d,".gitignore":h,"README.md":i?d_(a,t,r):x}}async function ud(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!nd.includes(i))throw new y(`Unknown scaffold capability "${n}". Supported capabilities: ${nd.join(", ")}.`,_.USAGE);let a=i;if(r&&t!=="package")throw new y("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",_.USAGE);let o=r?"declarative":"imperative",s=e.trim(),c=xn.resolve(process.cwd(),s),l=Or(xn.basename(c)).replace(/^(?:pm-)+/u,""),d=e_(l),u=h_(l,d,t,a,r),m=!1;if(await A(c)){if(!(await kn.stat(c)).isDirectory())throw new y(`Scaffold target "${c}" exists and is not a directory.`,_.CONFLICT)}else await kn.mkdir(c,{recursive:!0}),m=!0;for(let[f,g]of Object.entries(u)){let h=xn.join(c,f);if(!await A(h))continue;if(await kn.readFile(h,"utf8")!==g)throw new y(`Scaffold file "${f}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,_.CONFLICT)}let p=[];for(let[f,g]of Object.entries(u)){let h=xn.join(c,f);if(await A(h)){p.push({path:f,status:"unchanged"});continue}await kn.mkdir(xn.dirname(h),{recursive:!0}),await kn.writeFile(h,g,"utf8"),p.push({path:f,status:"created"})}return{extension_name:l,package_name:`pm-${l}`,command_name:d,invocation_command:`pm ${d}`,capability:a,style:o,target_path:c,created_directory:m,files:p}}(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 md(e,t){return`${e}:${S(t)}`}function g_(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let a=new Map;for(let o of i){let s=a.get(o.command)??[];a.set(o.command,[...s,o])}for(let[o,s]of a){if(t!==null&&!s.some(l=>t.has(S(l.name))))continue;let c=s.at(-1);n.push({command:o,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(l=>({name:l.name,layer:l.layer,winner:l===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function pd(e,t,n){let r=new Set(n.failed.map(l=>md(l.layer,l.name))),i=[...t.loaded.map(l=>({name:l.name,layer:l.layer,version:l.version,activation_status:r.has(md(l.layer,l.name))?"failed":"ok",surfaces:zt(n,{extensionName:l.name})})),...t.failed.map(l=>({name:l.name,layer:l.layer,version:"unknown",activation_status:"not_loaded",surfaces:zt(n,{extensionName:l.name})}))].sort((l,d)=>l.name.localeCompare(d.name)||l.layer.localeCompare(d.layer)),a=typeof e=="string"?S(e):null,o=a===null?null:new Set(t.loaded.filter(l=>S(l.name)===a||typeof l.source_package=="string"&&S(l.source_package)===a||(l.source_aliases??[]).some(d=>S(d)===a)).map(l=>S(l.name)).concat(a)),s=o===null?i:i.filter(l=>o.has(S(l.name))),c=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:zt(n,c),command_ownership:g_(n,o)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function Ra(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function Fr(e,t,n){let r=S(t),i=n.trim();if(r.length===0||i.length===0)return;let a=e.get(r)??new Set;a.add(i),e.set(r,a)}function __(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)Fr(t,r.name,r.command),Fr(n,r.name,r.action);for(let r of e.commands.handlers)Fr(t,r.name,r.command);for(let r of e.commands.overrides)Fr(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function fd(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function y_(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:a}=e;return t?i.has(n)||a.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 jr(e,t,n){let r=new Set(t.loaded.map(c=>S(c.name))),i=new Set(t.failed.map(c=>S(c.name))),a=new Set(n.failed.map(c=>S(c.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=__(n);return e.map(c=>{let l=S(c.name),d=fd(o.get(l)),u=fd(s.get(l)),m={...d?{command_paths:d}:{},...u?{action_paths:u}:{}},p=y_({enabled:c.enabled,normalizedName:l,loadedNames:r,loadFailedNames:i,activationFailedNames:a});return{...c,...p,...m}})}function w_(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function ce(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var _d=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 v_(e){return _d.has(xd(e))}function hd(e){return e==="project"||e==="global"}function yd(e){let t=e.split(":"),n=t[0];if(!n||!_d.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!hd(r)||!hd(a)||!i||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:a,name:o}}}function b_(e){let t=new Set;for(let n of e){let r=yd(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Ia(e,t){let n=e.filter(v_);if(n.length===0)return null;let r=b_(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 k_(e,t,n,r){let i=t.map(u=>yd(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let a=e==="global"?"--global":"--project",o=ce(r,"deactivate"),s=`${ce(r,"doctor")} ${a} --detail deep --trace`,c=new Map(n.map(u=>[S(u.name),u])),l=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let p=S(m);l.set(p,(l.get(p)??0)+1)}let d=[...l.entries()].map(([u,m])=>{let p=c.get(u),f=p?.name??u,g=p?.command_paths??[],h=p?.action_paths??[];return{action:"deactivate",extension:f,command:`${o} ${f} ${a}`,affected_collisions:m,feature_loss:{command_paths:[...g].sort((w,v)=>w.localeCompare(v)),action_paths:[...h].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let p=m.affected_collisions-u.affected_collisions;if(p!==0)return p;let f=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,g=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return f!==g?f-g:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:l.size,next_best_command:s,collisions:i,remediation_candidates:d}}function wd(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 vd(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function bd(e,t){let n=[];for(let r of ds(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var x_=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${ce(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: ${Fn.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 ${ce(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 ${ce(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 ${ce(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 ${ce(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 ${ce(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${ce(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 S_(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,u=[],m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o};if(t.length>0){let p=Ia(t,{deactivate:`${ce(n,"deactivate")} <name> ${i}`,doctor:`${ce(n,"doctor")} ${i} --detail deep --trace`});p&&u.push(p);for(let f of x_)f.matches(t,m)&&u.push(f.build(m))}return s?u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${ce(n,"manage")} ${i} --fix-managed-state (or ${ce(n,"adopt-all")} ${i}, ${ce(n,"adopt")} <name> ${i}, or reinstall via ${ce(n,"install")} ${i} <source>).`):c>0&&u.push(`Loaded unmanaged extensions are currently treated as informational. Use ${ce(n,"manage")} ${i} --fix-managed-state to adopt them for update checks.`),l>0&&u.push("Non-GitHub managed extensions are skipped by update checks. Use doctor output for non-update diagnostics."),d>0&&u.push(`Update available managed extensions via ${ce(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${ce(n,"manage")} ${i} after extension changes.`),u}function Ur(e,t,n,r={}){let i=[...new Set(t)].sort((E,U)=>E.localeCompare(U)),a=n.filter(E=>E.managed).length,o=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,c=n.filter(E=>E.update_available===!0).length,l=n.filter(E=>E.managed===!1),d=l.filter(E=>gd(E)).map(E=>E.name).sort((E,U)=>E.localeCompare(U)),u=l.filter(E=>!gd(E)).map(E=>E.name).sort((E,U)=>E.localeCompare(U)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)m[E.update_check_status]+=1;let p=m.failed,f=m.skipped_unmanaged,g=m.skipped_non_github,h=u.length>0,w=h?"partial":"full",v=h?[`extension_update_health_partial_coverage:skipped_unmanaged:${u.length}`]:[],b=[...new Set([...i,...v])].sort((E,U)=>E.localeCompare(U)),x=[...new Set(b.map(E=>xd(E)))].sort((E,U)=>E.localeCompare(U)),R=w_(b),k=e==="global"?"--global":"--project",F=k_(e,i,n,r),T=S_({normalizedWarnings:i,options:r,scope:e,scopeFlag:k,updateCheckFailedTotal:p,policyWarningCount:R.warning_count,updateHealthPartial:h,skippedUnmanagedTotal:f,skippedNonGithubTotal:g,updateAvailableTotal:c});return{status:b.length===0?"ok":"warn",warning_count:b.length,warning_codes:x,warnings:b,policy_warning_count:R.warning_count,policy_violation_count:R.violation_count,policy_blocked_count:R.blocked_count,total_extensions:n.length,managed_total:a,enabled_total:o,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:h,unmanaged_loaded_extension_count:l.length,unmanaged_loaded_extensions:l.map(E=>E.name).sort((E,U)=>E.localeCompare(U)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:p,top_warnings:b.slice(0,8),remediation:T,...F?{collision_plan:F}:{}}}function kd(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new y(`Invalid --detail value "${e}". Expected summary or deep.`,_.USAGE)}function xd(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Sn(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let a=$o(r);return a?[a]:To(r)})();for(let a of i){let o=`${a.layer}:${a.name}:${a.capability}`;t.has(o)||(t.add(o),n.push(a))}}return n}function En(){return{version:jn.version,capabilities:[...jn.capabilities],legacy_aliases:{...jn.legacy_aliases}}}function gd(e){let t=S(e.name),n=S(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Sd(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let a=[...new Set(t.filter(d=>d.active).map(d=>S(d.name)))].sort((d,u)=>d.localeCompare(u)),o=[...new Set(n.filter(d=>d.layer==="project").map(d=>S(d.name)))].sort((d,u)=>d.localeCompare(u)),s=new Set(r.map(d=>S(d.name))),c=a.filter(d=>!o.includes(d)&&!s.has(d)).sort((d,u)=>d.localeCompare(u));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:a.length,loaded_project_count:o.length,active_project_names:a,loaded_project_names:o,missing_active_project_names:c}}}import{randomUUID as E_}from"node:crypto";import ne from"node:fs/promises";import A_ from"node:os";import J from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="263602a2-c000-5df7-80d2-6f095985496f")}catch{}})();var Ed=3,R_=120,Ad=250,I_=12e4,C_=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Rd=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Id=e=>C_.has(String(Rd(e))),zr=(e,t)=>Rd(e)===t,Cd=e=>new Promise(t=>{setTimeout(t,e)}),$d=async e=>{let t=J.join(e,"package.json");await A(t)||await ne.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
35
35
|
`,"utf8")},Td=async e=>{let t=Ee(import.meta.url,["../../.."]),n=J.join(e,"node_modules","@unbrained"),r=J.join(n,"pm-cli");await ne.mkdir(n,{recursive:!0}),await ne.rm(r,{recursive:!0,force:!0}),await ne.symlink(t,r,process.platform==="win32"?"junction":"dir")},Ca=async e=>{let t=J.resolve(e),n=J.dirname(t),r=J.parse(n).root,i=await ne.realpath(r).catch(()=>r),a=J.relative(r,n),o=a===""?[]:a.split(J.sep);for(let[s,c]of o.entries()){let l=J.join(i,c);try{i=await ne.realpath(l)}catch{i=J.join(i,...o.slice(s));break}}return J.join(i,J.basename(t))},Od=async(e,t,n,r=A_.tmpdir())=>{let i=J.resolve(e),a=await ne.realpath(i).catch(()=>i),o=await Ca(t);if(a===o)return;if(!ye(a,o)){await n(e,t,{recursive:!0,force:!0});return}let s=m=>{let p=J.resolve(m);if(p!==i&&!ye(i,p))return!1;let f=J.resolve(a,J.relative(i,p));if(f===o||ye(o,f))return!1;let h=J.relative(a,f).split(J.sep);return h.some(w=>w==="node_modules"||w.startsWith(".pm-extension-install-backup-"))?!1:h[0]!==".agents"},c=await ne.realpath(J.resolve(r)).catch(()=>Ca(r)),l=ye(a,c)?J.dirname(a):c;if(ye(a,l))throw new y(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,_.USAGE,{code:"extension_install_source_contains_destination"});let d=await ne.mkdtemp(J.join(l,"pm-extension-copy-")),u=J.join(d,"extension");try{await n(e,u,{recursive:!0,force:!0,filter:s}),await n(u,t,{recursive:!0,force:!0})}finally{await ne.rm(d,{recursive:!0,force:!0})}},Dd=async(e,t,n=ne.cp)=>{for(let r=1;r<=Ed;r+=1)try{await ne.rm(t,{recursive:!0,force:!0}),await Od(e,t,n);return}catch(i){if(!Id(i)||r===Ed)throw i;await Cd(Ad)}},$a=async e=>{let t;try{t=await ne.readFile(J.join(e,"owner.json"),"utf8")}catch(i){if(!zn(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},Pd=async(e,t)=>await $a(e)!==t?!1:(await ne.rm(e,{recursive:!0,force:!0}),!0),$_=async(e,t)=>{let n;try{n=await ne.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await $a(e);return r===null?(await ne.rm(e,{recursive:!0,force:!0}),!0):Pd(e,r)},T_=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await $a(e)!==t)return;let a=new Date;await ne.utimes(e,a,a)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},O_=async(e,t)=>{await ne.mkdir(e);try{await ne.writeFile(J.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
36
36
|
`,"utf8")}catch(n){throw await ne.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},D_=async(e,t,n,r,i)=>{for(let a=1;a<=n;a+=1)try{return await O_(e,t),!0}catch(o){if(!zr(o,"EEXIST"))throw o;await $_(e,i)?a-=1:await Cd(r)}return!1},Ta=async(e,t,n,r)=>{let i=J.join(e,"runtime","extension-install-locks"),a=J.join(i,"scope.lock");await ne.mkdir(i,{recursive:!0});let{attempts:o=R_,delay_ms:s=Ad,stale_ms:c=I_,heartbeat_ms:l}=r??{};if(![o,s,c,l].filter(w=>w!==void 0).every(Number.isFinite))throw new y("Extension install lock timings must be finite numbers.",_.USAGE);let d=Math.max(1,Math.floor(o)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),p=Math.floor(l??m/3);if(m<=0||p<=0||p>=m)throw new y("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",_.USAGE);let f={pid:process.pid,token:E_(),created_at:$(),destination:t};if(!await D_(a,f,d,u,m))throw new y(`Timed out waiting for extension install lock for "${t}".`,_.CONFLICT);let h=T_(a,f.token,p);try{return await n()}finally{await h(),await Pd(a,f.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 Nd=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),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o])}});return await Promise.all(a),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 Md(e,t){let n=S(e),r=t.find(i=>S(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,a)=>i.localeCompare(a)),action_paths:[...r?.action_paths??[]].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]="0dc7b063-dc72-595f-8e40-8a06f9db69e1")}catch{}})();function Ld(e,t){let n=new Set((t?.loaded??[]).flatMap(a=>(a.activation?.commands?.length??0)>0?[`${a.layer}:${S(a.name)}`]:[])),r=e.services.overrides.filter(a=>a.service==="output_format").filter(a=>!n.has(`${a.layer}:${S(a.name)}`)).map(a=>`extension_output_service_override_global:${a.service}:${a.layer}:${a.name}`),i=e.renderers.overrides.filter(a=>(a.commands?.length??0)===0&&a.resultDiscriminator===void 0).map(a=>`extension_output_renderer_override_global:${a.format}:${a.layer}:${a.name}`);return[...new Set([...r,...i])].sort((a,o)=>a.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var Fd=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=Kn(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 P_=1e4,N_=(e,t,n)=>{let r=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c=""]=o.split(/\s+/);return{commit:s,ref:c}}),i=r.find(o=>o.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let a=t?.trim();return a?{checked_at:n,remote_commit:i.commit,available:i.commit!==a}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},jd=async(e,t=Nr)=>{let n=$();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),i=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,P_);return N_(i,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import M_ from"node:fs/promises";import L_ from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="56290db9-933c-590d-8b9f-df62ff45e515")}catch{}})();function Oa(e){return L_.join(e,"extension-migrations.json")}function Ud(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 zd(e,t){return`${e.layer}:${e.name}:${t}`}async function F_(e){let t=Oa(e);if(!await A(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await M_.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 Da(e,t){let n=await F_(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,a)=>{let o=Ud(i,a),s=r.get(zd(i,o));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function j_(e){let t=await Da(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),r=[],i=!1,a=e.migrations.map((d,u)=>({migration:d,index:u})).filter(({migration:d})=>e.scope===void 0||d.layer===e.scope);for(let{migration:d,index:u}of a){let m=Ud(d,u),p=zd(d,m),f=n.get(p),g=String(d.definition.status??"pending").toLowerCase(),h=f?.status??(g==="applied"||g==="failed"?g:"pending");if(h==="applied"){r.push({key:p,layer:d.layer,extension:d.name,id:m,before:h,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:p,layer:d.layer,extension:d.name,id:m,before:h,outcome:"pending"});continue}let w=d.runtime_definition?.run??d.definition.run;if(typeof w!="function"){r.push({key:p,layer:d.layer,extension:d.name,id:m,before:h,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:h}));let b={key:p,layer:d.layer,extension:d.name,id:m,status:"applied",attempted_at:v};n.set(p,b),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,r.push({key:p,layer:d.layer,extension:d.name,id:m,before:h,outcome:"applied"}),i=!0}catch(b){let x=b instanceof Error?b.message:String(b),R={key:p,layer:d.layer,extension:d.name,id:m,status:"failed",attempted_at:v,error:x};n.set(p,R),d.definition.status="failed",d.definition.reason=x,r.push({key:p,layer:d.layer,extension:d.name,id:m,before:h,outcome:"failed",error:x}),i=!0}}if(i){let d=await I(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,p)=>m.key.localeCompare(p.key))};await ar({pmRoot:e.pmRoot,filePath:Oa(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
|
|
37
37
|
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let o=r.filter(d=>d.outcome==="pending").length,s=r.filter(d=>d.outcome==="applied").length,c=r.filter(d=>d.outcome==="skipped").length,l=r.filter(d=>d.outcome==="failed").length;return{ok:l===0,dry_run:e.dryRun===!0,state_path:Oa(e.pmRoot),total:r.length,pending_count:o,applied_count:s,skipped_count:c,failed_count:l,migrations:r}}async function qd(e){let t=await I(e.resolvedRoots.settings_root),n=await Ne({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Me(n);e.warnings.push(...n.warnings,...r.warnings);let i=await j_({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}(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 Gd(e,t,n){let r=typeof t=="string"?null:await vn(e),i=r===null?null:e.trim().toLowerCase(),a=i===null?null:await Gl(i),o=Lr(r??e,{forceGithub:typeof t=="string",ref:n}),s=i===null?null:await Hl(e);return{bundledAliasName:i,bundledPackageName:a,installSource:o,sourceResolution:{requested:e,selected:{kind:i===null?o.kind:"builtin",input:i??o.input,...a===null?{}:{package:a}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...a===null?{}:{package:a},command:`pm install ${i}`}],...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 kt from"node:fs/promises";import U_ 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 Pa=async e=>kt.readFile(e).catch(t=>{if(zr(t,"ENOENT"))return null;throw t}),Wd=async(e,t,n,r,i)=>{let a=_n(e),o=K(t),[s,c]=await Promise.all([Pa(a),Pa(o)]);return r&&await kt.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:a,managedStateContents:s,settingsPath:o,settingsContents:c}},Bd=async e=>{await kt.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await kt.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 kt.rm(t,{force:!0}):(await kt.mkdir(U_.dirname(t),{recursive:!0}),await kt.writeFile(t,n))};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b0fbe09-2221-5b8e-8712-90a83df19306")}catch{}})();var z_=4,Kd=[["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"]],q_=Kd.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),G_={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"},W_="__pm_native_output",B_=["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"],Yd=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],H_=["disabled","require_trusted","require_provenance"],Xd={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:[]},J_=e=>{let t=e??Xd,n={};for(let r of B_)n[r]=ke(t[r]??[]);return n},V_=(e,t)=>{for(let n of Yd)t[n].length>0&&(e[n]=t[n]);return e},K_=(e,t)=>{for(let n of H_)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Y_=e=>{let t={};for(let n of Yd)t[n]=ke(e[n]??[]);return t},X_=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:V_(K_({name:t},e),Y_(e))},Z_=e=>(e??[]).map(t=>X_(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Q_=e=>{let t=Object.assign({},Xd,e??{}),n=J_(e),r=Z_(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}},Zd=async(e,t)=>{let n=[t],r=await Wl(t);r&&n.push(r);let i=[...new Set(n.map(a=>S(a)).filter(a=>a.length>0))];for(let a of i){let o=e.find(c=>S(c.name)===a);if(o)return o;let s=e.find(c=>S(c.directory)===a);if(s)return s}},Qd=(e,t)=>{let n=t.trim(),r=new Set(ke(e.extensions.enabled));return new Set(ke(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},eu=(e,t)=>{let n=t.trim(),r=new Set(ke(e.extensions.enabled)),i=new Set(ke(e.extensions.disabled)),a=[...r],o=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},ey=(e,t)=>{let n=t.trim(),r=new Set(ke(e.extensions.enabled)),i=new Set(ke(e.extensions.disabled)),a=[...r],o=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},ty=(e,t)=>{let n=t.trim(),r=new Set(ke(e.extensions.enabled)),i=new Set(ke(e.extensions.disabled)),a=[...r],o=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},ny=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=Kd.map(([i,a,o])=>({action:a,flag:o,distance:Co(t,i,n)})).filter(i=>i.distance!==null).sort((i,a)=>i.distance-a.distance)[0];return r?{action:r.action,flag:r.flag}:null},ry=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=ny(e);if(!r)return new y(`One action flag is required. Use one of: ${q_}. Bare \`pm package\` and \`pm extension\` default to --explore.`,_.USAGE);let i=`pm ${n} ${r.flag}`;return As({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(tu),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},iy=[["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"]],tu={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},ay=e=>tu[e]??null,oy=(e,t)=>{let n=[...new Set(iy.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=ay(e.trim().toLowerCase());if(r)return r;throw ry(e,t)}if(n.length>1)throw new y("Extension action flags are mutually exclusive.",_.USAGE);return n[0]},sy=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new y('Options "--project/--local" and "--global" are mutually exclusive.',_.USAGE);return n?"global":"project"},cy=[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"}}],nu=e=>{for(let t of cy){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},ru=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,update_error:i.update_error,update_check_status:r.status,update_check_reason:r.reason}},ly=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),a=r?Qd(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ru({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:a},t,r,nu(r))}},dy=async(e,t,n,r,i,a)=>{let o=Ie.join(e,t),s=Ie.join(o,"manifest.json"),c=a.get(S(t));if(!await A(s))return ly(t,n,r,c);let l=Symbol("invalid-extension-manifest-json"),d=await lt.readFile(s,"utf8").then(p=>JSON.parse(p)).catch(()=>l);if(d===l)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=_a(d);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(S(u.name))??a.get(S(t));return{summary:ru({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:Qd(r,u.name)},n,m,nu(m))}},qe=async(e,t,n,r)=>{if(!await A(e))return{extensions:[],warnings:[]};let a=(await lt.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,u)=>d.localeCompare(u)),o=new Map(r.entries.map(d=>[S(d.name),d])),s=new Map(r.entries.map(d=>[S(d.directory),d])),c=[],l=[];for(let d of a){let u=await dy(e,d,t,n,o,s);u.warning&&c.push(u.warning),u.summary&&l.push(u.summary)}return{extensions:l.sort((d,u)=>d.name.localeCompare(u.name)),warnings:c.sort((d,u)=>d.localeCompare(u))}},uy=ms(),my=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,py=(e,t,n,r)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),a=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return a&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:my(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:o,...a?{sdk_dependency_status:"missing"}:{}}},fy=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},iu=e=>e.map(t=>fy(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),au=(e,t,n)=>{let r=S(e);return t.find(i=>(n===void 0||i.layer===n)&&S(i.name)===r)},hy=(e,t,n,r)=>n.find(a=>a.scope===t&&S(a.name)===S(e))?.activation_status??(r?"failed":"unknown"),ou=(e,t,n,r,i)=>uy.enqueue(async()=>{let a=process.env.PM_CLI_PACKAGE_ROOT,o=await lt.mkdtemp(Ie.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Ee(import.meta.url,["../.."]);try{let s=await Ne({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:vi(),cache_bust:!0,module_graph_snapshot_root:o}),c=await Me({...s}),l=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...iu(c.failed)],d=Object.fromEntries(s.loaded.map(u=>[S(u.name),Go(zt(c,{extensionName:u.name}))]));return{installed:jr(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:l,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:d}}finally{await lt.rm(o,{recursive:!0,force:!0}),a===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=a}}),Ma=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),a=[...i].sort((c,l)=>{let d=c.name.localeCompare(l.name);return d!==0?d:c.directory.localeCompare(l.directory)}),o=r,s=[];for(let c of a){let l=Ie.join(e,c.directory),d=await Ht(l),u=$(),m={kind:"local",input:c.name,location:l};o=wn(o,{name:d.manifest.name,directory:c.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:u,updated_at:u,source:m}),s.push({name:d.manifest.name,directory:c.directory,version:d.manifest.version,entry:d.manifest.entry,source:m})}return s.length>0&&await vt(e,o),{state:o,adopted_entries:s,unmanaged_candidates:a,already_managed_count:n.length-i.length}},gy=(e,t)=>{let n=L(process.cwd(),t.path),r=Et(n,process.cwd()),i=e==="global"?qn(process.cwd()):n,a=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:a,roots:r}},qr=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 y('Options "--gh" and "--github" must match when both are provided.',_.USAGE);return n[0]},_y=e=>G_[e],yy=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,a=_y(e),o=`<${r}>`,s=`pm ${n} ${a} ${o}`;throw new y(`Action "${e}" requires ${i} input.`,_.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},Gr=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new y('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',_.USAGE);return yy(t,n)},wy=(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}:${S(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${S(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,i,a)=>a.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},vy=(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(i=>i.triggered&&!i.allowed);if(r)throw new y(r.message,_.USAGE)},by=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},ky=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},xy=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:ky(e),warnings:[...new Set(e.warnings)].sort((i,a)=>i.localeCompare(a)),details:t};return e.action==="doctor"&&Object.defineProperty(r,W_,{value:!0,enumerable:!1,configurable:!1}),r},La=async(e,t,n)=>{let r=oy(e,t);vy(r,t);let i=by(e,r,t),a=sy(t),o=gy(a,n),c={action:r,normalizedTarget:i,scope:a,resolvedRoots:o,warnings:[],options:t,global:n},d={...c,withResult:(u,m=!0)=>xy(c,u,m)};return await nw(d)},Sy=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=Qi(r),a={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[a[n],...s,`Install the scaffold: ${Kc(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},Ey=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([qr(r),r.ref].filter(l=>typeof l=="string").map(l=>l.trim()).filter(Boolean).length>0)throw new y('Action "init" does not accept --gh/--github/--ref options.',_.USAGE);let s=Gr(n,t,r),c=await ud(s,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:c.created_directory||c.files.some(l=>l.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:Sy(c,r)})},Ay=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:a,withResult:o}=e;if(t!==void 0)throw new y('Action "reload" does not accept a target argument.',_.USAGE);let s=await I(n.settings_root),c=vi(),l=await Ne({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:a.noExtensions,reload_token:c,cache_bust:!0});r.push(...l.warnings);let d=await Me(l);r.push(...d.warnings);let u={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:l.loaded.length,failed_count:l.failed.length,activated_count:Math.max(0,l.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:l.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(u)},Ry=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:a}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new y('Action "catalog" does not accept a package target.',_.USAGE);return a(await Bl(n,i,r))},Iy=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Cy=e=>({kind:"local",input:e.input,location:e.absolute_path}),$y=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),Ty=(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}),Oy=(e,t,n,r)=>e?Iy(e,t):n.kind==="local"?Cy(n):n.kind==="npm"?$y(n,r):Ty(n,r),Dy=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:Fl(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},Py=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:a,destinationDirectoryName:o}=t,s=await I(r.settings_root),c=await pe(r.selected_root);i.push(...c.warnings);let l=Ie.join(r.selected_root,o),d=await A(l),u=await Ql(a.directory,l);await lt.mkdir(r.selected_root,{recursive:!0});let m=await lt.mkdtemp(Ie.join(r.selected_root,".pm-extension-install-backup-")),p=Ie.join(m,"destination");try{let f=await Wd(r.selected_root,r.settings_root,l,d,p),g=Oy(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),h=c.state.entries.find(x=>S(x.name)===S(a.manifest.name)),w=Dy(h,a.manifest.version,g,$()),v=wn(c.state,{name:a.manifest.name,directory:o,scope:n,manifest_version:a.manifest.version,manifest_entry:a.manifest.entry,capabilities:[...a.manifest.capabilities],contributions:a.manifest.contributions,...w,source:g}),b=eu(s,a.manifest.name);try{u||await Dd(a.directory,l),await $d(l),await Td(l),await vt(r.selected_root,v),b&&await or(r.settings_root,s,"settings:write")}catch(x){try{await Bd(f)}catch(R){throw new AggregateError([x,R],`Extension install failed: ${String(x)}; rollback failed: ${String(R)}`,{cause:R})}throw x}return{settings:s,managedState:v,sourceRecord:g,destinationDirectory:l,destinationExists:d,installInPlace:u,activationChanged:b}}finally{await lt.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},Ny=async(e,t,n)=>{let r=n.filter(i=>S(i.name)===S(t)).flatMap(i=>i.types.map(a=>({name:a.name,folder:a.folder})));return e.scope==="project"&&r.length>0&&await hn(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},My=(e,t,n,r,i)=>{let a=au(t,n.activation_failures,e.scope),o=hy(t,e.scope,n.installed,a),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:a,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},Ly=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:a,withResult:o}=e,{validated:s,destinationDirectoryName:c}=t,l=await Py(e,t),d=await qe(r.selected_root,n,l.settings,l.managedState);i.push(...d.warnings);let u=await ou(r.pm_root,Ie.dirname(r.selected_root),l.settings,d.extensions,a);i.push(...u.warnings);let m=await Ny(e,s.manifest.name,u.item_type_registrations),p=Md(s.manifest.name,u.installed),f=My(e,s.manifest.name,u,p,m),g=u.contribution_inventories[S(s.manifest.name)];return g&&(l.managedState=await jl(r.selected_root,l.managedState,s.manifest.name,g)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:l.sourceRecord,source_resolution:t.sourceResolution,destination_path:l.destinationDirectory,overwritten:[l.destinationExists,!l.installInPlace].every(Boolean),installed_in_place:l.installInPlace,activated:f.activated,settings_changed:l.activationChanged,runtime_activation_status:f.status,command_paths:p.command_paths,action_paths:p.action_paths,contributions:g,command_discovery:py(s.manifest.name,l.sourceRecord,p,f.failure),verification:f.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:f.failure??null}},f.activated)},Fy=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new y('Action "install all" does not accept --ref.',_.USAGE);let a=[],o=new Map;for(let c of await Pr()){let l=await vn(c),d=Ie.resolve(l),u=o.get(d);u===void 0&&(u=await La(c,{...t,install:!0},n),o.set(d,u)),a.push({alias:c,result:u})}r.push(...a.flatMap(c=>c.result.warnings));let s=a.every(c=>c.result.ok);return i({installed_all:s,installed_count:a.filter(c=>c.result.ok).length,failed_count:a.filter(c=>!c.result.ok).length,packages:a.map(c=>{let l=c.result.details;return{alias:c.alias,ok:c.result.ok,extension:l.extension,source:l.source,source_resolution:l.source_resolution,destination_path:l.destination_path,activated:l.activated,settings_changed:l.settings_changed,command_paths:l.command_paths,action_paths:l.action_paths,command_discovery:l.command_discovery,verification:l.verification,runtime_activation_status:l.runtime_activation_status,activation_diagnostics:l.activation_diagnostics,warnings:c.result.warnings}})},s)},jy=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:a,installSource:o,sourceResolution:s}=await Gd(t,n,e.options.ref);if(s.ambiguous){let l=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${l.package}`)}let c=await Zl(o);try{let l=await Ht(c.directory,{source_kind:o.kind,source_input:o.input,source_root:c.source_root}),d=Or(l.manifest.name);return await Ta(r.settings_root,d,()=>Ly(e,{validated:l,destinationDirectoryName:d,bundledAliasName:i,bundledPackageName:a,sourceResolution:s,installSource:o,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},Uy=async e=>{let t=qr(e.options),n=t??Gr(e.normalizedTarget,e.action,e.options);return[t===void 0,zl(n)].every(Boolean)?Fy(e):jy(e,n,t)},zy=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e;if(t!==void 0)throw new y('Action "adopt-all" does not accept a target argument.',_.USAGE);if(qr(a)!==void 0||typeof a.ref=="string"&&a.ref.trim().length>0)throw new y('Action "adopt-all" does not accept --gh/--github/--ref options.',_.USAGE);let c=await I(r.settings_root),l=await pe(r.selected_root);i.push(...l.warnings);let d=await qe(r.selected_root,n,c,l.state);i.push(...d.warnings);let u=await Ma(r.selected_root,n,d.extensions,l.state),m=await qe(r.selected_root,n,c,u.state);i.push(...m.warnings);let p=Ur(n,i,m.extensions,a);i.push(...p.warnings);let f=new Map(m.extensions.map(w=>[`${S(w.name)}:${S(w.directory)}`,w])),g=new Map(m.extensions.map(w=>[S(w.directory),w])),h=u.adopted_entries.map(w=>{let v=S(w.directory),b=f.get(`${S(w.name)}:${v}`)??g.get(v);return{...w,...su(b)}});return o({adopted_all:h.length>0,adopted_count:h.length,already_managed_count:u.already_managed_count,extensions:h,triage:p,warning_codes:p.warning_codes,update_health_partial:p.update_health_partial,update_health_coverage:p.update_health_coverage})},su=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),qy=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=Lr(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new y(`Invalid GitHub shorthand "${e}".`,_.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},Gy=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o,withResult:s}=e,c=Gr(n,t,o),l=qr(o),d=await I(i.settings_root),u=await pe(i.selected_root);a.push(...u.warnings);let m=await qe(i.selected_root,r,d,u.state);a.push(...m.warnings);let p=await Zd(m.extensions,c);if(!p)throw new y(`Installed extension "${c}" was not found in ${r} scope.`,_.NOT_FOUND);if(p.managed)return s({adopted:!1,already_managed:!0,extension:{name:p.name,directory:p.directory}});let f=Ie.join(i.selected_root,p.directory),g=await Ht(f),h=$(),w=qy(l,c,f,o.ref),v=wn(u.state,{name:g.manifest.name,directory:p.directory,scope:r,manifest_version:g.manifest.version,manifest_entry:g.manifest.entry,capabilities:[...g.manifest.capabilities],contributions:g.manifest.contributions,installed_at:h,updated_at:h,source:w});await vt(i.selected_root,v);let b=await qe(i.selected_root,r,d,v);a.push(...b.warnings);let x=b.extensions.find(R=>S(R.name)===S(g.manifest.name))??b.extensions.find(R=>S(R.directory)===S(p.directory));return s({adopted:!0,extension:{name:g.manifest.name,directory:p.directory,version:g.manifest.version,entry:g.manifest.entry},source:w,...su(x)})},cu=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o}=e,s=Gr(n,t,o),c=await I(i.settings_root),l=await pe(i.selected_root);a.push(...l.warnings);let d=await qe(i.selected_root,r,c,l.state);a.push(...d.warnings);let u=await Zd(d.extensions,s);if(!u)throw new y(`Installed extension "${s}" was not found in ${r} scope.`,_.NOT_FOUND);return{settings:c,managedStateRead:l,candidate:u}},Wy=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:a}=await cu(e),o=Ie.join(t.selected_root,a.directory);await lt.rm(o,{recursive:!0,force:!0});let s={...i.state,updated_at:$(),entries:i.state.entries.filter(l=>S(l.name)!==S(a.name)&&S(l.directory)!==S(a.directory))};await vt(t.selected_root,s);let c=ty(r,a.name);return c&&await or(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:a.name,directory:a.directory},destination_path:o,settings_changed:c})},Hd=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:a}=e,{settings:o,candidate:s}=await cu(e),c=t==="activate"?eu(o,s.name):ey(o,s.name);c&&await or(n.settings_root,o,"settings:write");let l=t==="activate"?await ou(n.pm_root,Ie.dirname(n.selected_root),o,[s],i).then(d=>(r.push(...d.warnings),au(s.name,d.activation_failures,e.scope))):void 0;return l&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),a({extension:{name:s.name,directory:s.directory},active:t==="activate"&&l===void 0,runtime_active:t==="activate"&&l===void 0,activation_failure:l??null,settings_changed:c,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},l===void 0)},By=(e,t,n,r,i,a)=>{let o=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],c=i?.adopted_entries.length??0,l=[[a!==null,a??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...l.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},Na=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Hy=(e,t,n,r)=>{if(e!=="project"||t||!Na(r))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Jy=(e,t,n)=>{if(String(e??"").trim().length>0)throw new y('Action "doctor" does not accept a target argument.',_.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new y("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",_.USAGE);let i=kd(n.detail),a=n.trace===!0;if([a,i!=="deep"].every(Boolean))throw new y("--trace requires --detail deep with --doctor.",_.USAGE);return{isolated:r,detailMode:i,includeTrace:a}},Vy=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await Ma(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},Ky=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:Na(r),rerun_command:null,pm_global_path_recipe:null};let a=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:Na(r),rerun_command:t?null:a,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},Yy=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,global:o,withResult:s}=e,{isolated:c,detailMode:l,includeTrace:d}=Jy(t,n,a),u=await I(r.settings_root),m=await pe(r.selected_root);i.push(...m.warnings);let p=await qe(r.selected_root,n,u,m.state);i.push(...p.warnings);let{state:f,fix:g}=await Vy(e,p.extensions,m.state),h=await qe(r.selected_root,n,u,f);i.push(...h.warnings);let w=await Ne({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Me({...w,loaded:w.loaded});i.push(...w.warnings),i.push(...wd(w.failed)),i.push(...v.warnings),i.push(...vd(v.failed)),i.push(...bd(w,v)),i.push(...Ld(v,w)),i.push(...wy(w,v)),i.push(...Fd(v));let b=jr(h.extensions,w,v),x=Sd(n,b,w.loaded.map(M=>({layer:M.layer,name:M.name})),w.failed.map(M=>({name:M.name})),w.disabled_by_flag);i.push(...x.warnings);let R=b.filter(M=>M.update_check_status==="failed").map(M=>`extension_update_check_failed:${M.name}`);i.push(...R);let k=Ur(n,i,b,a);i.push(...k.warnings);let F=[...k.warnings],T={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},E=Sn(F),U=En(),B=k.warning_codes,D=Hy(n,c,a.vocabulary,w),W=By(k.remediation,w.failed.length,v.failed.length,a.vocabulary,g,D),_e=Ky(n,c,a.vocabulary,w),me={status:k.status,scope:n,warning_count:k.warning_count,warning_codes:B,total_extensions:b.length,managed_total:b.filter(M=>M.managed).length,enabled_total:b.filter(M=>M.enabled).length,active_total:b.filter(M=>M.active).length,unmanaged_loaded_extension_count:k.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:k.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:k.unmanaged_expected_extension_count,runtime_active_total:b.filter(M=>M.runtime_active===!0).length,activation_status_totals:{ok:b.filter(M=>M.activation_status==="ok").length,failed:b.filter(M=>M.activation_status==="failed").length,not_loaded:b.filter(M=>M.activation_status==="not_loaded").length,unknown:b.filter(M=>M.activation_status==="unknown").length},unknown_capability_count:E.length,capability_contract_version:U.version,update_available_total:b.filter(M=>M.update_available===!0).length,update_health_coverage:k.update_health_coverage,update_health_partial:k.update_health_partial,update_check_failed_total:b.filter(M=>M.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Ra(w.failed),activation_failures:Ra(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:x.warnings.length,trace_enabled:d,isolation:_e,policy:T,remediation:W},Ge=g?{requested:!0,applied:g.adopted_entries.length>0,adopted_count:g.adopted_entries.length,already_managed_count:g.already_managed_count,adopted_extensions:g.adopted_entries.map(M=>M.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:h.extensions.filter(M=>M.managed).length,adopted_extensions:[]},Pe={mode:l,summary:me,triage:k,trace_enabled:d,capability_contract:U,capability_guidance:E,managed_state_fix:Ge,isolation:_e,policy:w.policy};if(l==="deep"){let M=d?v.failed:v.failed.map(H=>{let{trace:mi,...pi}=H;return pi});Pe.deep={warnings:F,warning_codes:B,capability_contract:U,capability_guidance:E,trace_enabled:d,managed_state:{path:m.path,count:f.entries.length,entries:f.entries},installed_extensions:b,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(H=>({layer:H.layer,directory:H.directory,name:H.name,version:H.version,entry:H.entry,priority:H.priority}))},activation:{failed:M,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:x.summary},d&&(Pe.deep.trace={activation_failures:v.failed.filter(H=>H.trace!==void 0).map(H=>({layer:H.layer,name:H.name,entry_path:H.entry_path,error:H.error,method:H.trace.method,command:H.trace.command,capability:H.trace.capability,missing_capability:H.trace.missing_capability,registration_index:H.trace.registration_index,expected_schema:H.trace.expected_schema,hint:H.trace.hint,received:H.trace.received}))})}return s(Pe)},Xy=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,global:o,withResult:s}=e,c=await I(r.settings_root),l=await Ne({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),d=await Me(l);i.push(...l.warnings),i.push(...d.warnings);let u=pd(t,l,d);if(t!==void 0&&u.extensions.length===0){let m=a.vocabulary==="package"?"package":"extension",p=[...new Set(l.loaded.map(g=>a.vocabulary==="package"&&typeof g.source_package=="string"&&g.source_package.trim().length>0?g.source_package.trim():g.name))].sort((g,h)=>g.localeCompare(h)),f=p.length>0?` Loaded ${m} names: ${p.join(", ")}.`:"";throw new y(`No loaded ${m} named "${t}" was found in ${n} scope.${f} Run pm ${m} explore to list discovered ${m}s.`,_.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},Zy=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await Ma(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let a=await Nd(r.entries,z_,async o=>{if(o.source.kind!=="github")return o;let s=await jd(o.source);return{...o,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:$(),entries:yn(a)},await vt(e.resolvedRoots.selected_root,r)}return{state:r,fix:i}},Qy=async(e,t,n)=>{let r=await Ne({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Me({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:jr(n,r,i),failures:iu(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...r.warnings,...i.warnings])].length,policy:r.policy}}},ew=(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},Jd=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e,s=await I(r.settings_root),c=Q_(s.extensions.policy),l=await pe(r.selected_root);i.push(...l.warnings);let d=await qe(r.selected_root,n,s,l.state);i.push(...d.warnings);let{state:u,fix:m}=await Zy(e,d.extensions,l.state),p=await qe(r.selected_root,n,s,u);if(i.push(...p.warnings),t==="manage"){let v=p.extensions.filter(b=>b.update_check_status==="failed").map(b=>`extension_update_check_failed:${b.name}`);i.push(...v)}let f=await Qy(e,s,p.extensions),g=f.installed,h=Ur(n,i,g,a);i.push(...h.warnings);let w={total:g.length,managed_total:g.filter(v=>v.managed).length,enabled_total:g.filter(v=>v.enabled).length,active_total:g.filter(v=>v.active).length,extensions:g,triage:h,policy:c};return f.failures!==void 0&&(w.activation_diagnostics={failed_count:f.failures.length,failed:f.failures}),t==="explore"&&(w.runtime_probe=f.summary),t==="manage"&&(w.runtime_probe=f.summary,w.managed_state_fix=ew(m,g)),o(w)},Vd={init:Ey,install:Uy,uninstall:Wy,explore:Jd,manage:Jd,describe:Xy,reload:Ay,doctor:Yy,catalog:Ry,adopt:Gy,"adopt-all":zy,activate:Hd,deactivate:Hd,migrate:qd},tw=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),nw=e=>tw(e)?Ta(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Vd[e.action](e)):Vd[e.action](e);import{execFile as rw}from"node:child_process";import{realpath as iw}from"node:fs/promises";import lu from"node:path";import{promisify as aw}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]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var ow=aw(rw),sw=32*1024*1024,cw=1e4,lw=["search/eval-queries.json"];function Fa(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function dw(e){return`'${e.replaceAll("'","'\\''")}'`}async function uw(e,t=iw){return t(e).catch(()=>lu.resolve(e))}async function Wr(e){let t=await _t(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await uw(e),r=Fa(lu.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=ta.map(a=>`${r}/${Fa(a)}`);try{let{stdout:a}=await ow("git",["ls-files","-z","--",...i.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:sw,windowsHide:!0,timeout:cw}),o=new Set(lw.map(l=>`${r}/${l}`)),s=[...new Set(a.split("\0").filter(l=>l.length>0&&!o.has(Fa(l))))].sort((l,d)=>l.localeCompare(d)),c=i.filter(l=>s.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:s,tracked_path_count:s.length,remediation_command:s.length===0?null:`git rm --cached -r -- ${c.map(l=>dw(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import{execFile as mw}from"node:child_process";import{randomUUID as pw}from"node:crypto";import{readdir as fw,readFile as mu}from"node:fs/promises";import Se from"node:path";import{promisify as hw}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]="7b87b458-164a-5332-8803-6b0695481644")}catch{}})();var gw=hw(mw);async function ja(e){try{let{stdout:t}=await gw("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function pu(e,t){let n=Se.dirname(Se.resolve(e,t));for(let r=0;r<12;r+=1){if(await A(Se.join(n,"settings.json")))return n;let i=Se.dirname(n);if(i===n)break;n=i}return null}function Ua(e){return Se.join(e,"merge-receipts")}function Br(e){return`${e}.json`}function _w(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:du(t.retained)??wi(oe(t.retained)),discarded_hash:du(t.discarded)??wi(oe(t.discarded))}))}}function du(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}async function X$(e){let t=await ja(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,i=Se.basename(r,Se.extname(r)),a={version:1,id:pw(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:$(),value_availability:"clone_local"};await gi(t),await le(Se.join(t,Br(a.id)),`${JSON.stringify(a,null,2)}
|
|
@@ -47,4 +47,4 @@ ${a}`,_.GENERIC_FAILURE)}}async function qx(){return Mo(import.meta.url,["../../
|
|
|
47
47
|
`);ae(e.progressEnabled,"writing keyword artifacts"),await le(t,`${JSON.stringify(e.manifest,null,2)}
|
|
48
48
|
`),await le(n,`${i}
|
|
49
49
|
`);let a=[];if(e.mode!=="keyword")try{ae(e.progressEnabled,"writing vectorization status ledger"),await qs(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(o){a.push(`search_vectorization_status_ledger_write_failed:${o instanceof Error?o.message:String(o)}`)}return a}async function tP(e,t){let n=fS(e.mode),r=pS(e),i=e.full===!0;ae(r,`start mode=${n}`);let a=L(process.cwd(),t.path);if(!await A(K(a)))throw new y(`Tracker is not initialized at ${a}. Run pm init first.`,_.NOT_FOUND);let o=lr(await I(a)).settings,s=null;try{s=await de(a,Os,o.locks.ttl_seconds,Y(void 0,"pm-reindex"),!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms)}catch(c){throw c instanceof y&&c.exitCode===_.CONFLICT?new y("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",_.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=_S(o),l=yS(o),d=SS({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:l}),u=n;ae(r,"loading item corpus");let m=await ES({pmRoot:a,settings:o}),p=m.warnings,{documentCandidates:f,metadataDocuments:g}=m;ae(r,`loaded_items=${g.length}`);let h=$(),w=xS(u,h,g),v=Ln.join(a,Eo),b=Ln.join(a,Ao),x=u==="keyword"?await Io(a,f,o.schema,p):g,R=[],k={},F=null,T=kS(u);if(u==="keyword"&&await AS({pmRoot:a,settings:o,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:p}),u!=="keyword"){let B=await DS({pmRoot:a,settings:o,requestedMode:n,activeEmbeddingProvider:d.activeEmbeddingProvider,activeVectorStore:d.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:f,metadataDocuments:g,documentsForKeywordArtifacts:x,forceFullSemantic:i,reindexWarnings:p,semanticWarnings:R,semanticSummary:T,progressEnabled:r});x=B.documentsForKeywordArtifacts,k=B.vectorizationLedgerEntries,F=B.vectorizationEmbeddingMetadata}let E=await PS({pmRoot:a,mode:u,manifest:w,documentsForKeywordArtifacts:x,settings:o,vectorizationLedgerEntries:k,vectorizationEmbeddingMetadata:F,progressEnabled:r}),U=[...await re({path:v,scope:"project",op:"reindex:manifest"}),...await re({path:b,scope:"project",op:"reindex:embeddings"}),...await Zn({mode:u,total_items:g.length})];return ae(r,"done"),{ok:!0,mode:u,total_items:g.length,semantic:T,artifacts:{manifest:Eo,embeddings:Ao},warnings:[...p,...R,...E,...U],generated_at:h}}finally{await s?.()}}export{xA as a,vl as b,N as c,ve as d,Fe as e,Lt as f,Xs as g,Qs as h,gt as i,Pi as j,Cp as k,Mi as l,Li as m,rc as n,jt as o,sn as p,ji as q,zp as r,lc as s,cn as t,Ui as u,_r as v,zi as w,uc as x,mc as y,pc as z,wr as A,vr as B,hc as C,gc as D,_c as E,yc as F,xr as G,kc as H,C as I,ee as J,Vp as K,Hi as L,EE as M,AE as N,Rc as O,RE as P,IE as Q,CE as R,$E as S,TE as T,Ji as U,OE as V,DE as W,Bi as X,PE as Y,NE as Z,Ic as _,ME as $,nf as aa,Tc as ba,HE as ca,mn as da,JE as ea,df as fa,uf as ga,VE as ha,mf as ia,Kc as ja,Mf as ka,Lf as la,_t as ma,GA as na,Wf as oa,Th as pa,BR as qa,HR as ra,JR as sa,hn as ta,VR as ua,KR as va,YR as wa,XR as xa,ZR as ya,QR as za,eI as Aa,tI as Ba,nI as Ca,rI as Da,iI as Ea,La as Fa,ZE as Ga,QE as Ha,Lc as Ia,_w as Ja,X$ as Ka,An as La,Hr as Ma,Z$ as Na,Q$ as Oa,Iu as Pa,jT as Qa,$u as Ra,tm as Sa,XT as Ta,Pu as Ua,rm as Va,W0 as Wa,B0 as Xa,Ob as Ya,Db as Za,K0 as _a,Y0 as $a,X0 as ab,Z0 as bb,Nb as cb,Mb as db,Lb as eb,Q0 as fb,om as gb,jb as hb,sm as ib,oo as jb,lm as kb,Ub as lb,zb as mb,qb as nb,lk as ob,GO as pb,Xm as qb,Dn as rb,oi as sb,yo as tb,ip as ub,ap as vb,oD as wb,yx as xb,op as yb,sp as zb,cp as Ab,Ox as Bb,bD as Cb,ID as Db,YD as Eb,tP as Fb};
|
|
50
|
-
//# sourceMappingURL=chunk-
|
|
50
|
+
//# sourceMappingURL=chunk-ODOVCP45.js.map
|