@unbrained/pm-cli 2026.8.13 → 2026.8.14

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.
Files changed (136) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +141 -112
  3. package/dist/cli/main.js +39 -3
  4. package/dist/cli-bundle/bundle-manifest.json +144 -176
  5. package/dist/cli-bundle/chunks/{chunk-DEDU3DG7.js → chunk-BBOFSVAK.js} +66 -65
  6. package/dist/cli-bundle/chunks/chunk-BFALV3YP.js +5 -0
  7. package/dist/cli-bundle/chunks/{chunk-Q47C67TQ.js → chunk-FIW4P64F.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-QGTUPEU5.js → chunk-G5JUB66K.js} +41 -41
  9. package/dist/cli-bundle/chunks/{chunk-3ZMOWAFM.js → chunk-SBRKH6OR.js} +2 -2
  10. package/dist/cli-bundle/chunks/chunk-TMJ7URWS.js +13 -0
  11. package/dist/cli-bundle/chunks/{chunk-F7FJYGK3.js → chunk-TXMEUUUY.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-YLBAPY22.js → chunk-XAVMOK6B.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-TF3TPKPR.js → chunk-YAMTJL6Y.js} +33 -33
  14. package/dist/cli-bundle/chunks/{chunk-IMGIN7R6.js → chunk-YSVSMJ2B.js} +2 -2
  15. package/dist/cli-bundle/chunks/{register-list-query-4HIZ7EA3.js → register-list-query-T3EHHNNV.js} +2 -2
  16. package/dist/cli-bundle/chunks/{register-mutation-W64FZ5HN.js → register-mutation-E27WCLSZ.js} +2 -2
  17. package/dist/cli-bundle/chunks/{register-operations-C44ET7R5.js → register-operations-4R6I7CPY.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-setup-634MFRXU.js → register-setup-3YXZ444E.js} +2 -2
  19. package/dist/cli-bundle/focused-chunks/{chunk-OOYYKQWX.js → chunk-4DQ2YERC.js} +2 -2
  20. package/dist/cli-bundle/focused-chunks/chunk-F43TT2QQ.js +8 -0
  21. package/dist/cli-bundle/focused-chunks/{chunk-2RI2FESN.js → chunk-K7RWWOAG.js} +2 -2
  22. package/dist/cli-bundle/focused-chunks/chunk-KFSZ3BP6.js +16 -0
  23. package/dist/cli-bundle/focused-chunks/{chunk-3DJSGWVB.js → chunk-KSEDUWVZ.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-NFHFZH2Z.js → chunk-KYUQGTSB.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-IIS2FRKL.js → chunk-LZ4MV3RH.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/chunk-PGXJQLCT.js +155 -0
  27. package/dist/cli-bundle/focused-chunks/{chunk-E3AVJ655.js → chunk-PPFGQDSI.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/chunk-Q4YY3XNF.js +2 -0
  29. package/dist/cli-bundle/focused-chunks/chunk-QK753U3U.js +46 -0
  30. package/dist/cli-bundle/focused-chunks/{chunk-QDZUABWL.js → chunk-QUMB2J27.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/chunk-SM7MTG27.js +2 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-I75MANL7.js → chunk-WCVE2NIG.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-XDNAW5OI.js +18 -0
  34. package/dist/cli-bundle/focused-chunks/{chunk-2JP7W7GO.js → chunk-YOOI3UZX.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/chunk-ZM6TZVHC.js +2 -0
  36. package/dist/cli-bundle/main.js +13 -13
  37. package/dist/cli-bundle/sdk-authoring.js +1 -1
  38. package/dist/cli-bundle/sdk-contracts.js +1 -1
  39. package/dist/cli-bundle/sdk-core.js +44 -41
  40. package/dist/cli-bundle/sdk-governance.js +1 -1
  41. package/dist/cli-bundle/sdk-graph.js +1 -1
  42. package/dist/cli-bundle/sdk-merge.js +109 -1
  43. package/dist/cli-bundle/sdk-query.js +1 -1
  44. package/dist/cli-bundle/sdk-runtime.js +1 -1
  45. package/dist/cli-bundle/sdk-testing.js +1 -1
  46. package/dist/cli-bundle/sdk.js +2 -2
  47. package/dist/core/history/drift-scan.d.ts +6 -0
  48. package/dist/core/history/drift-scan.js +74 -50
  49. package/dist/core/history/workspace-history.d.ts +59 -0
  50. package/dist/core/history/workspace-history.js +197 -10
  51. package/dist/core/output/output.js +12 -4
  52. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +6 -1
  53. package/dist/sdk/cli-contracts/runtime-contracts.js +155 -60
  54. package/dist/sdk/cli-program.js +3 -3
  55. package/dist/sdk/context-relevance.js +12 -4
  56. package/dist/sdk/governance/assurance.js +4 -4
  57. package/dist/sdk/governance/health.js +15 -3
  58. package/dist/sdk/governance/validate-history-drift.d.ts +7 -0
  59. package/dist/sdk/governance/validate-history-drift.js +68 -0
  60. package/dist/sdk/governance/validate.js +4 -46
  61. package/dist/sdk/graph/assembly.d.ts +23 -0
  62. package/dist/sdk/graph/assembly.js +54 -2
  63. package/dist/sdk/graph/durable-cache.js +50 -20
  64. package/dist/sdk/graph/governance-contracts.d.ts +1 -1
  65. package/dist/sdk/graph/governance-contracts.js +4 -2
  66. package/dist/sdk/graph/governance.d.ts +21 -1
  67. package/dist/sdk/graph/governance.js +94 -32
  68. package/dist/sdk/graph/index.d.ts +2 -2
  69. package/dist/sdk/graph/index.js +4 -4
  70. package/dist/sdk/graph/mutation-advisory.js +15 -7
  71. package/dist/sdk/graph/remediation.js +12 -2
  72. package/dist/sdk/history-read.d.ts +8 -0
  73. package/dist/sdk/history-read.js +2 -2
  74. package/dist/sdk/index.d.ts +1 -1
  75. package/dist/sdk/index.js +3 -3
  76. package/dist/sdk/query/history.js +20 -3
  77. package/dist/sdk/read-output-budget.d.ts +2 -0
  78. package/dist/sdk/read-output-budget.js +12 -5
  79. package/dist/sdk/read-output-contracts.d.ts +61 -5
  80. package/dist/sdk/read-output-contracts.js +210 -28
  81. package/dist/sdk/read-output-rows.d.ts +11 -0
  82. package/dist/sdk/read-output-rows.js +47 -2
  83. package/dist/sdk/runtime-primitives.d.ts +1 -1
  84. package/dist/sdk/runtime-primitives.js +3 -3
  85. package/dist/sdk/runtime.js +5 -3
  86. package/docs/ASSURANCE.md +10 -1
  87. package/docs/COMMANDS.md +31 -2
  88. package/docs/READ_OUTPUT_CONTRACTS.md +44 -8
  89. package/docs/RELATIONSHIP_GRAPH.md +20 -5
  90. package/docs/SDK.md +12 -5
  91. package/docs/SDK_CONTEXT_INTEGRITY.md +32 -1
  92. package/docs/TESTING.md +23 -1
  93. package/docs/performance/sdk-entrypoint-import-costs.md +20 -13
  94. package/marketplace.json +2 -2
  95. package/package.json +6 -6
  96. package/packages/pm-beads/extensions/beads/index.ts +1 -0
  97. package/packages/pm-beads/package.json +1 -1
  98. package/packages/pm-calendar/extensions/calendar/index.ts +1 -0
  99. package/packages/pm-calendar/package.json +1 -1
  100. package/packages/pm-command-kit/package.json +1 -1
  101. package/packages/pm-digital-twin/extensions/digital-twin/index.ts +7 -0
  102. package/packages/pm-digital-twin/package.json +1 -1
  103. package/packages/pm-governance-audit/extensions/governance-audit/index.ts +4 -0
  104. package/packages/pm-governance-audit/package.json +1 -1
  105. package/packages/pm-guide-shell/extensions/guide-shell/index.ts +5 -0
  106. package/packages/pm-guide-shell/package.json +1 -1
  107. package/packages/pm-kanban/package.json +1 -1
  108. package/packages/pm-lifecycle-hooks/package.json +1 -1
  109. package/packages/pm-linked-test-adapters/extensions/linked-test-adapters/index.ts +6 -0
  110. package/packages/pm-linked-test-adapters/package.json +1 -1
  111. package/packages/pm-search-advanced/extensions/search-advanced/index.ts +2 -0
  112. package/packages/pm-search-advanced/package.json +1 -1
  113. package/packages/pm-templates/extensions/templates/index.ts +4 -0
  114. package/packages/pm-templates/package.json +1 -1
  115. package/packages/pm-todos/extensions/todos/index.ts +2 -0
  116. package/packages/pm-todos/package.json +1 -1
  117. package/packages/pm-vcs/extensions/vcs/index.ts +7 -0
  118. package/packages/pm-vcs/package.json +1 -1
  119. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  120. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  121. package/scripts/bundle-cli.mjs +17 -4
  122. package/sdk/public-surface.json +209 -29
  123. package/dist/cli-bundle/chunks/chunk-DL5M5J3V.js +0 -13
  124. package/dist/cli-bundle/chunks/chunk-HIUZVCMN.js +0 -5
  125. package/dist/cli-bundle/focused-chunks/chunk-27N23W6M.js +0 -31
  126. package/dist/cli-bundle/focused-chunks/chunk-3BNVU6LC.js +0 -8
  127. package/dist/cli-bundle/focused-chunks/chunk-6MLIRBLV.js +0 -5
  128. package/dist/cli-bundle/focused-chunks/chunk-6XYLENDV.js +0 -155
  129. package/dist/cli-bundle/focused-chunks/chunk-CP4K4WFS.js +0 -2
  130. package/dist/cli-bundle/focused-chunks/chunk-EBTNSFYE.js +0 -2
  131. package/dist/cli-bundle/focused-chunks/chunk-HC2OL2H2.js +0 -2
  132. package/dist/cli-bundle/focused-chunks/chunk-OGC4XSBC.js +0 -17
  133. package/dist/cli-bundle/focused-chunks/chunk-PKPOZXLL.js +0 -2
  134. package/dist/cli-bundle/focused-chunks/chunk-QQX5TDFT.js +0 -16
  135. package/dist/cli-bundle/focused-chunks/chunk-TEZIXMTH.js +0 -2
  136. package/dist/cli-bundle/focused-chunks/chunk-WEH6NSL6.js +0 -18
@@ -1,31 +0,0 @@
1
- import{a as fn,c as At,d as Ct,e as Lr,g as Mr,h as gn,i as Fr,j as Je,k as We,l as Ur,m as zr,n as _n,o as Jr,p as qe,q as Ge,r as Wr,s as qr,t as yn}from"./chunk-OOYYKQWX.js";import{A as Ta,M as Aa,Q as Ca,R as Ra,U as Oa,X as Da,Y as Pa,b as $a,c as Ia}from"./chunk-OGC4XSBC.js";import{a as Vr}from"./chunk-I75MANL7.js";import{B as Pt}from"./chunk-NFHFZH2Z.js";import{a as En}from"./chunk-TEZIXMTH.js";import{$ as _a,Aa as Sa,Ba as Ea,I as Ut,J as la,K as kn,L as ct,N as xn,R as da,S as ua,T as ma,U as pa,V as zt,X as fa,Y as ha,Z as ga,_ as Oe,aa as He,ba as ya,ca as Sn,da as Be,ea as wa,f as sa,fa as va,g as ca,ua as ba,va as ka,za as xa}from"./chunk-WEH6NSL6.js";import{a as Dr,b as Rt,c as hn,d as Pr,e as Nr,f as pe,g as Ot,h as jr,i as $e}from"./chunk-E3AVJ655.js";import{$a as Zr,Ra as vn,U as Q,Ua as Mt,V as A,Wa as he,Xa as Qr,Ya as R,Z,Za as Ft,b as Kr,ea as Yr,eb as ea,ha as Xr,kb as ta,l as F,la as wn,mb as na,na as Lt,nb as ra,o as z,ob as aa,q as fe,qb as ge,rb as oa,s as jt,ub as bn,wb as ia}from"./chunk-6XYLENDV.js";import{Aa as pn,Ba as Rr,Ca as Or,D as Er,Da as ze,E as $r,F as V,Fa as ce,Ha as le,Ja as H,K as mn,Ka as re,L as j,Ma as X,N as Tt,Na as de,O as ne,Q as Ir,Ra as st,Ta as Dt,V as Ee,Xa as Nt,Y as Tr,Ya as Hr,Za as Br,a as yr,d as wr,e as vr,h as It,p as E,q as xr,r as P,ra as Ar,s as G,sa as Cr,t as ie,w as se,x as Se,y as Sr}from"./chunk-2RI2FESN.js";import{P as br,R as kr,Y as w,Z as y,a as Et,d as $t,ka as Gr}from"./chunk-CP4K4WFS.js";import Na from"node:fs/promises";import ja 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]="60154e1b-8348-5b6b-badf-e76bba43bef8")}catch{}})();var ms=8388608,ps=new Set(["resolved","failed"]),fs=[{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 Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function hs(e){try{return(await Na.readdir(ja.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function gs(e,t,n){let r;try{r=await Na.open(ja.join(e,"history",t),"r");let a=(await r.stat()).size,o=Math.min(a,Math.max(0,n)),i=Buffer.alloc(o),{bytesRead:s}=await r.read(i,0,o,0),c=i.subarray(0,s).toString("utf8"),l=s>=a,d=c.lastIndexOf(`
2
- `),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 _s(e){try{let t=JSON.parse(e);return Ve(t)?t:null}catch{return null}}function ys(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let a=Ve(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(a).forEach(([i,s])=>{if(!Ve(s))return;let c=fs.find(u=>u.matches(s.value))?.kind;if(!c)return;let l=`${r}\0${i}\0${c}`,d=n.get(l)??{harness:r,dimension:i,kind:c,count:0};d.count+=1,n.set(l,d)}),!Ve(e.context))return;let o=e.context.agent_provenance_outcomes;Ve(o)&&Object.entries(o).forEach(([i,s])=>{if(!Ve(s)||typeof s.resolver!="string"||!ps.has(String(s.status)))return;let c=`${r}\0${i}\0${s.resolver}`,l=t.get(c)??{harness:r,dimension:i,resolver:s.resolver,attempts:0,successes:0};l.attempts+=1,s.status==="resolved"&&(l.successes+=1),t.set(c,l)})}function ws(e,t,n,r,a){let o=a;for(let i of e.split(`
3
- `)){if(i.trim().length===0)continue;if(o>=r)return{eventsRead:o,truncated:!0};o+=1;let s=_s(i);s&&ys(s,t,n)}return{eventsRead:o,truncated:!1}}async function La(e,t=1e4){let n=new Map,r=new Map,a=0,o=0,i=!1;for(let l of await hs(e)){let d=await gs(e,l,Math.max(0,ms-o));if(d===null)continue;o+=d.bytesRead;let u=ws(d.content,n,r,t,a);if(a=u.eventsRead,u.truncated){i=!0;break}if(!d.complete){i=!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:i?[]:[...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:a,truncated:i}}import ke from"node:fs/promises";import Y from"node:path";import lt from"node:fs/promises";import Jt 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 vs(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:a,created_at:o,ttl_seconds:i}=n;return typeof r!="string"||typeof a!="string"||typeof o!="string"||typeof i!="number"||!Number.isFinite(i)?null:{id:r,owner:a,created_at:o,ttl_seconds:i}}function Ma(e,t,n){let r=vs(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 a=Date.parse(r.created_at);if(!Number.isFinite(a))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 o=n-a,i=Math.floor(o/1e3),s=o>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:i,stale:s,reason:s?"expired":"active"}}}async function Fa(e,t){let n=t??Date.now(),r=Jt.join(e,"locks"),a={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await lt.readdir(r)).filter(s=>s.endsWith(".lock")).sort()}catch(i){if(P(i))return a;throw i}for(let i of o){let s;try{s=await lt.readFile(Jt.join(r,i),"utf8")}catch(l){if(P(l))continue;a.scanned+=1,a.unreadable_lock_count+=1;continue}a.scanned+=1;let{detail:c}=Ma(i,s,n);c==="active"?a.active_lock_count+=1:c==="expired"?a.stale_lock_count+=1:a.unparseable_lock_count+=1}return a}async function Ua(e,t){let{dryRun:n,hooks:r}=t,a=t.now??Date.now(),o=Jt.join(e,"locks"),i={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await lt.readdir(o)).filter(l=>l.endsWith(".lock")).sort()}catch(c){if(P(c))return i;throw c}for(let c of s){i.scanned+=1;let l=Jt.join(o,c),d=`locks/${c}`;if(r?.onRead){let h=await r.onRead(l);i.warnings.push(...h)}let u;try{u=await lt.readFile(l,"utf8")}catch(h){if(P(h)){i.scanned-=1;continue}i.warnings.push(`lock_unreadable:${c}`),i.retained.push(d),i.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=Ma(c,u,a);if(m.detail==="unparseable_json"){i.warnings.push(`lock_unparseable:${c}`),i.retained.push(d),i.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){i.warnings.push(`lock_invalid_timestamp:${c}`),i.retained.push(d),i.entries.push(m.entry);continue}if(m.detail==="active"){i.retained.push(d),i.entries.push(m.entry);continue}if(!n){try{await lt.unlink(l)}catch(h){if(!P(h)){i.warnings.push(`lock_remove_failed:${c}`),i.retained.push(d),i.entries.push(m.entry);continue}}if(r?.onWrite){let h=await r.onWrite(l);i.warnings.push(...h)}}i.removed.push(d),i.entries.push(m.entry)}return i}import Re from"node:fs/promises";import ae 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 bs=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Ke(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Nt(t.extensionName));for(let f of t.extensionNames??[])n.add(Nt(f));let r=f=>n.size===0||n.has(Nt(f)),a=(f,_)=>za(f.filter(v=>r(v.name)).map(_)),o=(f,_)=>za(f.filter(v=>r(v.name)).flatMap(_)),{registrations:i,commands:s,parsers:c,preflight:l,services:d,renderers:u,hooks:m}=e,h=o(i.relationship_kinds??[],f=>f.definitions.map(_=>_.kind)),p=u.overrides.filter(f=>r(f.name)&&((f.commands?.length??0)>0||f.resultDiscriminator!==void 0)).map(f=>({format:f.format,commands:[...f.commands??[]],result_discriminator:f.resultDiscriminator!==void 0})).sort((f,_)=>f.format.localeCompare(_.format)),g=a(i.assurance_providers??[],f=>f.definition.id);return{capabilities:Hr(e,t),commands:a(i.commands,f=>f.command),command_overrides:a(s.overrides,f=>f.command),command_handlers:a(s.handlers,f=>f.command),hooks:bs.filter(([f])=>m[f].some(_=>r(_.name))).map(([,f])=>f),flag_commands:a(i.flags,f=>f.target_command),item_types:o(i.item_types,f=>f.types.map(_=>_.name)),item_fields:o(i.item_fields,f=>f.fields.map(_=>_.name)),...h.length>0?{relationship_kinds:h}:{},migrations:o(i.migrations,f=>typeof f.definition.id=="string"?[f.definition.id]:[]),profiles:a(i.profiles,f=>f.profile.name),importers:a(i.importers,f=>f.importer),exporters:a(i.exporters,f=>f.exporter),search_providers:a(i.search_providers,f=>f.definition.name),vector_store_adapters:a(i.vector_store_adapters,f=>f.definition.name),...g.length>0?{assurance_providers:g}:{},parser_overrides:a(c.overrides,f=>f.command),service_overrides:a(d.overrides,f=>f.service),renderer_overrides:a(u.overrides,f=>f.format),...p.length>0?{renderer_ownership:p}:{},preflight_overrides:l.overrides.filter(f=>r(f.name)).length,preflight_ownership:l.overrides.filter(f=>r(f.name)).map(f=>({commands:[...f.commands??[]]}))}}function za(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 ks=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)}"`},$n=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?ks(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,Ja=(e,t=process.platform)=>{let n=e.map(r=>$n(r,t)).join(" ");return n.length>0?`pm ${n}`:"pm"};import dc from"node:path";import{mkdir as uc}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();var xs=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Ss(e){let t=xs.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Es(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Wa(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,a=new Map;for(let i of e){let s=typeof i=="string"?i.trim():"";if(s.length===0)continue;let c=Ss(s);if(c===void 0)continue;let l=a.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<r&&l.examples.push(s),a.set(c,l)}let o=[];for(let[i,s]of a.entries()){if(s.count<n)continue;let c=Es(i);o.push({name:c,prefix:i,count:s.count,examples:s.examples,shadows_builtin:Dr(c)!==void 0})}return o.sort((i,s)=>s.count-i.count||i.name.localeCompare(s.name)),o}import{createHash as to}from"node:crypto";import Pe from"node:fs/promises";import Xe from"node:path";import{mkdir as $s,readFile as Is}from"node:fs/promises";import Ka from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ed4a26f-2ae2-556a-87db-56844108757f")}catch{}})();var In=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Ts="sdk-workspace-transaction",As=/^[a-zA-Z0-9._-]+$/,Cs=30,Rs=3e3;function qa(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!As.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Ga(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function Ha(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function Ya(e,t){return Ka.join(e,"transactions","sdk",`${t}.json`)}async function Ie(e,t){t.updatedAt=A();let n=Ya(e,t.transactionId);await $s(Ka.dirname(n),{recursive:!0}),await ie(n,`${JSON.stringify(t,null,2)}
4
- `)}function Os(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function De(e){return Object.assign(Object.create(null),e)}function Ds(e,t){try{let n=JSON.stringify(e,(r,a)=>{if(typeof a=="number"&&!Number.isFinite(a))throw new TypeError(`${t} contains a non-finite number`);if(a===void 0||typeof a=="function"||typeof a=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return a});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function Tn(e,t){return e===void 0?void 0:Ds(e,t)}function An(e,t,n,r){let a=Tn(n,r);a===void 0?delete e[t]:e[t]=a}function Ba(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Va(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Ps(e,t){if(!Va(e.startedStepIds,t)||!Va(e.completedStepIds,t)||!Ba(e.results)||!Ba(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),a=e.completedStepIds,o=new Set(a);return Object.keys(e.compensationData).some(i=>!r.has(i))||Object.keys(e.results).some(i=>!o.has(i))?!1:e.status==="committed"?t.every(i=>o.has(i)):e.status!=="compensated"||o.size===0&&r.size===0}function Ns(e,t,n){let r;try{r=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let a=r,o=a.schemaVersion===1&&a.transactionId===t,i=Array.isArray(a.stepIds)&&a.stepIds.length===n.length&&a.stepIds.every((d,u)=>d===n[u]),s=Ps(a,n),c=Os(a),l=["applying","compensating","compensated","committed"].includes(String(a.status));if(!o||!i||!s||!c||!l)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...a,results:De(a.results),compensationData:De(a.compensationData)}}async function js(e,t,n,r,a){let o=a,i=o!==void 0;if(o?.status==="compensating"&&await Xa(e,o),o===void 0||o.status==="compensated"){let s=A();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:De(),compensationData:De()},await Ie(e.pmRoot,o),await _e(e,o,"prepared")}return{journal:o,recovered:i}}async function Ls(e,t,n){try{await Fs(t,e.steps),await Ie(e.pmRoot,t);let r=new Set(t.completedStepIds),a=new Set(t.startedStepIds);for(let o of e.steps){if(r.has(o.id))continue;let i=await o.inspect(),s=Tn(i.result,`Step ${o.id} result`);if(i.state!=="applied"){let c=await o.prepareCompensation?.();An(t.compensationData,o.id,c,`Step ${o.id} compensation data`),a.add(o.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>a.has(d)),await Ie(e.pmRoot,t);let l=await o.apply();s=Tn(l,`Step ${o.id} result`)}await _e(e,t,"step_applied",o.id),r.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),An(t.results,o.id,s,`Step ${o.id} result`),await Ie(e.pmRoot,t),await _e(e,t,"step_recorded",o.id)}return await _e(e,t,"committing"),t.status="committed",await Ie(e.pmRoot,t),await _e(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:De(t.results)}}catch(r){if(r instanceof In||t.status==="committed")throw r;try{await Xa(e,t)}catch(a){throw new AggregateError([r,a],`Workspace transaction failed and compensation failed: ${String(a)}`,{cause:a})}throw r}}async function Ms(e,t,n){try{return Ns(await Is(Ya(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&P(r))return;throw r}}async function _e(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function Fs(e,t){let n=new Set,r=De();for(let a of t){let o=await a.inspect();o.state==="applied"&&(n.add(a.id),An(r,a.id,o.result,`Step ${a.id} result`))}e.results=r,e.completedStepIds=t.map(a=>a.id).filter(a=>n.has(a))}async function Xa(e,t){t.status="compensating",await Ie(e.pmRoot,t),await _e(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let a of[...e.steps].reverse()){if(!r.has(a.id)&&!n.has(a.id))continue;let o;try{o=r.has(a.id)&&(await a.inspect()).state==="applied"}catch{o=r.has(a.id)}o&&(await _e(e,t,"step_compensating",a.id),await a.compensate(t.compensationData[a.id])),n.delete(a.id),r.delete(a.id),t.completedStepIds=e.steps.map(i=>i.id).filter(i=>n.has(i)),t.startedStepIds=e.steps.map(i=>i.id).filter(i=>r.has(i)),delete t.results[a.id],delete t.compensationData[a.id],await Ie(e.pmRoot,t),await _e(e,t,"step_compensated",a.id)}t.status="compensated",await Ie(e.pmRoot,t),await _e(e,t,"compensated")}async function Qa(e){let t=Ga(e.pmRoot,"Transaction pmRoot"),n=qa(e.transactionId,"Transaction id"),r=Ga(e.author,"Transaction author"),a=Ha(e.lockTtlSeconds,Cs,"Transaction lock TTL"),o=Ha(e.lockWaitMs,Rs,"Transaction lock wait"),i=[...e.steps];if(i.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=i.map(d=>{let u=qa(d.id,"Transaction step id");if(u!==d.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return u});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:i,lockTtlSeconds:a,lockWaitMs:o},l=await Z(t,Ts,a,r,!1,!1,o);try{let d=await Ms(t,n,s),u=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:De(d.results)};let m=await js(c,n,r,s,d);return await Ls(c,m.journal,u||m.recovered)}finally{await l()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd777de3-665f-5e01-ac98-8986f2a5a4c2")}catch{}})();function ye(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function no(e){let t=ye(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function ro(e,t){let n=Rn(e),r=ye(t,"migrationScope");return`auto-${to("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function Rn(e){let t=e.kind==="rename-type"?{kind:e.kind,from:ye(e.from,"source"),to:ye(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:H(ye(e.from,"source")),to:H(ye(e.to,"target")),...e.type===void 0?{}:{type:ye(e.type,"type")}}:{kind:e.kind,from:H(ye(e.from,"source")),to:H(ye(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Us(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function zs(e,t,n){let r=X(t.schema),a=Us(n);return de(e,r.files[a],re[a])}function ao(e,t){return Xe.join(e,"transactions","schema",`${t}-plan.json`)}function Wt(e){return e.length===0?null:JSON.parse(e)}async function Ye(e){let t=await G(e);return{exists:t!==null,raw:t??""}}async function oo(e,t){t.exists?await ie(e,t.raw):await Pe.rm(e,{force:!0})}function Js(e,t,n){let r=pe(e),a=r.definitions.findIndex(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),o=r.definitions.findIndex(i=>i.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return $e(r);if(a<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[a],name:t.to})}else a>=0&&r.definitions.splice(a,1);return $e(r)}function Ws(e,t,n){let r=Je(e),a=r.fields.findIndex(i=>i.key===t.from),o=r.fields.findIndex(i=>i.key===t.to);if(n==="stage"){if(o>=0)return We(r);if(a<0)throw new TypeError(`Unknown custom field "${t.from}".`);let i=r.fields[a];r.fields.push({...i,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else a>=0&&r.fields.splice(a,1);return We(r)}function qs(e,t,n){let r=qe(e),a=r.statuses.findIndex(i=>i.id===t.from),o=r.statuses.findIndex(i=>i.id===t.to);if(n==="stage"){if(o>=0)return Ge(r);if(a<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[a],id:t.to})}else a>=0&&r.statuses.splice(a,1);return Ge(r)}function Gs(e,t,n){return t.kind==="rename-type"?Js(e,t,n):t.kind==="rename-field"?Ws(e,t,n):qs(e,t,n)}function Te(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function On(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Qe(e){return Array.isArray(e)?e.map(t=>On(t)).filter(t=>t!==void 0):[]}function Hs(e,t){for(let n of Qe(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>Te(r,t)));for(let n of Qe(e.type_workflows))n.type=Te(n.type,t)}function Bs(e,t){for(let r of Qe(e.definitions))r.default_status=Te(r.default_status,t);let n=On(e.workflow);if(n)for(let[r,a]of Object.entries(n))n[r]=Te(a,t);for(let r of Qe(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(a=>Array.isArray(a)?a.map(o=>Te(o,t)):a))}function Vs(e,t){for(let n of Qe(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(a=>Te(a,t)));for(let r of["options","command_option_policies"])for(let a of Qe(n[r])){let o=r==="options"?"key":"option";a[o]=Te(a[o],t)}}}function Ks(e,t){let n=On(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=Te(n[r],t)}function Cn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?Hs(r,t):t.kind==="rename-field"?Vs(r,t):Bs(r,t),Ks(r,t),`${JSON.stringify(r,null,2)}
5
- `}function io(e,t){if(t.kind==="rename-type"){let r=pe(e).definitions;return{source:r.some(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(a=>a.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=Je(e).fields;return{source:r.some(a=>a.key===t.from),target:r.some(a=>a.key===t.to)}}let n=qe(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function Ys(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function Xs(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function so(e,t){let n=Rn(t.request),r=t.migrationId===void 0?ro(n,t.migrationScope??"plan"):no(t.migrationId),a=e.map(c=>Xs(c,n)).filter(c=>c!==null).sort((c,l)=>c.id.localeCompare(l.id)),o=to("sha256").update(JSON.stringify({migrationId:r,request:n,items:a})).digest("hex"),i=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=a.filter(c=>!i.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:o,affected_item_count:a.length,pending_item_count:s.length,skipped_completed_count:a.length-s.length,items:Object.freeze(s)})}async function Qs(e){let t=V(e.settings,F()),n=[...new Set(Object.values(t.type_to_folder))],r=await ta(e.pmRoot,n),a=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},o=r?await ea({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:a}):null;return o?{items:o.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await ge(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Zs(e,t){let n=await G(ao(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new y(`Stored schema migration plan "${t}" is invalid: ${Tr(r)}`,w.GENERIC_FAILURE)}}async function ec(e,t){let n=ao(e,t.migration_id);await Pe.mkdir(Xe.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await ie(n,`${JSON.stringify(r,null,2)}
6
- `)}function tc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function nc(e){let t=await ra(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new y(`Schema migration item "${e.id}" no longer exists.`,w.NOT_FOUND);return(await aa(t,{schema:e.settings.schema})).document.metadata}function Za(e,t,n){let r=n==="forward"?t.from:t.to,a=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===a.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=a,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===a.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=a,["status"]}let o=e.metadata;if(Object.prototype.hasOwnProperty.call(o,a)&&!Object.prototype.hasOwnProperty.call(o,r))return[];if(!Object.prototype.hasOwnProperty.call(o,r)||Object.prototype.hasOwnProperty.call(o,a))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return o[a]=o[r],delete o[r],[r,a]}function eo(e){return{id:e.id,inspect:async()=>{let t=await Ye(e.filePath),n=io(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Ye(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ye(e.filePath);return await ie(e.filePath,Gs(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await oo(e.filePath,{exists:t.exists,raw:t.raw})}}}function rc(e){return{id:e.stepId,inspect:async()=>{let t=await Ye(e.filePath);return{state:Cn(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Ye(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ye(e.filePath);return await ie(e.filePath,Cn(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await oo(e.filePath,{exists:t.exists,raw:t.raw})}}}function ac(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await R(e.pmRoot),n=V(t,F()).type_to_folder,r=await nc({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),a=Ys(r,e.request).length===0;return{state:a?"applied":"pending",...a?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await R(e.pmRoot),n=V(t,F()).type_to_folder,r=await bn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(a){return{changedFields:Za(a,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await R(e.pmRoot),n=V(t,F()).type_to_folder;await bn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:Za(r,e.request,"reverse")}}})}}}async function oc(e){let t=await Zs(e.pmRoot,e.migrationId);if(t){if(!tc(t.request,e.request))throw new y(`Schema migration id "${e.migrationId}" already belongs to a different request.`,w.CONFLICT);return{plan:t,stored:!0}}let n=await Qs({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...so(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function ic(e){let t=io(await G(e.schemaPath)??"",e.request);if(!t.source)throw new y(`Schema migration source "${e.request.from}" is not a custom definition.`,w.NOT_FOUND);if(t.target)throw new y(`Schema migration target "${e.request.to}" already exists.`,w.CONFLICT);await ec(e.pmRoot,e.plan)}async function sc(e){let t=X(e.settings.schema),n=[...new Set([["types",re.types],["fields",re.fields],["workflows",re.workflows]].map(([a,o])=>de(e.pmRoot,t.files[a],o)).filter(a=>a!==e.schemaPath))];try{let a=Xe.join(e.pmRoot,"templates"),o=await Pe.readdir(a,{withFileTypes:!0});n.push(...o.filter(i=>i.isFile()&&i.name.toLowerCase().endsWith(".json")).map(i=>Xe.join(a,i.name)))}catch(a){if(typeof a!="object"||a===null||!("code"in a)||!P(a))throw a}n.sort((a,o)=>a.localeCompare(o));let r=[];for(let a of n){let o=await G(a);o!==null&&Cn(o,e.request)!==o&&r.push({filePath:a,beforeRaw:o})}return{paths:n,snapshots:r}}async function cc(e){for(let t of e.snapshots){let n=await Pe.readFile(t.filePath,"utf8"),r=Xe.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await vn({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Wt(t.beforeRaw),after:Wt(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function lc(e,t,n){let r=Rn(e),a=j(process.cwd(),n.path);if(!await E(ne(a)))throw new y(`Tracker is not initialized at ${a}. Run pm init first.`,w.NOT_FOUND);let o=t.migrationId===void 0?ro(r,await Pe.realpath(a)):no(t.migrationId),i=await R(a),s=Q(t.author,i.author_default),c=await oc({pmRoot:a,settings:i,migrationId:o,request:r}),l=c.plan;if(t.dryRun===!0)return{...l,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=zs(a,i,r),u=await Pe.readFile(d,"utf8");c.stored||await ic({pmRoot:a,schemaPath:d,request:r,plan:l});let m=await sc({pmRoot:a,schemaPath:d,settings:i,request:r}),h=[eo({id:"stage-schema",filePath:d,request:r,phase:"stage"}),...m.paths.map((_,v)=>rc({filePath:_,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...l.items.map(_=>ac({pmRoot:a,id:_.id,request:r,author:s,force:t.force===!0})),eo({id:"retire-source",filePath:d,request:r,phase:"retire"})],p=await Qa({pmRoot:a,transactionId:`schema-${o}`,author:s,steps:h,lockTtlSeconds:Math.max(i.locks.ttl_seconds,300),lockWaitMs:i.locks.wait_ms}),g=await Pe.readFile(d,"utf8"),{historyPath:f}=await vn({pmRoot:a,author:s,documentPath:Xe.relative(a,d).replaceAll("\\","/"),before:Wt(u),after:Wt(g),op:"schema_migration",idempotencyKey:`${l.migration_id}:${l.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${l.affected_item_count}`,lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms});return await cc({pmRoot:a,author:s,settings:i,request:r,plan:l,snapshots:m.snapshots}),{...l,action:r.kind,applied:!0,recovered:p.recovered,migrated_item_count:l.affected_item_count,workspace_history_path:f}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a035e10-b8fe-52cd-a9c7-0762dd0ab160")}catch{}})();var rh=["add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],qt="schema-types",co="schema-statuses",lo="schema-fields";function Ae(e){return Mt({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function ah(e,t,n){let r=j(process.cwd(),n.path);await we(r);let a;try{a=hn({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(h){throw new y(h instanceof Error?h.message:String(h),w.USAGE)}let o=await R(r),i=X(o.schema),s=de(r,i.files.types,re.types),c=[],l=Q(t.author,o.author_default),d=he(o),u=await Z(r,qt,o.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms),m;try{let h=await G(s),p;try{p=pe(h)}catch(g){throw new y(g instanceof Error?g.message:String(g),w.GENERIC_FAILURE)}try{Pr(a,p);let g=new Map,f=V(o,F());for(let[_,v]of Object.entries(f.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!g.has(x)&&g.set(x,_)}Nr(a,p,g)}catch(g){throw new y(g instanceof Error?g.message:String(g),w.USAGE)}m=Ot(p,a),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await Ae({pmRoot:r,filePath:s,raw:$e(m.file),op:"schema:add-type",author:l,settings:o}),await dt(r,[m.definition],c,"schema:add-type-folder"),c.push(...await z({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await uo(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Ce(c),generated_at:A()}}async function we(e){if(!await E(ne(e)))throw new y(`Tracker is not initialized at ${e}. Run pm init first.`,w.NOT_FOUND)}async function uo(e,t){try{let n=await Ra(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Ce(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function mc(e,t,n,r){let a=V(t,F()),o=r.trim().toLowerCase();return(await ge(e,t.item_format,a.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===o).length}async function pc(e,t,n,r){let a=V(t,F()),o=st(n),i=H(r);return(await ge(e,t.item_format,a.type_to_folder,[],n)).filter(c=>{let l=typeof c.status=="string"?c.status:"";return(o.alias_to_id.get(H(l))??H(l))===i}).length}async function fc(e,t,n,r,a){if(a.length===0||_n.has(a))return;let o=await pc(t,n,r,a);o>0&&e.push(`items_using_status:${o}`);let i=hc(r.workflow,a);i.length>0&&e.push(`status_referenced_by_workflow:${i.join(",")}`)}function hc(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,r])=>r!==void 0&&H(r)===t).map(([r])=>r)}async function oh(e,t,n){let r=j(process.cwd(),n.path);await we(r);let a=await R(r),o=X(a.schema),i=de(r,o.files.types,re.types),s=[],c=Q(t.author,a.author_default),l=he(a),d=await Z(r,qt,a.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms),u;try{let m=await G(i),h;try{h=pe(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),w.GENERIC_FAILURE)}try{u=jr(h,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),w.USAGE)}if(u.removed){let p=(u.definition?.name??e??"").trim();if(p.length>0){let g=await mc(r,a,o,p);g>0&&s.push(`items_using_type:${g}`)}await Ae({pmRoot:r,filePath:i,raw:$e(u.file),op:"schema:remove-type",author:c,settings:a}),s.push(...await z({path:i,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return u.removed&&await uo(r,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:i,definitions:u.file.definitions.length},warnings:Ce(s),generated_at:A()}}function Dn(e,t){return de(e,t.files.statuses,re.statuses)}function Gt(e,t){return de(e,t.files.fields,re.fields)}function mo(e,t){return de(e,t.files.types,re.types)}async function dt(e,t,n,r){for(let a of t){let o=$r(a.folder??Er(a.name)),i=dc.join(e,o);await E(i)||(await uc(i,{recursive:!0}),n.push(...await z({path:i,scope:"project",op:r})))}}function Pn(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function gc(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function _c(e){let t=new Map;for(let n of e){let r=H(n.id);if(r.length!==0){t.set(r,r);for(let a of Array.isArray(n.aliases)?n.aliases:[]){let o=H(a);o.length>0&&!t.has(o)&&t.set(o,r)}}}return t}async function ih(e,t,n){let r=j(process.cwd(),n.path);await we(r);let a;try{a=Jr({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(g){throw new y(g instanceof Error?g.message:String(g),w.USAGE)}let o=await R(r),i=X(o.schema),s=Dn(r,i),c=st(i);try{yn(a,c.alias_to_id)}catch(g){throw new y(g instanceof Error?g.message:String(g),w.USAGE)}let l=gc(c.by_id.get(a.id)),d=[],u=Q(t.author,o.author_default),m=he(o),h=await Z(r,co,o.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,o.locks.wait_ms),p;try{let g=await G(s),f;try{f=qe(g)}catch(v){throw new y(v instanceof Error?v.message:String(v),w.GENERIC_FAILURE)}let _=_c(f.statuses);try{yn(a,_)}catch(v){throw new y(v instanceof Error?v.message:String(v),w.USAGE)}p=Wr(f,a,l),await Ae({pmRoot:r,filePath:s,raw:Ge(p.file),op:"schema:add-status",author:u,settings:o}),d.push(...await z({path:s,scope:"project",op:"schema:add-status"}))}finally{await h()}return{action:"add-status",registered:!0,replaced:p.replaced,status:p.definition,file:{path:s,statuses:p.file.statuses.length},warnings:Ce(d),generated_at:A()}}async function sh(e,t,n){let r=j(process.cwd(),n.path);await we(r);let a=await R(r),o=X(a.schema),i=Dn(r,o),s=[],c=Q(t.author,a.author_default),l=he(a),d=await Z(r,co,a.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms),u;try{let m=await G(i),h;try{h=qe(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),w.GENERIC_FAILURE)}try{u=qr(h,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),w.USAGE)}if(u.removed){let p=H(u.definition?.id??e);await fc(s,r,a,o,p),await Ae({pmRoot:r,filePath:i,raw:Ge(u.file),op:"schema:remove-status",author:c,settings:a}),s.push(...await z({path:i,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:i,statuses:u.file.statuses.length},warnings:Ce(s),generated_at:A()}}function po(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function yc(e,t,n){return{...po(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function fo(e){return{id:e.id,source:_n.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function ho(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function wc(){let e=new Map,t=F();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let a of r){if(typeof a!="object"||a===null||Array.isArray(a))continue;let o=a.name;typeof o=="string"&&o.trim().length>0&&e.set(o.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function vc(e){let t=st(e),n=[],r=[];for(let a of t.definitions){let o=fo(a);o.source==="builtin"?n.push(o):r.push(o)}return{builtin:n,custom:r}}async function ut(e){let t=j(process.cwd(),e.path);await we(t);let n=await R(t),r=X(n.schema),a=de(t,r.files.types,re.types),o=Dn(t,r),i=V(n,F()),s=wc(),c=new Set((n.item_types?.definitions??[]).map(l=>l.name.trim().toLowerCase()).filter(l=>l.length>0&&!s.has(l)));return{pmRoot:t,typesPath:a,statusesPath:o,byType:i.by_type,customNames:c,extensionProvenance:s,schema:r}}async function ch(e){let t=await ut(e),n=[],r=[],a=[];for(let s of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=ho(s.name,t.customNames,new Set(t.extensionProvenance.keys())),l=po(s);c==="extension"?a.push(l):c==="custom"?r.push(l):n.push(l)}let o=vc(t.schema),i=Dt(t.schema).definitions.map(Pn);return{action:"list",builtin:n,custom:r,extension:a,counts:{builtin:n.length,custom:r.length,extension:a.length,total:n.length+r.length+a.length},statuses:{builtin:o.builtin,custom:o.custom,counts:{builtin:o.builtin.length,custom:o.custom.length,total:o.builtin.length+o.custom.length}},fields:{custom:i,counts:{total:i.length}},file:{path:t.typesPath},generated_at:A()}}async function lh(e,t){let n=(e??"").trim();if(n.length===0)throw new y("Type name must not be empty.",w.USAGE);let r=await ut(t),a=Object.values(r.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(i=>i.toLowerCase()===n.toLowerCase()));if(!a)throw new y(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Rt(n)}" to register it.`,w.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:yc(a,ho(a.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(a.name.toLowerCase())),file:{path:r.typesPath},generated_at:A()}}async function dh(e,t){let n=H(e);if(n.length===0)throw new y("Status id must not be empty.",w.USAGE);let r=await ut(t),a=st(r.schema),o=a.alias_to_id.get(n)??n,i=a.by_id.get(o);if(!i)throw new y(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Rt(e??"")}" to register it.`,w.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:fo(i),file:{path:r.statusesPath},generated_at:A()}}async function uh(e,t,n){let r=j(process.cwd(),n.path);await we(r);let a;try{a=Fr({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(p){throw new y(p instanceof Error?p.message:String(p),w.USAGE)}let o=await R(r),i=X(o.schema),s=Gt(r,i),c=[],l=Pt(a.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let d=Q(t.author,o.author_default),u=he(o),m=await Z(r,lo,o.locks.ttl_seconds,d,!!t.force,u.force_required_for_stale_lock,o.locks.wait_ms),h;try{let p=await G(s),g;try{g=Je(p)}catch(f){throw new y(f instanceof Error?f.message:String(f),w.GENERIC_FAILURE)}h=Ur(g,a),await Ae({pmRoot:r,filePath:s,raw:We(h.file),op:"schema:add-field",author:d,settings:o}),c.push(...await z({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:h.replaced,field:h.definition,file:{path:s,fields:h.file.fields.length},warnings:Ce(c),generated_at:A()}}async function bc(e,t,n,r){let a=V(t,F());return(await ge(e,t.item_format,a.type_to_folder,[],n)).filter(i=>{let s=i[r];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function mh(e,t,n){let r=j(process.cwd(),n.path);await we(r);let a=await R(r),o=X(a.schema),i=Gt(r,o),s=[],c=Q(t.author,a.author_default),l=he(a),d=await Z(r,lo,a.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms),u;try{let m=await G(i),h;try{h=Je(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),w.GENERIC_FAILURE)}try{u=zr(h,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),w.USAGE)}if(u.removed){let p=H(u.definition?.key??e),g=H(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(g.length>0){let f=await bc(r,a,o,g);f>0&&s.push(`items_using_field:${f}`)}await Ae({pmRoot:r,filePath:i,raw:We(u.file),op:"schema:remove-field",author:c,settings:a}),s.push(...await z({path:i,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:i,fields:u.file.fields.length},warnings:Ce(s),generated_at:A()}}async function ph(e){let t=await ut(e),n=Dt(t.schema).definitions.map(Pn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Gt(t.pmRoot,t.schema)},generated_at:A()}}async function fh(e,t){let n=H(e);if(n.length===0)throw new y("Field key must not be empty.",w.USAGE);let r=await ut(t),a=Dt(r.schema).by_key.get(n);if(!a)throw new y(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Rt(e??"")}" to register it.`,w.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Pn(a),file:{path:Gt(r.pmRoot,r.schema)},generated_at:A()}}async function hh(e,t,n){let r=j(process.cwd(),n.path);await we(r);let a;try{let g=Mr(e);if(g===void 0)throw new Error(`Type preset name is required. Allowed: ${Lr.join(", ")}.`);a=g}catch(g){throw new y(g instanceof Error?g.message:String(g),w.USAGE)}let o=await R(r),i=X(o.schema),s=mo(r,i),c=[],l=Q(t.author,o.author_default),d=he(o),u=[],m=[],h,p=await Z(r,qt,o.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms);try{let g=await G(s),f;try{f=pe(g)}catch(v){throw new y(v instanceof Error?v.message:String(v),w.GENERIC_FAILURE)}let _=f;for(let v of gn(a)){let x=Ot(_,v);_=x.file,(x.replaced?m:u).push(x.definition.name)}h=_.definitions.length,await Ae({pmRoot:r,filePath:s,raw:$e(_),op:"schema:apply-preset",author:l,settings:o}),await dt(r,gn(a),c,"schema:apply-preset-folder"),c.push(...await z({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await p()}return{action:"apply-preset",preset:a,registered:u,replaced:m,file:{path:s,definitions:h},warnings:Ce(c),generated_at:A()}}function kc(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new y("--min-count must be a positive integer (>= 1).",w.USAGE);return e}async function gh(e,t){let n=j(process.cwd(),t.path);await we(n);let r=await R(n),a=X(r.schema),o=mo(n,a),i=kc(e.minCount),s=V(r,F()),l=(await ge(n,r.item_format,s.type_to_folder,[],a)).map(x=>typeof x.title=="string"?x.title:""),d=Wa(l,{minCount:i}),u=[],m=[],h=[],p=[],g;if(!e.apply){let x;try{x=pe(await G(o))}catch(T){throw new y(T instanceof Error?T.message:String(T),w.GENERIC_FAILURE)}return g=x.definitions.length,{action:"infer-types",applied:!1,min_count:i,candidates:d,registered:m,replaced:h,skipped:p,file:{path:o,definitions:g},warnings:u,generated_at:A()}}let f=Q(e.author,r.author_default),_=he(r),v=await Z(n,qt,r.locks.ttl_seconds,f,!!e.force,_.force_required_for_stale_lock,r.locks.wait_ms);try{let x=await G(o),T;try{T=pe(x)}catch(I){throw new y(I instanceof Error?I.message:String(I),w.GENERIC_FAILURE)}let b=T;for(let I of d){if(I.shadows_builtin){p.push({name:I.name,reason:"shadows_builtin"});continue}let W;try{W=hn({name:I.name})}catch{p.push({name:I.name,reason:"invalid_type_token"});continue}let q=Ot(b,W);b=q.file,(q.replaced?h:m).push(q.definition.name)}g=b.definitions.length,await Ae({pmRoot:n,filePath:o,raw:$e(b),op:"schema:infer-types",author:f,settings:r}),await dt(n,b.definitions.filter(I=>m.includes(I.name)||h.includes(I.name)),u,"schema:infer-types-folder"),u.push(...await z({path:o,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:i,candidates:d,registered:m,replaced:h,skipped:p,file:{path:o,definitions:g},warnings:Ce(u),generated_at:A()}}import go from"node:fs/promises";import Nn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af718efb-d1cf-5adc-9518-c858627e1b54")}catch{}})();function ee(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function k(e){return e.trim().toLowerCase()}function Ht(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let a=t.slice(n,r);if(a.length===0)throw new y("Extension manifest name must resolve to a non-empty directory name.",w.USAGE);if(a==="."||a==="..")throw new y('Extension manifest name must not resolve to "." or "..".',w.USAGE);return a}function jn(e){return Rr(e)}async function xc(e){try{let t=JSON.parse(await go.readFile(Nn.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(r=>typeof t.scripts?.[r]=="string")}}catch{return{has_build_script:!1}}}async function Sc(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new y(`Extension entry file is missing at "${t}".`,w.USAGE);let r=await xc(n.source_root),a=r.package_name?`pm install npm:${r.package_name}`:void 0,o=n.source_input??n.source_root;return new y(`Extension entry "${e.entry}" is absent from GitHub source "${o}". pm install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${a?`Try "${a}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,w.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:a?[a,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:a?[`Retry with ${a}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${o}`,normalized_args:["install",o],...a?{next_best_command:a}:{}}})}async function Ze(e,t={}){let n=Nn.join(e,"manifest.json");if(!await E(n))throw new y(`Extension manifest is missing at "${n}".`,w.USAGE);let r;try{r=JSON.parse(await go.readFile(n,"utf8"))}catch(i){throw new y(`Failed to parse extension manifest at "${n}": ${Ec(i)}`,w.USAGE)}let a=jn(r);if(!a)throw new y(`Extension manifest at "${n}" is invalid.`,w.USAGE);let o=Nn.resolve(e,a.entry);if(!se(e,o))throw new y(`Extension entry "${a.entry}" resolves outside extension directory "${e}".`,w.USAGE);if(!await E(o))throw await Sc(a,o,t);if(!await Or(e,o))throw new y(`Extension entry "${a.entry}" resolves outside extension directory after symlink resolution.`,w.USAGE);return{directory:e,manifest_path:n,entry_path:o,manifest:a}}function Ec(e){return e instanceof Error?e.message:String(e)}import Ln from"node:fs/promises";import $c from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="159d7bbd-1d2a-503d-b3ce-f32dcc6f6547")}catch{}})();var Ic=".managed-extensions.json",Bt=1;function mt(e){return $c.join(e,Ic)}function Tc(){return{version:Bt,updated_at:A(),entries:[]}}function pt(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let a=t.name.localeCompare(n.name);return a!==0?a:t.directory.localeCompare(n.directory)})}function _o(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function te(e){return typeof e=="string"?e:void 0}function Ac(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function Cc(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:te(t.name),package:te(t.package),version:te(t.version),repository:te(t.repository),owner:te(t.owner),repo:te(t.repo),ref:te(t.ref),subpath:te(t.subpath),commit:te(t.commit)}}function Rc(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Ac(t))return null;let n=Cc(t.source);if(!n)return null;let r=Ar(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:ee(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:te(t.last_update_check_at),last_update_remote_commit:te(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:te(t.update_error)}}function Oc(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Bt||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let a=Rc(r);a&&n.push(a)}return{version:Bt,updated_at:te(t.updated_at)??A(),entries:pt(n)}}async function K(e){let t=mt(e),n=Tc();try{let r=await Ln.readFile(t,"utf8"),a=JSON.parse(r),o=Oc(a);if(!o)throw new y(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,w.GENERIC_FAILURE);return{path:t,state:o,warnings:[]}}catch(r){if(r instanceof y)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&P(r))return{path:t,state:n,warnings:[]};throw new y(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,w.GENERIC_FAILURE)}}async function Ne(e,t){let n=mt(e),r={version:Bt,updated_at:A(),entries:pt(t.entries)};await Ln.mkdir(e,{recursive:!0}),await Ln.writeFile(n,`${JSON.stringify(r,null,2)}
7
- `,"utf8")}function ft(e,t){let n=e.entries.filter(r=>k(r.name)!==k(t.name)&&k(r.directory)!==k(t.directory));return n.push(t),{...e,updated_at:A(),entries:pt(n)}}async function yo(e,t,n,r){let a=t.entries.find(i=>k(i.name)===k(n));if(!a)return t;let o=ft(t,{...a,contributions:r});return await Ne(e,o),o}import{execFile as Wc}from"node:child_process";import O from"node:fs/promises";import Jn from"node:os";import $ from"node:path";import{fileURLToPath as qc}from"node:url";import{promisify as Gc}from"node:util";import Hc from"npm-package-arg";import{extract as Bc,list as Vc}from"tar";import Dc from"node:fs/promises";import oe 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]="259656b0-09b7-52c5-8f54-52ac29eec607")}catch{}})();var Pc="PM_CLI_PACKAGE_ROOT",wo={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Nc=new Set(["*","all"]);function Mn(){let e=[],t=process.env[Pc];return typeof t=="string"&&t.trim().length>0&&e.push(oe.resolve(t.trim())),e.push(Se(import.meta.url,["../../.."])),[...new Set(e)]}async function ht(e){let t=e.trim().toLowerCase(),n=await bo(t);if(n)return n;let r=wo[t];if(!r)return null;for(let a of Mn()){let o=oe.join(a,".agents","pm","extensions",r.legacy_extension_directory);if(await E(oe.join(o,"manifest.json")))return o}return null}function vo(e){return Nc.has(e.trim().toLowerCase())}function jc(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Lc(e,t){let n=await Dc.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let a=oe.join(e,r.name);if(!await E(oe.join(a,"package.json")))continue;let o=await At(a),i=o.aliases&&o.aliases.length>0?o.aliases:[jc(r.name)];for(let s of i){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:a,package_name:o.package_name??null})}}}async function Fn(){let e=new Map;for(let t of Mn()){let n=oe.join(t,"packages");await E(n)&&await Lc(n,e)}for(let[t,n]of Object.entries(wo))if(!e.has(t))for(let r of Mn()){let a=oe.join(r,"packages",n.package_directory);if(await E(oe.join(a,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:a,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Vt(){return(await Fn()).map(e=>e.alias)}async function bo(e){let t=e.trim().toLowerCase();return(await Fn()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function ko(e){let t=await bo(e);return t?(await At(t)).package_name??null:null}async function xo(e){let t=await ht(e);if(!t)return null;try{let n=await Ct(t);return n.length!==1?null:(await Ze(n[0])).manifest.name}catch{return null}}function Mc(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function Fc(e,t,n,r,a,o){let i=r==="global"?"--global":"--project",s=Object.fromEntries(fn.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>a.has(c))||o.has(oe.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${i}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:Mc(e),media:e.catalog?.media}}}async function So(e,t,n={}){let r=ze(j(process.cwd(),t.path),process.cwd()),a=e==="global"?r.global:r.project,o=await K(a),i=new Set(o.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>oe.resolve(m.source.location))),s=new Set(o.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),c=[],l=new Map;for(let m of await Fn()){let h=oe.resolve(m.package_root),p=l.get(h)??[];p.push(m),l.set(h,p)}for(let m of l.values()){let h=m[0],p=m.map(f=>f.alias).sort((f,_)=>f.localeCompare(_)),g=await At(h.package_root);c.push(Fc(g,h,p,e,s,i))}let d=zc(n.fields),u=d?c.map(m=>Jc(m,d)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:fn.filter(m=>m!=="extensions"),packages:u}}var Uc=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function zc(e){if(e===void 0)return;let t=ka(e);if(t.length===0)throw new y("Package catalog --fields requires a comma-separated list of field names",w.USAGE);let n=t.filter(r=>!Uc.has(r));if(n.length>0)throw new y(`Unknown package catalog --fields value(s): ${n.join(", ")}`,w.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function Jc(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8994c8e2-8e3a-5e00-a3ca-7bd553c045d7")}catch{}})();var Wn=Gc(Wc),Yt="@unbrained/pm-cli",Kc={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},Un;async function Eo(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=$.resolve(t);for(;;){let a=$.join(r,"node_modules",...n.split("/")),o=$.join(a,"package.json");if(await E(o))try{let s=JSON.parse(await O.readFile(o,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:a}}catch{return null}let i=$.dirname(r);if(i===r)return null;r=i}}function zn(e,t,n){let r=e.split("/").map(l=>l.trim()).filter(l=>l.length>0);if(r.length<2)return null;let a=r[0],o=r[1].replace(/\.git$/i,"");if(a.length===0||o.length===0)return null;let i=r.slice(2),s,c;return i[0]==="tree"&&i.length>=2?(s=i[1],c=i.slice(2).join("/")):i.length>0&&(c=i.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:a,repo:o,repository:`https://github.com/${a}/${o}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function Yc(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new y('npm package source must include a package spec after "npm:".',w.USAGE);if(t)throw new y('Options "--gh/--github" cannot be combined with npm: package sources.',w.USAGE);if(n)throw new y('Option "--ref" cannot be combined with npm: package sources.',w.USAGE);return{kind:"npm",input:e,spec:r}}function Xt(e,t={}){let n=e.trim();if(n.length===0)throw new y("Extension source is required for --install.",w.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Yc(n,t.forceGithub===!0,r);let a=(()=>{try{let i=new URL(n);if(i.hostname!=="github.com")return null;let s=i.pathname.replace(/^\/+/,"");return zn(s,n,r)}catch{return null}})();if(a)return a;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let i=zn(o,n,r);if(!i)throw new y(`Invalid GitHub source "${n}".`,w.USAGE);return i}if(t.forceGithub){let i=zn(n,n,r);if(!i)throw new y(`Invalid GitHub shorthand "${n}".`,w.USAGE);return i}if(/^https?:\/\//i.test(n))throw new y(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,w.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function Kt(e,t=Wn,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let a=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",o=a.trim().length>0?a.trim():r instanceof Error?r.message:String(r);throw new y(`Git command failed: git ${e.join(" ")}
8
- ${o}`,w.GENERIC_FAILURE)}}function Xc(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Qc(e=process.platform){return e==="win32"}async function $o(e,t,n=Wn,r=process.platform){let a=Xc(r);try{return((await n(a,e,{cwd:t,encoding:"utf8",shell:Qc(r)})).stdout??"").trim()}catch(o){let i=typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr):"",s=i.trim().length>0?i.trim():o instanceof Error?o.message:String(o);throw new y(`npm command failed: ${a} ${e.join(" ")}
9
- ${s}`,w.GENERIC_FAILURE)}}function Zc(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 el(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 tl(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return el(e)||n.includes("not found")}function nl(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function rl(e){let t=Zc(e),n=nl(t),r=t.replace(/^.*\//,""),a=n?`github.com/unbraind/${r}`:void 0,o=a?`pm install --project ${a}`: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:o?[o,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:o?[`Try ${o} 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}`],...a&&o?{fallback_candidates:[{source:a,command:o,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:o}:{}}}}}function al(e,t){if(!tl(t))return null;let n=rl(e);return new y(n.message,w.NOT_FOUND,n.context)}async function Io(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await E(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=qc(t);return await E(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await E(t))return t}return null}async function ol(e){let t=await Io(e);if(t)return t;let n=il(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function il(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(r<=0)return e;let a=e.slice(0,r),o=e.slice(r+n.length);if(a.trim().length===0||o.trim().length===0||o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${a}@${$.resolve(t,o)}`;let i;try{i=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(i)?i.slice(1):i;return`${a}@${s}`}function sl(e,t){try{let r=JSON.parse(e),a=Array.isArray(r)?r[0]:void 0;if(a&&typeof a.filename=="string"&&a.filename.trim().length>0)return{tarball:$.resolve(t,a.filename),package:typeof a.name=="string"?a.name:void 0,version:typeof a.version=="string"?a.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.",w.GENERIC_FAILURE);return{tarball:$.resolve(t,n)}}async function cl(e){return ll(e,$o)}async function ll(e,t){let n=await Io(e.spec);if(n){if((await O.stat(n)).isFile()&&To(n))return Ao(n);let s=$.join(n,"package.json"),c=await E(s)?JSON.parse(await O.readFile(s,"utf8")):{};return{directory:await gt(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 O.mkdtemp($.join(Jn.tmpdir(),"pm-npm-package-source-")),a=$.join(r,"pack"),o=$.join(r,"extract");await O.mkdir(a,{recursive:!0}),await O.mkdir(o,{recursive:!0});try{let i=await ol(e.spec),s=await t(["pack",i,"--json","--pack-destination",a]),c=sl(s,a);await Wn("tar",["-xzf",c.tarball,"-C",o],{encoding:"utf8"});let l=$.join(o,"package");return await Co(l),{directory:await gt(l,e.input),package:c.package,version:c.version,cleanup:async()=>{await O.rm(r,{recursive:!0,force:!0})}}}catch(i){await O.rm(r,{recursive:!0,force:!0});let s=al(e.spec,i);throw s||i}}function To(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ve(e){throw new y(e,w.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 dl(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&ve(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,a=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||a.some(o=>o===".."))&&ve(`Local package archive contains an escaping path: "${r}".`),a[0]!=="package"&&ve(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ve(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ve(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ve(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&ve(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function Ao(e,t=Kc){(await O.stat(e)).size>t.maxArchiveBytes&&ve(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await O.mkdtemp($.join(Jn.tmpdir(),"pm-local-package-archive-")),a=$.join(r,"extract");await O.mkdir(a,{recursive:!0});let o={entries:0,expandedBytes:0,packageJsonEntries:0},i;try{if(await Vc({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(i===void 0)try{dl(d,t,o)}catch(u){i=u}}}),i!==void 0)throw i;o.packageJsonEntries!==1&&ve(`Local package archive must contain exactly one package/package.json entry; found ${o.packageJsonEntries}.`),await Bc({file:e,cwd:a,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=$.join(a,"package"),c=$.join(s,"package.json"),l=JSON.parse(await O.readFile(c,"utf8"));return await Co(s),{directory:await gt(s,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.version:void 0,cleanup:async()=>{await O.rm(r,{recursive:!0,force:!0})}}}catch(s){throw await O.rm(r,{recursive:!0,force:!0}),s}}async function Co(e,t=$o){let n=$.join(e,"package.json");if(!await E(n))return;let r;try{r=JSON.parse(await O.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let a=r,o=gl(a),i=ul(a);if(o.length===0&&!i)return;let s={...r};delete s.devDependencies;let c={...s};ml(c),await O.writeFile(n,`${JSON.stringify(c,null,2)}
10
- `,"utf8");try{await Promise.all([O.rm($.join(e,"package-lock.json"),{force:!0}),O.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),o.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),i&&await pl(e)}finally{await O.writeFile(n,`${JSON.stringify(s,null,2)}
11
- `,"utf8")}}function ul(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Yt in t)return!0;return!1}function ml(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Yt],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function pl(e){let t=Se(import.meta.url,["../../.."]),[n,r]=Yt.split("/"),a=$.join(e,"node_modules",n),o=$.join(a,r);await O.mkdir(a,{recursive:!0}),await O.rm(o,{recursive:!0,force:!0}),await O.symlink(t,o,fl(process.platform))}function fl(e){return e==="win32"?"junction":"dir"}function hl(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.`,w.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 a=r.charCodeAt(0);return a<=31||a===127||"&|;()`\"'".includes(r)}))throw new y(`Extension runtime dependency "${e}" has an unsafe version specifier.`,w.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{Hc.resolve(e,t)}catch{throw new y(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,w.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 gl(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,a]of Object.entries(n)){if(r===Yt||typeof a!="string"||a.trim().length===0||t.has(r))continue;let o=a.trim();t.set(r,hl(r,o))}return[...t.values()]}async function gt(e,t){let n=await Ct(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(a=>$.relative(e,a).replaceAll($.sep,"/")).sort((a,o)=>a.localeCompare(o));throw new y(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,w.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.`,w.USAGE)}async function _l(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push($.posix.join(".agents/pm/extensions",t.subpath)),n.push($.posix.join(".custom/pm-extensions",t.subpath)),n.push($.posix.join(".custom/pm-extension",t.subpath)));for(let a of n){let o=$.resolve(e,a);if(se(e,o)&&await E($.join(o,"manifest.json")))return{directory:o,resolved_subpath:a}}if(await E($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await gt(e,t.input);return{directory:r,resolved_subpath:$.relative(e,r).replaceAll($.sep,"/")}}function yl(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 wl(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!yl(n))return new y(t,w.NOT_FOUND);let r=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,i=typeof o=="string"&&o.trim().length>0?$.resolve(o.trim()):"";Un?.key!==i&&(Un={key:i,aliases:await Vt()}),r=Un.aliases}catch{}let a=[`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}".`,w.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:a,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Ro(e){if(e.kind==="local"){let r;try{r=await O.stat(e.absolute_path)}catch{throw await wl(e)}if(r.isFile()&&To(e.absolute_path)){let o=await Ao(e.absolute_path);return{source:e,directory:o.directory,source_root:$.dirname(o.directory),resolved_subpath:$.relative($.dirname(o.directory),o.directory).replaceAll($.sep,"/"),npm_package:o.package,npm_version:o.version,cleanup:o.cleanup}}if(!r.isDirectory())throw new y(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,w.USAGE);let a=await gt(e.absolute_path,e.input);return{source:e,directory:a,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await cl(e);return{source:e,directory:r.directory,source_root:$.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:$.relative($.dirname(r.directory),r.directory).replaceAll($.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await O.mkdtemp($.join(Jn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Kt(n);let r=await Kt(["-C",t,"rev-parse","HEAD"]),a=await _l(t,e);return{source:e,directory:a.directory,source_root:t,resolved_subpath:a.resolved_subpath,commit:r,cleanup:async()=>{await O.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await O.rm(t,{recursive:!0,force:!0}),r}}async function Oo(e,t){if(!await E(e)||!await E(t))return!1;let[n,r]=await Promise.all([O.realpath(e),O.realpath(t)]);return n===r}import _t from"node:fs/promises";import yt 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 qn=1,je="2026.6.24",vl=">=22.18.0",bl={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Do=new Set([...Gr.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Vr).map(e=>e.toLowerCase()),"scaffold"]),kl="^6.0.0",xl="^22.0.0",jo=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],ue=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Po(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Lo(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 Mo(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 Sl={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},No=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Fo={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"]},El={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"]'},$l={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."},Il={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."},Uo="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Tl={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."]},Al={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."]},Cl={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`."]},Rl={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 zo(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 Jo(e,t){return e==="schema"?Cl[t]:e==="profile"?Rl[t]:Al[t]}function Ol(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 a=t[r]?.toLowerCase(),o=r>0&&(r===t.length||a!==void 0&&Do.has(a));return`${(Do.has(n)||o?["starter",...t]:t).join(" ")} ping`}function Wo(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),a=r===t?[]:[r],o=`${e.replace(/-/g,"_")}_owner`,i="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(a)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(i)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(o)},`,' 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(i)}],`,` [${JSON.stringify(i)}, "in_progress"],`,` [${JSON.stringify(i)}, "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 Dl(e,t,n){let r=`${e}-search`,a=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,i=[" 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 i;if(n==="search")return[...i,""," // 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(a)},`,' 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[...i,""," // 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"?[...i,""," // 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({",...Wo(e).map(s=>` ${s}`)," });"]:n==="importers"?[...i,""," // 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(o)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} 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(o)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} 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"?[...i,""," // 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"?[...i,""," // 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"?[...i,""," // 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 };`," });"]:[...i,""," // 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 Pl(e,t,n){let r=n==="hooks",a=n==="search",o=n==="importers",i=n==="schema",s=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",u=n==="services",m=El[n],h=e,p=`${e}s`,g=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`,_=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${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;",...ue,"});",""]:[],x=a?Gn(e,t,"search",m):[],T=o?Gn(e,t,"importers",m):[],b=i?[`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 {",...Po(Lo({extensionName:e,itemTypeName:h,itemTypeFolder:p,fieldName:g,migrationId:f,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],I=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 {",...Po(Mo(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],W=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;",...ue,"});",""]:[],q=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;",...ue,"});",""]:[],S=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;",...ue,"});",""]:[],M=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;",...ue,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",..._,'} from "@unbrained/pm-cli/sdk/testing";',...a?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...jo,`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;",...ue,"});","",...v,...x,...T,...b,...I,...W,...q,...S,...M,`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(`
12
- `)}function Nl(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 jl={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"},Ll={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 Ml(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 Fl(e,t,n){let r=[],a=[...Ml(e,t,n)],o=[" commands: [pingCommand],"],i=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,l=e,d=`${e}s`,u=e.replace(/-/g,""),m=u===l?[]:[u],h=`${e.replace(/-/g,"_")}_note`,p=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),a.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... */ }","});"),o.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),a.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(i)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","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 }),","});"),o.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),a.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,","}));"),o.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"),a.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(h)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(l)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(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(p)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),o.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),a.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({",...Wo(e),"});"),o.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),a.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);`," },","});"),o.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),a.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 };","});"),o.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),a.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,","});"),o.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),a.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 };`,"});"),o.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:a,blueprintFields:o}}function Ul(e,t,n){let r=Fl(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((o,i)=>o.localeCompare(i)).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(`
13
- `)}function Gn(e,t,n,r){if(n==="commands")return[];let a=`${e}-search`,o=`${e}-vector`,i=`${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=h=>[...u," let deactivated = false;"," try {",...h.map(p=>p===""?p:` ${p}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...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(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(o)}, 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(a)},`,' 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(a)},`,' operation: "embed",',' context: { input: "abc", settings: {} as PmSettings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(o)},`,' 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(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(i)},`,' 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(i)},`,' 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(Lo({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:l,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Mo(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 zl(e,t,n){let r=n==="parser",a=JSON.stringify([...Fo[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" };',"",...jo,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(je)},`," },",` target: { pmVersion: ${JSON.stringify(je)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${a});`,` assert.deepEqual(report.manifest?.capabilities, ${a});`,"});","",`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: ${a},`," });"," 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;",...ue,"});","",...Gn(e,t,n,a)].join(`
14
- `)}function Jl(e,t,n){let r=zo(n,"package"),a=Jo(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 (${jl[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`.",Uo,"- `.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 ${Ll[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.",...a,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${qn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${je}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
15
- `)}function Wl(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function ql(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function Gl(e,t,n,r){let a=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&a.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&a.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&a.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&a.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&a.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&a.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&a.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&a.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&a.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),a}function Hl(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function Bl(e,t,n,r="commands",a=!1){let o=`pm-${e}`,i=Fo[r],s=Nl(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:qn,pm_min_version:je,trusted:!0,sandbox_profile:"strict",permissions:{...bl},capabilities:i,...s.length>0?{activation:{commands:s}}:{}},null,2)}
16
- `,l=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Dl(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
17
- `),d=`${JSON.stringify(Sl,null,2)}
18
- `,u=$l[r],m=zo(r,"package"),h=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:vl},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${je}`},devDependencies:{"@types/node":xl,typescript:kl},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)}
19
- `,p=Pl(e,t,r),g=Il[r],f=["node_modules/","*.log","*.tsbuildinfo",""].join(`
20
- `),_=Wl(e),x=["```ts",`import { ${ql(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Gl(e,t,r,_),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Hl(t,r,_),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],T=[`# ${o}`,"","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,Uo,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...x,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Tl[r],...Jo(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${je}\`. 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 \`${qn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${je}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- 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(`
21
- `);return{"package.json":h,"manifest.json":c,"index.ts":a?Ul(e,t,r):l,"index.test.ts":a?zl(e,t,r):p,"tsconfig.json":d,".gitignore":f,"README.md":a?Jl(o,t,r):T}}async function qo(e,t="extension",n="commands",r=!1){let a=n.trim().toLowerCase();if(!No.includes(a))throw new y(`Unknown scaffold capability "${n}". Supported capabilities: ${No.join(", ")}.`,w.USAGE);let o=a;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`.",w.USAGE);let i=r?"declarative":"imperative",s=e.trim(),c=yt.resolve(process.cwd(),s),l=Ht(yt.basename(c)).replace(/^(?:pm-)+/u,""),d=Ol(l),u=Bl(l,d,t,o,r),m=!1;if(await E(c)){if(!(await _t.stat(c)).isDirectory())throw new y(`Scaffold target "${c}" exists and is not a directory.`,w.CONFLICT)}else await _t.mkdir(c,{recursive:!0}),m=!0;for(let[p,g]of Object.entries(u)){let f=yt.join(c,p);if(!await E(f))continue;if(await _t.readFile(f,"utf8")!==g)throw new y(`Scaffold file "${p}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,w.CONFLICT)}let h=[];for(let[p,g]of Object.entries(u)){let f=yt.join(c,p);if(await E(f)){h.push({path:p,status:"unchanged"});continue}await _t.mkdir(yt.dirname(f),{recursive:!0}),await _t.writeFile(f,g,"utf8"),h.push({path:p,status:"created"})}return{extension_name:l,package_name:`pm-${l}`,command_name:d,invocation_command:`pm ${d}`,capability:o,style:i,target_path:c,created_directory:m,files:h}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="536ed530-7726-50ab-bb2d-ace030818f1d")}catch{}})();function Go(e,t){return`${e}:${k(t)}`}function Vl(e,t){let n=[];for(let[r,a]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let i of a){let s=o.get(i.command)??[];o.set(i.command,[...s,i])}for(let[i,s]of o){if(t!==null&&!s.some(l=>t.has(k(l.name))))continue;let c=s.at(-1);n.push({command:i,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,a)=>r.command.localeCompare(a.command)||r.surface.localeCompare(a.surface))}function Ho(e,t,n){let r=new Set(n.failed.map(l=>Go(l.layer,l.name))),a=[...t.loaded.map(l=>({name:l.name,layer:l.layer,version:l.version,activation_status:r.has(Go(l.layer,l.name))?"failed":"ok",surfaces:Ke(n,{extensionName:l.name})})),...t.failed.map(l=>({name:l.name,layer:l.layer,version:"unknown",activation_status:"not_loaded",surfaces:Ke(n,{extensionName:l.name})}))].sort((l,d)=>l.name.localeCompare(d.name)||l.layer.localeCompare(d.layer)),o=typeof e=="string"?k(e):null,i=o===null?null:new Set(t.loaded.filter(l=>k(l.name)===o||typeof l.source_package=="string"&&k(l.source_package)===o||(l.source_aliases??[]).some(d=>k(d)===o)).map(l=>k(l.name)).concat(o)),s=i===null?a:a.filter(l=>i.has(k(l.name))),c=i===null?{}:{extensionNames:[...i]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Ke(n,c),command_ownership:Vl(n,i)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function Hn(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function Qt(e,t,n){let r=k(t),a=n.trim();if(r.length===0||a.length===0)return;let o=e.get(r)??new Set;o.add(a),e.set(r,o)}function Kl(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)Qt(t,r.name,r.command),Qt(n,r.name,r.action);for(let r of e.commands.handlers)Qt(t,r.name,r.command);for(let r of e.commands.overrides)Qt(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Bo(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Yl(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:a,activationFailedNames:o}=e;return t?a.has(n)||o.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 Zt(e,t,n){let r=new Set(t.loaded.map(c=>k(c.name))),a=new Set(t.failed.map(c=>k(c.name))),o=new Set(n.failed.map(c=>k(c.name))),{commandPathsByExtension:i,actionPathsByExtension:s}=Kl(n);return e.map(c=>{let l=k(c.name),d=Bo(i.get(l)),u=Bo(s.get(l)),m={...d?{command_paths:d}:{},...u?{action_paths:u}:{}},h=Yl({enabled:c.enabled,normalizedName:l,loadedNames:r,loadFailedNames:a,activationFailedNames:o});return{...c,...h,...m}})}function Xl(e){let t=0,n=0,r=0;for(let a of e)if(a.startsWith("extension_policy_")){if(t+=1,a.startsWith("extension_policy_violation_")){n+=1;continue}a.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function B(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Yo=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 Ql(e){return Yo.has(ni(e))}function Vo(e){return e==="project"||e==="global"}function Xo(e){let t=e.split(":"),n=t[0];if(!n||!Yo.has(n))return null;let r=t.at(-4),a=t.at(-3)?.trim(),o=t.at(-2),i=t.at(-1)?.trim();return!Vo(r)||!Vo(o)||!a||!i?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:a},displaced:{layer:o,name:i}}}function Zl(e){let t=new Set;for(let n of e){let r=Xo(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Bn(e,t){let n=e.filter(Ql);if(n.length===0)return null;let r=Zl(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 ed(e,t,n,r){let a=t.map(u=>Xo(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(a.length===0)return;let o=e==="global"?"--global":"--project",i=B(r,"deactivate"),s=`${B(r,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(u=>[k(u.name),u])),l=new Map;for(let u of a)for(let m of[u.winner.name,u.displaced.name]){let h=k(m);l.set(h,(l.get(h)??0)+1)}let d=[...l.entries()].map(([u,m])=>{let h=c.get(u),p=h?.name??u,g=h?.command_paths??[],f=h?.action_paths??[];return{action:"deactivate",extension:p,command:`${i} ${p} ${o}`,affected_collisions:m,feature_loss:{command_paths:[...g].sort((_,v)=>_.localeCompare(v)),action_paths:[...f].sort((_,v)=>_.localeCompare(v))}}}).sort((u,m)=>{let h=m.affected_collisions-u.affected_collisions;if(h!==0)return h;let p=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 p!==g?p-g:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:a.length,extension_count:l.size,next_best_command:s,collisions:a,remediation_candidates:d}}function Qo(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 Zo(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let a=r.trace?.missing_capability??r.trace?.capability;typeof a=="string"&&a.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${a.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,a)=>r.localeCompare(a))}function ei(e,t){let n=[];for(let r of Br(e.loaded,t))for(let a of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${a}`);return[...new Set(n)].sort((r,a)=>r.localeCompare(a))}var td=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${B(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: ${Et.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 ${B(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 ${B(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 ${B(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 ${B(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 ${B(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${B(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 nd(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:a,updateCheckFailedTotal:o,policyWarningCount:i,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,u=[],m={options:n,scope:r,scopeFlag:a,updateCheckFailedTotal:o,policyWarningCount:i};if(t.length>0){let h=Bn(t,{deactivate:`${B(n,"deactivate")} <name> ${a}`,doctor:`${B(n,"doctor")} ${a} --detail deep --trace`});h&&u.push(h);for(let p of td)p.matches(t,m)&&u.push(p.build(m))}return s?u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${B(n,"manage")} ${a} --fix-managed-state (or ${B(n,"adopt-all")} ${a}, ${B(n,"adopt")} <name> ${a}, or reinstall via ${B(n,"install")} ${a} <source>).`):c>0&&u.push(`Loaded unmanaged extensions are currently treated as informational. Use ${B(n,"manage")} ${a} --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 ${B(n,"install")} ${a} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${B(n,"manage")} ${a} after extension changes.`),u}function en(e,t,n,r={}){let a=[...new Set(t)].sort((S,M)=>S.localeCompare(M)),o=n.filter(S=>S.managed).length,i=n.filter(S=>S.enabled).length,s=n.filter(S=>S.active).length,c=n.filter(S=>S.update_available===!0).length,l=n.filter(S=>S.managed===!1),d=l.filter(S=>Ko(S)).map(S=>S.name).sort((S,M)=>S.localeCompare(M)),u=l.filter(S=>!Ko(S)).map(S=>S.name).sort((S,M)=>S.localeCompare(M)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let S of n)m[S.update_check_status]+=1;let h=m.failed,p=m.skipped_unmanaged,g=m.skipped_non_github,f=u.length>0,_=f?"partial":"full",v=f?[`extension_update_health_partial_coverage:skipped_unmanaged:${u.length}`]:[],x=[...new Set([...a,...v])].sort((S,M)=>S.localeCompare(M)),T=[...new Set(x.map(S=>ni(S)))].sort((S,M)=>S.localeCompare(M)),b=Xl(x),I=e==="global"?"--global":"--project",W=ed(e,a,n,r),q=nd({normalizedWarnings:a,options:r,scope:e,scopeFlag:I,updateCheckFailedTotal:h,policyWarningCount:b.warning_count,updateHealthPartial:f,skippedUnmanagedTotal:p,skippedNonGithubTotal:g,updateAvailableTotal:c});return{status:x.length===0?"ok":"warn",warning_count:x.length,warning_codes:T,warnings:x,policy_warning_count:b.warning_count,policy_violation_count:b.violation_count,policy_blocked_count:b.blocked_count,total_extensions:n.length,managed_total:o,enabled_total:i,active_total:s,update_available_total:c,update_health_coverage:_,update_health_partial:f,unmanaged_loaded_extension_count:l.length,unmanaged_loaded_extensions:l.map(S=>S.name).sort((S,M)=>S.localeCompare(M)),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:h,top_warnings:x.slice(0,8),remediation:q,...W?{collision_plan:W}:{}}}function ti(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.`,w.USAGE)}function ni(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function wt(e){let t=new Set,n=[];for(let r of e){let a=(()=>{let o=wr(r);return o?[o]:vr(r)})();for(let o of a){let i=`${o.layer}:${o.name}:${o.capability}`;t.has(i)||(t.add(i),n.push(o))}}return n}function vt(){return{version:$t.version,capabilities:[...$t.capabilities],legacy_aliases:{...$t.legacy_aliases}}}function Ko(e){let t=k(e.name),n=k(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function ri(e,t,n,r,a){if(e!=="project"||a)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let o=[...new Set(t.filter(d=>d.active).map(d=>k(d.name)))].sort((d,u)=>d.localeCompare(u)),i=[...new Set(n.filter(d=>d.layer==="project").map(d=>k(d.name)))].sort((d,u)=>d.localeCompare(u)),s=new Set(r.map(d=>k(d.name))),c=o.filter(d=>!i.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:o.length,loaded_project_count:i.length,active_project_names:o,loaded_project_names:i,missing_active_project_names:c}}}import{randomUUID as rd}from"node:crypto";import U from"node:fs/promises";import ad from"node:os";import D from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="263602a2-c000-5df7-80d2-6f095985496f")}catch{}})();var ai=3,od=120,oi=250,id=12e4,sd=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),ii=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,si=e=>sd.has(String(ii(e))),tn=(e,t)=>ii(e)===t,ci=e=>new Promise(t=>{setTimeout(t,e)}),li=async e=>{let t=D.join(e,"package.json");await E(t)||await U.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
22
- `,"utf8")},di=async e=>{let t=Se(import.meta.url,["../../.."]),n=D.join(e,"node_modules","@unbrained"),r=D.join(n,"pm-cli");await U.mkdir(n,{recursive:!0}),await U.rm(r,{recursive:!0,force:!0}),await U.symlink(t,r,process.platform==="win32"?"junction":"dir")},Vn=async e=>{let t=D.resolve(e),n=D.dirname(t),r=D.parse(n).root,a=await U.realpath(r).catch(()=>r),o=D.relative(r,n),i=o===""?[]:o.split(D.sep);for(let[s,c]of i.entries()){let l=D.join(a,c);try{a=await U.realpath(l)}catch{a=D.join(a,...i.slice(s));break}}return D.join(a,D.basename(t))},ui=async(e,t,n,r=ad.tmpdir())=>{let a=D.resolve(e),o=await U.realpath(a).catch(()=>a),i=await Vn(t);if(o===i)return;if(!se(o,i)){await n(e,t,{recursive:!0,force:!0});return}let s=m=>{let h=D.resolve(m);if(h!==a&&!se(a,h))return!1;let p=D.resolve(o,D.relative(a,h));if(p===i||se(i,p))return!1;let f=D.relative(o,p).split(D.sep);return f.some(_=>_==="node_modules"||_.startsWith(".pm-extension-install-backup-"))?!1:f[0]!==".agents"},c=await U.realpath(D.resolve(r)).catch(()=>Vn(r)),l=se(o,c)?D.dirname(o):c;if(se(o,l))throw new y(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,w.USAGE,{code:"extension_install_source_contains_destination"});let d=await U.mkdtemp(D.join(l,"pm-extension-copy-")),u=D.join(d,"extension");try{await n(e,u,{recursive:!0,force:!0,filter:s}),await n(u,t,{recursive:!0,force:!0})}finally{await U.rm(d,{recursive:!0,force:!0})}},mi=async(e,t,n=U.cp)=>{for(let r=1;r<=ai;r+=1)try{await U.rm(t,{recursive:!0,force:!0}),await ui(e,t,n);return}catch(a){if(!si(a)||r===ai)throw a;await ci(oi)}},Kn=async e=>{let t;try{t=await U.readFile(D.join(e,"owner.json"),"utf8")}catch(a){if(!xr(a))throw a;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},pi=async(e,t)=>await Kn(e)!==t?!1:(await U.rm(e,{recursive:!0,force:!0}),!0),cd=async(e,t)=>{let n;try{n=await U.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await Kn(e);return r===null?(await U.rm(e,{recursive:!0,force:!0}),!0):pi(e,r)},ld=(e,t,n)=>{let r=Promise.resolve(),a=setInterval(()=>{r=r.then(async()=>{if(await Kn(e)!==t)return;let o=new Date;await U.utimes(e,o,o)}).catch(()=>{})},n);return a.unref(),async()=>{clearInterval(a),await r}},dd=async(e,t)=>{await U.mkdir(e);try{await U.writeFile(D.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
23
- `,"utf8")}catch(n){throw await U.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},ud=async(e,t,n,r,a)=>{for(let o=1;o<=n;o+=1)try{return await dd(e,t),!0}catch(i){if(!tn(i,"EEXIST"))throw i;await cd(e,a)?o-=1:await ci(r)}return!1},Yn=async(e,t,n,r)=>{let a=D.join(e,"runtime","extension-install-locks"),o=D.join(a,"scope.lock");await U.mkdir(a,{recursive:!0});let{attempts:i=od,delay_ms:s=oi,stale_ms:c=id,heartbeat_ms:l}=r??{};if(![i,s,c,l].filter(_=>_!==void 0).every(Number.isFinite))throw new y("Extension install lock timings must be finite numbers.",w.USAGE);let d=Math.max(1,Math.floor(i)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),h=Math.floor(l??m/3);if(m<=0||h<=0||h>=m)throw new y("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",w.USAGE);let p={pid:process.pid,token:rd(),created_at:A(),destination:t};if(!await ud(o,p,d,u,m))throw new y(`Timed out waiting for extension install lock for "${t}".`,w.CONFLICT);let f=ld(o,p.token,h);try{return await n()}finally{await f(),await pi(o,p.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 fi=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),a=0,o=Array.from({length:Math.min(t,e.length)},async()=>{for(;a<e.length;){let i=a;a+=1,r[i]=await n(e[i])}});return await Promise.all(o),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 hi(e,t){let n=k(e),r=t.find(a=>k(a.name)===n);return{command_paths:[...r?.command_paths??[]].sort((a,o)=>a.localeCompare(o)),action_paths:[...r?.action_paths??[]].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]="0dc7b063-dc72-595f-8e40-8a06f9db69e1")}catch{}})();function gi(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${k(o.name)}`]:[])),r=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>!n.has(`${o.layer}:${k(o.name)}`)).map(o=>`extension_output_service_override_global:${o.service}:${o.layer}:${o.name}`),a=e.renderers.overrides.filter(o=>(o.commands?.length??0)===0&&o.resultDiscriminator===void 0).map(o=>`extension_output_renderer_override_global:${o.format}:${o.layer}:${o.name}`);return[...new Set([...r,...a])].sort((o,i)=>o.localeCompare(i))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var _i=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=Pt(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 md=1e4,pd=(e,t,n)=>{let r=e.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).map(i=>{let[s,c=""]=i.split(/\s+/);return{commit:s,ref:c}}),a=r.find(i=>i.ref.endsWith("^{}"))??r[0];if(!a)return{checked_at:n,available:null,error:"no_remote_reference_found"};let o=t?.trim();return o?{checked_at:n,remote_commit:a.commit,available:a.commit!==o}:{checked_at:n,remote_commit:a.commit,available:null,error:"missing_installed_commit"}},yi=async(e,t=Kt)=>{let n=A();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),a=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,md);return pd(a,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import fd from"node:fs/promises";import hd 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 Xn(e){return hd.join(e,"extension-migrations.json")}function wi(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 vi(e,t){return`${e.layer}:${e.name}:${t}`}async function gd(e){let t=Xn(e);if(!await E(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await fd.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 Qn(e,t){let n=await gd(e),r=new Map(n.entries.map(a=>[a.key,a]));return t.forEach((a,o)=>{let i=wi(a,o),s=r.get(vi(a,i));s&&(a.definition.status=s.status,s.status==="failed"?a.definition.reason=s.error:(delete a.definition.reason,delete a.definition.error,delete a.definition.message))}),n}async function _d(e){let t=await Qn(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),r=[],a=!1,o=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 o){let m=wi(d,u),h=vi(d,m),p=n.get(h),g=String(d.definition.status??"pending").toLowerCase(),f=p?.status??(g==="applied"||g==="failed"?g:"pending");if(f==="applied"){r.push({key:h,layer:d.layer,extension:d.name,id:m,before:f,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:h,layer:d.layer,extension:d.name,id:m,before:f,outcome:"pending"});continue}let _=d.runtime_definition?.run??d.definition.run;if(typeof _!="function"){r.push({key:h,layer:d.layer,extension:d.name,id:m,before:f,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(_({id:m,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:f}));let x={key:h,layer:d.layer,extension:d.name,id:m,status:"applied",attempted_at:v};n.set(h,x),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,r.push({key:h,layer:d.layer,extension:d.name,id:m,before:f,outcome:"applied"}),a=!0}catch(x){let T=x instanceof Error?x.message:String(x),b={key:h,layer:d.layer,extension:d.name,id:m,status:"failed",attempted_at:v,error:T};n.set(h,b),d.definition.status="failed",d.definition.reason=T,r.push({key:h,layer:d.layer,extension:d.name,id:m,before:f,outcome:"failed",error:T}),a=!0}}if(a){let d=await R(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,h)=>m.key.localeCompare(h.key))};await Mt({pmRoot:e.pmRoot,filePath:Xn(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
24
- `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let i=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:Xn(e.pmRoot),total:r.length,pending_count:i,applied_count:s,skipped_count:c,failed_count:l,migrations:r}}async function bi(e){let t=await R(e.resolvedRoots.settings_root),n=await ce({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await le(n);e.warnings.push(...n.warnings,...r.warnings);let a=await _d({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:a,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},a.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 ki(e,t,n){let r=typeof t=="string"?null:await ht(e),a=r===null?null:e.trim().toLowerCase(),o=a===null?null:await ko(a),i=Xt(r??e,{forceGithub:typeof t=="string",ref:n}),s=a===null?null:await Eo(e);return{bundledAliasName:a,bundledPackageName:o,installSource:i,sourceResolution:{requested:e,selected:{kind:a===null?i.kind:"builtin",input:a??i.input,...o===null?{}:{package:o}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...a===null?[]:[{kind:"builtin",input:a,...o===null?{}:{package:o},command:`pm install ${a}`}],...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 Le from"node:fs/promises";import yd 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 Zn=async e=>Le.readFile(e).catch(t=>{if(tn(t,"ENOENT"))return null;throw t}),xi=async(e,t,n,r,a)=>{let o=mt(e),i=ne(t),[s,c]=await Promise.all([Zn(o),Zn(i)]);return r&&await Le.cp(n,a,{recursive:!0,force:!0}),{backupDirectory:a,destinationDirectory:n,destinationExists:r,managedStatePath:o,managedStateContents:s,settingsPath:i,settingsContents:c}},Si=async e=>{await Le.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Le.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await Le.rm(t,{force:!0}):(await Le.mkdir(yd.dirname(t),{recursive:!0}),await Le.writeFile(t,n))};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b0fbe09-2221-5b8e-8712-90a83df19306")}catch{}})();var wd=4,Ti=[["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"]],vd=Ti.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),bd={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"},kd="__pm_native_output",xd=["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"],Ai=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Sd=["disabled","require_trusted","require_provenance"],Ci={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:[]},Ed=e=>{let t=e??Ci,n={};for(let r of xd)n[r]=ee(t[r]??[]);return n},$d=(e,t)=>{for(let n of Ai)t[n].length>0&&(e[n]=t[n]);return e},Id=(e,t)=>{for(let n of Sd)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Td=e=>{let t={};for(let n of Ai)t[n]=ee(e[n]??[]);return t},Ad=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:$d(Id({name:t},e),Td(e))},Cd=e=>(e??[]).map(t=>Ad(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Rd=e=>{let t=Object.assign({},Ci,e??{}),n=Ed(e),r=Cd(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}},Ri=async(e,t)=>{let n=[t],r=await xo(t);r&&n.push(r);let a=[...new Set(n.map(o=>k(o)).filter(o=>o.length>0))];for(let o of a){let i=e.find(c=>k(c.name)===o);if(i)return i;let s=e.find(c=>k(c.directory)===o);if(s)return s}},Oi=(e,t)=>{let n=t.trim(),r=new Set(ee(e.extensions.enabled));return new Set(ee(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},Di=(e,t)=>{let n=t.trim(),r=new Set(ee(e.extensions.enabled)),a=new Set(ee(e.extensions.disabled)),o=[...r],i=[...a];return a.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==i.join("\0")},Od=(e,t)=>{let n=t.trim(),r=new Set(ee(e.extensions.enabled)),a=new Set(ee(e.extensions.disabled)),o=[...r],i=[...a];return r.delete(n),a.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==i.join("\0")},Dd=(e,t)=>{let n=t.trim(),r=new Set(ee(e.extensions.enabled)),a=new Set(ee(e.extensions.disabled)),o=[...r],i=[...a];return r.delete(n),a.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==i.join("\0")},Pd=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=Ti.map(([a,o,i])=>({action:o,flag:i,distance:yr(t,a,n)})).filter(a=>a.distance!==null).sort((a,o)=>a.distance-o.distance)[0];return r?{action:r.action,flag:r.flag}:null},Nd=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=Pd(e);if(!r)return new y(`One action flag is required. Use one of: ${vd}. Bare \`pm package\` and \`pm extension\` default to --explore.`,w.USAGE);let a=`pm ${n} ${r.flag}`;return ia({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(Pi),retry_command:a,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:a,reason:`nearest lifecycle action for "${e}"`}]})},jd=[["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"]],Pi={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Ld=e=>Pi[e]??null,Md=(e,t)=>{let n=[...new Set(jd.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=Ld(e.trim().toLowerCase());if(r)return r;throw Nd(e,t)}if(n.length>1)throw new y("Extension action flags are mutually exclusive.",w.USAGE);return n[0]},Fd=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.',w.USAGE);return n?"global":"project"},Ud=[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"}}],Ni=e=>{for(let t of Ud){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},ji=(e,t,n,r)=>{let a=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:a.contributions,managed:!!n,source:a.source,update_available:a.update_available,last_update_check_at:a.last_update_check_at,last_update_remote_commit:a.last_update_remote_commit,update_error:a.update_error,update_check_status:r.status,update_check_reason:r.reason}},zd=(e,t,n,r)=>{let a=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),o=r?Oi(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ji({name:a.name,directory:e,version:a.manifest_version,entry:a.manifest_entry,enabled:o},t,r,Ni(r))}},Jd=async(e,t,n,r,a,o)=>{let i=ae.join(e,t),s=ae.join(i,"manifest.json"),c=o.get(k(t));if(!await E(s))return zd(t,n,r,c);let l=Symbol("invalid-extension-manifest-json"),d=await Re.readFile(s,"utf8").then(h=>JSON.parse(h)).catch(()=>l);if(d===l)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=jn(d);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=a.get(k(u.name))??o.get(k(t));return{summary:ji({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:Oi(r,u.name)},n,m,Ni(m))}},me=async(e,t,n,r)=>{if(!await E(e))return{extensions:[],warnings:[]};let o=(await Re.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,u)=>d.localeCompare(u)),i=new Map(r.entries.map(d=>[k(d.name),d])),s=new Map(r.entries.map(d=>[k(d.directory),d])),c=[],l=[];for(let d of o){let u=await Jd(e,d,t,n,i,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))}},Wd=Kr(),qd=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Gd=(e,t,n,r)=>{let a=n.command_paths.map(s=>`pm ${s} --help`),o=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,i=n.command_paths.length>0?[...a]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&i.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:qd(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:a,next_steps:i,...o?{sdk_dependency_status:"missing"}:{}}},Hd=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},Li=e=>e.map(t=>Hd(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),Mi=(e,t,n)=>{let r=k(e);return t.find(a=>(n===void 0||a.layer===n)&&k(a.name)===r)},Bd=(e,t,n,r)=>n.find(o=>o.scope===t&&k(o.name)===k(e))?.activation_status??(r?"failed":"unknown"),Fi=(e,t,n,r,a)=>Wd.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,i=await Re.mkdtemp(ae.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Se(import.meta.url,["../.."]);try{let s=await ce({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:a.noExtensions===!0,reload_token:pn(),cache_bust:!0,module_graph_snapshot_root:i}),c=await le({...s}),l=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...Li(c.failed)],d=Object.fromEntries(s.loaded.map(u=>[k(u.name),Cr(Ke(c,{extensionName:u.name}))]));return{installed:Zt(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 Re.rm(i,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),tr=async(e,t,n,r)=>{let a=n.filter(c=>!c.managed),o=[...a].sort((c,l)=>{let d=c.name.localeCompare(l.name);return d!==0?d:c.directory.localeCompare(l.directory)}),i=r,s=[];for(let c of o){let l=ae.join(e,c.directory),d=await Ze(l),u=A(),m={kind:"local",input:c.name,location:l};i=ft(i,{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 Ne(e,i),{state:i,adopted_entries:s,unmanaged_candidates:o,already_managed_count:n.length-a.length}},Vd=(e,t)=>{let n=j(process.cwd(),t.path),r=ze(n,process.cwd()),a=e==="global"?Tt(process.cwd()):n,o=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:a,selected_root:o,roots:r}},nn=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.',w.USAGE);return n[0]},Kd=e=>bd[e],Yd=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",a=`${n} ${r}`,o=Kd(e),i=`<${r}>`,s=`pm ${n} ${o} ${i}`;throw new y(`Action "${e}" requires ${a} input.`,w.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${i}`,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`}]}})},rn=(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).',w.USAGE);return Yd(t,n)},Xd=(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}:${k(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${k(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,a,o)=>o.indexOf(r)===a).sort((r,a)=>r.localeCompare(a))},Qd=(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(a=>a.triggered&&!a.allowed);if(r)throw new y(r.message,w.USAGE)},Zd=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),a=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:a?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},eu=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},tu=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:eu(e),warnings:[...new Set(e.warnings)].sort((a,o)=>a.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(r,kd,{value:!0,enumerable:!1,configurable:!1}),r},nr=async(e,t,n)=>{let r=Md(e,t);Qd(r,t);let a=Zd(e,r,t),o=Fd(t),i=Vd(o,n),c={action:r,normalizedTarget:a,scope:o,resolvedRoots:i,warnings:[],options:t,global:n},d={...c,withResult:(u,m=!0)=>tu(c,u,m)};return await Pu(d)},nu=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),a=$n(r),o={package:`Install dependencies: cd ${a}, then run "npm install"`,extension:`Install type-check dependencies: cd ${a}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},i={package:`Validate the package: cd ${a}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${a}, 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."),[o[n],...s,`Install the scaffold: ${Ja(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,i[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},ru=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:a}=e;if([nn(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.',w.USAGE);let s=rn(n,t,r),c=await qo(s,r.vocabulary??"extension",r.capability,r.declarative===!0);return a({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:nu(c,r)})},au=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:a,global:o,withResult:i}=e;if(t!==void 0)throw new y('Action "reload" does not accept a target argument.',w.USAGE);let s=await R(n.settings_root),c=pn(),l=await ce({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});r.push(...l.warnings);let d=await le(l);r.push(...d.warnings);let u={reload:{token:c,cache_bust:!0,watch:a.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 a.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),i(u)},ou=async e=>{let{normalizedTarget:t,scope:n,options:r,global:a,withResult:o}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new y('Action "catalog" does not accept a package target.',w.USAGE);return o(await So(n,a,r))},iu=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),su=e=>({kind:"local",input:e.input,location:e.absolute_path}),cu=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),lu=(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}),du=(e,t,n,r)=>e?iu(e,t):n.kind==="local"?su(n):n.kind==="npm"?cu(n,r):lu(n,r),uu=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:_o(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},mu=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:a}=e,{validated:o,destinationDirectoryName:i}=t,s=await R(r.settings_root),c=await K(r.selected_root);a.push(...c.warnings);let l=ae.join(r.selected_root,i),d=await E(l),u=await Oo(o.directory,l);await Re.mkdir(r.selected_root,{recursive:!0});let m=await Re.mkdtemp(ae.join(r.selected_root,".pm-extension-install-backup-")),h=ae.join(m,"destination");try{let p=await xi(r.selected_root,r.settings_root,l,d,h),g=du(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),f=c.state.entries.find(T=>k(T.name)===k(o.manifest.name)),_=uu(f,o.manifest.version,g,A()),v=ft(c.state,{name:o.manifest.name,directory:i,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,..._,source:g}),x=Di(s,o.manifest.name);try{u||await mi(o.directory,l),await li(l),await di(l),await Ne(r.selected_root,v),x&&await Ft(r.settings_root,s,"settings:write")}catch(T){try{await Si(p)}catch(b){throw new AggregateError([T,b],`Extension install failed: ${String(T)}; rollback failed: ${String(b)}`,{cause:b})}throw T}return{settings:s,managedState:v,sourceRecord:g,destinationDirectory:l,destinationExists:d,installInPlace:u,activationChanged:x}}finally{await Re.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},pu=async(e,t,n)=>{let r=n.filter(a=>k(a.name)===k(t)).flatMap(a=>a.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&r.length>0&&await dt(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},fu=(e,t,n,r,a)=>{let o=Mi(t,n.activation_failures,e.scope),i=Bd(t,e.scope,n.installed,o),s=[!n.extensions_disabled,i==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${i}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:i,failure:o,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:i,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:a,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},hu=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:a,global:o,withResult:i}=e,{validated:s,destinationDirectoryName:c}=t,l=await mu(e,t),d=await me(r.selected_root,n,l.settings,l.managedState);a.push(...d.warnings);let u=await Fi(r.pm_root,ae.dirname(r.selected_root),l.settings,d.extensions,o);a.push(...u.warnings);let m=await pu(e,s.manifest.name,u.item_type_registrations),h=hi(s.manifest.name,u.installed),p=fu(e,s.manifest.name,u,h,m),g=u.contribution_inventories[k(s.manifest.name)];return g&&(l.managedState=await yo(r.selected_root,l.managedState,s.manifest.name,g)),i({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:p.activated,settings_changed:l.activationChanged,runtime_activation_status:p.status,command_paths:h.command_paths,action_paths:h.action_paths,contributions:g,command_discovery:Gd(s.manifest.name,l.sourceRecord,h,p.failure),verification:p.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:p.failure??null}},p.activated)},gu=async e=>{let{options:t,global:n,warnings:r,withResult:a}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new y('Action "install all" does not accept --ref.',w.USAGE);let o=[],i=new Map;for(let c of await Vt()){let l=await ht(c),d=ae.resolve(l),u=i.get(d);u===void 0&&(u=await nr(c,{...t,install:!0},n),i.set(d,u)),o.push({alias:c,result:u})}r.push(...o.flatMap(c=>c.result.warnings));let s=o.every(c=>c.result.ok);return a({installed_all:s,installed_count:o.filter(c=>c.result.ok).length,failed_count:o.filter(c=>!c.result.ok).length,packages:o.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)},_u=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:a,bundledPackageName:o,installSource:i,sourceResolution:s}=await ki(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:${a}:npm:${l.package}`)}let c=await Ro(i);try{let l=await Ze(c.directory,{source_kind:i.kind,source_input:i.input,source_root:c.source_root}),d=Ht(l.manifest.name);return await Yn(r.settings_root,d,()=>hu(e,{validated:l,destinationDirectoryName:d,bundledAliasName:a,bundledPackageName:o,sourceResolution:s,installSource:i,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},yu=async e=>{let t=nn(e.options),n=t??rn(e.normalizedTarget,e.action,e.options);return[t===void 0,vo(n)].every(Boolean)?gu(e):_u(e,n,t)},wu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:a,options:o,withResult:i}=e;if(t!==void 0)throw new y('Action "adopt-all" does not accept a target argument.',w.USAGE);if(nn(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new y('Action "adopt-all" does not accept --gh/--github/--ref options.',w.USAGE);let c=await R(r.settings_root),l=await K(r.selected_root);a.push(...l.warnings);let d=await me(r.selected_root,n,c,l.state);a.push(...d.warnings);let u=await tr(r.selected_root,n,d.extensions,l.state),m=await me(r.selected_root,n,c,u.state);a.push(...m.warnings);let h=en(n,a,m.extensions,o);a.push(...h.warnings);let p=new Map(m.extensions.map(_=>[`${k(_.name)}:${k(_.directory)}`,_])),g=new Map(m.extensions.map(_=>[k(_.directory),_])),f=u.adopted_entries.map(_=>{let v=k(_.directory),x=p.get(`${k(_.name)}:${v}`)??g.get(v);return{..._,...Ui(x)}});return i({adopted_all:f.length>0,adopted_count:f.length,already_managed_count:u.already_managed_count,extensions:f,triage:h,warning_codes:h.warning_codes,update_health_partial:h.update_health_partial,update_health_coverage:h.update_health_coverage})},Ui=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),vu=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let a=Xt(e,{forceGithub:!0,ref:r});if(a.kind!=="github")throw new y(`Invalid GitHub shorthand "${e}".`,w.USAGE);return{kind:"github",input:a.input,location:a.subpath??".",repository:a.repository,owner:a.owner,repo:a.repo,ref:a.ref,subpath:a.subpath}},bu=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:a,warnings:o,options:i,withResult:s}=e,c=rn(n,t,i),l=nn(i),d=await R(a.settings_root),u=await K(a.selected_root);o.push(...u.warnings);let m=await me(a.selected_root,r,d,u.state);o.push(...m.warnings);let h=await Ri(m.extensions,c);if(!h)throw new y(`Installed extension "${c}" was not found in ${r} scope.`,w.NOT_FOUND);if(h.managed)return s({adopted:!1,already_managed:!0,extension:{name:h.name,directory:h.directory}});let p=ae.join(a.selected_root,h.directory),g=await Ze(p),f=A(),_=vu(l,c,p,i.ref),v=ft(u.state,{name:g.manifest.name,directory:h.directory,scope:r,manifest_version:g.manifest.version,manifest_entry:g.manifest.entry,capabilities:[...g.manifest.capabilities],contributions:g.manifest.contributions,installed_at:f,updated_at:f,source:_});await Ne(a.selected_root,v);let x=await me(a.selected_root,r,d,v);o.push(...x.warnings);let T=x.extensions.find(b=>k(b.name)===k(g.manifest.name))??x.extensions.find(b=>k(b.directory)===k(h.directory));return s({adopted:!0,extension:{name:g.manifest.name,directory:h.directory,version:g.manifest.version,entry:g.manifest.entry},source:_,...Ui(T)})},zi=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:a,warnings:o,options:i}=e,s=rn(n,t,i),c=await R(a.settings_root),l=await K(a.selected_root);o.push(...l.warnings);let d=await me(a.selected_root,r,c,l.state);o.push(...d.warnings);let u=await Ri(d.extensions,s);if(!u)throw new y(`Installed extension "${s}" was not found in ${r} scope.`,w.NOT_FOUND);return{settings:c,managedStateRead:l,candidate:u}},ku=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:a,candidate:o}=await zi(e),i=ae.join(t.selected_root,o.directory);await Re.rm(i,{recursive:!0,force:!0});let s={...a.state,updated_at:A(),entries:a.state.entries.filter(l=>k(l.name)!==k(o.name)&&k(l.directory)!==k(o.directory))};await Ne(t.selected_root,s);let c=Dd(r,o.name);return c&&await Ft(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:i,settings_changed:c})},Ei=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:a,withResult:o}=e,{settings:i,candidate:s}=await zi(e),c=t==="activate"?Di(i,s.name):Od(i,s.name);c&&await Ft(n.settings_root,i,"settings:write");let l=t==="activate"?await Fi(n.pm_root,ae.dirname(n.selected_root),i,[s],a).then(d=>(r.push(...d.warnings),Mi(s.name,d.activation_failures,e.scope))):void 0;return l&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),o({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:[...i.extensions.enabled],disabled:[...i.extensions.disabled]}},l===void 0)},xu=(e,t,n,r,a,o)=>{let i=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[i],c=a?.adopted_entries.length??0,l=[[o!==null,o??""],[t>0,`Run pm ${i} explore --project and pm ${i} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${i} ${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))]},er=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Su=(e,t,n,r)=>{if(e!=="project"||t||!er(r))return null;let a=n==="package"?"package":"extension";return`Global ${a} registrations are included in project diagnostics. For hermetic ${a} smoke tests, rerun pm ${a} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Eu=(e,t,n)=>{if(String(e??"").trim().length>0)throw new y('Action "doctor" does not accept a target argument.',w.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.",w.USAGE);let a=ti(n.detail),o=n.trace===!0;if([o,a!=="deep"].every(Boolean))throw new y("--trace requires --detail deep with --doctor.",w.USAGE);return{isolated:r,detailMode:a,includeTrace:o}},$u=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await tr(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},Iu=(e,t,n,r)=>{let a=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:er(r),rerun_command:null,pm_global_path_recipe:null};let o=`pm ${a} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:er(r),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${a} doctor --project --detail deep --trace`}},Tu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:a,options:o,global:i,withResult:s}=e,{isolated:c,detailMode:l,includeTrace:d}=Eu(t,n,o),u=await R(r.settings_root),m=await K(r.selected_root);a.push(...m.warnings);let h=await me(r.selected_root,n,u,m.state);a.push(...h.warnings);let{state:p,fix:g}=await $u(e,h.extensions,m.state),f=await me(r.selected_root,n,u,p);a.push(...f.warnings);let _=await ce({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:i.noExtensions===!0,ignoreGlobalExtensions:c}),v=await le({..._,loaded:_.loaded});a.push(..._.warnings),a.push(...Qo(_.failed)),a.push(...v.warnings),a.push(...Zo(v.failed)),a.push(...ei(_,v)),a.push(...gi(v,_)),a.push(...Xd(_,v)),a.push(..._i(v));let x=Zt(f.extensions,_,v),T=ri(n,x,_.loaded.map(C=>({layer:C.layer,name:C.name})),_.failed.map(C=>({name:C.name})),_.disabled_by_flag);a.push(...T.warnings);let b=x.filter(C=>C.update_check_status==="failed").map(C=>`extension_update_check_failed:${C.name}`);a.push(...b);let I=en(n,a,x,o);a.push(...I.warnings);let W=[...I.warnings],q={mode:_.policy.mode,trust_mode:_.policy.trust_mode,require_provenance:_.policy.require_provenance,default_sandbox_profile:_.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:_.policy.trusted_extensions.length,allowed_extensions_count:_.policy.allowed_extensions.length,blocked_extensions_count:_.policy.blocked_extensions.length,allowed_capabilities_count:_.policy.allowed_capabilities.length,blocked_capabilities_count:_.policy.blocked_capabilities.length,allowed_surfaces_count:_.policy.allowed_surfaces.length,blocked_surfaces_count:_.policy.blocked_surfaces.length,allowed_commands_count:_.policy.allowed_commands.length,blocked_commands_count:_.policy.blocked_commands.length,allowed_actions_count:_.policy.allowed_actions.length,blocked_actions_count:_.policy.blocked_actions.length,allowed_services_count:_.policy.allowed_services.length,blocked_services_count:_.policy.blocked_services.length,extension_override_count:_.policy.extension_overrides.length},S=wt(W),M=vt(),xe=I.warning_codes,St=Su(n,c,o.vocabulary,_),at=xu(I.remediation,_.failed.length,v.failed.length,o.vocabulary,g,St),Me=Iu(n,c,o.vocabulary,_),Fe={status:I.status,scope:n,warning_count:I.warning_count,warning_codes:xe,total_extensions:x.length,managed_total:x.filter(C=>C.managed).length,enabled_total:x.filter(C=>C.enabled).length,active_total:x.filter(C=>C.active).length,unmanaged_loaded_extension_count:I.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:I.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:I.unmanaged_expected_extension_count,runtime_active_total:x.filter(C=>C.runtime_active===!0).length,activation_status_totals:{ok:x.filter(C=>C.activation_status==="ok").length,failed:x.filter(C=>C.activation_status==="failed").length,not_loaded:x.filter(C=>C.activation_status==="not_loaded").length,unknown:x.filter(C=>C.activation_status==="unknown").length},unknown_capability_count:S.length,capability_contract_version:M.version,update_available_total:x.filter(C=>C.update_available===!0).length,update_health_coverage:I.update_health_coverage,update_health_partial:I.update_health_partial,update_check_failed_total:x.filter(C=>C.update_check_status==="failed").length,load_failure_count:_.failed.length,activation_failure_count:v.failed.length,load_failures:Hn(_.failed),activation_failures:Hn(v.failed),blocking_failure_count:_.failed.length+v.failed.length,has_blocking_failures:_.failed.length+v.failed.length>0,consistency_warning_count:T.warnings.length,trace_enabled:d,isolation:Me,policy:q,remediation:at},ot=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(C=>C.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:f.extensions.filter(C=>C.managed).length,adopted_extensions:[]},Ue={mode:l,summary:Fe,triage:I,trace_enabled:d,capability_contract:M,capability_guidance:S,managed_state_fix:ot,isolation:Me,policy:_.policy};if(l==="deep"){let C=d?v.failed:v.failed.map(N=>{let{trace:_r,...it}=N;return it});Ue.deep={warnings:W,warning_codes:xe,capability_contract:M,capability_guidance:S,trace_enabled:d,managed_state:{path:m.path,count:p.entries.length,entries:p.entries},installed_extensions:x,load:{roots:_.roots,policy:_.policy,warnings:_.warnings,failed:_.failed,loaded:_.loaded.map(N=>({layer:N.layer,directory:N.directory,name:N.name,version:N.version,entry:N.entry,priority:N.priority}))},activation:{failed:C,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:T.summary},d&&(Ue.deep.trace={activation_failures:v.failed.filter(N=>N.trace!==void 0).map(N=>({layer:N.layer,name:N.name,entry_path:N.entry_path,error:N.error,method:N.trace.method,command:N.trace.command,capability:N.trace.capability,missing_capability:N.trace.missing_capability,registration_index:N.trace.registration_index,expected_schema:N.trace.expected_schema,hint:N.trace.hint,received:N.trace.received}))})}return s(Ue)},Au=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:a,options:o,global:i,withResult:s}=e,c=await R(r.settings_root),l=await ce({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:i.noExtensions===!0}),d=await le(l);a.push(...l.warnings),a.push(...d.warnings);let u=Ho(t,l,d);if(t!==void 0&&u.extensions.length===0){let m=o.vocabulary==="package"?"package":"extension",h=[...new Set(l.loaded.map(g=>o.vocabulary==="package"&&typeof g.source_package=="string"&&g.source_package.trim().length>0?g.source_package.trim():g.name))].sort((g,f)=>g.localeCompare(f)),p=h.length>0?` Loaded ${m} names: ${h.join(", ")}.`:"";throw new y(`No loaded ${m} named "${t}" was found in ${n} scope.${p} Run pm ${m} explore to list discovered ${m}s.`,w.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},Cu=async(e,t,n)=>{let r=n,a=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(a=await tr(e.resolvedRoots.selected_root,e.scope,t,n),r=a.state),e.action==="manage"){let o=await fi(r.entries,wd,async i=>{if(i.source.kind!=="github")return i;let s=await yi(i.source);return{...i,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:A(),entries:pt(o)},await Ne(e.resolvedRoots.selected_root,r)}return{state:r,fix:a}},Ru=async(e,t,n)=>{let r=await ce({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),a=await le({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...a.warnings),{installed:Zt(n,r,a),failures:Li(a.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:a.failed.length,warning_count:[...new Set([...r.warnings,...a.warnings])].length,policy:r.policy}}},Ou=(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},$i=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:a,options:o,withResult:i}=e,s=await R(r.settings_root),c=Rd(s.extensions.policy),l=await K(r.selected_root);a.push(...l.warnings);let d=await me(r.selected_root,n,s,l.state);a.push(...d.warnings);let{state:u,fix:m}=await Cu(e,d.extensions,l.state),h=await me(r.selected_root,n,s,u);if(a.push(...h.warnings),t==="manage"){let v=h.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);a.push(...v)}let p=await Ru(e,s,h.extensions),g=p.installed,f=en(n,a,g,o);a.push(...f.warnings);let _={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:f,policy:c};return p.failures!==void 0&&(_.activation_diagnostics={failed_count:p.failures.length,failed:p.failures}),t==="explore"&&(_.runtime_probe=p.summary),t==="manage"&&(_.runtime_probe=p.summary,_.managed_state_fix=Ou(m,g)),i(_)},Ii={init:ru,install:yu,uninstall:ku,explore:$i,manage:$i,describe:Au,reload:au,doctor:Tu,catalog:ou,adopt:bu,"adopt-all":wu,activate:Ei,deactivate:Ei,migrate:bi},Du=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),Pu=e=>Du(e)?Yn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Ii[e.action](e)):Ii[e.action](e);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5cee1eaa-73f3-5709-867f-a8d73081da8b")}catch{}})();var Nu=new Set(Ea),Wi=25,bt=8,ju=Y.join("runtime","telemetry","events.jsonl"),Lu=Y.join("runtime","telemetry","state.json"),Mu=2500,Fu=500,qi=Sa-3,Uu=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Gi(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Hi(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function tt(e){return e.trim().toLowerCase()}function or(e,t){let n=tt(e),r=tt(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function cr(e){try{return(await ke.stat(e)).isDirectory()}catch{return!1}}async function zu(e){let t=(await ke.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>ke.readdir(Y.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(a=>a.isFile()).filter(a=>mn.some(o=>a.name.endsWith(o))).map(a=>Y.parse(a.name).name)))}async function Ju(e,t,n,r){let a=await fe({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:a,overThreshold:!1,classification:"live"};let i;try{i=await ke.readFile(e,"utf8")}catch{return{warnings:a,overThreshold:!1,classification:"unreadable"}}let s="live";if(o){let l=i.split(/\r?\n/).map(d=>d.trim()).filter(Boolean).at(-1);try{s=JSON.parse(l??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?i.split(/\r?\n/).filter(l=>l.trim().length>0).length:0;return{warnings:a,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function Wu(e,t,n){let r=Y.join(e,"history");if(!await cr(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let a=(await ke.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),i=t.enabled?t.max_entries:null,s=[],c=[],l=[],d=[];for(let u of a){let m=Y.join(r,u),h=u.slice(0,-6),p=await Ju(m,h,t,n);s.push(...p.warnings),p.classification==="tombstone"&&l.push(h),p.classification==="orphaned"&&d.push(h),p.overThreshold&&c.push(h)}return{count:a.length,warnings:[...s,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...d.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:i,tombstones:l,orphaned:d}}function ir(e,t){return Y.relative(e,t).replaceAll("\\","/")}async function Bi(e,t){let n=[...new Set(Object.values(t))].sort((a,o)=>a.localeCompare(o)),r=[];for(let a of n){let o=Y.join(e,a),i=[];try{i=await ke.readdir(o)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&P(s))continue;continue}for(let s of i)mn.some(c=>s.toLowerCase().endsWith(c))&&r.push(Y.join(o,s))}return r.sort((a,o)=>ir(e,a).localeCompare(ir(e,o))),r}function qu(e){return!(typeof e=="object"&&e!==null&&"code"in e&&P(e))}async function Gu(e,t,n){let r=await Bi(e,t),a=[],o=[],i=[],s=[],c=It(F());for(let l of r){let d=ir(e,l),u;try{u=await ke.readFile(l,"utf8")}catch{a.push(d);continue}let m=wn(u);if(m){o.push({path:d,...m});continue}try{let h=Lt(u,{format:Ir(l),schema:n,extensionFieldNames:c});s.push({ref:d,version:Yr(h.metadata)})}catch{i.push(d)}}return{paths:r,unreadable:a,conflictMarkers:o,parseFailures:i,formatVersions:s}}async function Hu(e){let t=Y.join(e,"history"),n=[],r=[],a=[],o=[];try{o=(await ke.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,s)=>i.localeCompare(s))}catch(i){qu(i)&&n.push("history")}for(let i of o){let s=i.slice(0,-6),c;try{c=await ke.readFile(Y.join(t,i),"utf8")}catch{n.push(s);continue}let l=wn(c);if(l){r.push({id:s,...l});continue}c.split(/\r?\n/).forEach((d,u)=>{if(d.trim())try{JSON.parse(d)}catch{a.push({id:s,line:u+1})}})}return{files:o,unreadable:n,conflictMarkers:r,invalidJson:a}}async function Bu(e,t,n,r){let a=await Gu(e,t,n),o=await Hu(e),i=Xr(a.formatVersions),s=await Oa(e),c=await Aa(e),l=c===null?null:await Ca(c),d=c===null?[]:await Da(c,{includeLossless:!0,pmRoot:e}),{pendingDecisions:u,lossless:m}=Pa(d),h=l?.status==="missing"&&l.missing_keys.length===5&&l.drifted_keys.length===0,p=[...a.unreadable.map(f=>`integrity_item_unreadable:${f}`),...a.conflictMarkers.map(f=>`integrity_item_conflict_marker:${f.path}:L${f.line}`),...a.parseFailures.map(f=>`integrity_item_parse_failed:${f}`),...o.unreadable.map(f=>`integrity_history_unreadable:${f}`),...o.conflictMarkers.map(f=>`integrity_history_conflict_marker:${f.id}:L${f.line}`),...o.invalidJson.map(f=>`integrity_history_invalid_json:${f.id}:L${f.line}`),...i.outdated.map(f=>`integrity_item_outdated_format_version:${f}`),...i.ahead.map(f=>`integrity_item_ahead_format_version:${f}`),...s.tracked_path_count>0?[`tracked_runtime_cache_files:${s.tracked_path_count}`]:[],...l!==null&&l.status!=="ok"?[`merge_driver_configuration_${h?"missing":"drift"}:${l.missing_keys.length+l.drifted_keys.length}`]:[],...u.length>0?[`merge_decisions_unreviewed:${u.length}`]:[]],g=[...new Set(p)].sort((f,_)=>f.localeCompare(_));return{check:{name:"integrity",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_item_files:a.paths.length,checked_history_streams:o.files.length,counts:{item_unreadable:a.unreadable.length,item_conflict_markers:a.conflictMarkers.length,item_parse_failures:a.parseFailures.length,history_unreadable:o.unreadable.length,history_conflict_markers:o.conflictMarkers.length,history_invalid_json:o.invalidJson.length,item_outdated_format_version:i.outdated.length,item_ahead_format_version:i.ahead.length,tracked_runtime_cache_files:s.tracked_path_count,merge_driver_configuration:l===null||l.status==="ok"?0:l.missing_keys.length+l.drifted_keys.length,pending_merge_decisions:u.length,lossless_merge_receipts:m.length},item_unreadable:a.unreadable,item_conflict_markers:a.conflictMarkers,item_parse_failures:a.parseFailures,item_outdated_format_version:i.outdated,item_ahead_format_version:i.ahead,history_unreadable:o.unreadable,history_conflict_markers:o.conflictMarkers,history_invalid_json:o.invalidJson,tracked_runtime_cache:{tracker_relative_root:s.tracker_relative_root,tracked_paths:s.tracked_paths,tracked_path_count:s.tracked_path_count,remediation_command:s.remediation_command},merge_driver_configuration:l===null?null:{...l,required:r},pending_merge_decision_items:[...new Set(u.map(f=>f.item_id))].sort((f,_)=>f.localeCompare(_)),lossless_merge_receipt_items:[...new Set(m.map(f=>f.item_id))].sort((f,_)=>f.localeCompare(_))}},warnings:g}}function Vu(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function Ku(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:Vu(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Yu(e,t){let n=Ee(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Xu(e){let n=Ee(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function Qu(e){return Ee(e.reason)??Ee(e.error)??Ee(e.message)}function rr(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function Zu(e){let t=[],n=[],r=[];e.forEach((o,i)=>{let s=Yu(o.definition,i),c=Xu(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:s,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:s,status:c,reason:Qu(o.definition)});return}n.push({layer:o.layer,name:o.name,id:s,status:c})}),t.sort(rr),n.sort(rr),r.sort(rr);let a=[...r.map(o=>`extension_migration_failed:${o.layer}:${o.name}:${o.id}`),...n.map(o=>`extension_migration_pending:${o.layer}:${o.name}:${o.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:a}}function Vi(e,t,n,r,a,o,i,s,c){let l=[...new Set(e)].sort((f,_)=>f.localeCompare(_)),d=[...new Set(l.map(f=>Hi(f)))].sort((f,_)=>f.localeCompare(_)),u=l.filter(f=>f.startsWith("extension_capability_unknown:")).length,m=c.length>0,h=m?"partial":"full",p=[],g=Bn(l,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return g&&p.push(g),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),a>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${Et.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),l.some(f=>f.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),l.some(f=>f.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):i.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:l.length===0?"ok":"warn",warning_count:l.length,warning_codes:d,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:a,managed_extension_entries_count:o,unmanaged_loaded_extension_count:i.length,unmanaged_loaded_extensions:i,unmanaged_expected_extension_count:s.length,unmanaged_expected_extensions:s,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:h,update_health_partial:m,unknown_capability_count:u,top_warnings:l.slice(0,8),remediation:p}}async function em(e,t,n){let r=await ce({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=r.loaded.map(b=>Ku(b)),o=await le({...r,loaded:r.loaded}),[i,s]=await Promise.all([K(r.roots.project),K(r.roots.global)]);await Qn(e,o.registrations.migrations);let c=Zu(o.registrations.migrations),l={failed:o.failed,warnings:o.warnings,hook_counts:o.hook_counts,command_override_count:o.command_override_count,command_handler_count:o.command_handler_count,parser_override_count:o.parser_override_count,preflight_override_count:o.preflight_override_count,service_override_count:o.service_override_count,renderer_override_count:o.renderer_override_count,registration_counts:o.registration_counts,registrations:o.registrations,migration_status:c.summary,managed_extensions:{project:{path:i.path,count:i.state.entries.length,entries:i.state.entries},global:{path:s.path,count:s.state.entries.length,entries:s.state.entries}}},d=new Set(i.state.entries.map(b=>tt(b.name))),u=new Set(s.state.entries.map(b=>tt(b.name))),m=[...new Map(r.loaded.filter(b=>!(b.layer==="project"?d:u).has(tt(b.name))).map(b=>[`${b.layer}:${b.name}`,{layer:b.layer,name:b.name,directory:b.directory}])).values()].sort((b,I)=>{let W=`${b.layer}:${b.name}`,q=`${I.layer}:${I.name}`;return W.localeCompare(q)}),h=m.map(b=>`${b.layer}:${b.name}`).sort((b,I)=>b.localeCompare(I)),p=m.filter(b=>or(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,I)=>b.localeCompare(I)),g=m.filter(b=>!or(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,I)=>b.localeCompare(I)),f=g.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${g.length}`]:[],_=[...r.warnings,...l.warnings,...c.warnings,...i.warnings,...s.warnings,...f],v=wt(_),x=vt(),T=Vi(_,r.failed.length,o.failed.length,c.summary,i.warnings.length+s.warnings.length,i.state.entries.length+s.state.entries.length,h,p,g);return{check:{name:"extensions",status:_.length===0?"ok":"warn",ok:_.length===0,details:{...r,loaded:a,warnings:_,activation:l,triage:T,...c.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:v}},warnings:_}}function tm(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function be(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function nm(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function an(e,t){let n=be(e,t);return{...n,sample:n.sample.map(r=>nm(r))}}function L(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function rm(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var am={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:L(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:L(e.missing_required,t),missing_optional:L(e.missing_optional,t),missing:L(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:L(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:an(e.discovered,t),effective:an(e.effective,t),loaded:an(e.loaded,t),failed:be(e.failed,t),warnings:L(e.warnings,t),activation:{failed:be(n.failed,t),warnings:L(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:rm(n.migration_status)},triage:e.triage,capability_contract:e.capability_contract,capability_guidance:be(e.capability_guidance,t)}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:L(n.affected_item_ids,t),samples:be(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:L(e.item_unreadable,t),item_conflict_markers:be(e.item_conflict_markers,t),item_parse_failures:L(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:L(n.tracked_paths,t)},history_unreadable:L(e.history_unreadable,t),history_conflict_markers:be(e.history_conflict_markers,t),history_invalid_json:be(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>({checked_items:e.checked_items,counts:e.counts,drifted_items:L(e.drifted_items,t),missing_streams:L(e.missing_streams,t),unreadable_streams:L(e.unreadable_streams,t),hash_mismatches:L(e.hash_mismatches,t),chain_mismatches:L(e.chain_mismatches,t),skipped:e.skipped}),vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:L(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:L(e.stale_items_after,t),skipped:e.skipped})};function Ki(e,t){let n=am[e.name];return n?n(e.details,t):e.details}function om(e){let t=L(e.warnings,bt);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:Ki(n,bt)})),warnings:t.sample,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:bt},generated_at:e.generated_at}}function Ji(e){return e.details.skipped===!0}function im(e){let t=L(e.warnings,bt),n=e.checks.filter(Ji).map(r=>r.name);return{ok:e.ok,checks:e.checks.filter(r=>!Ji(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:bt,omitted_checks:n},generated_at:e.generated_at}}function sr(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=tm(e,Wi);return{values:n.values,truncated:n.truncated,total:e.length}}function et(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function sm(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return Nu.has(e)?e:null}function on(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function Yi(e){let t=0,n=0,r=0,a=0,o=0;for(let i of e.split(`
25
- `)){let s=i.trim();if(s.length!==0){r+=1;try{let c=JSON.parse(s);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let l=Math.max(0,Math.trunc(c.attempts));t+=1,o=Math.max(o,l),l>=qi&&(a+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:a,maxAttempts:o}}function cm(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function lm(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function dm(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await Xi(n)}}function um(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let a=n.last_successful_flush_at,o=n.last_failed_flush_at,i=o&&(!a||o>a),s=!a,c=t.validEntries>=Fu;return(i||s||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function mm(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function pm(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>xa?[`telemetry_schema_version_behind:${t}`]:[]}function fm(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,a=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!a&&(!r||a>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function hm(){return{telemetry_disabled:et("PM_TELEMETRY_DISABLED")||et("PM_NO_TELEMETRY"),pm_no_telemetry:et("PM_NO_TELEMETRY"),telemetry_otel_disabled:et("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:et("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:sm()}}function gm(e,t){return e.telemetry.enabled&&t.validEntries>0}function _m(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Xi(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(Mu)});return{probe_url:on(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of Uu){let a=n.headers.get(r)?.trim();if(a&&a.length>0)return a}})()}}catch(n){return{probe_url:on(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function ym(e,t){let n=Tt(process.cwd()),r=Y.join(n,ju),a=Y.join(n,Lu),o=await G(r),i=o!==null,s=o?Buffer.byteLength(o,"utf8"):0,c=o?Yi(o):cm(),l=await G(a),{runtimeState:d,stateParseFailed:u}=lm(l),m=e.telemetry.endpoint.trim(),h=on(m),p=await dm(e,t.checkTelemetry),g=[];u&&g.push("telemetry_state_invalid_json"),g.push(...um(e,c,d),...mm(p),...pm(p),...fm(e,d));let f=gm(e,c),_=typeof d.pending_otel_spans=="number"?d.pending_otel_spans:0;return{check:{name:"telemetry",status:g.length===0?"ok":"warn",ok:g.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:h,global_pm_root:n,queue_path:r,queue_exists:i,queue_entries:c.validEntries,queue_draining:_m(f,g),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:qi,queue_max_attempts:c.maxAttempts,runtime_state_path:a,last_attempted_flush_at:d.last_attempted_flush_at??null,last_successful_flush_at:d.last_successful_flush_at??null,last_failed_flush_at:d.last_failed_flush_at??null,last_failed_flush_error:d.last_failed_flush_error??null,pending_otel_spans:_,last_otel_attempt_at:d.last_otel_attempt_at??null,last_otel_success_at:d.last_otel_success_at??null,last_otel_failure_at:d.last_otel_failure_at??null,last_otel_failure_error:d.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:hm()}},warnings:g}}async function wm(e){let t;try{t=await Fa(e)}catch(r){let a=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:a,pm_root:e}},warnings:[`locks_scan_failed:${a}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function vm(e,t){let n="metadata",{missingStreams:r,unreadableStreams:a,hashMismatches:o,chainMismatches:i,driftedItems:s}=await $a(e,t,{cacheHitVerification:n}),c=[...r.map(l=>`history_drift_missing_stream:${l}`),...a.map(l=>`history_drift_unreadable_stream:${l}`),...o.map(l=>`history_drift_hash_mismatch:${l}`),...i.map(l=>`history_drift_chain_mismatch:${l}`)];return{check:{name:"history_drift",status:c.length===0?"ok":"warn",ok:c.length===0,details:{checked_items:t.length,cache_hit_verification:n,drifted_items:s,counts:{drifted:s.length,missing_streams:r.length,unreadable_streams:a.length,hash_mismatches:o.length,chain_mismatches:i.length},missing_streams:r,unreadable_streams:a,hash_mismatches:o,chain_mismatches:i}},warnings:c}}function bm(e,t){let n=Ut(e),r=ct(n.settings),a=zt(n.settings,t),o=r.active?Oe(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:a,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(r.active&&a.active)}}function km(){return{refreshed:[],skipped:[],warnings:[]}}async function xm(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?km():va(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function Sm(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&He(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function Em(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function $m(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Qi(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:kn(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:kn(r,e.vector_store?.adapter??null)}}function Im(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function Tm(e,t,n){return e.enabled&&n.length>0&&t}async function Am(e,t,n,r,a){let o=bm(t,e),i=await Be(e),s=o.semanticRuntimeAvailable?En(n,i.entries):[],c=await xm({pmRoot:e,snapshot:o,refreshPolicy:r,staleBefore:s}),l=await Be(e),d=o.semanticRuntimeAvailable?En(n,l.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,m=Sm({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:i,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),h=Em({ledgerBefore:i,ledgerAfter:l,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:d}),p=sr(s,a),g=sr(d,a),f=Tm(r,o.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:h.length===0?"ok":"warn",ok:h.length===0,details:{semantic_runtime_available:o.semanticRuntimeAvailable,compatibility_mode_auto_defaults:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:o.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:o.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:Im(r),...Qi(t,o),embedding_identity_changed:m,embedding_identity_before:i.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(i.entries).length,stale_items_detail_mode:a?"full":"summary",stale_items_summary_limit:Wi,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:f,refresh_skipped_reason:$m(r,o.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(l.entries).length,stale_items_after_total:g.total,stale_items_after:g.values,stale_items_after_truncated:g.truncated}},warnings:h}}function Cm(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function Zi(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new y("--check-only cannot be combined with --refresh-vectors",w.USAGE);if(n&&e.noRefresh===!0)throw new y("--no-refresh cannot be combined with --refresh-vectors",w.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var Rm=new Set(["extensions","locks","search"]);function Om(e){let t=new Set(br.filter(a=>a.length>0)),n=new Set,r=new Set(Object.values(kr));for(let a of e.folders)t.has(a)&&!r.has(a)||(t.delete(a),n.add(a));for(let a of Rm)t.delete(a),n.add(a);return{requiredDirs:[...t].sort((a,o)=>a.localeCompare(o)),optionalDirs:[...n].sort((a,o)=>a.localeCompare(o)),optionalDirSet:n}}async function Dm(e,t,n){let{requiredDirs:r,optionalDirs:a,optionalDirSet:o}=Om(t),i=[],s=[],c=[];for(let l of[...r,...a]){let d=Y.join(e,l);c.push(...await fe({path:d,scope:"project"})),!await cr(d)&&(o.has(l)?s.push(l):i.push(l))}return{requiredDirs:r,optionalDirs:a,missingRequiredDirs:i,missingOptionalDirs:s,missingDirs:n?[...i,...s]:[...i],hookWarnings:c}}function es(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function Pm(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?ge(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):oa(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function ar(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function Nm(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function jm(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function Lm(e){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e}}}var lr=e=>e.unknown_event_count??0,dr=e=>e.actionable_unknown_event_count??lr(e);function Mm(e,t,n,r,a,o,i){let s=lr(r),c=dr(r),l=s>0,d=c>0,u=a.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...l?{author_attribution:r}:{},...u?{stale_in_progress:a}:{},...o.length>0?{provenance_resolver_outcomes:o}:{},...i.length>0?{provenance_invalid_values:i}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function ts(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function Fm(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function Um(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function zm(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historySummary.over_threshold.map(t=>`history_stream_over_compact_threshold:${t}`),...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:e.integrityCheck.warnings,history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function Jm(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-repair --all";if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function Wm(e){for(let t of e.checks){let n=Ia(e.remediationSources[t.name]);Jm({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}function ns(e,t,n){return n?im(e):t.brief===!0?om(e):e}async function Ry(e,t={}){let n=j(process.cwd(),e.path),r=ne(n);if(!await E(r))throw new y(`Tracker is not initialized at ${n}. Run pm init first.`,w.NOT_FOUND);let{settings:a,warnings:o}=await Qr(n),i=[...new Set(o)],s=V(a,F()),c=t.strictDirectories===!0,l=Zi(t),d=await Dm(n,s,c),u=Cm(a),m=await ym(a,{checkTelemetry:t.checkTelemetry===!0}),h=await em(n,a,!!e.noExtensions),p=es(t),g=[],f=await Pm({pmRoot:n,settings:a,typeRegistry:s,skipPolicy:p,itemReadWarnings:g}),_=f,v=[...new Set(g)],x=p.skipDrift?{warnings:[]}:await Zr({pmRoot:n,settings:a,itemIds:f.map(it=>it.id),commandLabel:"health"}),T=await Wu(n,a.history.compact_policy,await zu(n)),b=await Ta(n,20,t.verboseAuthorEvents===!0),I=dr(b),W=I>0?[`history_unknown_author_events:${I}`]:[],q=ts(await ba(n,f,{in_progress_status:a.schema.workflow.in_progress_status,threshold_hours:a.mutation_guard.stale_in_progress_hours})),S=await La(n),M=S.outcomes,xe=S.invalid_values,St=S.warnings,at=await wm(n),Me=p.skipIntegrity?ar("integrity"):await Bu(n,s.type_to_folder,a.schema,t.requireMergeDrivers===!0),Fe=p.skipDrift?ar("history_drift"):await vm(n,_),ot=p.skipVectors?ar("vectorization"):await Am(n,a,_,l,t.verboseStaleItems===!0),Ue=[Nm(r,a,i),jm(d,c),Lm(u),m.check,h.check,Mm(f,a,T,b,q.scan,M,xe),at.check,Me.check,Fe.check,ot.check],C=Fm({directoryState:d,normalizedSettingsReadWarnings:i,settingWarnings:u,normalizedItemReadWarnings:v,telemetryCheck:m,extensionCheck:h,historyPolicyWarnings:x.warnings,historySummary:T,authorAttributionWarnings:W,staleInProgressWarnings:q.warnings,provenanceWarnings:St,locksCheck:at,integrityCheck:Me,historyDriftCheck:Fe,vectorizationCheck:ot});Wm({checks:Ue,remediationSources:zm({directoryState:d,normalizedSettingsReadWarnings:i,settingWarnings:u,telemetryCheck:m,extensionCheck:h,historySummary:T,authorAttributionWarnings:W,staleInProgressWarnings:q.warnings,provenanceWarnings:St,locksCheck:at,integrityCheck:Me,historyDriftCheck:Fe,vectorizationCheck:ot}),historyDriftedCount:Um(Fe),overThresholdCount:T.over_threshold.length});let _r={ok:C.filter(it=>!Gi(it,t.requireMergeDrivers===!0)).length===0,checks:Ue,warnings:C,generated_at:A()};return ns(_r,t,p.summaryMode)}var Oy={buildExtensionHealthTriageSummary:Vi,buildCapabilityContractMetadata:vt,buildStaleInProgressHealthSummary:ts,buildVectorizationProviderDetails:Qi,collectUnknownCapabilityGuidance:wt,isAdvisoryHealthWarning:Gi,isDirectory:cr,isExpectedUnmanagedExtension:or,listItemDocumentPaths:Bi,normalizeEndpointForDisplay:on,normalizeExtensionNameForMatch:tt,parseTelemetryQueue:Yi,probeTelemetryEndpointHealth:Xi,projectHealthResult:ns,resolveActionableUnknownAuthorEventCount:dr,resolveHealthSkipPolicy:es,resolveUnknownAuthorEventCount:lr,resolveVectorRefreshPolicy:Zi,selectStaleItemDetail:sr,summarizeHealthCheckDetails:Ki,summarizeExtensionList:an,summarizeRecordList:be,summarizeStringList:L,telemetryEnvFlagEnabled:et,warningCode:Hi};import{execFile as qm}from"node:child_process";import Gm from"node:path";import{promisify as Hm}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]="cdfc451a-1148-50c5-934a-cd8bc2bb39e7")}catch{}})();var Bm=Hm(qm),Vm="@unbrained/pm-cli",Km="latest";function Ym(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.',w.USAGE);return n?"global":"project"}function cn(e){return e.trim().toLowerCase()}function rs(e,t){let n=cn(t);return[e.name,e.directory,e.source.input,e.source.location,e.source.package,e.source.repository,e.source.owner&&e.source.repo?`${e.source.owner}/${e.source.repo}`:void 0].some(a=>typeof a=="string"&&cn(a)===n)}function Xm(e,t){let n=j(process.cwd(),t.path),r=ze(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function Qm(e,t,n){try{let r=await Bm(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:r.stdout,stderr:r.stderr}}catch(r){let a=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr??""):"",o=a.trim().length>0?a.trim():r instanceof Error?r.message:String(r);throw new y(`Command failed: ${e} ${t.join(" ")}
26
- ${o}`,w.GENERIC_FAILURE)}}async function Zm(){return Sr(import.meta.url,["../../.."])}function ln(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():Km}function sn(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():Vm}async function ep(e,t){let n=e.commandRunner??Qm,r=sn(e),a=ln(e),o=`${r}@${a}`,i=["npm","install","-g",o];e.repair===!0&&i.push("--force");let s=await Zm(),c={requested:!0,status:"planned",package:r,target:o,command:i,before_version:s,repair:e.repair===!0};if(t)return c;try{await n(i[0],i.slice(1));let l=await n("pm",["--version"]);return{...c,status:"updated",after_version:l.stdout.trim()||void 0}}catch(l){return{...c,status:"failed",error:l instanceof Error?l.message:String(l)}}}function tp(e){return Gm.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function np(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!tp(n)&&e.package&&e.package.trim().length>0?`npm:${e.package.trim()}@${t}`:e.input.startsWith("npm:")?e.input:`npm:${e.input}`}return e.input}async function rp(e,t){let n=np(e,t);return e.kind!=="local"||await E(n)?n:await E(e.location)?e.location:n}function ap(e,t,n,r){let a=["pm","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&r&&r.trim().length>0&&a.push("--ref",r.trim()),a}async function as(e,t){let n=Xm(e,t);return(await K(n.selected_root)).state.entries.filter(a=>a.scope===e)}async function op(e,t,n){let r=await as(e,t);return r.find(a=>rs(a,n.name))??r.find(a=>cn(a.directory)===cn(n.directory))}async function ip(e,t,n,r,a){let o=ln(t),i=await rp(e.source,o),s=ap(e.source,i,r,e.source.ref),c={name:e.name,directory:e.directory,scope:r,source:e.source,status:"planned",command:s,previous_version:e.manifest_version};if(a)return c;try{await nr(i,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let l=await op(r,n,e);return{...c,status:"updated",installed_version:l?.manifest_version}}catch(l){return{...c,status:"failed",error:l instanceof Error?l.message:String(l)}}}function sp(e,t,n,r){let a=[n?e.status:void 0,...t.map(o=>o.status)].filter(o=>typeof o=="string");return{requested_cli:n,requested_packages:r,planned:a.filter(o=>o==="planned").length,updated:a.filter(o=>o==="updated").length,skipped:a.filter(o=>o==="skipped").length,failed:a.filter(o=>o==="failed").length}}async function Fy(e,t,n){if(t.cliOnly===!0&&t.packagesOnly===!0)throw new y('Options "--cli-only" and "--packages-only" are mutually exclusive.',w.USAGE);let r=Ym(t),a=t.dryRun===!0,o=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&o)throw new y('A package target cannot be used with "--cli-only".',w.USAGE);let i=!(t.packagesOnly===!0||o),s=t.cliOnly!==!0,c=i?await ep(t,a):{requested:!1,status:"skipped",package:sn(t),target:`${sn(t)}@${ln(t)}`,command:["npm","install","-g",`${sn(t)}@${ln(t)}`],repair:t.repair===!0,reason:"not_requested"},l=s?await as(r,n):[];if(o&&(l=l.filter(m=>rs(m,o)),l.length===0))throw new y(`Managed package "${o}" was not found in ${r} scope.`,w.NOT_FOUND);let d=[];for(let m of l)d.push(await ip(m,t,n,r,a));let u=sp(c,d,i,s);return{ok:u.failed===0,action:"upgrade",dry_run:a,scope:r,target:o,cli:c,packages:d,summary:u}}import nt from"node:fs/promises";import un from"node:path";import dn from"node:fs/promises";import ur 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]="b26cf702-330e-5cf5-8371-204220d5c5c9")}catch{}})();var cp=864e5;function lp(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.created_at;return typeof n=="string"?n:null}async function dp(e,t){let n;try{n=await dn.readdir(e,{withFileTypes:!0})}catch(a){if(P(a))return[];throw a}let r=[];for(let a of n)if(a.isDirectory()){let o=ur.join(e,a.name),i;try{i=await dn.readdir(o)}catch(s){P(s)||t.push(`checkpoint_subdir_unreadable:${a.name}`);continue}for(let s of i)s.endsWith(".json")&&r.push(`${a.name}/${s}`)}else a.name.endsWith(".json")&&r.push(a.name);return r.sort()}async function os(e,t){let{dryRun:n,hooks:r}=t,a=t.now??Date.now(),o=Math.max(0,t.retentionDays)*cp,i=ur.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await dp(i,s.warnings);for(let l of c){let d=ur.join(i,l),u=`checkpoints/${l}`;s.scanned+=1,r?.onRead&&s.warnings.push(...await r.onRead(d));let m;try{m=await dn.readFile(d,"utf8")}catch(_){if(P(_)){s.scanned-=1;continue}s.warnings.push(`checkpoint_unreadable:${l}`),s.retained.push(u),s.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=lp(m),p=h===null?Number.NaN:Date.parse(h);if(!Number.isFinite(p)){s.warnings.push(`checkpoint_unparseable:${l}`),s.retained.push(u),s.entries.push({file:u,created_at:h,age_seconds:null,stale:!1,reason:"unparseable"});continue}let g=a-p,f={file:u,created_at:h,age_seconds:Math.floor(g/1e3),stale:g>o,reason:g>o?"expired":"active"};if(!f.stale){s.retained.push(u),s.entries.push(f);continue}if(!n){try{await dn.unlink(d)}catch(_){if(!P(_)){s.warnings.push(`checkpoint_remove_failed:${l}`),s.retained.push(u),s.entries.push(f);continue}}r?.onWrite&&s.warnings.push(...await r.onWrite(d))}s.removed.push(u),s.entries.push(f)}return s}import mr from"node:fs/promises";import is 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]="7df80849-51e1-5efa-b40a-b44088f941a9")}catch{}})();var up=1440*60*1e3,mp=new Set(["committed","compensated"]);function pp(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function fp(e,t,n,r,a){let o=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(o))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let i=r-o;return mp.has(t)?i>a?{entry:{file:e,status:t,age_seconds:Math.floor(i/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(i/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(i/1e3),stale:!1,reason:"active"},remove:!1}}async function hp(e,t,n,r){let a=r.hooks?.onRead?await r.hooks.onRead(e):[],o=pp(await mr.readFile(e,"utf8")),i=fp(t,o.status,o.updatedAt,r.nowMs,r.retentionMs);return i.entry.reason==="unparseable"&&a.push(`transaction_journal_unparseable:${n}`),i.remove&&!r.dryRun&&(await mr.rm(e,{force:!0}),r.hooks?.onWrite&&a.push(...await r.hooks.onWrite(e))),{decision:i,warnings:a}}async function ss(e,t){let{dryRun:n,hooks:r}=t,a=t.now??Date.now(),o=Math.max(0,t.retentionDays)*up,i=is.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await mr.readdir(i)).filter(l=>l.endsWith(".json")).sort((l,d)=>l.localeCompare(d))}catch(l){if(P(l))return s;throw l}for(let l of c){let d=is.join(i,l),u=`transactions/sdk/${l}`,m=await hp(d,u,l,{dryRun:n,hooks:r,nowMs:a,retentionMs:o});s.warnings.push(...m.warnings),s.scanned+=1;let{decision:h}=m;if(!h.remove){s.retained.push(u),s.entries.push(h.entry);continue}s.removed.push(u),s.entries.push(h.entry)}return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e982158e-4a8d-57a9-bd0b-24bd73aef342")}catch{}})();var kt=["index","embeddings","runtime","locks","checkpoints","transactions"],gp=1440*60*1e3,_p=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function yp(e,t,n){let r=t.relativePath,a=un.join(e,r),o=await fe({path:a,scope:"project"});try{let i=await nt.stat(a);if(t.kind==="file"&&!i.isFile())return{removed:!1,warnings:[...o,`not_a_file:${r}`]};if(t.kind==="directory"&&!i.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await nt.unlink(a):await nt.rm(a,{recursive:!0,force:!0});let s=await z({path:a,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...s]}}catch(i){if(P(i))return{removed:!1,warnings:o};throw i}}async function wp(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],a=[],o=[],i=Date.now()-gp;for(let s of n){let c=un.join(e,s.relativePath);if(!await E(c))continue;let l=(await nt.readdir(c)).filter(d=>d.startsWith(s.prefix)).sort();for(let d of l){let u=un.posix.join(s.relativePath,d),m=un.join(c,d);o.push(...await fe({path:m,scope:"project"}));let h=await nt.stat(m).catch(p=>{if(!P(p))throw p});if(h){if(h.mtimeMs>i){a.push(u);continue}r.push(u),!t&&(await nt.rm(m,{recursive:!0,force:!0}),o.push(...await z({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:a,warnings:o}}function vp(e){if(!e||e.length===0)return[...kt];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new y(`--scope requires at least one value (${kt.join(",")})`,w.USAGE);let n=new Set;for(let r of t){if(!kt.includes(r))throw new y(`Invalid --scope value "${r}". Expected one or more of: ${kt.join(", ")}`,w.USAGE);n.add(r)}return kt.filter(r=>n.has(r))}function bp(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(a=>a==="index/manifest.json"||a==="search/embeddings.jsonl"||a==="search/vectorization-status.json"||a==="search/lancedb"||a==="search/pending-refresh.json"||a==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(a=>a.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(a=>a.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function sw(e,t={}){let n=j(process.cwd(),e.path);if(!await E(ne(n)))throw new y(`Tracker is not initialized at ${n}. Run pm init first.`,w.NOT_FOUND);let r=await R(n),a=t.dryRun===!0,o=vp(t.scope),i=_p.filter(p=>o.includes(p.scope)),s=[],c=[],l=[];for(let p of i){let g=await yp(n,p,a);g.removed?s.push(p.relativePath):c.push(p.relativePath),l.push(...g.warnings)}if(o.includes("runtime")){let p=await wp(n,a);s.push(...p.removed),c.push(...p.retained),l.push(...p.warnings)}let d;if(o.includes("locks")){let p=await Ua(n,{dryRun:a,hooks:{onRead:g=>fe({path:g,scope:"project"}),onWrite:g=>z({path:g,scope:"project",op:"gc:lock_remove"})}});s.push(...p.removed),c.push(...p.retained),l.push(...p.warnings),d={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(o.includes("transactions")){let p=r.checkpoints.retention_days,g=await ss(n,{dryRun:a,retentionDays:p,hooks:{onRead:f=>fe({path:f,scope:"project"}),onWrite:f=>z({path:f,scope:"project",op:"gc:transaction_journal_remove"})}});s.push(...g.removed),c.push(...g.retained),l.push(...g.warnings),u={scanned:g.scanned,removed:g.removed.length,retained:g.retained.length,retention_days:p}}let m;if(o.includes("checkpoints")){let p=r.checkpoints.retention_days,g=await os(n,{dryRun:a,retentionDays:p,hooks:{onRead:f=>fe({path:f,scope:"project"}),onWrite:f=>z({path:f,scope:"project",op:"gc:checkpoint_remove"})}});s.push(...g.removed),c.push(...g.retained),l.push(...g.warnings),m={scanned:g.scanned,removed:g.removed.length,retained:g.retained.length,retention_days:p}}l.push(...await jt({mode:a?"gc:dry-run":"gc",total_items:i.length}));let h=bp({dryRun:a,scopes:o,removed:s});return{ok:l.length===0,dry_run:a,scope:o,removed:s,retained:c,warnings:l,...d?{locks:d}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:h,generated_at:A()}}import kp from"node:fs/promises";import xt 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]="fc124f85-8d28-508b-a3f7-2fe767382197")}catch{}})();var pr="index/manifest.json",fr="search/embeddings.jsonl",xp="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function Sp(e){return e.progress===!0||process.stderr.isTTY===!0}function J(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
27
- `)}catch{}}function Ep(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new y("Reindex mode must be one of keyword|semantic|hybrid",w.USAGE)}async function $p(e,t,n,r){let a=[];return{candidates:await na(e,t,n,a,r),warnings:a}}async function gr(e,t,n,r,a){let o=It(F()),i=[];for(let s of t)if(!(a&&!a.has(s.metadata.id))){if(typeof s.body=="string"){i.push({metadata:s.metadata,body:s.body});continue}try{let c=await kp.readFile(s.item_path,"utf8"),l=Lt(c,{format:s.item_format,schema:n,extensionFieldNames:o,onWarning:d=>r.push(d)});i.push({metadata:s.metadata,body:l.body})}catch{r.push(`item_list_item_read_failed:${xt.relative(e,s.item_path)}`),i.push({metadata:s.metadata,body:""})}}return i}function Ip(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:da(e,{fields:n})}}var rt=Ee;function Tp(e){let t=F(),n=rt(e.search?.provider);if(!n)return null;let r=sa(t,n);if(!r)return null;let a=r.runtime_definition??r.definition,o=rt(a.name)??rt(r.definition.name);if(!o)return null;let i=a.embedBatch,s=a.embed_batch,c=a.embed,l=typeof i=="function"?i:typeof s=="function"?s:void 0,d=typeof c=="function"?c:void 0;return!l&&!d?null:{name:o,embedBatch:l,embed:d}}function Ap(e){let t=F(),n=rt(e.vector_store?.adapter);if(!n)return null;let r=ca(t,n);if(!r)return null;let a=r.runtime_definition??r.definition,o=rt(a.name)??rt(r.definition.name);if(!o)return null;let i=a.upsert,s=a.delete;return{adapterName:o,...typeof i=="function"?{upsert:i}:{},...typeof s=="function"?{delete:s}:{}}}function hr(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new y(`Invalid vector returned by ${t}`,w.GENERIC_FAILURE);return e}async function Cp(e,t,n){let r=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let o=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:r}));if(!Array.isArray(o))throw new y(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,w.GENERIC_FAILURE);return o.map((i,s)=>hr(i,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new y(`Extension search provider "${e.name}" does not implement embed/embedBatch`,w.GENERIC_FAILURE);let a=[];for(let[o,i]of n.entries()){let s=await Promise.resolve(e.embed({input:i,settings:t,model:r}));a.push(hr(s,`extension search provider "${e.name}" embed output at index ${o}`))}return a}function cs(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function ls(e,t,n){let r=n?Oe(n.name,cs(e)):t?Oe(t.name,t.model):null;if(!r)throw new y("No embedding identity available for semantic reindex mode",w.USAGE);return r}function Rp(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function ds(e,t,n,r,a,o,i,s){let c=r?.name??n?.name,l=ua(c,e.search.embedding_corpus_max_characters).maxCharacters,d=xn(e),u=a.map(p=>ma(p,{providerName:c,maxCharacters:l,fields:d})),m=[],h=null;if(r)try{m=await Cp(r,e,u),h=Oe(r.name,cs(e))}catch(p){if(!n)throw new y(`Extension search provider "${r.name}" failed to generate embeddings: ${p instanceof Error?p.message:String(p)}`,w.GENERIC_FAILURE);o.push(`Extension search provider "${r.name}" failed; falling back to built-in provider (${p instanceof Error?p.message:String(p)})`)}if(m.length===0){if(!n)throw new y(`No embedding executor available for reindex mode '${t}'`,w.USAGE);let p=await pa(n,e,u,{onProgress:g=>{g.phase==="complete"&&(i.batches_completed=g.batch_index),J(s,`embedding_batch_${g.phase} batch=${g.batch_index}/${g.batch_total} size=${g.batch_size} completed_inputs=${g.completed_inputs}/${g.total_inputs}`)}});o.push(...p.warnings),m=p.vectors,h=Oe(n.name,n.model)}if(J(s,`embedding_complete vectors=${m.length}`),m.length!==a.length)throw new y(`Embedding output size mismatch (expected ${a.length}, received ${m.length})`,w.GENERIC_FAILURE);if(!h)throw new y(`No embedding identity available for reindex mode '${t}'`,w.USAGE);return{vectors:m,embeddingIdentity:h}}async function Op(e,t,n,r,a,o){let i=Object.keys(n);if(t){if(i.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:i.sort((s,c)=>s.localeCompare(c)),settings:r}))}catch(s){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,w.GENERIC_FAILURE)}else i.length>0&&a.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${i.length}`);if(!e)return}e&&await ga(e,i,{},o)}async function us(e,t,n,r,a){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:r}))}catch(o){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${o instanceof Error?o.message:String(o)}`,w.GENERIC_FAILURE)}else a.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await ha(e,n)}}function Dp(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function Pp(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(r=>({id:r.metadata.id,type:r.metadata.type,status:r.metadata.status,priority:r.metadata.priority,updated_at:r.metadata.updated_at}))}}function Np(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=ct(e.settings);if(!t.active&&!e.extensionEmbedding)throw new y(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,w.USAGE);let n=zt(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new y(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,w.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function jp(e){let t=V(e.settings,F()),n=await $p(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(r=>({metadata:r.metadata,body:typeof r.body=="string"?r.body:""}))}}async function Lp(e){let t=await Be(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return ls(e.settings,ct(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&He(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(xp))}async function Mp(e){let t=await Be(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=ls(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(l=>l.metadata.id)),a=Rp(t.entries,r),o=He(t.embedding,n);e.forceFullSemantic&&!o&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let i=e.forceFullSemantic||o?e.metadataDocuments:e.metadataDocuments.filter(l=>t.entries[l.metadata.id]!==l.metadata.updated_at),s=new Set(i.map(l=>l.metadata.id)),c=s.size>0?await gr(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:a,resetRequired:o,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function Fp(e){let t=new Set(e.metadataDocuments.map(a=>a.metadata.id)),n=await gr(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,J(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await ds(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:Sn(r.vectors,"Reindex embeddings")}}async function Up(e){let t=await ds(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,a=Sn(n,"Reindex embeddings");if(!(!e.resetRequired&&(He(e.ledgerEmbedding,r)||ya(e.ledgerEmbedding,a))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:a,resetRequired:e.resetRequired};let i=await Fp(e);return n=i.vectors,r=i.embeddingIdentity,a=i.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:i.staleDocuments,vectorDimension:a,resetRequired:!0}}async function zp(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(J(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new y(`Extension vector adapter "${t}" does not support upserting vectors.`,w.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,J(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof y)throw t;if(!e.activeVectorStore)throw new y(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,w.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),J(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){J(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await fa(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,J(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new y(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,w.USAGE)}function Jp(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:hr(t[r],`reindex embeddings output at index ${r}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function Wp(e){J(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await Up({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(J(e.progressEnabled,"vector_reset_start"),await Op(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),J(e.progressEnabled,"vector_reset_complete")):await us(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=Jp(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await zp({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:_a(t.embeddingIdentity,t.vectorDimension)}}async function qp(e){let t=await Mp(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(o=>[o.metadata.id,o.metadata.updated_at]));if(J(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return J(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await us(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await Wp({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let a=new Map(r.staleDocuments.map(o=>[o.metadata.id,o]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(o=>a.get(o.metadata.id)??o),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:r.embeddingMetadata}}async function Gp(e){let t=xt.join(e.pmRoot,pr),n=xt.join(e.pmRoot,fr),r=xn(e.settings),a=e.documentsForKeywordArtifacts.map(i=>JSON.stringify(Ip(i,e.mode,r))).join(`
28
- `);J(e.progressEnabled,"writing keyword artifacts"),await ie(t,`${JSON.stringify(e.manifest,null,2)}
29
- `),await ie(n,`${a}
30
- `);let o=[];if(e.mode!=="keyword")try{J(e.progressEnabled,"writing vectorization status ledger"),await wa(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(i){o.push(`search_vectorization_status_ledger_write_failed:${i instanceof Error?i.message:String(i)}`)}return o}async function mw(e,t){let n=Ep(e.mode),r=Sp(e),a=e.full===!0;J(r,`start mode=${n}`);let o=j(process.cwd(),t.path);if(!await E(ne(o)))throw new y(`Tracker is not initialized at ${o}. Run pm init first.`,w.NOT_FOUND);let i=Ut(await R(o)).settings,s=null;try{s=await Z(o,la,i.locks.ttl_seconds,Q(void 0,"pm-reindex"),!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms)}catch(c){throw c instanceof y&&c.exitCode===w.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.",w.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=Tp(i),l=Ap(i),d=Np({requestedMode:n,pmRoot:o,settings:i,extensionEmbedding:c,extensionVectorAdapter:l}),u=n;J(r,"loading item corpus");let m=await jp({pmRoot:o,settings:i}),h=m.warnings,{documentCandidates:p,metadataDocuments:g}=m;J(r,`loaded_items=${g.length}`);let f=A(),_=Pp(u,f,g),v=xt.join(o,pr),x=xt.join(o,fr),T=u==="keyword"?await gr(o,p,i.schema,h):g,b=[],I={},W=null,q=Dp(u);if(u==="keyword"&&await Lp({pmRoot:o,settings:i,forceFullSemantic:a,extensionEmbedding:c,reindexWarnings:h}),u!=="keyword"){let xe=await qp({pmRoot:o,settings:i,requestedMode:n,activeEmbeddingProvider:d.activeEmbeddingProvider,activeVectorStore:d.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:p,metadataDocuments:g,documentsForKeywordArtifacts:T,forceFullSemantic:a,reindexWarnings:h,semanticWarnings:b,semanticSummary:q,progressEnabled:r});T=xe.documentsForKeywordArtifacts,I=xe.vectorizationLedgerEntries,W=xe.vectorizationEmbeddingMetadata}let S=await Gp({pmRoot:o,mode:u,manifest:_,documentsForKeywordArtifacts:T,settings:i,vectorizationLedgerEntries:I,vectorizationEmbeddingMetadata:W,progressEnabled:r}),M=[...await z({path:v,scope:"project",op:"reindex:manifest"}),...await z({path:x,scope:"project",op:"reindex:embeddings"}),...await jt({mode:u,total_items:g.length})];return J(r,"done"),{ok:!0,mode:u,total_items:g.length,semantic:q,artifacts:{manifest:pr,embeddings:fr},warnings:[...h,...b,...S,...M],generated_at:f}}finally{await s?.()}}export{Qa as a,Ja as b,lc as c,rh as d,ah as e,oh as f,dt as g,ih as h,sh as i,ch as j,lh as k,dh as l,uh as m,mh as n,ph as o,fh as p,hh as q,gh as r,nr as s,La as t,Ry as u,Oy as v,Fy as w,sw as x,mw as y};
31
- //# sourceMappingURL=chunk-27N23W6M.js.map