@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
@@ -0,0 +1,46 @@
1
+ import{a as Fr,c as kn,d as xn,e as Ja,g as Va,h as Ur,i as Ka,j as gt,k as _t,l as Ya,m as Xa,n as zr,o as Za,p as yt,q as wt,r as Qa,s as eo,t as Br}from"./chunk-4DQ2YERC.js";import{a as io,f as Cn,g as Wr}from"./chunk-WCVE2NIG.js";import{B as An,a as za,g as Mr,i as Ba}from"./chunk-KYUQGTSB.js";import{h as Wo,j as Go}from"./chunk-SM7MTG27.js";import{$ as No,Aa as zo,Ba as Bo,Da as Kr,I as Fn,J as Ao,K as Hr,L as Ht,N as Jr,R as Io,S as Co,T as To,U as $o,V as jn,X as Oo,Y as Do,Z as Po,_ as ot,aa as St,ba as Lo,ca as Vr,da as Et,ea as Mo,f as xo,fa as Fo,g as So,t as Gt,u as Eo,ua as jo,v as qt,va as Un,w as Ro,za as Uo}from"./chunk-XDNAW5OI.js";import{a as Wa,b as Sn,c as jr,d as Ga,e as qa,f as Le,g as En,h as Ha,i as Ke}from"./chunk-PPFGQDSI.js";import{La as mo,Pa as ge,Qa as po,Ra as fo,Sa as qr,Ta as ho,U as ne,V as I,Va as Dn,Wa as go,Xa as Se,Ya as _o,Z as ce,Za as T,_a as Pn,ab as yo,b as oo,da as co,ea as $n,fb as wo,gb as vo,ha as On,ia as lo,l as j,la as vt,lb as Nn,na as bt,nb as bo,o as te,ob as kt,pb as xt,q as Me,qb as Ln,r as so,rb as Fe,s as Tn,sb as Mn,vb as at,xa as Gr,xb as ko,za as uo}from"./chunk-PGXJQLCT.js";import{Aa as Lr,Ba as ja,Ca as Ua,D as Ta,Da as ht,E as $a,F as G,Fa as Ie,Ha as Ce,Ja as ae,K as Bt,Ka as ve,L as N,M as Wt,Ma as he,N as bn,Na as Te,O as V,Q as Oa,R as Da,Ra as it,Ta as Rn,V as K,Xa as In,Y as Pa,Ya as no,Za as ro,a as ka,aa as Na,d as xa,da as Dr,e as Sa,h as ft,o as Or,p as R,q as vn,r as L,ra as La,s as ee,sa as Ma,t as se,w as fe,x as Ae,y as Ca}from"./chunk-K7RWWOAG.js";import{b as ao}from"./chunk-ZM6TZVHC.js";import{N as Ea,P as Ra,R as Aa,U as Ia,V as wn,Y as y,Z as _,a as _n,aa as Pr,ba as Fa,ca as Nr,d as yn,ka as to,t as $r}from"./chunk-Q4YY3XNF.js";import Wn from"node:fs/promises";import Gn from"node:path";import{Option as Ub}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daefefd1-3b0b-513d-8b8c-ab17f90b995a")}catch{}})();function Ru(e,t){let n=[],r=new Set;for(let i of t.keys){if(!Object.hasOwn(e,i))continue;let a=e[i];if(a!=null){if(typeof a=="string"){n.push(a);continue}if(!Array.isArray(a)||!a.every(o=>typeof o=="string"))return;r.has(a)||(r.add(a),n.push(...a))}}return n.length>0?n.join("; "):void 0}function zn(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function D(e,t){return e[t]===!0?!0:void 0}function je(e,t){return e[t]===!1?!0:void 0}function qo(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Ho(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function Jo(e){let t=i=>Mr(e,zn(Cn,i)),n=i=>Ba(e,zn(Wr,i)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:Ru(e,zn(Wr,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),allowUnresolvedDeps:qo(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:D(e,"replaceDeps"),replaceTests:D(e,"replaceTests"),replaceFiles:D(e,"replaceFiles"),replaceDocs:D(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:D(e,"clearDeps"),clearComments:D(e,"clearComments"),clearNotes:D(e,"clearNotes"),clearLearnings:D(e,"clearLearnings"),clearFiles:D(e,"clearFiles"),clearTests:D(e,"clearTests"),clearDocs:D(e,"clearDocs"),clearReminders:D(e,"clearReminders"),clearEvents:D(e,"clearEvents"),clearTypeOptions:D(e,"clearTypeOptions")};return Ho(r,e),r}function Y(e,t){let n=zn(za,t),r=Mr(e,n);if(r!==void 0)return r;for(let i of n.keys){let a=e[i];if(Array.isArray(a)){let o=a.filter(s=>typeof s=="string");if(o.length>0)return o.join(",")}if(t==="ids"&&typeof a=="string")return a;if(typeof a=="number"&&Number.isFinite(a))return String(a)}}function Au(e){let t=D(e,"filterFilesMissing"),n=D(e,"filterDocsMissing");return{filterReviewerMissing:D(e,"filterReviewerMissing"),filterRiskMissing:D(e,"filterRiskMissing"),filterConfidenceMissing:D(e,"filterConfidenceMissing"),filterSprintMissing:D(e,"filterSprintMissing"),filterReleaseMissing:D(e,"filterReleaseMissing"),hasNotes:D(e,"hasNotes"),hasLearnings:D(e,"hasLearnings"),hasFiles:D(e,"hasFiles"),hasDocs:D(e,"hasDocs"),hasTests:D(e,"hasTests"),hasComments:D(e,"hasComments"),hasDeps:D(e,"hasDeps"),hasBody:D(e,"hasBody"),hasLinkedCommand:D(e,"hasLinkedCommand"),noNotes:je(e,"notes"),noLearnings:je(e,"learnings"),noFiles:je(e,"files")??t,filterFilesMissing:t,noDocs:je(e,"docs")??n,filterDocsMissing:n,noTests:je(e,"tests"),noComments:je(e,"comments"),noDeps:je(e,"deps"),emptyBody:D(e,"emptyBody"),noLinkedCommand:je(e,"linkedCommand")}}function Yr(e){let t={status:Y(e,"status"),type:Y(e,"type"),tag:Y(e,"tag"),priority:Y(e,"priority"),deadlineBefore:Y(e,"deadlineBefore"),deadlineAfter:Y(e,"deadlineAfter"),updatedAfter:Y(e,"updatedAfter"),updatedBefore:Y(e,"updatedBefore"),createdAfter:Y(e,"createdAfter"),createdBefore:Y(e,"createdBefore"),today:D(e,"today"),recent:D(e,"recent"),ids:Y(e,"ids"),assignee:Y(e,"assignee"),assigneeFilter:Y(e,"assigneeFilter"),parent:Y(e,"parent"),sprint:Y(e,"sprint"),release:Y(e,"release"),limit:Y(e,"limit"),offset:Y(e,"offset"),noTruncate:je(e,"truncate"),includeBody:D(e,"includeBody"),strictRead:D(e,"strictRead"),compact:D(e,"compact"),brief:D(e,"brief"),full:D(e,"full"),fields:Y(e,"fields"),sort:Y(e,"sort"),order:Y(e,"order"),tree:D(e,"tree"),treeDepth:Y(e,"treeDepth"),filterAcMissing:D(e,"filterAcMissing"),filterEstimatesMissing:qo(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:D(e,"filterResolutionMissing"),filterMetadataMissing:D(e,"filterMetadataMissing"),...Au(e)};return Ho(t,e),t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bcda2578-3b01-5e64-9d53-cd32c0f927b8")}catch{}})();function M(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function X(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Iu(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Jt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Kb(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new _(`${t} must be a finite integer.`,y.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new _(`${t} must be a finite integer.`,y.USAGE);return n}}function Yb(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:M(e,"limit")??M(t,"limit")}function Xb(e){let t=M(e,"outputFormat");return{json:!0,quiet:!0,author:M(e,"author"),path:M(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:M(e,"outputInclude"),outputLimit:X(e,"outputLimit"),outputBudget:X(e,"outputBudget"),outputSession:M(e,"outputSession"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Cu=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Tu=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),$u=new Set(["files","files-discover","docs","test","test-all"]),Ou=new Set(["claim","release","start-task","pause-task","close-task"]),Du={list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt"],append:["body"]},Pu=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession"];function Ko(e,t){let n={},r=t!==void 0&&$u.has(t),i=t==="files"||t==="files-discover"||t==="docs";for(let[a,o]of Object.entries(e)){if(Array.isArray(o)&&Cu.has(a)){n[a]=o.join(",");continue}if(a==="note"&&i){n[a]=o;continue}if(typeof o=="string"&&Tu.has(a)){n[a]=[o];continue}if(typeof o=="string"&&r&&(a==="add"||a==="remove")){n[a]=[o];continue}n[a]=o}return n}function Zb(e,t){let n=Na(e.options),r={},i=c=>{n[c]!==void 0||e[c]===void 0||(r[c]=e[c])};for(let c of Du[t??""]??[])i(c);for(let c of Pu)i(c);let a=Ko({...r,...n},t),o=M(e,"author"),s=t!==void 0&&Ou.has(t)?M(e,"assignee")??M(a,"assignee"):void 0;return o&&a.author===void 0?{...a,author:o}:s&&a.author===void 0?{...a,author:s}:a}function Qb(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function ek(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function tk(e){let t=[],n=!0;for(let r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function nk(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function Qr(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function rk(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[a,o]of Object.entries(e))n.has(a)||(r[a]=o);let i={...r,...t};return delete i.args,i}function ik(e,t){return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:{...t}}}function Zr(e){return{type:X(e,"filterType"),tag:X(e,"filterTag"),priority:X(e,"filterPriority"),deadlineBefore:X(e,"filterDeadlineBefore"),deadlineAfter:X(e,"filterDeadlineAfter"),updatedAfter:X(e,"filterUpdatedAfter"),updatedBefore:X(e,"filterUpdatedBefore"),createdAfter:X(e,"filterCreatedAfter"),createdBefore:X(e,"filterCreatedBefore"),ids:Iu(e,"ids"),assignee:X(e,"filterAssignee"),assigneeFilter:X(e,"filterAssigneeFilter")??X(e,"filterAssignee_filter"),parent:X(e,"filterParent"),sprint:X(e,"filterSprint"),release:X(e,"filterRelease"),limit:X(e,"limit"),offset:X(e,"offset")}}function Xr(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return Qr(e)}function Bn(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function ak(e){let t=Xr(e.kind),n=Xr(e.exemptIsolate),r=Xr(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Bn(e.maxDepth),limit:Bn(e.limit),after:M(e,"after"),direction:M(e,"direction"),maxPaths:Bn(e.maxPaths),sample:Bn(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function ok(e){return{status:M(e,"filterStatus"),list:Jt(e.list)?Yr(e.list):Zr(e),reason:M(e,"reason"),resolution:M(e,"resolution"),expectedResult:M(e,"expectedResult")??M(e,"expected_result")??M(e,"expected"),actualResult:M(e,"actualResult")??M(e,"actual_result")??M(e,"actual"),validateClose:M(e,"validateClose")??M(e,"validate_close"),author:M(e,"author"),message:M(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:M(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var Nu=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function Vo(e){let t={};for(let[n,r]of Object.entries(e))Nu.has(n)||(t[n]=r);return Yo(t)}function Yo(e){let t=Ko(e,"update-many");for(let n of Cn)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return Jo(t)}function sk(e){if(Jt(e.list)||Jt(e.update)){let t=Jt(e.update)?e.update:Vo(e);return{status:X(e,"filterStatus"),list:Jt(e.list)?Yr(e.list):Zr(e),update:Yo(t),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:M(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:X(e,"filterStatus"),list:Zr(e),update:Vo(e),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:M(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4fd16197-979e-5269-bed7-f2fb0e2038c2")}catch{}})();function Ue(e,t){throw new _(e,y.USAGE,t)}var Lu="2026-07-15T06:22:12.276Z",Mu=Date.parse(Lu),Fu=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Xo=e=>typeof e=="string"?e:"",Zo=e=>{let t=e??{},n=Xo(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Xo(t.ts))>=Mu);return Fu[r][i]};function Qo(e,t,n=20,r=new Set,i=!1){let a=[],o=[],s={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let h;try{h=JSON.parse(f)}catch{continue}l+=1;let g=Zo(h);if(g!=="attributed"){if(d+=1,g==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}s[g]+=1,i&&g==="actionable_unknown"&&o.push({item_id:e,line:m+1}),a.length<c&&a.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:s.legacy_unknown,actionable_unknown_event_count:s.actionable_unknown,acknowledged_actionable_event_count:u,samples:a,samples_truncated:s.legacy_unknown+s.actionable_unknown>a.length,actionable_events:o}}var gk=(e,t,n=20,r=new Set)=>Qo(e,t,n,r);function ju(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let a=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof a!="object"||a===null||!Array.isArray(a.events)))for(let o of a.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Vt=async(e,t=20,n=!1)=>{let r=Gn.join(e,"history"),i;try{i=(await Wn.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let a=new Set,o=[],s=[],c=0,l=0,d=0,u=0,m=0,f=0,h="_workspace.jsonl",g=new Set;if(i.includes(h))try{g=ju(await Wn.readFile(Gn.join(r,h),"utf8"))}catch{g=new Set}for(let w of i){let v;try{v=await Wn.readFile(Gn.join(r,w),"utf8")}catch{continue}let k=w.slice(0,-6),x=Qo(k,v,t-o.length,g,n);c+=1,l+=x.checked_events,d+=x.unknown_event_count,u+=x.legacy_unknown_event_count,m+=x.actionable_unknown_event_count,f+=x.acknowledged_actionable_event_count,x.unknown_event_count>0&&a.add(k),o.push(...x.samples),n&&s.push(...x.actionable_events)}let p=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...a].sort((w,v)=>w.localeCompare(v)),samples:o,samples_truncated:p>o.length,...n?{actionable_events:s}:{}}};function Uu(e,t){let n=e.length>0;return n&&t&&Ue("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&Ue("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:zu(e),all_actionable:t}}function zu(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),a=r===ge||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!a||!Number.isSafeInteger(i)||i<1)&&Ue(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function _k(e,t){let n=Uu(Qr(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Bu(e,{events:n.events,all_actionable:n.all_actionable,attributed_author:M(t,"attributedAuthor")??M(t,"attributed_author")??"",reviewer:M(t,"reviewer")??"",reason:M(t,"reason")??""})}async function Bu(e,t){let n=t.reviewer.trim(),r=t.attributed_author.trim(),i=t.reason.trim(),a=t.events??[],o=+(t.all_actionable===!0)+ +(a.length>0);o===0&&Ue("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),o>1&&Ue("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"});let s=t.all_actionable===!0?(await Vt(e,0,!0)).actionable_events:a;[s.length>0,n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Ue("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"});let l=[...new Map(s.map(m=>[`${m.item_id}:${m.line}`,{item_id:m.item_id,line:m.line}])).values()].sort((m,f)=>m.item_id.localeCompare(f.item_id)||m.line-f.line);for(let m of l){[m.item_id===ge||/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1)&&Ue(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"});let h;try{let p=(await Wn.readFile(Gn.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];h=JSON.parse(p??"")}catch{Ue(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}Zo(h)!=="actionable_unknown"&&Ue(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"})}let d=await T(e),u=await ho({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:l,attributed_author:r}},message:i,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms});return{acknowledged:l.length,history_path:u.historyPath}}import es from"node:fs/promises";import ts 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 Wu=8388608,Gu=new Set(["resolved","failed"]),qu=[{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 Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function Hu(e){try{return(await es.readdir(ts.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function Ju(e,t,n){let r;try{r=await es.open(ts.join(e,"history",t),"r");let i=(await r.stat()).size,a=Math.min(i,Math.max(0,n)),o=Buffer.alloc(a),{bytesRead:s}=await r.read(o,0,a,0),c=o.subarray(0,s).toString("utf8"),l=s>=i,d=c.lastIndexOf(`
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 Vu(e){try{let t=JSON.parse(e);return Rt(t)?t:null}catch{return null}}function Ku(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=Rt(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([o,s])=>{if(!Rt(s))return;let c=qu.find(u=>u.matches(s.value))?.kind;if(!c)return;let l=`${r}\0${o}\0${c}`,d=n.get(l)??{harness:r,dimension:o,kind:c,count:0};d.count+=1,n.set(l,d)}),!Rt(e.context))return;let a=e.context.agent_provenance_outcomes;Rt(a)&&Object.entries(a).forEach(([o,s])=>{if(!Rt(s)||typeof s.resolver!="string"||!Gu.has(String(s.status)))return;let c=`${r}\0${o}\0${s.resolver}`,l=t.get(c)??{harness:r,dimension:o,resolver:s.resolver,attempts:0,successes:0};l.attempts+=1,s.status==="resolved"&&(l.successes+=1),t.set(c,l)})}function Yu(e,t,n,r,i){let a=i;for(let o of e.split(`
3
+ `)){if(o.trim().length===0)continue;if(a>=r)return{eventsRead:a,truncated:!0};a+=1;let s=Vu(o);s&&Ku(s,t,n)}return{eventsRead:a,truncated:!1}}async function ns(e,t=1e4){let n=new Map,r=new Map,i=0,a=0,o=!1;for(let l of await Hu(e)){let d=await Ju(e,l,Math.max(0,Wu-a));if(d===null)continue;a+=d.bytesRead;let u=Yu(d.content,n,r,t,i);if(i=u.eventsRead,u.truncated){o=!0;break}if(!d.complete){o=!0;break}}let s=[...n.values()].sort((l,d)=>l.harness.localeCompare(d.harness)||l.dimension.localeCompare(d.dimension)||l.resolver.localeCompare(d.resolver)),c=[...r.values()].sort((l,d)=>l.harness.localeCompare(d.harness)||l.dimension.localeCompare(d.dimension)||l.kind.localeCompare(d.kind));return{outcomes:s,invalid_values:c,warnings:o?[]:[...s.filter(l=>l.attempts>0&&l.successes===0).map(l=>`provenance_resolver_zero_success:${l.harness}:${l.dimension}:${l.resolver}:${String(l.attempts)}`),...c.map(l=>`provenance_value_domain_invalid:${l.harness}:${l.dimension}:${l.kind}:${String(l.count)}`)],events_read:i,truncated:o}}import He from"node:fs/promises";import ue from"node:path";import At from"node:fs/promises";import{createHash as Xu}from"node:crypto";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]="32538934-2cbb-50fe-b721-ad9197cef7d8")}catch{}})();var as=4,Zu="history-drift-cache.json";function os(e){return is.join(e,"runtime",Zu)}async function Qu(e){try{let t=await At.readFile(os(e),"utf8"),n=JSON.parse(t);return n.version!==as||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}async function em(e,t,n,r,i){let a=po(e),o;try{o=await At.stat(a)}catch(l){return L(l)||i.unreadableStreams.push(ge),!1}let s=i.missingStreams.length,c=await cs({itemId:ge,historyPath:a,stat:o,cached:t[ge],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.chainOk||i.chainMismatches.push(ge),n[ge]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(i.missingStreams.splice(s),c.cacheDirty)}function ss(e){return Xu("sha256").update(e).digest("hex")}async function tm(e){let t=await At.readFile(e,"utf8");return ss(t)}async function nm(e){let t=await At.readFile(e,"utf8"),n=ss(t);if(t.trim().length===0)return null;let r=[],i=null;for(let o of t.split(/\r?\n/)){let s=o.trim();if(s.length===0)continue;let c=JSON.parse(s);if(typeof c.after_hash!="string"||c.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(c),i=c.after_hash}if(!i)return null;let a=mo(r);return{latestAfterHash:i,chainOk:a.ok,contentHash:n,itemHashVersion:a.item_hash_version??Gr}}function rm(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function rs(e,t,n){try{let r=await nm(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function cs(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(rm(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await rs(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await tm(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else r=t;return!e.verifyCacheHitByContent||r===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:r,itemHashVersion:e.cached.item_hash_version??Gr},cacheDirty:!1}:{verification:await rs(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function im(e,t,n,r){let i=Da(e,t.id),a;try{a=await At.stat(i)}catch(d){return(L(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let o=await cs({itemId:t.id,historyPath:i,stat:a,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!o.verification)return o.cacheDirty;o.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:o.verification.contentHash,latest_after_hash:o.verification.latestAfterHash,chain_ok:o.verification.chainOk,item_hash_version:o.verification.itemHashVersion};let{body:s,...c}=t;return uo({metadata:c,body:s},o.verification.itemHashVersion)!==o.verification.latestAfterHash&&r.hashMismatches.push(t.id),o.cacheDirty}async function am(e,t){if(!(t.unreadableStreams.includes(ge)||t.chainMismatches.includes(ge)))try{let n=await fo(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(ge)}}async function qn(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},a=(await Qu(e))?.entries??{},o={},s=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:a,nextEntries:o,verifyCacheHitByContent:c};for(let m of t)await im(e,m,l,r)&&(s=!0);let d=await em(e,a,o,c,r);if(s||=d,await am(e,r),s||Object.keys(a).length!==Object.keys(o).length){let m=os(e);try{await At.mkdir(is.dirname(m),{recursive:!0}),await se(m,JSON.stringify({version:as,entries:o}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[ge]:[]])].sort((m,f)=>m.localeCompare(f));return{...r,driftedItems:u}}import Kt from"node:fs/promises";import Hn 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 om(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:a,ttl_seconds:o}=n;return typeof r!="string"||typeof i!="string"||typeof a!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:r,owner:i,created_at:a,ttl_seconds:o}}function ls(e,t,n){let r=om(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let a=n-i,o=Math.floor(a/1e3),s=a>r.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:o,stale:s,reason:s?"expired":"active"}}}async function ds(e,t){let n=t??Date.now(),r=Hn.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},a;try{a=(await Kt.readdir(r)).filter(s=>s.endsWith(".lock")).sort()}catch(o){if(L(o))return i;throw o}for(let o of a){let s;try{s=await Kt.readFile(Hn.join(r,o),"utf8")}catch(l){if(L(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=ls(o,s,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function us(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Hn.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await Kt.readdir(a)).filter(l=>l.endsWith(".lock")).sort()}catch(c){if(L(c))return o;throw c}for(let c of s){o.scanned+=1;let l=Hn.join(a,c),d=`locks/${c}`;if(r?.onRead){let f=await r.onRead(l);o.warnings.push(...f)}let u;try{u=await Kt.readFile(l,"utf8")}catch(f){if(L(f)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${c}`),o.retained.push(d),o.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=ls(c,u,i);if(m.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}if(m.detail==="active"){o.retained.push(d),o.entries.push(m.entry);continue}if(!n){try{await Kt.unlink(l)}catch(f){if(!L(f)){o.warnings.push(`lock_remove_failed:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}}if(r?.onWrite){let f=await r.onWrite(l);o.warnings.push(...f)}}o.removed.push(d),o.entries.push(m.entry)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="31d625d8-44be-5298-ab64-c17508ed07d0")}catch{}})();var sm=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function cm(e){if(typeof e!="string")return;let t=e.trim();for(let n of sm)if(t===n.code||t.startsWith(`${n.code}:`))return n}function ei(e){let t={};for(let n of e){let r=cm(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function ms(e){return Object.values(ei(e))}import et from"node:fs/promises";import be from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c514907-377f-59f9-bfdd-a184abf7ffb7")}catch{}})();var lm=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function It(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(In(t.extensionName));for(let p of t.extensionNames??[])n.add(In(p));let r=p=>n.size===0||n.has(In(p)),i=(p,w)=>ps(p.filter(v=>r(v.name)).map(w)),a=(p,w)=>ps(p.filter(v=>r(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:c,preflight:l,services:d,renderers:u,hooks:m}=e,f=a(o.relationship_kinds??[],p=>p.definitions.map(w=>w.kind)),h=u.overrides.filter(p=>r(p.name)&&((p.commands?.length??0)>0||p.resultDiscriminator!==void 0)).map(p=>({format:p.format,commands:[...p.commands??[]],result_discriminator:p.resultDiscriminator!==void 0})).sort((p,w)=>p.format.localeCompare(w.format)),g=i(o.assurance_providers??[],p=>p.definition.id);return{capabilities:no(e,t),commands:i(o.commands,p=>p.command),command_overrides:i(s.overrides,p=>p.command),command_handlers:i(s.handlers,p=>p.command),hooks:lm.filter(([p])=>m[p].some(w=>r(w.name))).map(([,p])=>p),flag_commands:i(o.flags,p=>p.target_command),item_types:a(o.item_types,p=>p.types.map(w=>w.name)),item_fields:a(o.item_fields,p=>p.fields.map(w=>w.name)),...f.length>0?{relationship_kinds:f}:{},migrations:a(o.migrations,p=>typeof p.definition.id=="string"?[p.definition.id]:[]),profiles:i(o.profiles,p=>p.profile.name),importers:i(o.importers,p=>p.importer),exporters:i(o.exporters,p=>p.exporter),search_providers:i(o.search_providers,p=>p.definition.name),vector_store_adapters:i(o.vector_store_adapters,p=>p.definition.name),...g.length>0?{assurance_providers:g}:{},parser_overrides:i(c.overrides,p=>p.command),service_overrides:i(d.overrides,p=>p.service),renderer_overrides:i(u.overrides,p=>p.format),...h.length>0?{renderer_ownership:h}:{},preflight_overrides:l.overrides.filter(p=>r(p.name)).length,preflight_ownership:l.overrides.filter(p=>r(p.name)).map(p=>({commands:[...p.commands??[]]}))}}function ps(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 dm=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)}"`},ti=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?dm(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,fs=(e,t=process.platform)=>{let n=e.map(r=>ti(r,t)).join(" ");return n.length>0?`pm ${n}`:"pm"};import up from"node:path";import{mkdir as mp}from"node:fs/promises";import{readFile as Vn,realpath as ai,writeFile as _m}from"node:fs/promises";import{execFile as ym}from"node:child_process";import Z from"node:path";import{promisify as wm}from"node:util";import{readFile as um,writeFile as mm}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]="89261a49-97e5-5ffc-a81c-2409f0b529cf")}catch{}})();var gs="# pm-cli:runtime-cache:start",ni="# pm-cli:runtime-cache:end",_s=".agents/pm",ri=["runtime/","search/","locks/","transactions/","checkpoints/"],pm=["search/eval-queries.json"];async function hs(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new _("The workspace .gitignore is not writable.",y.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function ys(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function ii(e){let t=e.replaceAll("\\","/");return Yt.isAbsolute(e)||t===".."||t.startsWith("../")}function fm(e=_s){let t=ys(e);return[gs,...ri.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...pm.map(n=>`!${t}/${n}`),ni].join(`
4
+ `)}async function Gk(e,t={}){let n=Yt.join(e,".gitignore"),r=_s;if(t.pmRoot!==void 0){let d=ys(Yt.relative(Yt.resolve(e),Yt.resolve(t.pmRoot)));if(ii(d))return{path:n,changed:!1};d.length>0&&(r=d)}let i="";try{i=await hs(()=>um(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&L(d)))throw d}let a=i.indexOf(gs),o=i.indexOf(ni),c=(a>=0&&o>=a?`${i.slice(0,a)}${i.slice(o+ni.length)}`:i).trimEnd(),l=`${c.length>0?`${c}
5
+
6
+ `:""}${fm(r)}
7
+ `;return l===i?{path:n,changed:!1}:(await hs(()=>mm(n,l,"utf8")),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var hm="PM_SOURCE_CONTEXT_ACCESS",gm="PM_ALLOW_SOURCE_CONTEXT_WRITES";function ws(e){let t=e[hm],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[gm]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||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]="5e1810a5-04b8-5929-8eee-7a63f1684860")}catch{}})();var si=wm(ym),Jn="# pm-cli:merge-drivers:start",xs="# pm-cli:merge-drivers:end",Ct="# pm-cli:merge-drivers:v2:start",oi="# pm-cli:merge-drivers:v2:end",vm="merge-fence";function vs(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Ss(){let e=Ae(import.meta.url,["../../.."]);return`${vs(process.execPath)} ${vs(Z.join(e,"dist","cli.js"))}`}var Es=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function bm(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=ws(e.environment),a=!!(n&&r),o=t===void 0&&a&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let s=N(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}return o?{pm_root:Z.resolve(r),workspace_start:Z.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:a?N(e.cwd,".agents/pm"):N(e.cwd),workspace_start:e.cwd,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}async function st(e){try{let{stdout:t}=await si("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await ai(t.trim())}catch{return null}}async function Rs(e){let t=await st(e);if(t===null)throw new _("pm merge install requires a git repository (merge drivers are git configuration).",y.USAGE);return t}function ci(e,t){return Z.relative(e,t).replaceAll("\\","/")}function $e(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function bs(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function km(e,t){let n=bs(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=bs(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(Z.basename(n.value))||Z.basename(r.value)!=="cli.js"||Z.basename(Z.dirname(r.value))!=="dist"||!await R(n.value)||!await R(r.value))return!1;try{let i=Z.dirname(Z.dirname(r.value)),a=JSON.parse(await Vn(Z.join(i,"package.json"),"utf8")),o=typeof a.bin=="object"&&a.bin!==null&&"pm"in a.bin?a.bin.pm:void 0;return a.name==="@unbrained/pm-cli"&&(a.bin==="dist/cli.js"||o==="dist/cli.js")}catch{return!1}}function li(e,t){let n=e.length>0?`${e}/`:"",r=[`${$e(`${n}**/*.toon`)} merge=pm-item-toon`,`${$e(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${$e(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${$e(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${$e(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${$e(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${$e(`${n}settings.json`)} merge=pm-json`),r.push(`${$e(`${n}**/*.json`)} merge=pm-json`),r.push(`${$e(`${n}extensions/**`)} -merge`),r.push(`${$e(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function ks(e,t,n){let r=e.indexOf(t),i=e.indexOf(n);return r>=0&&i>r?`${e.slice(0,r)}${e.slice(i+n.length)}`:e.replace(t,"").replace(n,"")}async function As(e,t,n){let r=Z.join(e,".gitattributes"),i="";try{i=await Vn(r,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&L(l)))throw l}let a=[Ct,...t,oi].join(`
8
+ `),s=ks(ks(i,Ct,oi),Jn,xs).trimEnd(),c=`${s.length>0?`${s}
9
+
10
+ `:""}${a}
11
+ `;return c===i?{path:r,changed:!1}:(n||await _m(r,c,"utf8"),{path:r,changed:!0})}function Kn(e){let t=G(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function Is(e,t){let n=Z.resolve(e),r=null,i="",a=n;for(let v=0;v<8;v+=1){let k=Z.join(a,".gitattributes");try{let b=await Vn(k,"utf8");if(b.includes(Ct)||b.includes(Jn)){r=a,i=b;break}}catch{}let x=Z.dirname(a);if(x===a)break;a=x}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=Z.join(r,".gitattributes"),s=i.includes(Ct),c=s?Ct:Jn,l=s?oi:xs,d=i.indexOf(c),u=i.indexOf(l),m=u>d?i.slice(d+c.length,u).split(`
12
+ `).map(v=>v.trim()).filter(v=>v.length>0):[],f=li(ci(r,n),t),h=new Set(m),g=new Set(f),p=f.filter(v=>!h.has(v)),w=m.filter(v=>!g.has(v));return{status:p.length>0||w.length>0?"drift":"ok",path:o,missing_patterns:p,stale_patterns:w,schema_scope:"project"}}async function Yn(e){let t=Ss(),n=[],r=[];for(let i of Es){let a=`merge.${i.key}.driver`,o=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`,s=`${t}${o}`;try{let{stdout:c}=await si("git",["config","--local","--get",a],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==s&&!await km(l,o)&&r.push(a)}catch{n.push(a)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function Cs(e){let t;try{t=await Rs(Z.resolve(e))}catch{return{status:"no_git"}}let n=ci(t,Z.resolve(e)),r=await T(e),i=ne(void 0,r.author_default),a=await ce(e,vm,r.locks.ttl_seconds,i,!1,Se(r).force_required_for_stale_lock,r.locks.wait_ms);try{let o=Z.join(t,".gitattributes"),s;try{s=await Vn(o,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&L(u))return{status:"not_installed",path:o};throw u}if(!s.includes(Ct)&&!s.includes(Jn))return{status:"not_installed",path:o};let c=await T(e),l=Kn(c),d=await As(t,li(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await a()}}async function dx(e,t){let n=bm({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;if(!await R(V(r)))throw new _(`Tracker is not initialized at ${r}. Run pm init first.`,y.NOT_FOUND);let i=await Rs(n.workspace_start);return xm({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function xm(e){let t=Z.resolve(e.pmRoot),n=Z.resolve(e.workspaceRoot),r=e.dryRun===!0,i,a;try{[i,a]=await Promise.all([ai(t),ai(n)])}catch(f){throw new _(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,y.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let o=ci(a,i);if(ii(o))throw new _(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,y.USAGE);let s=await T(i),c=Kn(s),l=li(o,c),d=[],u=Ss();for(let f of Es)d.push({key:`merge.${f.key}.name`,value:f.name}),d.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!r)try{for(let f of d)await si("git",["config","--local",f.key,f.value],{cwd:a,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new _(`Cannot install repository-local merge drivers in ${a}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,y.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await As(a,l,r);return{ok:!0,dry_run:r,workspace_root:a,pm_root:i,gitattributes:{path:m.path,changed:m.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at: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]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();var Sm=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Em(e){let t=Sm.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Rm(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Ts(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,i=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let c=Em(s);if(c===void 0)continue;let l=i.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<r&&l.examples.push(s),i.set(c,l)}let a=[];for(let[o,s]of i.entries()){if(s.count<n)continue;let c=Rm(o);a.push({name:c,prefix:o,count:s.count,examples:s.examples,shadows_builtin:Wa(c)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}import{createHash as Bs}from"node:crypto";import lt from"node:fs/promises";import $t from"node:path";import{mkdir as Am,readFile as Im}from"node:fs/promises";import Ls 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 di=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Cm="sdk-workspace-transaction",Tm=/^[a-zA-Z0-9._-]+$/,$m=30,Om=3e3;function $s(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Tm.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Os(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 Ds(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 Ms(e,t){return Ls.join(e,"transactions","sdk",`${t}.json`)}async function Ye(e,t){t.updatedAt=I();let n=Ms(e,t.transactionId);await Am(Ls.dirname(n),{recursive:!0}),await se(n,`${JSON.stringify(t,null,2)}
13
+ `)}function Dm(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function ct(e){return Object.assign(Object.create(null),e)}function Pm(e,t){try{let n=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function ui(e,t){return e===void 0?void 0:Pm(e,t)}function mi(e,t,n,r){let i=ui(n,r);i===void 0?delete e[t]:e[t]=i}function Ps(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ns(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Nm(e,t){if(!Ns(e.startedStepIds,t)||!Ns(e.completedStepIds,t)||!Ps(e.results)||!Ps(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,a=new Set(i);return Object.keys(e.compensationData).some(o=>!r.has(o))||Object.keys(e.results).some(o=>!a.has(o))?!1:e.status==="committed"?t.every(o=>a.has(o)):e.status!=="compensated"||a.size===0&&r.size===0}function Lm(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 i=r,a=i.schemaVersion===1&&i.transactionId===t,o=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((d,u)=>d===n[u]),s=Nm(i,n),c=Dm(i),l=["applying","compensating","compensated","committed"].includes(String(i.status));if(!a||!o||!s||!c||!l)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...i,results:ct(i.results),compensationData:ct(i.compensationData)}}async function Mm(e,t,n,r,i){let a=i,o=a!==void 0;if(a?.status==="compensating"&&await Fs(e,a),a===void 0||a.status==="compensated"){let s=I();a={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(a?.attempt??0)+1,createdAt:a?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:ct(),compensationData:ct()},await Ye(e.pmRoot,a),await ze(e,a,"prepared")}return{journal:a,recovered:o}}async function Fm(e,t,n){try{await Um(t,e.steps),await Ye(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let a of e.steps){if(r.has(a.id))continue;let o=await a.inspect(),s=ui(o.result,`Step ${a.id} result`);if(o.state!=="applied"){let c=await a.prepareCompensation?.();mi(t.compensationData,a.id,c,`Step ${a.id} compensation data`),i.add(a.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>i.has(d)),await Ye(e.pmRoot,t);let l=await a.apply();s=ui(l,`Step ${a.id} result`)}await ze(e,t,"step_applied",a.id),r.add(a.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),mi(t.results,a.id,s,`Step ${a.id} result`),await Ye(e.pmRoot,t),await ze(e,t,"step_recorded",a.id)}return await ze(e,t,"committing"),t.status="committed",await Ye(e.pmRoot,t),await ze(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:ct(t.results)}}catch(r){if(r instanceof di||t.status==="committed")throw r;try{await Fs(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function jm(e,t,n){try{return Lm(await Im(Ms(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&L(r))return;throw r}}async function ze(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function Um(e,t){let n=new Set,r=ct();for(let i of t){let a=await i.inspect();a.state==="applied"&&(n.add(i.id),mi(r,i.id,a.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function Fs(e,t){t.status="compensating",await Ye(e.pmRoot,t),await ze(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!r.has(i.id)&&!n.has(i.id))continue;let a;try{a=r.has(i.id)&&(await i.inspect()).state==="applied"}catch{a=r.has(i.id)}a&&(await ze(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),r.delete(i.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>r.has(o)),delete t.results[i.id],delete t.compensationData[i.id],await Ye(e.pmRoot,t),await ze(e,t,"step_compensated",i.id)}t.status="compensated",await Ye(e.pmRoot,t),await ze(e,t,"compensated")}async function js(e){let t=Os(e.pmRoot,"Transaction pmRoot"),n=$s(e.transactionId,"Transaction id"),r=Os(e.author,"Transaction author"),i=Ds(e.lockTtlSeconds,$m,"Transaction lock TTL"),a=Ds(e.lockWaitMs,Om,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(d=>{let u=$s(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:o,lockTtlSeconds:i,lockWaitMs:a},l=await ce(t,Cm,i,r,!1,!1,a);try{let d=await jm(t,n,s),u=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:ct(d.results)};let m=await Mm(c,n,r,s,d);return await Fm(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 Be(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Ws(e){let t=Be(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Gs(e,t){let n=fi(e),r=Be(t,"migrationScope");return`auto-${Bs("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function fi(e){let t=e.kind==="rename-type"?{kind:e.kind,from:Be(e.from,"source"),to:Be(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:ae(Be(e.from,"source")),to:ae(Be(e.to,"target")),...e.type===void 0?{}:{type:Be(e.type,"type")}}:{kind:e.kind,from:ae(Be(e.from,"source")),to:ae(Be(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function zm(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Bm(e,t,n){let r=he(t.schema),i=zm(n);return Te(e,r.files[i],ve[i])}function qs(e,t){return $t.join(e,"transactions","schema",`${t}-plan.json`)}function Xn(e){return e.length===0?null:JSON.parse(e)}async function Tt(e){let t=await ee(e);return{exists:t!==null,raw:t??""}}async function Hs(e,t){t.exists?await se(e,t.raw):await lt.rm(e,{force:!0})}function Wm(e,t,n){let r=Le(e),i=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),a=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(a>=0)return Ke(r);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[i],name:t.to})}else i>=0&&r.definitions.splice(i,1);return Ke(r)}function Gm(e,t,n){let r=gt(e),i=r.fields.findIndex(o=>o.key===t.from),a=r.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(a>=0)return _t(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=r.fields[i];r.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&r.fields.splice(i,1);return _t(r)}function qm(e,t,n){let r=yt(e),i=r.statuses.findIndex(o=>o.id===t.from),a=r.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(a>=0)return wt(r);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[i],id:t.to})}else i>=0&&r.statuses.splice(i,1);return wt(r)}function Hm(e,t,n){return t.kind==="rename-type"?Wm(e,t,n):t.kind==="rename-field"?Gm(e,t,n):qm(e,t,n)}function Xe(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Ot(e){return Array.isArray(e)?e.map(t=>hi(t)).filter(t=>t!==void 0):[]}function Jm(e,t){for(let n of Ot(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>Xe(r,t)));for(let n of Ot(e.type_workflows))n.type=Xe(n.type,t)}function Vm(e,t){for(let r of Ot(e.definitions))r.default_status=Xe(r.default_status,t);let n=hi(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=Xe(i,t);for(let r of Ot(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(a=>Xe(a,t)):i))}function Km(e,t){for(let n of Ot(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>Xe(i,t)));for(let r of["options","command_option_policies"])for(let i of Ot(n[r])){let a=r==="options"?"key":"option";i[a]=Xe(i[a],t)}}}function Ym(e,t){let n=hi(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]=Xe(n[r],t)}function pi(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"?Jm(r,t):t.kind==="rename-field"?Km(r,t):Vm(r,t),Ym(r,t),`${JSON.stringify(r,null,2)}
14
+ `}function Js(e,t){if(t.kind==="rename-type"){let r=Le(e).definitions;return{source:r.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=gt(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=yt(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function Xm(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 Zm(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 Vs(e,t){let n=fi(t.request),r=t.migrationId===void 0?Gs(n,t.migrationScope??"plan"):Ws(t.migrationId),i=e.map(c=>Zm(c,n)).filter(c=>c!==null).sort((c,l)=>c.id.localeCompare(l.id)),a=Bs("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!o.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:a,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function Qm(e){let t=G(e.settings,j()),n=[...new Set(Object.values(t.type_to_folder))],r=await Nn(e.pmRoot,n),i=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]}},a=r?await wo({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:i}):null;return a?{items:a.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Fe(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function ep(e,t){let n=await ee(qs(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 _(`Stored schema migration plan "${t}" is invalid: ${Pa(r)}`,y.GENERIC_FAILURE)}}async function tp(e,t){let n=qs(e,t.migration_id);await lt.mkdir($t.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await se(n,`${JSON.stringify(r,null,2)}
15
+ `)}function np(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function rp(e){let t=await kt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new _(`Schema migration item "${e.id}" no longer exists.`,y.NOT_FOUND);return(await xt(t,{schema:e.settings.schema})).document.metadata}function Us(e,t,n){let r=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.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=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.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=i,["status"]}let a=e.metadata;if(Object.prototype.hasOwnProperty.call(a,i)&&!Object.prototype.hasOwnProperty.call(a,r))return[];if(!Object.prototype.hasOwnProperty.call(a,r)||Object.prototype.hasOwnProperty.call(a,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return a[i]=a[r],delete a[r],[r,i]}function zs(e){return{id:e.id,inspect:async()=>{let t=await Tt(e.filePath),n=Js(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 Tt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Tt(e.filePath);return await se(e.filePath,Hm(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 Hs(e.filePath,{exists:t.exists,raw:t.raw})}}}function ip(e){return{id:e.stepId,inspect:async()=>{let t=await Tt(e.filePath);return{state:pi(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Tt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Tt(e.filePath);return await se(e.filePath,pi(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 Hs(e.filePath,{exists:t.exists,raw:t.raw})}}}function ap(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await T(e.pmRoot),n=G(t,j()).type_to_folder,r=await rp({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=Xm(r,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await T(e.pmRoot),n=G(t,j()).type_to_folder,r=await at({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(i){return{changedFields:Us(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await T(e.pmRoot),n=G(t,j()).type_to_folder;await at({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:Us(r,e.request,"reverse")}}})}}}async function op(e){let t=await ep(e.pmRoot,e.migrationId);if(t){if(!np(t.request,e.request))throw new _(`Schema migration id "${e.migrationId}" already belongs to a different request.`,y.CONFLICT);return{plan:t,stored:!0}}let n=await Qm({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Vs(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function sp(e){let t=Js(await ee(e.schemaPath)??"",e.request);if(!t.source)throw new _(`Schema migration source "${e.request.from}" is not a custom definition.`,y.NOT_FOUND);if(t.target)throw new _(`Schema migration target "${e.request.to}" already exists.`,y.CONFLICT);await tp(e.pmRoot,e.plan)}async function cp(e){let t=he(e.settings.schema),n=[...new Set([["types",ve.types],["fields",ve.fields],["workflows",ve.workflows]].map(([i,a])=>Te(e.pmRoot,t.files[i],a)).filter(i=>i!==e.schemaPath))];try{let i=$t.join(e.pmRoot,"templates"),a=await lt.readdir(i,{withFileTypes:!0});n.push(...a.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>$t.join(i,o.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!L(i))throw i}n.sort((i,a)=>i.localeCompare(a));let r=[];for(let i of n){let a=await ee(i);a!==null&&pi(a,e.request)!==a&&r.push({filePath:i,beforeRaw:a})}return{paths:n,snapshots:r}}async function lp(e){for(let t of e.snapshots){let n=await lt.readFile(t.filePath,"utf8"),r=$t.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await qr({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Xn(t.beforeRaw),after:Xn(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 dp(e,t,n){let r=fi(e),i=N(process.cwd(),n.path);if(!await R(V(i)))throw new _(`Tracker is not initialized at ${i}. Run pm init first.`,y.NOT_FOUND);let a=t.migrationId===void 0?Gs(r,await lt.realpath(i)):Ws(t.migrationId),o=await T(i),s=ne(t.author,o.author_default),c=await op({pmRoot:i,settings:o,migrationId:a,request:r}),l=c.plan;if(t.dryRun===!0)return{...l,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=Bm(i,o,r),u=await lt.readFile(d,"utf8");c.stored||await sp({pmRoot:i,schemaPath:d,request:r,plan:l});let m=await cp({pmRoot:i,schemaPath:d,settings:o,request:r}),f=[zs({id:"stage-schema",filePath:d,request:r,phase:"stage"}),...m.paths.map((w,v)=>ip({filePath:w,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...l.items.map(w=>ap({pmRoot:i,id:w.id,request:r,author:s,force:t.force===!0})),zs({id:"retire-source",filePath:d,request:r,phase:"retire"})],h=await js({pmRoot:i,transactionId:`schema-${a}`,author:s,steps:f,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),g=await lt.readFile(d,"utf8"),{historyPath:p}=await qr({pmRoot:i,author:s,documentPath:$t.relative(i,d).replaceAll("\\","/"),before:Xn(u),after:Xn(g),op:"schema_migration",idempotencyKey:`${l.migration_id}:${l.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${l.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await lp({pmRoot:i,author:s,settings:o,request:r,plan:l,snapshots:m.snapshots}),{...l,action:r.kind,applied:!0,recovered:h.recovered,migrated_item_count:l.affected_item_count,workspace_history_path:p}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a035e10-b8fe-52cd-a9c7-0762dd0ab160")}catch{}})();var mS=["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"],Zn="schema-types",Ks="schema-statuses",Ys="schema-fields";function Ze(e){return Dn({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 pS(e,t,n){let r=N(process.cwd(),n.path);await We(r);let i;try{i=jr({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(f){throw new _(f instanceof Error?f.message:String(f),y.USAGE)}let a=await T(r),o=he(a.schema),s=Te(r,o.files.types,ve.types),c=[],l=ne(t.author,a.author_default),d=Se(a),u=await ce(r,Zn,a.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,a.locks.wait_ms),m;try{let f=await ee(s),h;try{h=Le(f)}catch(g){throw new _(g instanceof Error?g.message:String(g),y.GENERIC_FAILURE)}try{Ga(i,h);let g=new Map,p=G(a,j());for(let[w,v]of Object.entries(p.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!g.has(k)&&g.set(k,w)}qa(i,h,g)}catch(g){throw new _(g instanceof Error?g.message:String(g),y.USAGE)}m=En(h,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await Ze({pmRoot:r,filePath:s,raw:Ke(m.file),op:"schema:add-type",author:l,settings:a}),await Xt(r,[m.definition],c,"schema:add-type-folder"),c.push(...await te({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await Xs(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Qe(c),generated_at:I()}}async function We(e){if(!await R(V(e)))throw new _(`Tracker is not initialized at ${e}. Run pm init first.`,y.NOT_FOUND)}async function Xs(e,t){try{let n=await Cs(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 Qe(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function pp(e,t,n,r){let i=G(t,j()),a=r.trim().toLowerCase();return(await Fe(e,t.item_format,i.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===a).length}async function fp(e,t,n,r){let i=G(t,j()),a=it(n),o=ae(r);return(await Fe(e,t.item_format,i.type_to_folder,[],n)).filter(c=>{let l=typeof c.status=="string"?c.status:"";return(a.alias_to_id.get(ae(l))??ae(l))===o}).length}async function hp(e,t,n,r,i){if(i.length===0||zr.has(i))return;let a=await fp(t,n,r,i);a>0&&e.push(`items_using_status:${a}`);let o=gp(r.workflow,i);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function gp(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&&ae(r)===t).map(([r])=>r)}async function fS(e,t,n){let r=N(process.cwd(),n.path);await We(r);let i=await T(r),a=he(i.schema),o=Te(r,a.files.types,ve.types),s=[],c=ne(t.author,i.author_default),l=Se(i),d=await ce(r,Zn,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await ee(o),f;try{f=Le(m)}catch(h){throw new _(h instanceof Error?h.message:String(h),y.GENERIC_FAILURE)}try{u=Ha(f,e)}catch(h){throw new _(h instanceof Error?h.message:String(h),y.USAGE)}if(u.removed){let h=(u.definition?.name??e??"").trim();if(h.length>0){let g=await pp(r,i,a,h);g>0&&s.push(`items_using_type:${g}`)}await Ze({pmRoot:r,filePath:o,raw:Ke(u.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await te({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return u.removed&&await Xs(r,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:o,definitions:u.file.definitions.length},warnings:Qe(s),generated_at:I()}}function gi(e,t){return Te(e,t.files.statuses,ve.statuses)}function Qn(e,t){return Te(e,t.files.fields,ve.fields)}function Zs(e,t){return Te(e,t.files.types,ve.types)}async function Xt(e,t,n,r){for(let i of t){let a=$a(i.folder??Ta(i.name)),o=up.join(e,a);await R(o)||(await mp(o,{recursive:!0}),n.push(...await te({path:o,scope:"project",op:r})))}}function _i(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 _p(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 yp(e){let t=new Map;for(let n of e){let r=ae(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let a=ae(i);a.length>0&&!t.has(a)&&t.set(a,r)}}}return t}async function hS(e,t,n){let r=N(process.cwd(),n.path);await We(r);let i;try{i=Za({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(g){throw new _(g instanceof Error?g.message:String(g),y.USAGE)}let a=await T(r),o=he(a.schema),s=gi(r,o),c=it(o);try{Br(i,c.alias_to_id)}catch(g){throw new _(g instanceof Error?g.message:String(g),y.USAGE)}let l=_p(c.by_id.get(i.id)),d=[],u=ne(t.author,a.author_default),m=Se(a),f=await ce(r,Ks,a.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,a.locks.wait_ms),h;try{let g=await ee(s),p;try{p=yt(g)}catch(v){throw new _(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let w=yp(p.statuses);try{Br(i,w)}catch(v){throw new _(v instanceof Error?v.message:String(v),y.USAGE)}h=Qa(p,i,l),await Ze({pmRoot:r,filePath:s,raw:wt(h.file),op:"schema:add-status",author:u,settings:a}),d.push(...await te({path:s,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:h.replaced,status:h.definition,file:{path:s,statuses:h.file.statuses.length},warnings:Qe(d),generated_at:I()}}async function gS(e,t,n){let r=N(process.cwd(),n.path);await We(r);let i=await T(r),a=he(i.schema),o=gi(r,a),s=[],c=ne(t.author,i.author_default),l=Se(i),d=await ce(r,Ks,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await ee(o),f;try{f=yt(m)}catch(h){throw new _(h instanceof Error?h.message:String(h),y.GENERIC_FAILURE)}try{u=eo(f,e)}catch(h){throw new _(h instanceof Error?h.message:String(h),y.USAGE)}if(u.removed){let h=ae(u.definition?.id??e);await hp(s,r,i,a,h),await Ze({pmRoot:r,filePath:o,raw:wt(u.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await te({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:o,statuses:u.file.statuses.length},warnings:Qe(s),generated_at:I()}}function Qs(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 wp(e,t,n){return{...Qs(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 ec(e){return{id:e.id,source:zr.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 tc(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function vp(){let e=new Map,t=j();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let i of r){if(typeof i!="object"||i===null||Array.isArray(i))continue;let a=i.name;typeof a=="string"&&a.trim().length>0&&e.set(a.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function bp(e){let t=it(e),n=[],r=[];for(let i of t.definitions){let a=ec(i);a.source==="builtin"?n.push(a):r.push(a)}return{builtin:n,custom:r}}async function Zt(e){let t=N(process.cwd(),e.path);await We(t);let n=await T(t),r=he(n.schema),i=Te(t,r.files.types,ve.types),a=gi(t,r),o=G(n,j()),s=vp(),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:i,statusesPath:a,byType:o.by_type,customNames:c,extensionProvenance:s,schema:r}}async function _S(e){let t=await Zt(e),n=[],r=[],i=[];for(let s of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=tc(s.name,t.customNames,new Set(t.extensionProvenance.keys())),l=Qs(s);c==="extension"?i.push(l):c==="custom"?r.push(l):n.push(l)}let a=bp(t.schema),o=Rn(t.schema).definitions.map(_i);return{action:"list",builtin:n,custom:r,extension:i,counts:{builtin:n.length,custom:r.length,extension:i.length,total:n.length+r.length+i.length},statuses:{builtin:a.builtin,custom:a.custom,counts:{builtin:a.builtin.length,custom:a.custom.length,total:a.builtin.length+a.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:I()}}async function yS(e,t){let n=(e??"").trim();if(n.length===0)throw new _("Type name must not be empty.",y.USAGE);let r=await Zt(t),i=Object.values(r.byType).find(a=>a.name.toLowerCase()===n.toLowerCase()||a.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!i)throw new _(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Sn(n)}" to register it.`,y.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:wp(i,tc(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:I()}}async function wS(e,t){let n=ae(e);if(n.length===0)throw new _("Status id must not be empty.",y.USAGE);let r=await Zt(t),i=it(r.schema),a=i.alias_to_id.get(n)??n,o=i.by_id.get(a);if(!o)throw new _(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Sn(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:ec(o),file:{path:r.statusesPath},generated_at:I()}}async function vS(e,t,n){let r=N(process.cwd(),n.path);await We(r);let i;try{i=Ka({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(h){throw new _(h instanceof Error?h.message:String(h),y.USAGE)}let a=await T(r),o=he(a.schema),s=Qn(r,o),c=[],l=An(i.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let d=ne(t.author,a.author_default),u=Se(a),m=await ce(r,Ys,a.locks.ttl_seconds,d,!!t.force,u.force_required_for_stale_lock,a.locks.wait_ms),f;try{let h=await ee(s),g;try{g=gt(h)}catch(p){throw new _(p instanceof Error?p.message:String(p),y.GENERIC_FAILURE)}f=Ya(g,i),await Ze({pmRoot:r,filePath:s,raw:_t(f.file),op:"schema:add-field",author:d,settings:a}),c.push(...await te({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:s,fields:f.file.fields.length},warnings:Qe(c),generated_at:I()}}async function kp(e,t,n,r){let i=G(t,j());return(await Fe(e,t.item_format,i.type_to_folder,[],n)).filter(o=>{let s=o[r];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function bS(e,t,n){let r=N(process.cwd(),n.path);await We(r);let i=await T(r),a=he(i.schema),o=Qn(r,a),s=[],c=ne(t.author,i.author_default),l=Se(i),d=await ce(r,Ys,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await ee(o),f;try{f=gt(m)}catch(h){throw new _(h instanceof Error?h.message:String(h),y.GENERIC_FAILURE)}try{u=Xa(f,e)}catch(h){throw new _(h instanceof Error?h.message:String(h),y.USAGE)}if(u.removed){let h=ae(u.definition?.key??e),g=ae(u.definition?.metadata_key??u.definition?.front_matter_key??h);if(g.length>0){let p=await kp(r,i,a,g);p>0&&s.push(`items_using_field:${p}`)}await Ze({pmRoot:r,filePath:o,raw:_t(u.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await te({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:o,fields:u.file.fields.length},warnings:Qe(s),generated_at:I()}}async function kS(e){let t=await Zt(e),n=Rn(t.schema).definitions.map(_i);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Qn(t.pmRoot,t.schema)},generated_at:I()}}async function xS(e,t){let n=ae(e);if(n.length===0)throw new _("Field key must not be empty.",y.USAGE);let r=await Zt(t),i=Rn(r.schema).by_key.get(n);if(!i)throw new _(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Sn(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:_i(i),file:{path:Qn(r.pmRoot,r.schema)},generated_at:I()}}async function SS(e,t,n){let r=N(process.cwd(),n.path);await We(r);let i;try{let g=Va(e);if(g===void 0)throw new Error(`Type preset name is required. Allowed: ${Ja.join(", ")}.`);i=g}catch(g){throw new _(g instanceof Error?g.message:String(g),y.USAGE)}let a=await T(r),o=he(a.schema),s=Zs(r,o),c=[],l=ne(t.author,a.author_default),d=Se(a),u=[],m=[],f,h=await ce(r,Zn,a.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,a.locks.wait_ms);try{let g=await ee(s),p;try{p=Le(g)}catch(v){throw new _(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let w=p;for(let v of Ur(i)){let k=En(w,v);w=k.file,(k.replaced?m:u).push(k.definition.name)}f=w.definitions.length,await Ze({pmRoot:r,filePath:s,raw:Ke(w),op:"schema:apply-preset",author:l,settings:a}),await Xt(r,Ur(i),c,"schema:apply-preset-folder"),c.push(...await te({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await h()}return{action:"apply-preset",preset:i,registered:u,replaced:m,file:{path:s,definitions:f},warnings:Qe(c),generated_at:I()}}function xp(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new _("--min-count must be a positive integer (>= 1).",y.USAGE);return e}async function ES(e,t){let n=N(process.cwd(),t.path);await We(n);let r=await T(n),i=he(r.schema),a=Zs(n,i),o=xp(e.minCount),s=G(r,j()),l=(await Fe(n,r.item_format,s.type_to_folder,[],i)).map(k=>typeof k.title=="string"?k.title:""),d=Ts(l,{minCount:o}),u=[],m=[],f=[],h=[],g;if(!e.apply){let k;try{k=Le(await ee(a))}catch(x){throw new _(x instanceof Error?x.message:String(x),y.GENERIC_FAILURE)}return g=k.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:d,registered:m,replaced:f,skipped:h,file:{path:a,definitions:g},warnings:u,generated_at:I()}}let p=ne(e.author,r.author_default),w=Se(r),v=await ce(n,Zn,r.locks.ttl_seconds,p,!!e.force,w.force_required_for_stale_lock,r.locks.wait_ms);try{let k=await ee(a),x;try{x=Le(k)}catch(A){throw new _(A instanceof Error?A.message:String(A),y.GENERIC_FAILURE)}let b=x;for(let A of d){if(A.shadows_builtin){h.push({name:A.name,reason:"shadows_builtin"});continue}let U;try{U=jr({name:A.name})}catch{h.push({name:A.name,reason:"invalid_type_token"});continue}let C=En(b,U);b=C.file,(C.replaced?f:m).push(C.definition.name)}g=b.definitions.length,await Ze({pmRoot:n,filePath:a,raw:Ke(b),op:"schema:infer-types",author:p,settings:r}),await Xt(n,b.definitions.filter(A=>m.includes(A.name)||f.includes(A.name)),u,"schema:infer-types-folder"),u.push(...await te({path:a,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:o,candidates:d,registered:m,replaced:f,skipped:h,file:{path:a,definitions:g},warnings:Qe(u),generated_at:I()}}import nc from"node:fs/promises";import yi 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 _e(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function S(e){return e.trim().toLowerCase()}function er(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 i=t.slice(n,r);if(i.length===0)throw new _("Extension manifest name must resolve to a non-empty directory name.",y.USAGE);if(i==="."||i==="..")throw new _('Extension manifest name must not resolve to "." or "..".',y.USAGE);return i}function wi(e){return ja(e)}async function Sp(e){try{let t=JSON.parse(await nc.readFile(yi.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 Ep(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new _(`Extension entry file is missing at "${t}".`,y.USAGE);let r=await Sp(n.source_root),i=r.package_name?`pm install npm:${r.package_name}`:void 0,a=n.source_input??n.source_root;return new _(`Extension entry "${e.entry}" is absent from GitHub source "${a}". pm install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" 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."}`,y.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:i?[i,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"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 ${a}`,normalized_args:["install",a],...i?{next_best_command:i}:{}}})}async function Dt(e,t={}){let n=yi.join(e,"manifest.json");if(!await R(n))throw new _(`Extension manifest is missing at "${n}".`,y.USAGE);let r;try{r=JSON.parse(await nc.readFile(n,"utf8"))}catch(o){throw new _(`Failed to parse extension manifest at "${n}": ${Rp(o)}`,y.USAGE)}let i=wi(r);if(!i)throw new _(`Extension manifest at "${n}" is invalid.`,y.USAGE);let a=yi.resolve(e,i.entry);if(!fe(e,a))throw new _(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,y.USAGE);if(!await R(a))throw await Ep(i,a,t);if(!await Ua(e,a))throw new _(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,y.USAGE);return{directory:e,manifest_path:n,entry_path:a,manifest:i}}function Rp(e){return e instanceof Error?e.message:String(e)}import vi from"node:fs/promises";import Ap 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 Ip=".managed-extensions.json",tr=1;function Qt(e){return Ap.join(e,Ip)}function Cp(){return{version:tr,updated_at:I(),entries:[]}}function en(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function rc(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 ye(e){return typeof e=="string"?e:void 0}function Tp(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 $p(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:ye(t.name),package:ye(t.package),version:ye(t.version),repository:ye(t.repository),owner:ye(t.owner),repo:ye(t.repo),ref:ye(t.ref),subpath:ye(t.subpath),commit:ye(t.commit)}}function Op(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Tp(t))return null;let n=$p(t.source);if(!n)return null;let r=La(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:_e(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:ye(t.last_update_check_at),last_update_remote_commit:ye(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:ye(t.update_error)}}function Dp(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==tr||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=Op(r);i&&n.push(i)}return{version:tr,updated_at:ye(t.updated_at)??I(),entries:en(n)}}async function de(e){let t=Qt(e),n=Cp();try{let r=await vi.readFile(t,"utf8"),i=JSON.parse(r),a=Dp(i);if(!a)throw new _(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE);return{path:t,state:a,warnings:[]}}catch(r){if(r instanceof _)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&L(r))return{path:t,state:n,warnings:[]};throw new _(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE)}}async function dt(e,t){let n=Qt(e),r={version:tr,updated_at:I(),entries:en(t.entries)};await vi.mkdir(e,{recursive:!0}),await vi.writeFile(n,`${JSON.stringify(r,null,2)}
16
+ `,"utf8")}function tn(e,t){let n=e.entries.filter(r=>S(r.name)!==S(t.name)&&S(r.directory)!==S(t.directory));return n.push(t),{...e,updated_at:I(),entries:en(n)}}async function ic(e,t,n,r){let i=t.entries.find(o=>S(o.name)===S(n));if(!i)return t;let a=tn(t,{...i,contributions:r});return await dt(e,a),a}import{execFile as Gp}from"node:child_process";import z from"node:fs/promises";import Ei from"node:os";import $ from"node:path";import{fileURLToPath as qp}from"node:url";import{promisify as Hp}from"node:util";import Jp from"npm-package-arg";import{extract as Vp,list as Kp}from"tar";import Pp from"node:fs/promises";import Ee 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 Np="PM_CLI_PACKAGE_ROOT",ac={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Lp=new Set(["*","all"]);function bi(){let e=[],t=process.env[Np];return typeof t=="string"&&t.trim().length>0&&e.push(Ee.resolve(t.trim())),e.push(Ae(import.meta.url,["../../.."])),[...new Set(e)]}async function nn(e){let t=e.trim().toLowerCase(),n=await sc(t);if(n)return n;let r=ac[t];if(!r)return null;for(let i of bi()){let a=Ee.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await R(Ee.join(a,"manifest.json")))return a}return null}function oc(e){return Lp.has(e.trim().toLowerCase())}function Mp(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Fp(e,t){let n=await Pp.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=Ee.join(e,r.name);if(!await R(Ee.join(i,"package.json")))continue;let a=await kn(i),o=a.aliases&&a.aliases.length>0?a.aliases:[Mp(r.name)];for(let s of o){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:i,package_name:a.package_name??null})}}}async function ki(){let e=new Map;for(let t of bi()){let n=Ee.join(t,"packages");await R(n)&&await Fp(n,e)}for(let[t,n]of Object.entries(ac))if(!e.has(t))for(let r of bi()){let i=Ee.join(r,"packages",n.package_directory);if(await R(Ee.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function nr(){return(await ki()).map(e=>e.alias)}async function sc(e){let t=e.trim().toLowerCase();return(await ki()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function cc(e){let t=await sc(e);return t?(await kn(t)).package_name??null:null}async function lc(e){let t=await nn(e);if(!t)return null;try{let n=await xn(t);return n.length!==1?null:(await Dt(n[0])).manifest.name}catch{return null}}function jp(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 Up(e,t,n,r,i,a){let o=r==="global"?"--global":"--project",s=Object.fromEntries(Fr.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=>i.has(c))||a.has(Ee.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,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:jp(e),media:e.catalog?.media}}}async function dc(e,t,n={}){let r=ht(N(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,a=await de(i),o=new Set(a.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>Ee.resolve(m.source.location))),s=new Set(a.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 ki()){let f=Ee.resolve(m.package_root),h=l.get(f)??[];h.push(m),l.set(f,h)}for(let m of l.values()){let f=m[0],h=m.map(p=>p.alias).sort((p,w)=>p.localeCompare(w)),g=await kn(f.package_root);c.push(Up(g,f,h,e,s,o))}let d=Bp(n.fields),u=d?c.map(m=>Wp(m,d)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Fr.filter(m=>m!=="extensions"),packages:u}}var zp=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 Bp(e){if(e===void 0)return;let t=Un(e);if(t.length===0)throw new _("Package catalog --fields requires a comma-separated list of field names",y.USAGE);let n=t.filter(r=>!zp.has(r));if(n.length>0)throw new _(`Unknown package catalog --fields value(s): ${n.join(", ")}`,y.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function Wp(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 Ri=Hp(Gp),ir="@unbrained/pm-cli",Yp={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},xi;async function uc(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=$.resolve(t);for(;;){let i=$.join(r,"node_modules",...n.split("/")),a=$.join(i,"package.json");if(await R(a))try{let s=JSON.parse(await z.readFile(a,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let o=$.dirname(r);if(o===r)return null;r=o}}function Si(e,t,n){let r=e.split("/").map(l=>l.trim()).filter(l=>l.length>0);if(r.length<2)return null;let i=r[0],a=r[1].replace(/\.git$/i,"");if(i.length===0||a.length===0)return null;let o=r.slice(2),s,c;return o[0]==="tree"&&o.length>=2?(s=o[1],c=o.slice(2).join("/")):o.length>0&&(c=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:a,repository:`https://github.com/${i}/${a}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function Xp(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new _('npm package source must include a package spec after "npm:".',y.USAGE);if(t)throw new _('Options "--gh/--github" cannot be combined with npm: package sources.',y.USAGE);if(n)throw new _('Option "--ref" cannot be combined with npm: package sources.',y.USAGE);return{kind:"npm",input:e,spec:r}}function ar(e,t={}){let n=e.trim();if(n.length===0)throw new _("Extension source is required for --install.",y.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Xp(n,t.forceGithub===!0,r);let i=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return Si(s,n,r)}catch{return null}})();if(i)return i;let a=n.startsWith("github.com/")?n.slice(11):null;if(a){let o=Si(a,n,r);if(!o)throw new _(`Invalid GitHub source "${n}".`,y.USAGE);return o}if(t.forceGithub){let o=Si(n,n,r);if(!o)throw new _(`Invalid GitHub shorthand "${n}".`,y.USAGE);return o}if(/^https?:\/\//i.test(n))throw new _(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,y.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function rr(e,t=Ri,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",a=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new _(`Git command failed: git ${e.join(" ")}
17
+ ${a}`,y.GENERIC_FAILURE)}}function Zp(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Qp(e=process.platform){return e==="win32"}async function mc(e,t,n=Ri,r=process.platform){let i=Zp(r);try{return((await n(i,e,{cwd:t,encoding:"utf8",shell:Qp(r)})).stdout??"").trim()}catch(a){let o=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr):"",s=o.trim().length>0?o.trim():a instanceof Error?a.message:String(a);throw new _(`npm command failed: ${i} ${e.join(" ")}
18
+ ${s}`,y.GENERIC_FAILURE)}}function ef(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 tf(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 nf(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return tf(e)||n.includes("not found")}function rf(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function af(e){let t=ef(e),n=rf(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,a=i?`pm install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:a?[a,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:a?[`Try ${a} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&a?{fallback_candidates:[{source:i,command:a,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:a}:{}}}}}function of(e,t){if(!nf(t))return null;let n=af(e);return new _(n.message,y.NOT_FOUND,n.context)}async function pc(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await R(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=qp(t);return await R(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await R(t))return t}return null}async function sf(e){let t=await pc(e);if(t)return t;let n=cf(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function cf(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(r<=0)return e;let i=e.slice(0,r),a=e.slice(r+n.length);if(i.trim().length===0||a.trim().length===0||a.startsWith("//")&&!a.startsWith("///"))return e;if(!a.startsWith("/"))return`${i}@${$.resolve(t,a)}`;let o;try{o=decodeURIComponent(new URL(`file:${a}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${i}@${s}`}function lf(e,t){try{let r=JSON.parse(e),i=Array.isArray(r)?r[0]:void 0;if(i&&typeof i.filename=="string"&&i.filename.trim().length>0)return{tarball:$.resolve(t,i.filename),package:typeof i.name=="string"?i.name:void 0,version:typeof i.version=="string"?i.version:void 0}}catch{}let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).at(-1);if(!n)throw new _("npm pack did not report a tarball filename.",y.GENERIC_FAILURE);return{tarball:$.resolve(t,n)}}async function df(e){return uf(e,mc)}async function uf(e,t){let n=await pc(e.spec);if(n){if((await z.stat(n)).isFile()&&fc(n))return hc(n);let s=$.join(n,"package.json"),c=await R(s)?JSON.parse(await z.readFile(s,"utf8")):{};return{directory:await rn(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 z.mkdtemp($.join(Ei.tmpdir(),"pm-npm-package-source-")),i=$.join(r,"pack"),a=$.join(r,"extract");await z.mkdir(i,{recursive:!0}),await z.mkdir(a,{recursive:!0});try{let o=await sf(e.spec),s=await t(["pack",o,"--json","--pack-destination",i]),c=lf(s,i);await Ri("tar",["-xzf",c.tarball,"-C",a],{encoding:"utf8"});let l=$.join(a,"package");return await gc(l),{directory:await rn(l,e.input),package:c.package,version:c.version,cleanup:async()=>{await z.rm(r,{recursive:!0,force:!0})}}}catch(o){await z.rm(r,{recursive:!0,force:!0});let s=of(e.spec,o);throw s||o}}function fc(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function Ge(e){throw new _(e,y.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 mf(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&Ge(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,i=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||i.some(a=>a===".."))&&Ge(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&Ge(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&Ge(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&Ge(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&Ge(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&Ge(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function hc(e,t=Yp){(await z.stat(e)).size>t.maxArchiveBytes&&Ge(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await z.mkdtemp($.join(Ei.tmpdir(),"pm-local-package-archive-")),i=$.join(r,"extract");await z.mkdir(i,{recursive:!0});let a={entries:0,expandedBytes:0,packageJsonEntries:0},o;try{if(await Kp({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(o===void 0)try{mf(d,t,a)}catch(u){o=u}}}),o!==void 0)throw o;a.packageJsonEntries!==1&&Ge(`Local package archive must contain exactly one package/package.json entry; found ${a.packageJsonEntries}.`),await Vp({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=$.join(i,"package"),c=$.join(s,"package.json"),l=JSON.parse(await z.readFile(c,"utf8"));return await gc(s),{directory:await rn(s,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.version:void 0,cleanup:async()=>{await z.rm(r,{recursive:!0,force:!0})}}}catch(s){throw await z.rm(r,{recursive:!0,force:!0}),s}}async function gc(e,t=mc){let n=$.join(e,"package.json");if(!await R(n))return;let r;try{r=JSON.parse(await z.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,a=yf(i),o=pf(i);if(a.length===0&&!o)return;let s={...r};delete s.devDependencies;let c={...s};ff(c),await z.writeFile(n,`${JSON.stringify(c,null,2)}
19
+ `,"utf8");try{await Promise.all([z.rm($.join(e,"package-lock.json"),{force:!0}),z.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),a.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await hf(e)}finally{await z.writeFile(n,`${JSON.stringify(s,null,2)}
20
+ `,"utf8")}}function pf(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&ir in t)return!0;return!1}function ff(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[ir],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function hf(e){let t=Ae(import.meta.url,["../../.."]),[n,r]=ir.split("/"),i=$.join(e,"node_modules",n),a=$.join(i,r);await z.mkdir(i,{recursive:!0}),await z.rm(a,{recursive:!0,force:!0}),await z.symlink(t,a,gf(process.platform))}function gf(e){return e==="win32"?"junction":"dir"}function _f(e,t){if(e.startsWith("-"))throw new _(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,y.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(r=>{let i=r.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(r)}))throw new _(`Extension runtime dependency "${e}" has an unsafe version specifier.`,y.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{Jp.resolve(e,t)}catch{throw new _(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,y.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 yf(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===ir||typeof i!="string"||i.trim().length===0||t.has(r))continue;let a=i.trim();t.set(r,_f(r,a))}return[...t.values()]}async function rn(e,t){let n=await xn(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>$.relative(e,i).replaceAll($.sep,"/")).sort((i,a)=>i.localeCompare(a));throw new _(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,y.USAGE)}throw new _(`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.`,y.USAGE)}async function wf(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 i of n){let a=$.resolve(e,i);if(fe(e,a)&&await R($.join(a,"manifest.json")))return{directory:a,resolved_subpath:i}}if(await R($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await rn(e,t.input);return{directory:r,resolved_subpath:$.relative(e,r).replaceAll($.sep,"/")}}function vf(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 bf(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!vf(n))return new _(t,y.NOT_FOUND);let r=[];try{let a=process.env.PM_CLI_PACKAGE_ROOT,o=typeof a=="string"&&a.trim().length>0?$.resolve(a.trim()):"";xi?.key!==o&&(xi={key:o,aliases:await nr()}),r=xi.aliases}catch{}let i=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${r.join(", ")}`];return new _(`${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}".`,y.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function _c(e){if(e.kind==="local"){let r;try{r=await z.stat(e.absolute_path)}catch{throw await bf(e)}if(r.isFile()&&fc(e.absolute_path)){let a=await hc(e.absolute_path);return{source:e,directory:a.directory,source_root:$.dirname(a.directory),resolved_subpath:$.relative($.dirname(a.directory),a.directory).replaceAll($.sep,"/"),npm_package:a.package,npm_version:a.version,cleanup:a.cleanup}}if(!r.isDirectory())throw new _(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,y.USAGE);let i=await rn(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await df(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 z.mkdtemp($.join(Ei.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await rr(n);let r=await rr(["-C",t,"rev-parse","HEAD"]),i=await wf(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await z.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await z.rm(t,{recursive:!0,force:!0}),r}}async function yc(e,t){if(!await R(e)||!await R(t))return!1;let[n,r]=await Promise.all([z.realpath(e),z.realpath(t)]);return n===r}import an from"node:fs/promises";import on 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 Ai=1,ut="2026.6.24",kf=">=22.18.0",xf={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},wc=new Set([...to.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(io).map(e=>e.toLowerCase()),"scaffold"]),Sf="^6.0.0",Ef="^22.0.0",kc=["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."," }"," }","}",""],Oe=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function vc(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function xc(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 Sc(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 Rf={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},bc=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Ec={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"]},Af={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"]'},If={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."},Cf={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."},Rc="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Tf={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."]},$f={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."]},Of={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`."]},Df={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 Ac(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 Ic(e,t){return e==="schema"?Of[t]:e==="profile"?Df[t]:$f[t]}function Pf(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),a=r>0&&(r===t.length||i!==void 0&&wc.has(i));return`${(wc.has(n)||a?["starter",...t]:t).join(" ")} ping`}function Cc(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],a=`${e.replace(/-/g,"_")}_owner`,o="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(a)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function Nf(e,t,n){let r=`${e}-search`,i=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,o=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,l=e.replace(/-/g,""),d=l===s?[]:[l],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...Cc(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(a)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(a)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...o,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...o,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function Lf(e,t,n){let r=n==="hooks",i=n==="search",a=n==="importers",o=n==="schema",s=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",u=n==="services",m=Af[n],f=e,h=`${e}s`,g=`${e.replace(/-/g,"_")}_note`,p=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Oe,"});",""]:[],k=i?Ii(e,t,"search",m):[],x=a?Ii(e,t,"importers",m):[],b=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...vc(xc({extensionName:e,itemTypeName:f,itemTypeFolder:h,fieldName:g,migrationId:p,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Oe,"});",""]:[],A=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 {",...vc(Sc(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Oe,"});",""]:[],U=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;",...Oe,"});",""]:[],C=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;",...Oe,"});",""]:[],E=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Oe,"});",""]:[],F=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;",...Oe,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...kc,`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;",...Oe,"});","",...v,...k,...x,...b,...A,...U,...C,...E,...F,`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(`
21
+ `)}function Mf(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 Ff={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"},jf={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 Uf(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 zf(e,t,n){let r=[],i=[...Uf(e,t,n)],a=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,l=e,d=`${e}s`,u=e.replace(/-/g,""),m=u===l?[]:[u],f=`${e.replace(/-/g,"_")}_note`,h=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),a.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),a.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),a.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(f)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(l)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(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(h)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),a.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...Cc(e),"});"),a.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),a.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),a.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),a.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),a.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:a}}function Bf(e,t,n){let r=zf(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((a,o)=>a.localeCompare(o)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
22
+ `)}function Ii(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,a=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,l=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],m=f=>[...u," let deactivated = false;"," try {",...f.map(h=>h===""?h:` ${h}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Oe];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings: {} as PmSettings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings: {} as PmSettings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(a)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings: {} as PmSettings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(xc({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:l,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Sc(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 Wf(e,t,n){let r=n==="parser",i=JSON.stringify([...Ec[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" };',"",...kc,`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(ut)},`," },",` target: { pmVersion: ${JSON.stringify(ut)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Oe,"});","",...Ii(e,t,n,i)].join(`
23
+ `)}function Gf(e,t,n){let r=Ac(n,"package"),i=Ic(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 (${Ff[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`.",Rc,"- `.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 ${jf[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Ai}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${ut}\`. 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(`
24
+ `)}function qf(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 Hf(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 Jf(e,t,n,r){let i=["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"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.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"&&i.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"&&i.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"&&i.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"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.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"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function Vf(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 Kf(e,t,n,r="commands",i=!1){let a=`pm-${e}`,o=Ec[r],s=Mf(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Ai,pm_min_version:ut,trusted:!0,sandbox_profile:"strict",permissions:{...xf},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
25
+ `,l=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Nf(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(`
26
+ `),d=`${JSON.stringify(Rf,null,2)}
27
+ `,u=If[r],m=Ac(r,"package"),f=`${JSON.stringify({name:a,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:kf},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${ut}`},devDependencies:{"@types/node":Ef,typescript:Sf},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)}
28
+ `,h=Lf(e,t,r),g=Cf[r],p=["node_modules/","*.log","*.tsbuildinfo",""].join(`
29
+ `),w=qf(e),k=["```ts",`import { ${Hf(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Jf(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Vf(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],x=[`# ${a}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,g,Rc,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...k,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Tf[r],...Ic(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${ut}\`. 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 \`${Ai}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${ut}\`. 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(`
30
+ `);return{"package.json":f,"manifest.json":c,"index.ts":i?Bf(e,t,r):l,"index.test.ts":i?Wf(e,t,r):h,"tsconfig.json":d,".gitignore":p,"README.md":i?Gf(a,t,r):x}}async function Tc(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!bc.includes(i))throw new _(`Unknown scaffold capability "${n}". Supported capabilities: ${bc.join(", ")}.`,y.USAGE);let a=i;if(r&&t!=="package")throw new _("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",y.USAGE);let o=r?"declarative":"imperative",s=e.trim(),c=on.resolve(process.cwd(),s),l=er(on.basename(c)).replace(/^(?:pm-)+/u,""),d=Pf(l),u=Kf(l,d,t,a,r),m=!1;if(await R(c)){if(!(await an.stat(c)).isDirectory())throw new _(`Scaffold target "${c}" exists and is not a directory.`,y.CONFLICT)}else await an.mkdir(c,{recursive:!0}),m=!0;for(let[h,g]of Object.entries(u)){let p=on.join(c,h);if(!await R(p))continue;if(await an.readFile(p,"utf8")!==g)throw new _(`Scaffold file "${h}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,y.CONFLICT)}let f=[];for(let[h,g]of Object.entries(u)){let p=on.join(c,h);if(await R(p)){f.push({path:h,status:"unchanged"});continue}await an.mkdir(on.dirname(p),{recursive:!0}),await an.writeFile(p,g,"utf8"),f.push({path:h,status:"created"})}return{extension_name:l,package_name:`pm-${l}`,command_name:d,invocation_command:`pm ${d}`,capability:a,style:o,target_path:c,created_directory:m,files: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]="536ed530-7726-50ab-bb2d-ace030818f1d")}catch{}})();function $c(e,t){return`${e}:${S(t)}`}function Yf(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let a=new Map;for(let o of i){let s=a.get(o.command)??[];a.set(o.command,[...s,o])}for(let[o,s]of a){if(t!==null&&!s.some(l=>t.has(S(l.name))))continue;let c=s.at(-1);n.push({command:o,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(l=>({name:l.name,layer:l.layer,winner:l===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function Oc(e,t,n){let r=new Set(n.failed.map(l=>$c(l.layer,l.name))),i=[...t.loaded.map(l=>({name:l.name,layer:l.layer,version:l.version,activation_status:r.has($c(l.layer,l.name))?"failed":"ok",surfaces:It(n,{extensionName:l.name})})),...t.failed.map(l=>({name:l.name,layer:l.layer,version:"unknown",activation_status:"not_loaded",surfaces:It(n,{extensionName:l.name})}))].sort((l,d)=>l.name.localeCompare(d.name)||l.layer.localeCompare(d.layer)),a=typeof e=="string"?S(e):null,o=a===null?null:new Set(t.loaded.filter(l=>S(l.name)===a||typeof l.source_package=="string"&&S(l.source_package)===a||(l.source_aliases??[]).some(d=>S(d)===a)).map(l=>S(l.name)).concat(a)),s=o===null?i:i.filter(l=>o.has(S(l.name))),c=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:It(n,c),command_ownership:Yf(n,o)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function Ci(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function or(e,t,n){let r=S(t),i=n.trim();if(r.length===0||i.length===0)return;let a=e.get(r)??new Set;a.add(i),e.set(r,a)}function Xf(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)or(t,r.name,r.command),or(n,r.name,r.action);for(let r of e.commands.handlers)or(t,r.name,r.command);for(let r of e.commands.overrides)or(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Dc(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Zf(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:a}=e;return t?i.has(n)||a.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function sr(e,t,n){let r=new Set(t.loaded.map(c=>S(c.name))),i=new Set(t.failed.map(c=>S(c.name))),a=new Set(n.failed.map(c=>S(c.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=Xf(n);return e.map(c=>{let l=S(c.name),d=Dc(o.get(l)),u=Dc(s.get(l)),m={...d?{command_paths:d}:{},...u?{action_paths:u}:{}},f=Zf({enabled:c.enabled,normalizedName:l,loadedNames:r,loadFailedNames:i,activationFailedNames:a});return{...c,...f,...m}})}function Qf(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function oe(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Lc=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 eh(e){return Lc.has(Bc(e))}function Pc(e){return e==="project"||e==="global"}function Mc(e){let t=e.split(":"),n=t[0];if(!n||!Lc.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!Pc(r)||!Pc(a)||!i||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:a,name:o}}}function th(e){let t=new Set;for(let n of e){let r=Mc(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Ti(e,t){let n=e.filter(eh);if(n.length===0)return null;let r=th(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 nh(e,t,n,r){let i=t.map(u=>Mc(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let a=e==="global"?"--global":"--project",o=oe(r,"deactivate"),s=`${oe(r,"doctor")} ${a} --detail deep --trace`,c=new Map(n.map(u=>[S(u.name),u])),l=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let f=S(m);l.set(f,(l.get(f)??0)+1)}let d=[...l.entries()].map(([u,m])=>{let f=c.get(u),h=f?.name??u,g=f?.command_paths??[],p=f?.action_paths??[];return{action:"deactivate",extension:h,command:`${o} ${h} ${a}`,affected_collisions:m,feature_loss:{command_paths:[...g].sort((w,v)=>w.localeCompare(v)),action_paths:[...p].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let f=m.affected_collisions-u.affected_collisions;if(f!==0)return f;let h=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 h!==g?h-g:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:l.size,next_best_command:s,collisions:i,remediation_candidates:d}}function Fc(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 jc(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function Uc(e,t){let n=[];for(let r of ro(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var rh=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${oe(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: ${_n.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 ${oe(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 ${oe(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 ${oe(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 ${oe(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 ${oe(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${oe(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 ih(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,u=[],m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o};if(t.length>0){let f=Ti(t,{deactivate:`${oe(n,"deactivate")} <name> ${i}`,doctor:`${oe(n,"doctor")} ${i} --detail deep --trace`});f&&u.push(f);for(let h of rh)h.matches(t,m)&&u.push(h.build(m))}return s?u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${oe(n,"manage")} ${i} --fix-managed-state (or ${oe(n,"adopt-all")} ${i}, ${oe(n,"adopt")} <name> ${i}, or reinstall via ${oe(n,"install")} ${i} <source>).`):c>0&&u.push(`Loaded unmanaged extensions are currently treated as informational. Use ${oe(n,"manage")} ${i} --fix-managed-state to adopt them for update checks.`),l>0&&u.push("Non-GitHub managed extensions are skipped by update checks. Use doctor output for non-update diagnostics."),d>0&&u.push(`Update available managed extensions via ${oe(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${oe(n,"manage")} ${i} after extension changes.`),u}function cr(e,t,n,r={}){let i=[...new Set(t)].sort((E,F)=>E.localeCompare(F)),a=n.filter(E=>E.managed).length,o=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,c=n.filter(E=>E.update_available===!0).length,l=n.filter(E=>E.managed===!1),d=l.filter(E=>Nc(E)).map(E=>E.name).sort((E,F)=>E.localeCompare(F)),u=l.filter(E=>!Nc(E)).map(E=>E.name).sort((E,F)=>E.localeCompare(F)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)m[E.update_check_status]+=1;let f=m.failed,h=m.skipped_unmanaged,g=m.skipped_non_github,p=u.length>0,w=p?"partial":"full",v=p?[`extension_update_health_partial_coverage:skipped_unmanaged:${u.length}`]:[],k=[...new Set([...i,...v])].sort((E,F)=>E.localeCompare(F)),x=[...new Set(k.map(E=>Bc(E)))].sort((E,F)=>E.localeCompare(F)),b=Qf(k),A=e==="global"?"--global":"--project",U=nh(e,i,n,r),C=ih({normalizedWarnings:i,options:r,scope:e,scopeFlag:A,updateCheckFailedTotal:f,policyWarningCount:b.warning_count,updateHealthPartial:p,skippedUnmanagedTotal:h,skippedNonGithubTotal:g,updateAvailableTotal:c});return{status:k.length===0?"ok":"warn",warning_count:k.length,warning_codes:x,warnings:k,policy_warning_count:b.warning_count,policy_violation_count:b.violation_count,policy_blocked_count:b.blocked_count,total_extensions:n.length,managed_total:a,enabled_total:o,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:p,unmanaged_loaded_extension_count:l.length,unmanaged_loaded_extensions:l.map(E=>E.name).sort((E,F)=>E.localeCompare(F)),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:f,top_warnings:k.slice(0,8),remediation:C,...U?{collision_plan:U}:{}}}function zc(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new _(`Invalid --detail value "${e}". Expected summary or deep.`,y.USAGE)}function Bc(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function sn(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let a=xa(r);return a?[a]:Sa(r)})();for(let a of i){let o=`${a.layer}:${a.name}:${a.capability}`;t.has(o)||(t.add(o),n.push(a))}}return n}function cn(){return{version:yn.version,capabilities:[...yn.capabilities],legacy_aliases:{...yn.legacy_aliases}}}function Nc(e){let t=S(e.name),n=S(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Wc(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let a=[...new Set(t.filter(d=>d.active).map(d=>S(d.name)))].sort((d,u)=>d.localeCompare(u)),o=[...new Set(n.filter(d=>d.layer==="project").map(d=>S(d.name)))].sort((d,u)=>d.localeCompare(u)),s=new Set(r.map(d=>S(d.name))),c=a.filter(d=>!o.includes(d)&&!s.has(d)).sort((d,u)=>d.localeCompare(u));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:a.length,loaded_project_count:o.length,active_project_names:a,loaded_project_names:o,missing_active_project_names:c}}}import{randomUUID as ah}from"node:crypto";import Q from"node:fs/promises";import oh from"node:os";import q 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 Gc=3,sh=120,qc=250,ch=12e4,lh=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Hc=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Jc=e=>lh.has(String(Hc(e))),lr=(e,t)=>Hc(e)===t,Vc=e=>new Promise(t=>{setTimeout(t,e)}),Kc=async e=>{let t=q.join(e,"package.json");await R(t)||await Q.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
31
+ `,"utf8")},Yc=async e=>{let t=Ae(import.meta.url,["../../.."]),n=q.join(e,"node_modules","@unbrained"),r=q.join(n,"pm-cli");await Q.mkdir(n,{recursive:!0}),await Q.rm(r,{recursive:!0,force:!0}),await Q.symlink(t,r,process.platform==="win32"?"junction":"dir")},$i=async e=>{let t=q.resolve(e),n=q.dirname(t),r=q.parse(n).root,i=await Q.realpath(r).catch(()=>r),a=q.relative(r,n),o=a===""?[]:a.split(q.sep);for(let[s,c]of o.entries()){let l=q.join(i,c);try{i=await Q.realpath(l)}catch{i=q.join(i,...o.slice(s));break}}return q.join(i,q.basename(t))},Xc=async(e,t,n,r=oh.tmpdir())=>{let i=q.resolve(e),a=await Q.realpath(i).catch(()=>i),o=await $i(t);if(a===o)return;if(!fe(a,o)){await n(e,t,{recursive:!0,force:!0});return}let s=m=>{let f=q.resolve(m);if(f!==i&&!fe(i,f))return!1;let h=q.resolve(a,q.relative(i,f));if(h===o||fe(o,h))return!1;let p=q.relative(a,h).split(q.sep);return p.some(w=>w==="node_modules"||w.startsWith(".pm-extension-install-backup-"))?!1:p[0]!==".agents"},c=await Q.realpath(q.resolve(r)).catch(()=>$i(r)),l=fe(a,c)?q.dirname(a):c;if(fe(a,l))throw new _(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,y.USAGE,{code:"extension_install_source_contains_destination"});let d=await Q.mkdtemp(q.join(l,"pm-extension-copy-")),u=q.join(d,"extension");try{await n(e,u,{recursive:!0,force:!0,filter:s}),await n(u,t,{recursive:!0,force:!0})}finally{await Q.rm(d,{recursive:!0,force:!0})}},Zc=async(e,t,n=Q.cp)=>{for(let r=1;r<=Gc;r+=1)try{await Q.rm(t,{recursive:!0,force:!0}),await Xc(e,t,n);return}catch(i){if(!Jc(i)||r===Gc)throw i;await Vc(qc)}},Oi=async e=>{let t;try{t=await Q.readFile(q.join(e,"owner.json"),"utf8")}catch(i){if(!vn(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},Qc=async(e,t)=>await Oi(e)!==t?!1:(await Q.rm(e,{recursive:!0,force:!0}),!0),dh=async(e,t)=>{let n;try{n=await Q.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await Oi(e);return r===null?(await Q.rm(e,{recursive:!0,force:!0}),!0):Qc(e,r)},uh=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await Oi(e)!==t)return;let a=new Date;await Q.utimes(e,a,a)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},mh=async(e,t)=>{await Q.mkdir(e);try{await Q.writeFile(q.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
32
+ `,"utf8")}catch(n){throw await Q.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},ph=async(e,t,n,r,i)=>{for(let a=1;a<=n;a+=1)try{return await mh(e,t),!0}catch(o){if(!lr(o,"EEXIST"))throw o;await dh(e,i)?a-=1:await Vc(r)}return!1},Di=async(e,t,n,r)=>{let i=q.join(e,"runtime","extension-install-locks"),a=q.join(i,"scope.lock");await Q.mkdir(i,{recursive:!0});let{attempts:o=sh,delay_ms:s=qc,stale_ms:c=ch,heartbeat_ms:l}=r??{};if(![o,s,c,l].filter(w=>w!==void 0).every(Number.isFinite))throw new _("Extension install lock timings must be finite numbers.",y.USAGE);let d=Math.max(1,Math.floor(o)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),f=Math.floor(l??m/3);if(m<=0||f<=0||f>=m)throw new _("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",y.USAGE);let h={pid:process.pid,token:ah(),created_at:I(),destination:t};if(!await ph(a,h,d,u,m))throw new _(`Timed out waiting for extension install lock for "${t}".`,y.CONFLICT);let p=uh(a,h.token,f);try{return await n()}finally{await p(),await Qc(a,h.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 el=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o])}});return await Promise.all(a),r};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b17dfc10-9e07-5912-b294-c5663133f192")}catch{}})();function tl(e,t){let n=S(e),r=t.find(i=>S(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,a)=>i.localeCompare(a)),action_paths:[...r?.action_paths??[]].sort((i,a)=>i.localeCompare(a))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0dc7b063-dc72-595f-8e40-8a06f9db69e1")}catch{}})();function nl(e,t){let n=new Set((t?.loaded??[]).flatMap(a=>(a.activation?.commands?.length??0)>0?[`${a.layer}:${S(a.name)}`]:[])),r=e.services.overrides.filter(a=>a.service==="output_format").filter(a=>!n.has(`${a.layer}:${S(a.name)}`)).map(a=>`extension_output_service_override_global:${a.service}:${a.layer}:${a.name}`),i=e.renderers.overrides.filter(a=>(a.commands?.length??0)===0&&a.resultDiscriminator===void 0).map(a=>`extension_output_renderer_override_global:${a.format}:${a.layer}:${a.name}`);return[...new Set([...r,...i])].sort((a,o)=>a.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var rl=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=An(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 fh=1e4,hh=(e,t,n)=>{let r=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c=""]=o.split(/\s+/);return{commit:s,ref:c}}),i=r.find(o=>o.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let a=t?.trim();return a?{checked_at:n,remote_commit:i.commit,available:i.commit!==a}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},il=async(e,t=rr)=>{let n=I();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let r=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,fh);return hh(i,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import gh from"node:fs/promises";import _h 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 Pi(e){return _h.join(e,"extension-migrations.json")}function al(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 ol(e,t){return`${e.layer}:${e.name}:${t}`}async function yh(e){let t=Pi(e);if(!await R(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await gh.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 Ni(e,t){let n=await yh(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,a)=>{let o=al(i,a),s=r.get(ol(i,o));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function wh(e){let t=await Ni(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),r=[],i=!1,a=e.migrations.map((d,u)=>({migration:d,index:u})).filter(({migration:d})=>e.scope===void 0||d.layer===e.scope);for(let{migration:d,index:u}of a){let m=al(d,u),f=ol(d,m),h=n.get(f),g=String(d.definition.status??"pending").toLowerCase(),p=h?.status??(g==="applied"||g==="failed"?g:"pending");if(p==="applied"){r.push({key:f,layer:d.layer,extension:d.name,id:m,before:p,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:f,layer:d.layer,extension:d.name,id:m,before:p,outcome:"pending"});continue}let w=d.runtime_definition?.run??d.definition.run;if(typeof w!="function"){r.push({key:f,layer:d.layer,extension:d.name,id:m,before:p,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:p}));let k={key:f,layer:d.layer,extension:d.name,id:m,status:"applied",attempted_at:v};n.set(f,k),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,r.push({key:f,layer:d.layer,extension:d.name,id:m,before:p,outcome:"applied"}),i=!0}catch(k){let x=k instanceof Error?k.message:String(k),b={key:f,layer:d.layer,extension:d.name,id:m,status:"failed",attempted_at:v,error:x};n.set(f,b),d.definition.status="failed",d.definition.reason=x,r.push({key:f,layer:d.layer,extension:d.name,id:m,before:p,outcome:"failed",error:x}),i=!0}}if(i){let d=await T(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,f)=>m.key.localeCompare(f.key))};await Dn({pmRoot:e.pmRoot,filePath:Pi(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
33
+ `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let o=r.filter(d=>d.outcome==="pending").length,s=r.filter(d=>d.outcome==="applied").length,c=r.filter(d=>d.outcome==="skipped").length,l=r.filter(d=>d.outcome==="failed").length;return{ok:l===0,dry_run:e.dryRun===!0,state_path:Pi(e.pmRoot),total:r.length,pending_count:o,applied_count:s,skipped_count:c,failed_count:l,migrations:r}}async function sl(e){let t=await T(e.resolvedRoots.settings_root),n=await Ie({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Ce(n);e.warnings.push(...n.warnings,...r.warnings);let i=await wh({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39bc7f14-2d32-5b58-97ab-647f9f238273")}catch{}})();async function cl(e,t,n){let r=typeof t=="string"?null:await nn(e),i=r===null?null:e.trim().toLowerCase(),a=i===null?null:await cc(i),o=ar(r??e,{forceGithub:typeof t=="string",ref:n}),s=i===null?null:await uc(e);return{bundledAliasName:i,bundledPackageName:a,installSource:o,sourceResolution:{requested:e,selected:{kind:i===null?o.kind:"builtin",input:i??o.input,...a===null?{}:{package:a}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...a===null?{}:{package:a},command:`pm install ${i}`}],...s===null?[]:[{kind:"npm",input:`npm:${s.package}`,package:s.package,...s.version===void 0?{}:{version:s.version},directory:s.directory,command:`pm install npm:${s.package}`}]]}}}import mt from"node:fs/promises";import vh 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 Li=async e=>mt.readFile(e).catch(t=>{if(lr(t,"ENOENT"))return null;throw t}),ll=async(e,t,n,r,i)=>{let a=Qt(e),o=V(t),[s,c]=await Promise.all([Li(a),Li(o)]);return r&&await mt.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:a,managedStateContents:s,settingsPath:o,settingsContents:c}},dl=async e=>{await mt.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await mt.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 mt.rm(t,{force:!0}):(await mt.mkdir(vh.dirname(t),{recursive:!0}),await mt.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 bh=4,fl=[["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"]],kh=fl.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),xh={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"},Sh="__pm_native_output",Eh=["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"],hl=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Rh=["disabled","require_trusted","require_provenance"],gl={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:[]},Ah=e=>{let t=e??gl,n={};for(let r of Eh)n[r]=_e(t[r]??[]);return n},Ih=(e,t)=>{for(let n of hl)t[n].length>0&&(e[n]=t[n]);return e},Ch=(e,t)=>{for(let n of Rh)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Th=e=>{let t={};for(let n of hl)t[n]=_e(e[n]??[]);return t},$h=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Ih(Ch({name:t},e),Th(e))},Oh=e=>(e??[]).map(t=>$h(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Dh=e=>{let t=Object.assign({},gl,e??{}),n=Ah(e),r=Oh(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}},_l=async(e,t)=>{let n=[t],r=await lc(t);r&&n.push(r);let i=[...new Set(n.map(a=>S(a)).filter(a=>a.length>0))];for(let a of i){let o=e.find(c=>S(c.name)===a);if(o)return o;let s=e.find(c=>S(c.directory)===a);if(s)return s}},yl=(e,t)=>{let n=t.trim(),r=new Set(_e(e.extensions.enabled));return new Set(_e(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},wl=(e,t)=>{let n=t.trim(),r=new Set(_e(e.extensions.enabled)),i=new Set(_e(e.extensions.disabled)),a=[...r],o=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Ph=(e,t)=>{let n=t.trim(),r=new Set(_e(e.extensions.enabled)),i=new Set(_e(e.extensions.disabled)),a=[...r],o=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Nh=(e,t)=>{let n=t.trim(),r=new Set(_e(e.extensions.enabled)),i=new Set(_e(e.extensions.disabled)),a=[...r],o=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Lh=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=fl.map(([i,a,o])=>({action:a,flag:o,distance:ka(t,i,n)})).filter(i=>i.distance!==null).sort((i,a)=>i.distance-a.distance)[0];return r?{action:r.action,flag:r.flag}:null},Mh=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=Lh(e);if(!r)return new _(`One action flag is required. Use one of: ${kh}. Bare \`pm package\` and \`pm extension\` default to --explore.`,y.USAGE);let i=`pm ${n} ${r.flag}`;return ko({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(vl),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},Fh=[["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"]],vl={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},jh=e=>vl[e]??null,Uh=(e,t)=>{let n=[...new Set(Fh.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=jh(e.trim().toLowerCase());if(r)return r;throw Mh(e,t)}if(n.length>1)throw new _("Extension action flags are mutually exclusive.",y.USAGE);return n[0]},zh=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new _('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"},Bh=[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"}}],bl=e=>{for(let t of Bh){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},kl=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,update_error:i.update_error,update_check_status:r.status,update_check_reason:r.reason}},Wh=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),a=r?yl(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:kl({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:a},t,r,bl(r))}},Gh=async(e,t,n,r,i,a)=>{let o=be.join(e,t),s=be.join(o,"manifest.json"),c=a.get(S(t));if(!await R(s))return Wh(t,n,r,c);let l=Symbol("invalid-extension-manifest-json"),d=await et.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>l);if(d===l)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=wi(d);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(S(u.name))??a.get(S(t));return{summary:kl({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:yl(r,u.name)},n,m,bl(m))}},De=async(e,t,n,r)=>{if(!await R(e))return{extensions:[],warnings:[]};let a=(await et.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,u)=>d.localeCompare(u)),o=new Map(r.entries.map(d=>[S(d.name),d])),s=new Map(r.entries.map(d=>[S(d.directory),d])),c=[],l=[];for(let d of a){let u=await Gh(e,d,t,n,o,s);u.warning&&c.push(u.warning),u.summary&&l.push(u.summary)}return{extensions:l.sort((d,u)=>d.name.localeCompare(u.name)),warnings:c.sort((d,u)=>d.localeCompare(u))}},qh=oo(),Hh=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Jh=(e,t,n,r)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),a=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return a&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Hh(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:o,...a?{sdk_dependency_status:"missing"}:{}}},Vh=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},xl=e=>e.map(t=>Vh(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),Sl=(e,t,n)=>{let r=S(e);return t.find(i=>(n===void 0||i.layer===n)&&S(i.name)===r)},Kh=(e,t,n,r)=>n.find(a=>a.scope===t&&S(a.name)===S(e))?.activation_status??(r?"failed":"unknown"),El=(e,t,n,r,i)=>qh.enqueue(async()=>{let a=process.env.PM_CLI_PACKAGE_ROOT,o=await et.mkdtemp(be.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Ae(import.meta.url,["../.."]);try{let s=await Ie({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:Lr(),cache_bust:!0,module_graph_snapshot_root:o}),c=await Ce({...s}),l=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...xl(c.failed)],d=Object.fromEntries(s.loaded.map(u=>[S(u.name),Ma(It(c,{extensionName:u.name}))]));return{installed:sr(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 et.rm(o,{recursive:!0,force:!0}),a===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=a}}),Fi=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),a=[...i].sort((c,l)=>{let d=c.name.localeCompare(l.name);return d!==0?d:c.directory.localeCompare(l.directory)}),o=r,s=[];for(let c of a){let l=be.join(e,c.directory),d=await Dt(l),u=I(),m={kind:"local",input:c.name,location:l};o=tn(o,{name:d.manifest.name,directory:c.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:u,updated_at:u,source:m}),s.push({name:d.manifest.name,directory:c.directory,version:d.manifest.version,entry:d.manifest.entry,source:m})}return s.length>0&&await dt(e,o),{state:o,adopted_entries:s,unmanaged_candidates:a,already_managed_count:n.length-i.length}},Yh=(e,t)=>{let n=N(process.cwd(),t.path),r=ht(n,process.cwd()),i=e==="global"?bn(process.cwd()):n,a=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:a,roots:r}},dr=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 _('Options "--gh" and "--github" must match when both are provided.',y.USAGE);return n[0]},Xh=e=>xh[e],Zh=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,a=Xh(e),o=`<${r}>`,s=`pm ${n} ${a} ${o}`;throw new _(`Action "${e}" requires ${i} input.`,y.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},ur=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new _('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',y.USAGE);return Zh(t,n)},Qh=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${S(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${S(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,i,a)=>a.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},eg=(e,t)=>{let r=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate",message:"--dry-run is only valid with --migrate."}].find(i=>i.triggered&&!i.allowed);if(r)throw new _(r.message,y.USAGE)},tg=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},ng=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},rg=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:ng(e),warnings:[...new Set(e.warnings)].sort((i,a)=>i.localeCompare(a)),details:t};return e.action==="doctor"&&Object.defineProperty(r,Sh,{value:!0,enumerable:!1,configurable:!1}),r},ji=async(e,t,n)=>{let r=Uh(e,t);eg(r,t);let i=tg(e,r,t),a=zh(t),o=Yh(a,n),c={action:r,normalizedTarget:i,scope:a,resolvedRoots:o,warnings:[],options:t,global:n},d={...c,withResult:(u,m=!0)=>rg(c,u,m)};return await Lg(d)},ig=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=ti(r),a={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[a[n],...s,`Install the scaffold: ${fs(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},ag=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([dr(r),r.ref].filter(l=>typeof l=="string").map(l=>l.trim()).filter(Boolean).length>0)throw new _('Action "init" does not accept --gh/--github/--ref options.',y.USAGE);let s=ur(n,t,r),c=await Tc(s,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:c.created_directory||c.files.some(l=>l.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:ig(c,r)})},og=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:a,withResult:o}=e;if(t!==void 0)throw new _('Action "reload" does not accept a target argument.',y.USAGE);let s=await T(n.settings_root),c=Lr(),l=await Ie({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:a.noExtensions,reload_token:c,cache_bust:!0});r.push(...l.warnings);let d=await Ce(l);r.push(...d.warnings);let u={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:l.loaded.length,failed_count:l.failed.length,activated_count:Math.max(0,l.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:l.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(u)},sg=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:a}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new _('Action "catalog" does not accept a package target.',y.USAGE);return a(await dc(n,i,r))},cg=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),lg=e=>({kind:"local",input:e.input,location:e.absolute_path}),dg=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),ug=(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}),mg=(e,t,n,r)=>e?cg(e,t):n.kind==="local"?lg(n):n.kind==="npm"?dg(n,r):ug(n,r),pg=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:rc(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},fg=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:a,destinationDirectoryName:o}=t,s=await T(r.settings_root),c=await de(r.selected_root);i.push(...c.warnings);let l=be.join(r.selected_root,o),d=await R(l),u=await yc(a.directory,l);await et.mkdir(r.selected_root,{recursive:!0});let m=await et.mkdtemp(be.join(r.selected_root,".pm-extension-install-backup-")),f=be.join(m,"destination");try{let h=await ll(r.selected_root,r.settings_root,l,d,f),g=mg(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),p=c.state.entries.find(x=>S(x.name)===S(a.manifest.name)),w=pg(p,a.manifest.version,g,I()),v=tn(c.state,{name:a.manifest.name,directory:o,scope:n,manifest_version:a.manifest.version,manifest_entry:a.manifest.entry,capabilities:[...a.manifest.capabilities],contributions:a.manifest.contributions,...w,source:g}),k=wl(s,a.manifest.name);try{u||await Zc(a.directory,l),await Kc(l),await Yc(l),await dt(r.selected_root,v),k&&await Pn(r.settings_root,s,"settings:write")}catch(x){try{await dl(h)}catch(b){throw new AggregateError([x,b],`Extension install failed: ${String(x)}; rollback failed: ${String(b)}`,{cause:b})}throw x}return{settings:s,managedState:v,sourceRecord:g,destinationDirectory:l,destinationExists:d,installInPlace:u,activationChanged:k}}finally{await et.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},hg=async(e,t,n)=>{let r=n.filter(i=>S(i.name)===S(t)).flatMap(i=>i.types.map(a=>({name:a.name,folder:a.folder})));return e.scope==="project"&&r.length>0&&await Xt(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},gg=(e,t,n,r,i)=>{let a=Sl(t,n.activation_failures,e.scope),o=Kh(t,e.scope,n.installed,a),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:a,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},_g=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:a,withResult:o}=e,{validated:s,destinationDirectoryName:c}=t,l=await fg(e,t),d=await De(r.selected_root,n,l.settings,l.managedState);i.push(...d.warnings);let u=await El(r.pm_root,be.dirname(r.selected_root),l.settings,d.extensions,a);i.push(...u.warnings);let m=await hg(e,s.manifest.name,u.item_type_registrations),f=tl(s.manifest.name,u.installed),h=gg(e,s.manifest.name,u,f,m),g=u.contribution_inventories[S(s.manifest.name)];return g&&(l.managedState=await ic(r.selected_root,l.managedState,s.manifest.name,g)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:l.sourceRecord,source_resolution:t.sourceResolution,destination_path:l.destinationDirectory,overwritten:[l.destinationExists,!l.installInPlace].every(Boolean),installed_in_place:l.installInPlace,activated:h.activated,settings_changed:l.activationChanged,runtime_activation_status:h.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:g,command_discovery:Jh(s.manifest.name,l.sourceRecord,f,h.failure),verification:h.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:h.failure??null}},h.activated)},yg=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new _('Action "install all" does not accept --ref.',y.USAGE);let a=[],o=new Map;for(let c of await nr()){let l=await nn(c),d=be.resolve(l),u=o.get(d);u===void 0&&(u=await ji(c,{...t,install:!0},n),o.set(d,u)),a.push({alias:c,result:u})}r.push(...a.flatMap(c=>c.result.warnings));let s=a.every(c=>c.result.ok);return i({installed_all:s,installed_count:a.filter(c=>c.result.ok).length,failed_count:a.filter(c=>!c.result.ok).length,packages:a.map(c=>{let l=c.result.details;return{alias:c.alias,ok:c.result.ok,extension:l.extension,source:l.source,source_resolution:l.source_resolution,destination_path:l.destination_path,activated:l.activated,settings_changed:l.settings_changed,command_paths:l.command_paths,action_paths:l.action_paths,command_discovery:l.command_discovery,verification:l.verification,runtime_activation_status:l.runtime_activation_status,activation_diagnostics:l.activation_diagnostics,warnings:c.result.warnings}})},s)},wg=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:a,installSource:o,sourceResolution:s}=await cl(t,n,e.options.ref);if(s.ambiguous){let l=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${l.package}`)}let c=await _c(o);try{let l=await Dt(c.directory,{source_kind:o.kind,source_input:o.input,source_root:c.source_root}),d=er(l.manifest.name);return await Di(r.settings_root,d,()=>_g(e,{validated:l,destinationDirectoryName:d,bundledAliasName:i,bundledPackageName:a,sourceResolution:s,installSource:o,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},vg=async e=>{let t=dr(e.options),n=t??ur(e.normalizedTarget,e.action,e.options);return[t===void 0,oc(n)].every(Boolean)?yg(e):wg(e,n,t)},bg=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e;if(t!==void 0)throw new _('Action "adopt-all" does not accept a target argument.',y.USAGE);if(dr(a)!==void 0||typeof a.ref=="string"&&a.ref.trim().length>0)throw new _('Action "adopt-all" does not accept --gh/--github/--ref options.',y.USAGE);let c=await T(r.settings_root),l=await de(r.selected_root);i.push(...l.warnings);let d=await De(r.selected_root,n,c,l.state);i.push(...d.warnings);let u=await Fi(r.selected_root,n,d.extensions,l.state),m=await De(r.selected_root,n,c,u.state);i.push(...m.warnings);let f=cr(n,i,m.extensions,a);i.push(...f.warnings);let h=new Map(m.extensions.map(w=>[`${S(w.name)}:${S(w.directory)}`,w])),g=new Map(m.extensions.map(w=>[S(w.directory),w])),p=u.adopted_entries.map(w=>{let v=S(w.directory),k=h.get(`${S(w.name)}:${v}`)??g.get(v);return{...w,...Rl(k)}});return o({adopted_all:p.length>0,adopted_count:p.length,already_managed_count:u.already_managed_count,extensions:p,triage:f,warning_codes:f.warning_codes,update_health_partial:f.update_health_partial,update_health_coverage:f.update_health_coverage})},Rl=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),kg=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=ar(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new _(`Invalid GitHub shorthand "${e}".`,y.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},xg=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o,withResult:s}=e,c=ur(n,t,o),l=dr(o),d=await T(i.settings_root),u=await de(i.selected_root);a.push(...u.warnings);let m=await De(i.selected_root,r,d,u.state);a.push(...m.warnings);let f=await _l(m.extensions,c);if(!f)throw new _(`Installed extension "${c}" was not found in ${r} scope.`,y.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let h=be.join(i.selected_root,f.directory),g=await Dt(h),p=I(),w=kg(l,c,h,o.ref),v=tn(u.state,{name:g.manifest.name,directory:f.directory,scope:r,manifest_version:g.manifest.version,manifest_entry:g.manifest.entry,capabilities:[...g.manifest.capabilities],contributions:g.manifest.contributions,installed_at:p,updated_at:p,source:w});await dt(i.selected_root,v);let k=await De(i.selected_root,r,d,v);a.push(...k.warnings);let x=k.extensions.find(b=>S(b.name)===S(g.manifest.name))??k.extensions.find(b=>S(b.directory)===S(f.directory));return s({adopted:!0,extension:{name:g.manifest.name,directory:f.directory,version:g.manifest.version,entry:g.manifest.entry},source:w,...Rl(x)})},Al=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o}=e,s=ur(n,t,o),c=await T(i.settings_root),l=await de(i.selected_root);a.push(...l.warnings);let d=await De(i.selected_root,r,c,l.state);a.push(...d.warnings);let u=await _l(d.extensions,s);if(!u)throw new _(`Installed extension "${s}" was not found in ${r} scope.`,y.NOT_FOUND);return{settings:c,managedStateRead:l,candidate:u}},Sg=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:a}=await Al(e),o=be.join(t.selected_root,a.directory);await et.rm(o,{recursive:!0,force:!0});let s={...i.state,updated_at:I(),entries:i.state.entries.filter(l=>S(l.name)!==S(a.name)&&S(l.directory)!==S(a.directory))};await dt(t.selected_root,s);let c=Nh(r,a.name);return c&&await Pn(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:a.name,directory:a.directory},destination_path:o,settings_changed:c})},ul=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:a}=e,{settings:o,candidate:s}=await Al(e),c=t==="activate"?wl(o,s.name):Ph(o,s.name);c&&await Pn(n.settings_root,o,"settings:write");let l=t==="activate"?await El(n.pm_root,be.dirname(n.selected_root),o,[s],i).then(d=>(r.push(...d.warnings),Sl(s.name,d.activation_failures,e.scope))):void 0;return l&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),a({extension:{name:s.name,directory:s.directory},active:t==="activate"&&l===void 0,runtime_active:t==="activate"&&l===void 0,activation_failure:l??null,settings_changed:c,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},l===void 0)},Eg=(e,t,n,r,i,a)=>{let o=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],c=i?.adopted_entries.length??0,l=[[a!==null,a??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...l.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},Mi=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Rg=(e,t,n,r)=>{if(e!=="project"||t||!Mi(r))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Ag=(e,t,n)=>{if(String(e??"").trim().length>0)throw new _('Action "doctor" does not accept a target argument.',y.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new _("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",y.USAGE);let i=zc(n.detail),a=n.trace===!0;if([a,i!=="deep"].every(Boolean))throw new _("--trace requires --detail deep with --doctor.",y.USAGE);return{isolated:r,detailMode:i,includeTrace:a}},Ig=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await Fi(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},Cg=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:Mi(r),rerun_command:null,pm_global_path_recipe:null};let a=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:Mi(r),rerun_command:t?null:a,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},Tg=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,global:o,withResult:s}=e,{isolated:c,detailMode:l,includeTrace:d}=Ag(t,n,a),u=await T(r.settings_root),m=await de(r.selected_root);i.push(...m.warnings);let f=await De(r.selected_root,n,u,m.state);i.push(...f.warnings);let{state:h,fix:g}=await Ig(e,f.extensions,m.state),p=await De(r.selected_root,n,u,h);i.push(...p.warnings);let w=await Ie({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Ce({...w,loaded:w.loaded});i.push(...w.warnings),i.push(...Fc(w.failed)),i.push(...v.warnings),i.push(...jc(v.failed)),i.push(...Uc(w,v)),i.push(...nl(v,w)),i.push(...Qh(w,v)),i.push(...rl(v));let k=sr(p.extensions,w,v),x=Wc(n,k,w.loaded.map(P=>({layer:P.layer,name:P.name})),w.failed.map(P=>({name:P.name})),w.disabled_by_flag);i.push(...x.warnings);let b=k.filter(P=>P.update_check_status==="failed").map(P=>`extension_update_check_failed:${P.name}`);i.push(...b);let A=cr(n,i,k,a);i.push(...A.warnings);let U=[...A.warnings],C={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},E=sn(U),F=cn(),W=A.warning_codes,O=Rg(n,c,a.vocabulary,w),B=Eg(A.remediation,w.failed.length,v.failed.length,a.vocabulary,g,O),pe=Cg(n,c,a.vocabulary,w),le={status:A.status,scope:n,warning_count:A.warning_count,warning_codes:W,total_extensions:k.length,managed_total:k.filter(P=>P.managed).length,enabled_total:k.filter(P=>P.enabled).length,active_total:k.filter(P=>P.active).length,unmanaged_loaded_extension_count:A.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:A.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:A.unmanaged_expected_extension_count,runtime_active_total:k.filter(P=>P.runtime_active===!0).length,activation_status_totals:{ok:k.filter(P=>P.activation_status==="ok").length,failed:k.filter(P=>P.activation_status==="failed").length,not_loaded:k.filter(P=>P.activation_status==="not_loaded").length,unknown:k.filter(P=>P.activation_status==="unknown").length},unknown_capability_count:E.length,capability_contract_version:F.version,update_available_total:k.filter(P=>P.update_available===!0).length,update_health_coverage:A.update_health_coverage,update_health_partial:A.update_health_partial,update_check_failed_total:k.filter(P=>P.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Ci(w.failed),activation_failures:Ci(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:x.warnings.length,trace_enabled:d,isolation:pe,policy:C,remediation:B},Pe=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(P=>P.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:p.extensions.filter(P=>P.managed).length,adopted_extensions:[]},Ne={mode:l,summary:le,triage:A,trace_enabled:d,capability_contract:F,capability_guidance:E,managed_state_fix:Pe,isolation:pe,policy:w.policy};if(l==="deep"){let P=d?v.failed:v.failed.map(J=>{let{trace:ba,...zt}=J;return zt});Ne.deep={warnings:U,warning_codes:W,capability_contract:F,capability_guidance:E,trace_enabled:d,managed_state:{path:m.path,count:h.entries.length,entries:h.entries},installed_extensions:k,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(J=>({layer:J.layer,directory:J.directory,name:J.name,version:J.version,entry:J.entry,priority:J.priority}))},activation:{failed:P,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:x.summary},d&&(Ne.deep.trace={activation_failures:v.failed.filter(J=>J.trace!==void 0).map(J=>({layer:J.layer,name:J.name,entry_path:J.entry_path,error:J.error,method:J.trace.method,command:J.trace.command,capability:J.trace.capability,missing_capability:J.trace.missing_capability,registration_index:J.trace.registration_index,expected_schema:J.trace.expected_schema,hint:J.trace.hint,received:J.trace.received}))})}return s(Ne)},$g=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,global:o,withResult:s}=e,c=await T(r.settings_root),l=await Ie({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),d=await Ce(l);i.push(...l.warnings),i.push(...d.warnings);let u=Oc(t,l,d);if(t!==void 0&&u.extensions.length===0){let m=a.vocabulary==="package"?"package":"extension",f=[...new Set(l.loaded.map(g=>a.vocabulary==="package"&&typeof g.source_package=="string"&&g.source_package.trim().length>0?g.source_package.trim():g.name))].sort((g,p)=>g.localeCompare(p)),h=f.length>0?` Loaded ${m} names: ${f.join(", ")}.`:"";throw new _(`No loaded ${m} named "${t}" was found in ${n} scope.${h} Run pm ${m} explore to list discovered ${m}s.`,y.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},Og=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await Fi(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let a=await el(r.entries,bh,async o=>{if(o.source.kind!=="github")return o;let s=await il(o.source);return{...o,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});r={...r,updated_at:I(),entries:en(a)},await dt(e.resolvedRoots.selected_root,r)}return{state:r,fix:i}},Dg=async(e,t,n)=>{let r=await Ie({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Ce({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:sr(n,r,i),failures:xl(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...r.warnings,...i.warnings])].length,policy:r.policy}}},Pg=(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},ml=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e,s=await T(r.settings_root),c=Dh(s.extensions.policy),l=await de(r.selected_root);i.push(...l.warnings);let d=await De(r.selected_root,n,s,l.state);i.push(...d.warnings);let{state:u,fix:m}=await Og(e,d.extensions,l.state),f=await De(r.selected_root,n,s,u);if(i.push(...f.warnings),t==="manage"){let v=f.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);i.push(...v)}let h=await Dg(e,s,f.extensions),g=h.installed,p=cr(n,i,g,a);i.push(...p.warnings);let w={total:g.length,managed_total:g.filter(v=>v.managed).length,enabled_total:g.filter(v=>v.enabled).length,active_total:g.filter(v=>v.active).length,extensions:g,triage:p,policy:c};return h.failures!==void 0&&(w.activation_diagnostics={failed_count:h.failures.length,failed:h.failures}),t==="explore"&&(w.runtime_probe=h.summary),t==="manage"&&(w.runtime_probe=h.summary,w.managed_state_fix=Pg(m,g)),o(w)},pl={init:ag,install:vg,uninstall:Sg,explore:ml,manage:ml,describe:$g,reload:og,doctor:Tg,catalog:sg,adopt:xg,"adopt-all":bg,activate:ul,deactivate:ul,migrate:sl},Ng=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),Lg=e=>Ng(e)?Di(e.resolvedRoots.settings_root,`${e.action}-state`,()=>pl[e.action](e)):pl[e.action](e);import{execFile as Mg}from"node:child_process";import{realpath as Fg}from"node:fs/promises";import Il from"node:path";import{promisify as jg}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var Ug=jg(Mg),zg=32*1024*1024,Bg=1e4,Wg=["search/eval-queries.json"];function Ui(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Gg(e){return`'${e.replaceAll("'","'\\''")}'`}async function qg(e,t=Fg){return t(e).catch(()=>Il.resolve(e))}async function mr(e){let t=await st(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await qg(e),r=Ui(Il.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=ri.map(a=>`${r}/${Ui(a)}`);try{let{stdout:a}=await Ug("git",["ls-files","-z","--",...i.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:zg,windowsHide:!0,timeout:Bg}),o=new Set(Wg.map(l=>`${r}/${l}`)),s=[...new Set(a.split("\0").filter(l=>l.length>0&&!o.has(Ui(l))))].sort((l,d)=>l.localeCompare(d)),c=i.filter(l=>s.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:s,tracked_path_count:s.length,remediation_command:s.length===0?null:`git rm --cached -r -- ${c.map(l=>Gg(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import{execFile as Hg}from"node:child_process";import{randomUUID as Jg}from"node:crypto";import{readdir as Vg,readFile as $l}from"node:fs/promises";import we from"node:path";import{promisify as Kg}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7b87b458-164a-5332-8803-6b0695481644")}catch{}})();var Yg=Kg(Hg);async function zi(e){try{let{stdout:t}=await Yg("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Ol(e,t){let n=we.dirname(we.resolve(e,t));for(let r=0;r<12;r+=1){if(await R(we.join(n,"settings.json")))return n;let i=we.dirname(n);if(i===n)break;n=i}return null}function Bi(e){return we.join(e,"merge-receipts")}function pr(e){return`${e}.json`}function Xg(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Cl(t.retained)??Nr(Pr(t.retained)),discarded_hash:Cl(t.discarded)??Nr(Pr(t.discarded))}))}}function Cl(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}async function yA(e){let t=await zi(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,i=we.basename(r,we.extname(r)),a={version:1,id:Jg(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:I(),value_availability:"clone_local"};await Or(t),await se(we.join(t,pr(a.id)),`${JSON.stringify(a,null,2)}
34
+ `);let o=await Ol(e.cwd,a.item_path);if(o!==null){let s=Bi(o),c=Xg(a),l={...a,decisions:c.decisions.map(d=>({field:d.field,base:null,ours:null,theirs:null,retained:{pm_value_hash:d.retained_hash},discarded:{pm_value_hash:d.discarded_hash}})),value_availability:"hash_only"};await Or(s),await se(we.join(s,pr(a.id)),`${JSON.stringify(l,null,2)}
35
+ `)}return a}async function Tl(e,t){if(!await R(e))return[];let n;try{n=await Vg(e)}catch{return[]}let r=[];for(let i of n.sort((a,o)=>a.localeCompare(o)))if(i.endsWith(".json"))try{let a=JSON.parse(await $l(we.join(e,i),"utf8")),{preferred:o,...s}=a,c={...s,requested_preference:a.requested_preference??o??"ours",conflict_resolution:a.conflict_resolution??"preferred_side"};c.version===1&&(t.includeReconciled||c.state==="pending")&&(t.includeLossless!==!1||c.decisions.length>0)&&r.push(c)}catch{}return r}async function ln(e,t={}){let n=await zi(e),r=n===null?[]:await Tl(n,t),i=t.pmRoot??we.join(e,".agents","pm"),a=await Tl(Bi(i),t),o=new Map(a.map(s=>[s.id,s]));for(let s of r)o.set(s.id,s);return[...o.values()].sort((s,c)=>s.created_at.localeCompare(c.created_at))}function fr(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function wA(e,t){let n=await zi(e);if(n===null)return;await se(we.join(n,pr(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:I()},null,2)}
36
+ `);let r=await Ol(e,t.item_path);if(r!==null){let i=we.join(Bi(r),pr(t.id));if(await R(i)){let a=JSON.parse(await $l(i,"utf8"));await se(i,`${JSON.stringify({...a,state:"reconciled",reconciled_at:I()},null,2)}
37
+ `)}}}async function vA(e){let t=await ln(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at: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]="97fd3651-47de-5505-be2b-bc466313e91f")}catch{}})();var Zg=new Set(Bo),Pl=25,dn=8,Qg=ue.join("runtime","telemetry","events.jsonl"),e_=ue.join("runtime","telemetry","state.json"),t_=2500,n_=500,Nl=zo-3,r_=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Ll(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 Ml(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Nt(e){return e.trim().toLowerCase()}function qi(e,t){let n=Nt(e),r=Nt(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function Vi(e){try{return(await He.stat(e)).isDirectory()}catch{return!1}}async function i_(e){let t=(await He.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>He.readdir(ue.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>Bt.some(a=>i.name.endsWith(a))).map(i=>ue.parse(i.name).name)))}async function a_(e,t,n,r){let i=await Me({path:e,scope:"project"}),a=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!a)return{warnings:i,overThreshold:!1,classification:"live"};let o;try{o=await He.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let s="live";if(a){let l=o.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?o.split(/\r?\n/).filter(l=>l.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function o_(e,t,n){let r=ue.join(e,"history");if(!await Vi(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await He.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),o=t.enabled?t.max_entries:null,s=[],c=[],l=[],d=[];for(let u of i){let m=ue.join(r,u),f=u.slice(0,-6),h=await a_(m,f,t,n);s.push(...h.warnings),h.classification==="tombstone"&&l.push(f),h.classification==="orphaned"&&d.push(f),h.overThreshold&&c.push(f)}return{count:i.length,warnings:[...s,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...d.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:o,tombstones:l,orphaned:d}}function Hi(e,t){return ue.relative(e,t).replaceAll("\\","/")}async function Fl(e,t){let n=[...new Set(Object.values(t))].sort((i,a)=>i.localeCompare(a)),r=[];for(let i of n){let a=ue.join(e,i),o=[];try{o=await He.readdir(a)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&L(s))continue;continue}for(let s of o)Bt.some(c=>s.toLowerCase().endsWith(c))&&r.push(ue.join(a,s))}return r.sort((i,a)=>Hi(e,i).localeCompare(Hi(e,a))),r}function s_(e){return!(typeof e=="object"&&e!==null&&"code"in e&&L(e))}async function c_(e,t,n){let r=await Fl(e,t),i=[],a=[],o=[],s=[],c=ft(j());for(let l of r){let d=Hi(e,l),u;try{u=await He.readFile(l,"utf8")}catch{i.push(d);continue}let m=vt(u);if(m){a.push({path:d,...m});continue}try{let f=bt(u,{format:Oa(l),schema:n,extensionFieldNames:c});s.push({ref:d,version:$n(f.metadata)})}catch{o.push(d)}}return{paths:r,unreadable:i,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function l_(e){let t=ue.join(e,"history"),n=[],r=[],i=[],a=[];try{a=(await He.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,s)=>o.localeCompare(s))}catch(o){s_(o)&&n.push("history")}for(let o of a){let s=o.slice(0,-6),c;try{c=await He.readFile(ue.join(t,o),"utf8")}catch{n.push(s);continue}let l=vt(c);if(l){r.push({id:s,...l});continue}c.split(/\r?\n/).forEach((d,u)=>{if(d.trim())try{JSON.parse(d)}catch{i.push({id:s,line:u+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:i}}async function d_(e,t,n,r){let i=await c_(e,t,n),a=await l_(e),o=On(i.formatVersions),s=await mr(e),c=await st(e),l=c===null?null:await Yn(c),d=c===null?[]:await ln(c,{includeLossless:!0,pmRoot:e}),{pendingDecisions:u,lossless:m}=fr(d),f=l?.status==="missing"&&l.missing_keys.length===5&&l.drifted_keys.length===0,h=[...i.unreadable.map(p=>`integrity_item_unreadable:${p}`),...i.conflictMarkers.map(p=>`integrity_item_conflict_marker:${p.path}:L${p.line}`),...i.parseFailures.map(p=>`integrity_item_parse_failed:${p}`),...a.unreadable.map(p=>`integrity_history_unreadable:${p}`),...a.conflictMarkers.map(p=>`integrity_history_conflict_marker:${p.id}:L${p.line}`),...a.invalidJson.map(p=>`integrity_history_invalid_json:${p.id}:L${p.line}`),...o.outdated.map(p=>`integrity_item_outdated_format_version:${p}`),...o.ahead.map(p=>`integrity_item_ahead_format_version:${p}`),...s.tracked_path_count>0?[`tracked_runtime_cache_files:${s.tracked_path_count}`]:[],...l!==null&&l.status!=="ok"?[`merge_driver_configuration_${f?"missing":"drift"}:${l.missing_keys.length+l.drifted_keys.length}`]:[],...u.length>0?[`merge_decisions_unreviewed:${u.length}`]:[]],g=[...new Set(h)].sort((p,w)=>p.localeCompare(w));return{check:{name:"integrity",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_item_files:i.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:i.unreadable.length,item_conflict_markers:i.conflictMarkers.length,item_parse_failures:i.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:o.outdated.length,item_ahead_format_version:o.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:i.unreadable,item_conflict_markers:i.conflictMarkers,item_parse_failures:i.parseFailures,item_outdated_format_version:o.outdated,item_ahead_format_version:o.ahead,history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.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(p=>p.item_id))].sort((p,w)=>p.localeCompare(w)),lossless_merge_receipt_items:[...new Set(m.map(p=>p.item_id))].sort((p,w)=>p.localeCompare(w))}},warnings:g}}function u_(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function m_(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:u_(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function p_(e,t){let n=K(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function f_(e){let n=K(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function h_(e){return K(e.reason)??K(e.error)??K(e.message)}function Wi(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 g_(e){let t=[],n=[],r=[];e.forEach((a,o)=>{let s=p_(a.definition,o),c=f_(a.definition);if(c==="applied"){t.push({layer:a.layer,name:a.name,id:s,status:c});return}if(c==="failed"){r.push({layer:a.layer,name:a.name,id:s,status:c,reason:h_(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(Wi),n.sort(Wi),r.sort(Wi);let i=[...r.map(a=>`extension_migration_failed:${a.layer}:${a.name}:${a.id}`),...n.map(a=>`extension_migration_pending:${a.layer}:${a.name}:${a.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function jl(e,t,n,r,i,a,o,s,c){let l=[...new Set(e)].sort((p,w)=>p.localeCompare(w)),d=[...new Set(l.map(p=>Ml(p)))].sort((p,w)=>p.localeCompare(w)),u=l.filter(p=>p.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",h=[],g=Ti(l,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return g&&h.push(g),t>0&&h.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&h.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&h.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&h.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&h.push(`Unknown extension capabilities detected. Allowed capabilities: ${_n.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),l.some(p=>p.startsWith("extension_capability_legacy_alias:"))&&h.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),l.some(p=>p.startsWith("extension_command_definition_legacy_handler_alias:"))&&h.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?h.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>."):o.length>0&&h.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),h.length===0&&h.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:i,managed_extension_entries_count:a,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,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:f,update_health_partial:m,unknown_capability_count:u,top_warnings:l.slice(0,8),remediation:h}}async function __(e,t,n){let r=await Ie({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),i=r.loaded.map(b=>m_(b)),a=await Ce({...r,loaded:r.loaded}),[o,s]=await Promise.all([de(r.roots.project),de(r.roots.global)]);await Ni(e,a.registrations.migrations);let c=g_(a.registrations.migrations),l={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:c.summary,managed_extensions:{project:{path:o.path,count:o.state.entries.length,entries:o.state.entries},global:{path:s.path,count:s.state.entries.length,entries:s.state.entries}}},d=new Set(o.state.entries.map(b=>Nt(b.name))),u=new Set(s.state.entries.map(b=>Nt(b.name))),m=[...new Map(r.loaded.filter(b=>!(b.layer==="project"?d:u).has(Nt(b.name))).map(b=>[`${b.layer}:${b.name}`,{layer:b.layer,name:b.name,directory:b.directory}])).values()].sort((b,A)=>{let U=`${b.layer}:${b.name}`,C=`${A.layer}:${A.name}`;return U.localeCompare(C)}),f=m.map(b=>`${b.layer}:${b.name}`).sort((b,A)=>b.localeCompare(A)),h=m.filter(b=>qi(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,A)=>b.localeCompare(A)),g=m.filter(b=>!qi(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,A)=>b.localeCompare(A)),p=g.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${g.length}`]:[],w=[...r.warnings,...l.warnings,...c.warnings,...o.warnings,...s.warnings,...p],v=sn(w),k=cn(),x=jl(w,r.failed.length,a.failed.length,c.summary,o.warnings.length+s.warnings.length,o.state.entries.length+s.state.entries.length,f,h,g);return{check:{name:"extensions",status:w.length===0?"ok":"warn",ok:w.length===0,details:{...r,loaded:i,warnings:w,activation:l,triage:x,...c.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:k,capability_guidance:v}},warnings:w}}function y_(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function qe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function w_(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 hr(e,t){let n=qe(e,t);return{...n,sample:n.sample.map(r=>w_(r))}}function H(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 v_(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 b_={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:H(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:H(e.missing_required,t),missing_optional:H(e.missing_optional,t),missing:H(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:H(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:hr(e.discovered,t),effective:hr(e.effective,t),loaded:hr(e.loaded,t),failed:qe(e.failed,t),warnings:H(e.warnings,t),activation:{failed:qe(n.failed,t),warnings:H(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:v_(n.migration_status)},triage:e.triage,capability_contract:e.capability_contract,capability_guidance:qe(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:H(n.affected_item_ids,t),samples:qe(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:H(e.item_unreadable,t),item_conflict_markers:qe(e.item_conflict_markers,t),item_parse_failures:H(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:H(n.tracked_paths,t)},history_unreadable:H(e.history_unreadable,t),history_conflict_markers:qe(e.history_conflict_markers,t),history_invalid_json:qe(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>({checked_items:e.checked_items,counts:e.counts,drifted_items:H(e.drifted_items,t),missing_streams:H(e.missing_streams,t),unreadable_streams:H(e.unreadable_streams,t),hash_mismatches:H(e.hash_mismatches,t),chain_mismatches:H(e.chain_mismatches,t),workspace_state_mismatches:H(e.workspace_state_mismatches,t),workspace_state_missing:H(e.workspace_state_missing,t),workspace_state_unreadable:H(e.workspace_state_unreadable,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:H(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:H(e.stale_items_after,t),skipped:e.skipped})};function Ul(e,t){let n=b_[e.name];return n?n(e.details,t):e.details}function k_(e){let t=H(e.warnings,dn);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:Ul(n,dn)})),warnings:t.sample,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:dn},generated_at:e.generated_at}}function Dl(e){return e.details.skipped===!0}function x_(e){let t=H(e.warnings,dn),n=e.checks.filter(Dl).map(r=>r.name);return{ok:e.ok,checks:e.checks.filter(r=>!Dl(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:dn,omitted_checks:n},generated_at:e.generated_at}}function Ji(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=y_(e,Pl);return{values:n.values,truncated:n.truncated,total:e.length}}function Pt(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function S_(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return Zg.has(e)?e:null}function gr(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 zl(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e.split(`
38
+ `)){let s=o.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,a=Math.max(a,l),l>=Nl&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:a}}function E_(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function R_(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 A_(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await Bl(n)}}function I_(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 i=n.last_successful_flush_at,a=n.last_failed_flush_at,o=a&&(!i||a>i),s=!i,c=t.validEntries>=n_;return(o||s||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function C_(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function T_(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Uo?[`telemetry_schema_version_behind:${t}`]:[]}function $_(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function O_(){return{telemetry_disabled:Pt("PM_TELEMETRY_DISABLED")||Pt("PM_NO_TELEMETRY"),pm_no_telemetry:Pt("PM_NO_TELEMETRY"),telemetry_otel_disabled:Pt("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:Pt("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:S_()}}function D_(e,t){return e.telemetry.enabled&&t.validEntries>0}function P_(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Bl(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(t_)});return{probe_url:gr(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of r_){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:gr(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function N_(e,t){let n=bn(process.cwd()),r=ue.join(n,Qg),i=ue.join(n,e_),a=await ee(r),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?zl(a):E_(),l=await ee(i),{runtimeState:d,stateParseFailed:u}=R_(l),m=e.telemetry.endpoint.trim(),f=gr(m),h=await A_(e,t.checkTelemetry),g=[];u&&g.push("telemetry_state_invalid_json"),g.push(...I_(e,c,d),...C_(h),...T_(h),...$_(e,d));let p=D_(e,c),w=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:f,global_pm_root:n,queue_path:r,queue_exists:o,queue_entries:c.validEntries,queue_draining:P_(p,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:Nl,queue_max_attempts:c.maxAttempts,runtime_state_path:i,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:w,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:h??{attempted:!1},env_overrides:O_()}},warnings:g}}async function L_(e){let t;try{t=await ds(e)}catch(r){let i=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:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}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 M_(e,t){let n="metadata",{missingStreams:r,unreadableStreams:i,hashMismatches:a,chainMismatches:o,driftedItems:s,workspaceStateMismatches:c,workspaceStateMissing:l,workspaceStateUnreadable:d}=await qn(e,t,{cacheHitVerification:n}),u=[...r.map(m=>`history_drift_missing_stream:${m}`),...i.map(m=>`history_drift_unreadable_stream:${m}`),...a.map(m=>`history_drift_hash_mismatch:${m}`),...o.map(m=>`history_drift_chain_mismatch:${m}`),...c.map(m=>`history_drift_workspace_state_mismatch:${m}`),...l.map(m=>`history_drift_workspace_state_missing:${m}`),...d.map(m=>`history_drift_workspace_state_unreadable:${m}`)];return{check:{name:"history_drift",status:u.length===0?"ok":"warn",ok:u.length===0,details:{checked_items:t.length,cache_hit_verification:n,drifted_items:s,counts:{drifted:s.length,missing_streams:r.length,unreadable_streams:i.length,hash_mismatches:a.length,chain_mismatches:o.length,workspace_state_mismatches:c.length,workspace_state_missing:l.length,workspace_state_unreadable:d.length},missing_streams:r,unreadable_streams:i,hash_mismatches:a,chain_mismatches:o,workspace_state_mismatches:c,workspace_state_missing:l,workspace_state_unreadable:d}},warnings:u}}function F_(e,t){let n=Fn(e),r=Ht(n.settings),i=jn(n.settings,t),a=r.active?ot(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(r.active&&i.active)}}function j_(){return{refreshed:[],skipped:[],warnings:[]}}async function U_(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?j_():Fo(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function z_(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&St(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function B_(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 W_(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Wl(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:Hr(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:Hr(r,e.vector_store?.adapter??null)}}function G_(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function q_(e,t,n){return e.enabled&&n.length>0&&t}async function H_(e,t,n,r,i){let a=F_(t,e),o=await Et(e),s=a.semanticRuntimeAvailable?Kr(n,o.entries):[],c=await U_({pmRoot:e,snapshot:a,refreshPolicy:r,staleBefore:s}),l=await Et(e),d=a.semanticRuntimeAvailable?Kr(n,l.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=z_({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=B_({ledgerBefore:o,ledgerAfter:l,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:d}),h=Ji(s,i),g=Ji(d,i),p=q_(r,a.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:a.semanticRuntimeAvailable,compatibility_mode_auto_defaults:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:a.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:a.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:G_(r),...Wl(t,a),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:a.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Pl,stale_items_before_total:h.total,stale_items_before:h.values,stale_items_before_truncated:h.truncated,refresh_attempted:p,refresh_skipped_reason:W_(r,a.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:f}}function J_(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 Gl(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new _("--check-only cannot be combined with --refresh-vectors",y.USAGE);if(n&&e.noRefresh===!0)throw new _("--no-refresh cannot be combined with --refresh-vectors",y.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var V_=new Set(["extensions","locks","search"]);function K_(e){let t=new Set(Ra.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(Aa));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of V_)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,a)=>i.localeCompare(a)),optionalDirs:[...n].sort((i,a)=>i.localeCompare(a)),optionalDirSet:n}}async function Y_(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:a}=K_(t),o=[],s=[],c=[];for(let l of[...r,...i]){let d=ue.join(e,l);c.push(...await Me({path:d,scope:"project"})),!await Vi(d)&&(a.has(l)?s.push(l):o.push(l))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:o,missingOptionalDirs:s,missingDirs:n?[...o,...s]:[...o],hookWarnings:c}}function ql(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 X_(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Fe(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):Mn(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Gi(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function Z_(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 Q_(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 ey(e){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e}}}var Ki=e=>e.unknown_event_count??0,Yi=e=>e.actionable_unknown_event_count??Ki(e);function ty(e,t,n,r,i,a,o){let s=Ki(r),c=Yi(r),l=s>0,d=c>0,u=i.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:i}:{},...a.length>0?{provenance_resolver_outcomes:a}:{},...o.length>0?{provenance_invalid_values:o}:{},...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 Hl(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function ny(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 ry(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function iy(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 ay(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 oy(e){for(let t of e.checks){let n=ei(e.remediationSources[t.name]);ay({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}function Jl(e,t,n){return n?x_(e):t.brief===!0?k_(e):e}async function aI(e,t={}){let n=N(process.cwd(),e.path),r=V(n);if(!await R(r))throw new _(`Tracker is not initialized at ${n}. Run pm init first.`,y.NOT_FOUND);let{settings:i,warnings:a}=await _o(n),o=[...new Set(a)],s=G(i,j()),c=t.strictDirectories===!0,l=Gl(t),d=await Y_(n,s,c),u=J_(i),m=await N_(i,{checkTelemetry:t.checkTelemetry===!0}),f=await __(n,i,!!e.noExtensions),h=ql(t),g=[],p=await X_({pmRoot:n,settings:i,typeRegistry:s,skipPolicy:h,itemReadWarnings:g}),w=p,v=[...new Set(g)],k=h.skipDrift?{warnings:[]}:await yo({pmRoot:n,settings:i,itemIds:p.map(zt=>zt.id),commandLabel:"health"}),x=await o_(n,i.history.compact_policy,await i_(n)),b=await Vt(n,20,t.verboseAuthorEvents===!0),A=Yi(b),U=A>0?[`history_unknown_author_events:${A}`]:[],C=Hl(await jo(n,p,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),E=await ns(n),F=E.outcomes,W=E.invalid_values,O=E.warnings,B=await L_(n),pe=h.skipIntegrity?Gi("integrity"):await d_(n,s.type_to_folder,i.schema,t.requireMergeDrivers===!0),le=h.skipDrift?Gi("history_drift"):await M_(n,w),Pe=h.skipVectors?Gi("vectorization"):await H_(n,i,w,l,t.verboseStaleItems===!0),Ne=[Z_(r,i,o),Q_(d,c),ey(u),m.check,f.check,ty(p,i,x,b,C.scan,F,W),B.check,pe.check,le.check,Pe.check],P=ny({directoryState:d,normalizedSettingsReadWarnings:o,settingWarnings:u,normalizedItemReadWarnings:v,telemetryCheck:m,extensionCheck:f,historyPolicyWarnings:k.warnings,historySummary:x,authorAttributionWarnings:U,staleInProgressWarnings:C.warnings,provenanceWarnings:O,locksCheck:B,integrityCheck:pe,historyDriftCheck:le,vectorizationCheck:Pe});oy({checks:Ne,remediationSources:iy({directoryState:d,normalizedSettingsReadWarnings:o,settingWarnings:u,telemetryCheck:m,extensionCheck:f,historySummary:x,authorAttributionWarnings:U,staleInProgressWarnings:C.warnings,provenanceWarnings:O,locksCheck:B,integrityCheck:pe,historyDriftCheck:le,vectorizationCheck:Pe}),historyDriftedCount:ry(le),overThresholdCount:x.over_threshold.length});let ba={ok:P.filter(zt=>!Ll(zt,t.requireMergeDrivers===!0)).length===0,checks:Ne,warnings:P,generated_at:I()};return Jl(ba,t,h.summaryMode)}var oI={buildExtensionHealthTriageSummary:jl,buildCapabilityContractMetadata:cn,buildStaleInProgressHealthSummary:Hl,buildVectorizationProviderDetails:Wl,collectUnknownCapabilityGuidance:sn,isAdvisoryHealthWarning:Ll,isDirectory:Vi,isExpectedUnmanagedExtension:qi,listItemDocumentPaths:Fl,normalizeEndpointForDisplay:gr,normalizeExtensionNameForMatch:Nt,parseTelemetryQueue:zl,probeTelemetryEndpointHealth:Bl,projectHealthResult:Jl,resolveActionableUnknownAuthorEventCount:Yi,resolveHealthSkipPolicy:ql,resolveUnknownAuthorEventCount:Ki,resolveVectorRefreshPolicy:Gl,selectStaleItemDetail:Ji,summarizeHealthCheckDetails:Ul,summarizeExtensionList:hr,summarizeRecordList:qe,summarizeStringList:H,telemetryEnvFlagEnabled:Pt,warningCode:Ml};import Lt from"node:fs/promises";import Mt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function sy(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let a;try{a=await Lt.readdir(Mt.join(e,i))}catch{return}for(let o of a)for(let s of Bt)if(o.toLowerCase().endsWith(s)){r.push({relativePath:`${i}/${o}`,id:o.slice(0,-s.length)});break}})),r.sort((i,a)=>i.relativePath.localeCompare(a.relativePath))}function cy(e,t){let{id:n,relativePath:r,liveItemIds:i,out:a}=e,o=vt(t);if(o){a.conflictMarkers.push({id:n,path:r,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=null,c=t.split(/\r?\n/).map((l,d)=>({content:l.trim(),number:d+1})).filter(l=>l.content.length>0);for(let l of c)try{let d=JSON.parse(l.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");s=d}catch{a.unparseable.push({id:n,path:r,line:l.number,detail:"history line is not a valid JSON object"});return}s!==null&&(s.op==="delete"&&i.has(n)&&a.resurrected.push({id:n,deleted_at:typeof s.ts=="string"?s.ts:"",deleted_by:typeof s.author=="string"?s.author:""}),s.op==="history_repair"&&Array.isArray(s.patch)&&s.patch.length>0&&(a.repairReconciliations+=1))}function Xi(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function ly(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Lt.readdir(Mt.join(e,"history"))}catch{return n}for(let i of r.sort((a,o)=>a.localeCompare(o))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let a;try{a=await Lt.readFile(Mt.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Xi("history stream",o)});continue}cy({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},a)}return n}function Vl(e){let t=vt(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function dy(e){let t=[],n=0,r=null;try{r=await ee(V(e))}catch(a){n+=1,t.push({path:"settings.json",detail:Xi("configuration file",a)})}if(r!==null){n+=1;let a=Vl(r);a!==null&&t.push({path:"settings.json",detail:a})}let i;try{i=await Lt.readdir(Mt.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let a of i.sort((o,s)=>o.localeCompare(s))){if(!a.endsWith(".json"))continue;n+=1;let o;try{o=await Lt.readFile(Mt.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:Xi("configuration file",c)});continue}let s=Vl(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function Kl(e,t,n,r={}){let i=await sy(e,n),a=new Set(i.map(u=>u.id)),o=new Map;for(let u of i){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let s=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,h)=>f.localeCompare(h))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Mt.join(e,u.relativePath);return bt(await Lt.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await ly(e,a),d=await dy(e);return{item_files_on_disk:i.length,item_ids_on_disk:a.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:s,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import{execFile as uy}from"node:child_process";import Yl 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]="b8b3f729-be32-5a77-b08f-f616ee068e0f")}catch{}})();function Xl(e,t){return new Promise((n,r)=>{uy("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,a)=>{i?r(i):n(a)})})}function Zl(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function yI(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Zl(n),!n)throw new RangeError("Source line range must use start:end.");return n}function my(e){let t=new Map;for(let n of e.split(`
39
+ `)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function py(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let a=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,s)=>o.localeCompare(s));n.set(i,a)}return n}async function fy(e){let t=Yl.relative(e.workspaceRoot,Yl.resolve(e.workspaceRoot,e.sourcePath)),n=await Xl(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Xl(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:my(n),commitItems:py(r),available:!0}}function hy(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let a=i.source===t,o=a?i.target:i.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let s=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,a?i.kind:s.inverse??i.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function gy(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let a=t.shift(),o=a.kinds.length;i!==void 0&&o>=i||o>=e.maxDepth||(i=hy({current:a,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((a,o)=>a.nodes.join("\0").localeCompare(o.nodes.join("\0"))),r}function _y(e,t,n){let r=Go(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=gy({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(s=>[s.id,s]))}),a=i[0];if(!a)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(i.map(s=>s.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:a.nodes,kinds:a.kinds,alternative_decision_ids:o.slice(1)}}async function yy(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await fy({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function wy(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function vy(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Ql(e){Zl(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await yy(e),r=vy(n),i=new Map;for(let a of e.candidates){let o=[...n.commitLines.entries()].filter(([d])=>n.commitItems.get(d)?.includes(a.item.id)),s=o.reduce((d,[,u])=>d+u,0),c=_y(a.item.id,e.corpus,t),l=wy({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:s,decisionStatus:c.status});i.set(a.item.id,{score:s*100+a.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(a.item.updated_at))/(720*60*60*1e3))),contribution_lines:s,evidence:[...a.files.map(d=>({kind:"linked_file",reference:d.path})),...o.map(([d,u])=>({kind:"git_commit",reference:d.slice(0,12),contribution_lines:u}))],rationale:{value:a.item.value?.trim()||null,why_now:a.item.why_now?.trim()||null,outcome:a.item.outcome?.trim()||null,objective:a.item.objective?.trim()||null},decision_path:c,ambiguities:l})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}import da from"node:fs/promises";import{realpathSync as xw}from"node:fs";import{execFile as Sw}from"node:child_process";import me from"node:path";import{promisify as Ew}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]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var by=["metadata","resolution"],Zi=["metadata","resolution","estimates","lifecycle"],ky="completed";function Qi(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function ed(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function td(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=ed(n.close_reason)??ky;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Qi(r)}`,gate:"resolution"})}return t}function nd(e){let t=[];for(let n of e){let r=ed(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${Qi(r)}`,gate:"metadata"})}return t}function rd(e,t){return e.map(n=>{let r=go(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function id(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function ad(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${Qi(n.path)}`})}return t}function od(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new _(`--fix-scope values must not be empty. Supported values: ${Zi.join(", ")}.`,y.USAGE);return new Set(by)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Zi.includes(i)){n.add(i);continue}throw new _(`Unknown --fix-scope value "${r}". Supported values: ${Zi.join(", ")}.`,y.USAGE)}return n}function sd(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function un(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(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]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var xy=/^([A-Z][A-Z0-9]*-\d+)\b/;function Sy(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=xy.exec(t);return n?n[1]:null}function cd(e){return typeof e=="string"&&e.trim().length>0}function ld(e){let t=new Map;for(let r of e){if(typeof r.title!="string"||cd(r.duplicate_of))continue;let i=Sy(r.title);if(i===null)continue;let a=t.get(i);a||(a=[],t.set(i,a)),a.some(o=>o.id===r.id)||a.push({id:r.id,title:r.title,parent:cd(r.parent)?r.parent.trim():null})}let n=[];for(let[r,i]of t){if(i.length<2)continue;let a=new Set(i.map(c=>c.id.toLowerCase())),o=i.filter(c=>c.parent===null||!a.has(c.parent.toLowerCase()));if(o.length<2)continue;let s=[...o].sort((c,l)=>c.id.localeCompare(l.id));n.push({code:r,count:s.length,ids:s.map(c=>c.id),titles:s.map(c=>c.title)})}return n.sort((r,i)=>r.code.localeCompare(i.code))}(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]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function dd(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,a)=>i.localeCompare(a))){let i=t.get(r),a={};for(let o of[...i.keys()].sort((s,c)=>s.localeCompare(c)))a[o]=i.get(o);n[r]=a}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]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var ud=3;function md(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function pd(e,t,n=ud){let r=Number.isFinite(n)&&n>=1?Math.floor(n):ud,i=new Map;for(let a of t){let o=md(a);if(o.length===0)continue;let s=i.get(o);s?s.push(a):i.set(o,[a])}return e.map(a=>{let o=(i.get(md(a))??[]).filter(s=>s!==a).sort((s,c)=>s.localeCompare(c));return o.length===0?{path:a,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:a,classification:"moved",candidates:o.slice(0,r),candidates_truncated:o.length>r}})}function fd(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(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]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var Ey=/^[a-z][a-z0-9+.-]+:\/\//i;function mn(e){return Ey.test(e.trim())}(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]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function Ry(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function hd(e){return`${e.item_id} ${e.link_kind}`}function gd(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=Ry(i.classification,r.classification),i.owners.set(hd(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[hd(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(a=>{let o=t(a.item_id);return{id:a.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:a.link_kind}}).sort((a,o)=>{let s=a.id.localeCompare(o.id);return s!==0?s:a.field.localeCompare(o.field)})}))}function Ay(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function _d(e){let t=[];for(let n of e)for(let r of n.items)t.push(`${n.path}:${n.classification} owner=${r.id} status=${r.status} field=${r.field} title="${Ay(r.title)}"`);return t}import Iy from"node:fs/promises";import ke from"node:path";import Cy from"fast-glob";(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]="585364aa-e5ff-56b6-8276-8f741fbd6be4")}catch{}})();var Ty=["path","scope","note"],$y=["pattern","glob","path","scope","note"],Oy=["path"],Dy=["from","to"],Py=new Set(["note","scope"]);function wd(e){let t=e??"project";if(!$r.includes(t))throw new _(`Invalid scope "${e}". Valid scopes: ${$r.join(", ")} (default: project).`,y.USAGE);return t}function vd(e){return e.startsWith("```")||e.includes(`
40
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:Eo(e)}function Ny(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||vd(n)||!n.includes(",")?[t]:Un(n)})}function Ly(e,t){return e?Ny(e).map(n=>{let r=n.trim(),i=vd(r)?Gt(n,"--add"):{path:r};if(qt(i,"--add",Ty),!i.path)throw new _(`--add requires path=<value> or a bare ${t} path`,y.USAGE);return{path:i.path,scope:wd(i.scope),note:i.note?.trim()||void 0}}):[]}function My(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--add-glob requires a glob pattern value",y.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=Gt(n,"--add-glob");qt(r,"--add-glob",$y);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new _("--add-glob key/value form requires pattern=<glob>",y.USAGE);return{pattern:i,scope:wd(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Fy(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--remove requires a path value",y.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=Gt(n,"--remove"),i=Object.keys(r).filter(a=>Py.has(a.toLowerCase()));if(i.length>0)throw new _(`--remove identifies a linked artifact by path only and does not accept ${i.map(a=>`"${a}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,y.USAGE);if(qt(r,"--remove",Oy),!r.path)throw new _("--remove key/value form requires path=<value>",y.USAGE);return r.path}return n}):[]}function jy(e){return e?e.map(t=>{let n=Gt(t,"--migrate");qt(n,"--migrate",Dy);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new _("--migrate requires from=<value> and to=<value>",y.USAGE);return{from:r,to:i}}):[]}function pn(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function Uy(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(a=>pn(a.path,n))),i=[...new Set(t.map(a=>pn(a,n)).filter(a=>r.has(a)))].sort((a,o)=>a.localeCompare(o));if(i.length!==0)throw new _(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,y.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function Je(e){return e.split(ke.sep).join("/")}function ea(e,t,n=process.cwd()){let r=e.trim();if(mn(r))return r;if(ke.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return Je(r.replaceAll("\\",ke.sep));let i=ke.relative(t,n);return i.startsWith(`..${ke.sep}`)||i===".."||ke.isAbsolute(i)?Je(ke.normalize(r)):Je(ke.relative(t,ke.resolve(n,r)))}async function zy(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){let a=ke.isAbsolute(i.pattern),o=await Cy(i.pattern,{cwd:n,absolute:a,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),s=[...new Set(o.map(c=>ea(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of s)r.push({path:c,scope:i.scope,note:i.note})}return r}function By(e,t,n){if(t===void 0)return e;if(!n)throw new _("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",y.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function Wy(e){return`${e.path}::${e.scope}`}function ta(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function na(e){return[...new Map(e.map(t=>[Wy(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function Gy(e,t=process.cwd()){let n=[...new Set(e)].sort((s,c)=>s.localeCompare(c)),r=[],i=[],a=[],o=[];for(let s of n){if(mn(s)){o.push(s.trim());continue}let c=ke.isAbsolute(s)?s:ke.resolve(t,s);try{(await Iy.stat(c)).isFile()?r.push(s):a.push(s)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&vn(l)){i.push(s);continue}a.push(s)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:a,remote_references:o}}function qy(e,t,n,r){let i=0;for(let o=0;o<e.length;o+=1){let s=pn(e[o].path,r);s!==e[o].path&&(e[o]={...e[o],path:s},i+=1)}return{adds:t.map(o=>{let s=pn(o.path,r);return s!==o.path&&(i+=1),{...o,path:s}}),removes:n.map(o=>pn(o,r)),count:i}}function Hy(e,t,n,r){for(let a of t)e.some(o=>o.path===a.path&&o.scope===a.scope)||e.push(a);if(n.length>0)for(let a=e.length-1;a>=0;a-=1)n.includes(e[a].path)&&e.splice(a,1);let i=na(e);return r?i:ta(i)}async function yd(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths?await Gy(t,e.workspaceRoot):void 0}}async function _r(e,t,n,r){let{metadataKey:i}=r,a=Ro(),o=N(process.cwd(),n.path),s=Wt(o),c=process.cwd();if(!await R(V(o)))throw new _(`Tracker is not initialized at ${o}. Run pm init first.`,y.NOT_FOUND);let l=await T(o),d=G(l,j()),u=await a.resolveList(t.add,"--add"),m=await a.resolveList(t.addGlob,"--add-glob"),f=await a.resolveList(t.remove,"--remove"),h=await a.resolveList(t.migrate,"--migrate"),g=Ly(u,r.bareNoun).map(W=>({...W,path:ea(W.path,s,c)})),p=My(m),w=await zy(p,s,c),v=By([...g,...w],t.note,g.length>0||p.length>0),k=Fy(f).map(W=>ea(W,s,c)),x=jy(h);if(Uy(v,k,x),!(v.length>0||k.length>0||x.length>0)){let W=await kt(o,e,l.id_prefix,l.item_format,d.type_to_folder);if(!W)throw new _(`Item ${e} not found`,y.NOT_FOUND);let B=(await xt(W,{schema:l.schema})).document.metadata[i]??[];return yd({id:W.id,artifacts:B,changed:!1,options:t,workspaceRoot:s})}let A=ne(t.author,l.author_default),U=await at({pmRoot:o,settings:l,id:e,op:r.op,author:A,message:t.message,force:t.force,skipNoop:!0,mutate(W){let O=W.metadata,B=O[i]??[],pe=[...B],le=qy(pe,v,k,x),Pe=Hy(pe,le.adds,le.removes,r.supportsAppendStable&&t.appendStable===!0);Pe.length>0?O[i]=Pe:delete O[i];let Ne=!Fa(B,Pe);return{changedFields:Ne?[i]:[],warnings:Ne&&le.count>0?[`path_migrations_applied:${le.count}`]:[]}}}),C=U.item[i]??[],E=U.warnings.find(W=>W.startsWith("path_migrations_applied:")),F=E?Number(E.slice(24)):0;return yd({id:U.item.id,artifacts:C,changed:U.changedFields.includes(i),migrationsApplied:F,options:t,workspaceRoot:s})}function yr(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;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]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function bd(e,t,n){let r=await _r(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return yr(r,"docs")}import kd from"node:fs/promises";import xe 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]="515cd35c-8e0e-51d4-8ad9-1cea5be8a572")}catch{}})();var Jy=32768;function ra(e){return Je(xe.normalize(e))}async function wr(e){try{return await kd.realpath(e)}catch{return xe.resolve(e)}}function Ft(e,t){let n=xe.isAbsolute(e.path)?xe.resolve(e.path):xe.resolve(t,e.path);return`${ra(n)}::${e.scope}`}function vr(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>vr(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))vr(i,t?`${t}.${r}`:r,n)}function Vy(e){let t=[];return vr(e.metadata,"metadata",t),vr(e.body,"body",t),t}function Ky(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function Yy(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let a=new Set,o=i.value.slice(0,Jy);for(let[s,c]of[[n,i.value],[r,o]]){s.lastIndex=0;for(let l of c.matchAll(s)){let d=Ky(l[0]);!d||a.has(d)||(a.add(d),t.push({field:i.field,value:d}))}}}return t}async function Xy(e,t,n=t){let r=xe.isAbsolute(e)?xe.resolve(e):xe.resolve(n,e),i;try{i=await kd.stat(r)}catch{return}if(!i.isFile())return;let[a,o]=await Promise.all([wr(t),wr(r)]);if(fe(a,o)){let s=xe.relative(a,o);return!s||s.startsWith("..")||xe.isAbsolute(s)?void 0:{path:ra(s),scope:"project"}}return{path:ra(r),scope:"global"}}async function Zy(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>Ft(c,t))),i=new Map,a=Yy(Vy(e)),o=new Map;await Promise.all([...new Set(a.map(c=>c.value))].map(async c=>{o.set(c,await Xy(c,t,n))}));let s=a.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:l}of s){if(!l)continue;let d=Ft(l,t),u=i.get(d)??{path:l.path,scope:l.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(d,u)}return[...i.entries()].map(([c,l])=>({path:l.path,scope:l.scope,status:r.has(c)?"already_linked":"addable",source_count:l.sourceCount,source_fields:[...l.sourceFields].sort((d,u)=>d.localeCompare(u)),original_paths:[...l.originalPaths].sort((d,u)=>d.localeCompare(u))})).sort((c,l)=>{let d=c.status.localeCompare(l.status);if(d!==0)return d;let u=c.path.localeCompare(l.path);return u!==0?u:c.scope.localeCompare(l.scope)})}async function xd(e,t,n){let r=await _r(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return yr(r,"files")}async function Qy(e,t){let n=await wr(t),r=await Promise.all(e.map(async a=>{let o=a.trim();if(!o)throw new _("Files lookup paths must not be empty.",y.USAGE);if(!xe.isAbsolute(o))return Je(o);let s=await wr(o);return fe(n,s)?Je(xe.relative(n,s)):Je(s)})),i=[...new Set(r)].sort((a,o)=>a.localeCompare(o));if(i.length===0)throw new _("Files lookup requires at least one path.",y.USAGE);return i}function ew(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new _(`Files lookup ${r} must be a non-negative integer.`,y.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function Sd(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Ed(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function tw(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(Je(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(Ed)}async function nw(e){if(e.explain)return Ql({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function rw(e){if([e.strictRead,e.noTruncate,e.explain,so()].includes(!0))return null;let t=await Nn(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?vo({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function iw(e){let t=[],n=await Ln(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=tw({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&i.length>0)throw new _(`Files lookup could not read every item: ${i.join("; ")}`,y.GENERIC_FAILURE);let a=await nw({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),s=(a?[...r].sort((c,l)=>{let d=a.explanations.get(l.item.id).score-a.explanations.get(c.item.id).score;return d!==0?d:Ed(c,l)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:s.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+s.length<r.length,truncated:e.offset+s.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:s.map(c=>({item:Sd(c.item),files:c.files,...a?{traceability:a.explanations.get(c.item.id)}:{}})),...a?{traceability_receipt:a.receipt}:{}}}async function uC(e,t){let n=N(process.cwd(),t.path),r=Wt(n);if(!await R(V(n)))throw new _(`Tracker is not initialized at ${n}. Run pm init first.`,y.NOT_FOUND);let i=await Qy(e.paths,r);if(e.lineRange&&i.length!==1)throw new _("Files lookup line attribution requires exactly one source path.",y.USAGE);let a=await T(n),o=G(a,j()),{offset:s,limit:c}=ew(e),l=await rw({pmRoot:n,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return l?{paths:i,total:l.total,count:l.matches.length,offset:s,limit:c,has_more:s+l.matches.length<l.total,truncated:s+l.matches.length<l.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:l.matches.map(d=>({item:Sd(d.item),files:d.files}))}:iw({pmRoot:n,settings:a,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function mC(e,t,n){let r=N(process.cwd(),n.path),i=Wt(r);if(!await R(V(r)))throw new _(`Tracker is not initialized at ${r}. Run pm init first.`,y.NOT_FOUND);let a=await T(r),o=G(a,j()),s=await kt(r,e,a.id_prefix,a.item_format,o.type_to_folder);if(!s)throw new _(`Item ${e} not found`,y.NOT_FOUND);let c=await xt(s,{schema:a.schema}),l=await Zy(c.document,i,process.cwd()),d=l.filter(C=>C.status==="addable"),u=l.filter(C=>C.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let C=c.document.metadata.files??[];return{id:s.id,files:C,changed:!1,apply:m,count:C.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let h=ne(t.author,a.author_default),g=d.map(C=>({path:C.path,scope:C.scope,note:f})),p=[],w=new Set,v=await at({pmRoot:r,settings:a,id:e,op:"files_discover",author:h,message:t.message??"Discover referenced file links",force:t.force,mutate(C){let E=[...C.metadata.files??[]],F=new Set(E.map(B=>Ft(B,i)));p=[],w.clear();for(let[B,pe]of g.entries()){let le=Ft(pe,i);F.has(le)||(E.push(pe),F.add(le),p.push(pe),w.add(B))}let W=na(E),O=t.appendStable?W:ta(W);return O.length>0?C.metadata.files=O:delete C.metadata.files,{changedFields:p.length>0?["files"]:[],warnings:p.length!==g.length?[`files_discover_skipped_existing:${g.length-p.length}`]:[]}}}),k=v.item.files??[],x=new Set(p.map(C=>Ft(C,i))),b=k.filter(C=>x.has(Ft(C,i))),A=d.filter((C,E)=>!w.has(E)),U=[...u,...A];return{id:v.item.id,files:k,changed:b.length>0,apply:!0,count:k.length,candidate_count:l.length,addable_count:d.length,added_count:b.length,skipped_existing_count:U.length,candidates:l,added:b,skipped_existing:U}}import{readFileSync as aw}from"node:fs";import br 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]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var ow=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),ia=new Set(["--pm-path","--path","--author"]),sw={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},cw=new Set(["-p","--package"]),lw=new Set(["-c","--call"]),dw=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),uw=new Set(["-C","--prefix","--userconfig","--cache"]),gC=new Set(["--cwd"]),_C=new Set(["--cwd"]),mw=new Set(["exec","x"]),yC=new Set(["run","run-script"]),wC=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function pw(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function fw(e,t=process.cwd()){let n=hw(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[r,...i]=n;if(Rd(r)||Ad(r,t))return i;if(r==="node"&&i[0]&&Ad(i[0],t))return i.slice(1);let a=r==="npx"||r==="bunx"?aa(i):r==="pnpm"?yw(i):r==="npm"?ww(i):null;return a&&(Rd(a.command)||_w(a.command))?a.args:null}var Id=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let a=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let s of pw(a)){let c=fw(s),l=c?vw(c):null,d=l&&ow.has(l.subcommand)?bw(l.remaining,sw[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&o.add(d)}return[...o].sort((s,c)=>s.localeCompare(c))};function hw(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function vC(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(ia.has(n)){t+=2;continue}t+=1;continue}return n}}function Rd(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function gw(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function _w(e){let t=gw(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Ad(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=br.resolve(t,e);try{return JSON.parse(aw(br.join(br.dirname(br.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function aa(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let a=i[1];return a?{command:a,args:e.slice(t+1)}:null}if(lw.has(r)){t+=1;break}t+=cw.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Cd(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function yw(e){let t=Cd(e,dw);return t?.subcommand!=="dlx"?null:aa(t.args)}function ww(e){let t=Cd(e,uw);return!t||!mw.has(t.subcommand)?null:aa(t.args)}function vw(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(ia.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function bw(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(ia.has(r)||t.has(r))&&(n+=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]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function Td(e){return e.includeBody?Mn(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Ln(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(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]="a1261d65-222c-5c6c-8634-a4413a91aba9")}catch{}})();var kw=5;async function $d(e,t,n){let r=await qn(e,t),a=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,l])=>`${c}:${l}`),o=n?Number.POSITIVE_INFINITY:kw,s=r.driftedItems.slice(0,o);return{check:{name:"history_drift",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:s,drifted_items_truncated:s.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable}},warnings:a}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7b47a375-e72c-5108-bd93-75dd8cf93218")}catch{}})();var Rw=["src","tests","docs"],Aw=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],Iw=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),Cw=["resolution","expected_result","actual_result"],Tw=["default","tracked-all","tracked-all-strict"],Od=["core","strict","custom"],xr=["off","warn","error"];var sa=["author","acceptance_criteria","estimated_minutes","close_reason"],Md=[...sa,"reviewer","risk","confidence","sprint","release"],ua=Array.from(new Set(Md)),$w={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},Ow={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},Dw={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},Pw={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},Nw={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},Lw=32*1024*1024,Mw=1e4,Fd=40,rt=5,Fw=4096,jw=255,Uw=Ew(Sw);function jd(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?jd(r):r);return t}function zw(e){return{...e,checks:e.checks.map(t=>({...t,details:jd(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function pt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Dd(e){return pt(e).replace(/\/+$/,"")}function Re(e){let t=K(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Er(e,t){return lo(e,t)??e}function fn(e,t){return t.terminal_statuses.has(Er(e,t))}function tt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function kr(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Bw(e){let t=tt(Ia),n={blocked_reason:tt(wn.blocked_reason),resolution:tt(wn.resolution),actual_result:tt(wn.actual_result)},r=tt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:tt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:tt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:tt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:kr(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:kr(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:kr(i.resolution,n.resolution)?"default":"settings",actual_result:kr(i.actual_result,n.actual_result)?"default":"settings"}}}function Ud(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Od.includes(t))return t;throw new _(`Unknown --metadata-profile value "${e}". Supported values: ${Od.join(", ")}.`,y.USAGE)}function zd(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(xr.includes(t))return t;throw new _(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${xr.join(", ")}.`,y.USAGE)}function Bd(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(xr.includes(t))return t;throw new _(`Unknown --parent-cycle-severity value "${e}". Supported values: ${xr.join(", ")}.`,y.USAGE)}function Ww(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>$w[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function Gw(e,t,n){let r=Ww(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...sa],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Md],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...sa],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var qw=new Set(["acceptance_criteria","estimated_minutes"]);function Wd(e,t,n,r){return!r&&qw.has(t)&&fn(e.status,n)?!1:t==="author"?!K(e.author):t==="acceptance_criteria"?!K(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Er(e.status,n)===n.close_status&&!K(e.close_reason):t==="reviewer"?!K(e.reviewer):t==="risk"?!K(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!K(e.confidence):t==="sprint"?!K(e.sprint):!K(e.release)}function Gd(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new _(`Unknown --scan-mode value "${e}". Supported values: ${Tw.join(", ")}.`,y.USAGE)}function qd(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return me.resolve(t);let n=me.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return me.dirname(me.dirname(n));let i=me.resolve(process.cwd()),a=Pd(n),o=Pd(i),s=me.relative(a,o);return s.length===0||!s.startsWith("..")&&!me.isAbsolute(s)?n:i}function Pd(e){try{return xw.native(e)}catch{return me.resolve(e)}}function Hw(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function ma(e,t,n){let r=t.length>0?me.join(e,t):e,i;try{i=await da.readdir(r,{withFileTypes:!0})}catch(a){if(L(a))return;throw a}for(let a of i){if(a.name.startsWith("."))continue;let o=t.length>0?me.join(t,a.name):a.name;if(a.isDirectory()){if(Iw.has(a.name))continue;await ma(e,o,n);continue}a.isFile()&&n.push(pt(o))}}async function ca(e){let t=[];for(let n of Rw)await ma(e,n,t);for(let n of Aw){let r=me.join(e,n);try{(await da.stat(r)).isFile()&&t.push(pt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function Hd(e){try{let{stdout:t}=await Uw("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:Lw,windowsHide:!0,timeout:Mw}),n=t.split("\0").map(r=>pt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function Jw(e,t){let n=new Set,r=Dd(Ea);r.length>0&&n.add(r);let i=Dd(me.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((a,o)=>a.localeCompare(o))}function Nd(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function Vw(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await Hd(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await ca(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await ca(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function re(e,t=rt){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function nt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=re(e,Fd);return{values:n.values,truncated:n.truncated,total:e.length}}var Kw={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},Yw={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function Xw(e){let t=e.missing_fields.map(n=>`${Kw[n]} "${Yw[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Jd(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(o=>typeof o=="string"):ms(t);if(i.length===0)return;let a=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...a?{fix_hints_truncated:!0}:{}}}function Vd(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var Zw="validate_metadata_duplicate_issue_codes";function Kd(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:rt,r=e.slice(0,n);return{rows:r.map(a=>({code:a.code,count:a.count,ids:a.ids,titles:a.titles,remediation_hint:`Items ${a.ids.join(", ")} share issue code "${a.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${Zw}:${e.length}`]}}function Qw(){return Object.fromEntries(ua.map(e=>[e,[]]))}function ev(e,t,n){let r=Qw();for(let i of e)for(let a of ua)Wd(i,a,t,n)&&r[a].push(i.id);return r}function tv(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let a=t[i];a.length>0&&r.push(`${Ow[i]}:${a.length}`)}return r.push(...n),r}function Yd(e,t){let n={};for(let r of e.required_fields){let i=t[r],a=i?i.length:0,o=Dw[r];a>0&&o&&(n[o]=a)}return n}function Xd(e,t,n){let r=[];for(let i of e.required_fields){let a=t[i];if(a)for(let o of a){let s=n.get(o)?.type,c=typeof s=="string"&&s.length>0?s:"Unknown";r.push({item_type:c,field:i})}}return r}function nv(e,t,n,r){for(let i of t.required_fields){let a=n[i];if(!a||a.length===0)continue;let o=Pw[i],s=Nw[i];if(!o||!s)continue;let c=re(a,r?a.length:rt);e[o]=c.values,e[s]=c.truncated}}function Zd(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:K(n.get(i)?.resolution)})):[]}function Qd(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:K(n.get(i)?.type)})):[]}function rv(e,t,n,r){let i=new Map(e.map(p=>[p.id,p])),a=t.profile==="strict",o=ev(e,n,a),s=ld(e),c=Kd(s,r),l=tv(t,o,c.warnings),d=Yd(t,o),u=Xd(t,o,i),m=dd(u),f={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...ua],counts:d,missing_by_type:m,duplicate_issue_codes_count:s.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),nv(f,t,o,r);let h=Zd(t,o,i),g=Qd(t,o,i);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:f},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:g}}function iv(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Er(m.status,t))),a=[],o=[];for(let m of i){let f=Cw.filter(h=>!K(m[h]));f.length!==0&&(a.push({id:m.id,missing_fields:f}),o.push({id:m.id,missing_fields:f,close_reason:K(m.close_reason)}))}let s=a.length>0?[`validate_resolution_missing_fields:${a.length}`]:[],c=n?Number.POSITIVE_INFINITY:rt,l=re(a.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=a.map(m=>Xw(m)),u=re(d,c);return{check:{name:"resolution",status:s.length===0?"ok":"warn",ok:s.length===0,details:{checked_closed_items:i.length,missing_resolution_items:a.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:s,resolutionBackfillRows:o}}function eu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tu(e,t="pm",n=Dr()){let r=new Set(e.map(a=>a.id)),i=[...e].sort((a,o)=>a.id.localeCompare(o.id));return new Map(i.map(a=>{let o=new Set,s=Re(a.blocked_by);s&&r.has(s)&&o.add(s),(a.dependencies??[]).filter(l=>{let d=Re(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>Re(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>o.add(l));let c=Re(a.definition_of_ready);return ru(c??"",t).filter(l=>r.has(l)).forEach(l=>o.add(l)),[a.id,[...o].sort((l,d)=>l.localeCompare(d))]}))}function nu(e,t,n){let r=Wo(e,n?d=>fn(d,n):void 0),i=r.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),a=r.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),o=t?Number.POSITIVE_INFINITY:rt,s=re(i,o),c=re(a,o),l=re(r.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+a.length,active_dangling_reference_count:i.length,dangling_reference_rows:s.values,dangling_reference_rows_truncated:s.truncated,legacy_terminal_dangling_reference_count:a.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function ru(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${eu(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,a)=>i.localeCompare(a))}function pa(e){let t=0,n=new Map,r=new Map,i=[],a=new Set,o=[],s=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),a.add(d);for(let m of e.get(d)??[])n.has(m)?a.has(m)&&r.set(d,Math.min(r.get(d),n.get(m))):(s(m),r.set(d,Math.min(r.get(d),r.get(m))));if(r.get(d)!==n.get(d))return;let u=[];for(;i.length>0;){let m=i.pop();if(a.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),o.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||s(d);return o.filter(d=>{if(d.length>1)return!0;let u=d[0];return(e.get(u)??[]).includes(u)}).sort((d,u)=>d[0].localeCompare(u[0])||d.length-u.length||d.join(",").localeCompare(u.join(",")))}function fa(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],a=new Set([n]),o=s=>{let c=(t.get(s)??[]).filter(l=>r.has(l));for(let l of c){if(l===n&&i.length>1)return i.push(n),!0;if(!a.has(l)){if(a.add(l),i.push(l),o(l))return!0;i.pop(),a.delete(l)}}return!1};return o(n)?[...i]:[...e,n]}function iu(e,t="pm"){let n=tu(e,t),r=pa(n),i=[...new Set(r.flat())].sort((o,s)=>o.localeCompare(s)),a=r.map(o=>fa(o,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:a}}function au(e,t=Dr()){let n=new Map(e.map(a=>[a.id.toLowerCase(),a.id])),r=new Map(e.map(a=>[a.id,[]]));return[...e].sort((a,o)=>a.id.localeCompare(o.id)).forEach(a=>{let o=r.get(a.id),s=Re(a.parent),c=s?n.get(s.toLowerCase()):void 0;c&&o.push(c),(a.dependencies??[]).forEach(l=>{let d=t.resolve(l.kind);if(!d?.hierarchy)return;let u=n.get(l.id.toLowerCase());u&&(d.hierarchyDirection==="source_parent"?r.get(u).push(a.id):o.push(u))})}),r.forEach((a,o)=>{r.set(o,[...new Set(a)].sort((s,c)=>s.localeCompare(c)))}),r}function ou(e){let t=au(e),n=pa(t),r=[...new Set(n.flat())].sort((a,o)=>a.localeCompare(o)),i=n.map(a=>fa(a,t).join("->"));return{cycle_count:n.length,cycle_item_ids:r,cycle_sample_paths:i}}function su(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function Sr(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function cu(e,t){let n=Sr(e).split("/").filter(Boolean),r=Sr(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function av(e,t){let n=Sr(t),r=Sr(e),i=t.endsWith("/")?t:`${t}/`,a=e.startsWith(i),o=n.length>0&&n===r,s=cu(e,t);return!a&&!o&&s===0?null:a?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:s+500,confidence:"same_directory"}:{score:s,confidence:"shared_directory"}}function ov(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function sv(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(a=>(r==="docs"?a.docs??[]:a.files??[]).map(o=>({item:a,link:o}))).forEach(({item:a,link:o})=>{if(o.scope!=="project")return;let s=pt(o.path);if(s.length===0||s===e)return;let c=av(e,s);c!==null&&ov(i,a,c.score)&&(i={item:a,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function lu(e,t){return e.map(n=>{let r=su(n),i=r==="docs_unowned"?"docs":"files",a=sv(n,r,t),o=a?.id??"<id>";return{path:n,classification:r,owner_candidate:a,remediation_hint:`pm ${i} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function du(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function cv(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Re(e[n]);return i?r.some(a=>i.toLowerCase().includes(a)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function lv(e,t,n,r,i){let a=Re(t.parent),o=a?n.get(r.get(a.toLowerCase())??a):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!fn(o.status,i)}}function dv(e,t,n,r){let i=Re(e.blocked_by),a=Re(e.blocked_reason),o=a?.toLowerCase(),s=Er(e.status,n),c=[];return t.has(s)?(!i&&!a&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&r.stale_blocker_reason_patterns.some(l=>o.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),a&&c.push("non_blocked_status_has_blocked_reason"),c)}function uv(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),a=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),s={activeItems:e.filter(c=>!fn(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of s.activeItems){let l=cv(c,r);l.length>0&&s.closureLikeRows.push({id:c.id,fields:l});let d=Re(c.parent),u=d?i.get(a.get(d.toLowerCase())??d):void 0;if(u&&fn(u.status,n)&&(s.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),s.terminalParentFixRows.push(lv(c,u,i,a,n))),t){let m=dv(c,o,n,r);m.length>0&&s.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,h)=>f.localeCompare(h))})}}return s}function mv(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function Ld(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function pv(e,t,n,r,i,a){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=Ld("validate_lifecycle_dependency_cycles",n,i),c=Ld("validate_hierarchy_parent_cycle",r,a);return[...o,...s?[s]:[],...c?[c]:[]]}function uu(e){let t=pt(e);return t.length>Fw||t.split(/[\\/]/).some(n=>n.length>jw)}async function fv(e,t){let n=me.isAbsolute(t)?t:me.resolve(e,t);if(uu(n))return!1;try{let r=await da.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return Hw(r,["ENOENT","ENOTDIR"])}}async function hv(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(a=>({item:i,artifact:a,link_kind:"files"})),...(i.docs??[]).map(a=>({item:i,artifact:a,link_kind:"docs"}))]);for(let{item:i,artifact:a,link_kind:o}of r){if(a.scope!=="project")continue;if(mn(a.path)){n.remoteLinkedPaths.add(a.path.trim());continue}let s=pt(a.path);s.length!==0&&(n.linkedProjectPaths.add(s),await fv(t,a.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:i.id,path:s,link_kind:o})))}return n}function gv(e,t,n,r,i,a){let o=r==="tracked-all-strict",s=o&&!i,c=i||o,l=c?[]:Jw(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>Nd(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Nd(f,l)),m={};if(d.length>0){let f=nt(d,a);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:s,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function mu(e,t,n,r,i,a,o,s="pm"){let c=uv(e,t,i,a);mv(c);let l=iu(c.activeItems,s),d=ou(e),u=pv(c,t,n,r,l.cycle_count,d.cycle_count),m=o?Number.POSITIVE_INFINITY:rt,f=re(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),m),h=re(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),m),g=re(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),m),p=re(l.cycle_item_ids,m),w=re(l.cycle_sample_paths,m),v=re(d.cycle_item_ids,m),k=re(d.cycle_sample_paths,m),x=l.cycle_count>0&&n==="error"||d.cycle_count>0&&r==="error";return{check:{name:"lifecycle",status:x?"error":u.length===0?"ok":"warn",ok:!x&&u.length===0,details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:g.values,stale_blocker_rows_truncated:g.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:p.values,dependency_cycle_item_ids_truncated:p.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:v.values,parent_cycle_item_ids_truncated:v.truncated,parent_cycle_sample_paths:k.values,parent_cycle_sample_paths_truncated:k.truncated,stale_blocker_reason_patterns:[...a.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:a.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...a.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:a.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...a.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:a.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...a.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:a.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function pu(e,t,n,r,i,a){let o=await hv(e,t),s=new Map(e.map(O=>[O.id,O])),c=[...new Set(o.missingLinkedPaths)].sort((O,B)=>O.localeCompare(B)),l=await Vw(t,r),d=gv(l,n,t,r,i,a),u=d.candidateFiles.filter(O=>!o.linkedProjectPaths.has(O)),m=lu(u,e),f=pd(c,d.candidateFiles),h=new Map(f.map(O=>[O.path,O.classification])),g=f.filter(O=>O.classification==="moved").length,p=o.staleLinkRows.map(O=>({...O,classification:h.get(O.path)??"deleted"})).sort((O,B)=>O.item_id.localeCompare(B.item_id)||O.path.localeCompare(B.path)||O.link_kind.localeCompare(B.link_kind)),w=[];d.strictModeForcesPmInternals&&w.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&w.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&w.push(`validate_files_orphaned_paths:${u.length}`);let v=[...o.remoteLinkedPaths].sort((O,B)=>O.localeCompare(B)),k=nt(v,a),x=nt(c,a),b=nt(u,a),A=nt(m.map(O=>`${O.path}:${O.classification}:owner_candidate=${O.owner_candidate?.id??"unowned"}`),a),U=a?m:nt(du(m),!1).values,C=nt(fd(f),a),E=p.map(O=>({item_id:O.item_id,path:O.path,link_kind:O.link_kind,classification:O.classification})),F=gd(E,O=>{let B=s.get(O);return B?{type:B.type,title:B.title,status:B.status}:void 0}),W=a?F:nt(_d(F),!1).values;return{check:{name:"files",status:w.length===0?"ok":"warn",ok:w.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:d.strictTrackedAllMode,strict_mode_forces_pm_internals:d.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:d.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:a?"full":"summary",file_list_summary_limit:Fd,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:d.pmInternalCandidatePrefixes,pm_internal_excluded_count:d.excludedPmInternalPaths.length,excluded_total:d.excludedPmInternalPaths.length,excluded_by_reason:d.excludedByReason,linked_project_paths:o.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:k.total,remote_linked_paths:k.values,remote_linked_paths_truncated:k.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:d.candidateFiles.length,candidate_scanned:d.candidateFiles.length,scanned_candidate_files:d.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:x.total,missing_linked_paths:x.values,missing_linked_paths_truncated:x.truncated,missing_linked_paths_moved_count:g,missing_linked_paths_deleted_count:c.length-g,missing_linked_path_classifications:C.values,missing_linked_path_classifications_truncated:C.truncated,missing_linked_path_rows_count:F.length,missing_linked_path_rows:W,orphaned_paths_count:u.length,orphaned_paths_total:b.total,orphaned_paths:b.values,orphaned_paths_truncated:b.truncated,orphaned_path_classifications:A.values,orphaned_path_classifications_truncated:A.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:U}},warnings:w,staleLinkPruneRows:p}}function _v(e,t,n){let r=n.trim().replaceAll(/\s+/g," "),i=r.length>120?`${r.slice(0,117)}...`:r;return`${e}:${t}:${i}`}function fu(e,t,n){let r=new Set(e.map(p=>p.id.toLowerCase())),i=0,a=0,o=new Set,s=[],c=e.flatMap(p=>(p.tests??[]).map(w=>({item:p,linkedTest:w})));for(let{item:p,linkedTest:w}of c){if(typeof w.command!="string"||w.command.trim().length===0)continue;i+=1;let v=Id(w.command,t);if(v.length!==0){a+=v.length;for(let k of v)o.add(k),r.has(k.toLowerCase())||s.push(_v(p.id,k,w.command))}}let l=[...new Set(s)].sort((p,w)=>p.localeCompare(w)),d=[...new Set(l.map(p=>p.split(":")[1]??""))].filter(p=>p.length>0).sort((p,w)=>p.localeCompare(w)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],m=n?Number.POSITIVE_INFINITY:rt,f=re(l,m),h=re(d,m),g=re([...o].sort((p,w)=>p.localeCompare(w)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",ok:u.length===0,details:{checked_items:e.length,linked_commands_scanned:i,referenced_pm_ids_count:a,unique_referenced_pm_ids_count:o.size,unique_referenced_pm_ids:g.values,unique_referenced_pm_ids_truncated:g.truncated,stale_pm_id_references_count:l.length,stale_pm_ids_count:d.length,stale_pm_ids:h.values,stale_pm_ids_truncated:h.truncated,stale_pm_id_reference_rows:f.values,stale_pm_id_reference_rows_truncated:f.truncated}},warnings:u}}function yv(e,t){let n=On(e.map(c=>({ref:c.id,version:$n(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:rt,a=re(n.outdated,i),o=re(n.ahead,i),s=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:s,ok:s==="ok",details:{checked_items:e.length,current_format_version:co,outdated_items_count:n.outdated.length,outdated_items:a.values,outdated_items_truncated:a.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:r}}var la="pm validate auto-fix";async function hu(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:la};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new _("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",y.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function oa(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function gu(e,t,n){let r=[],i=[],a=new Map;for(let o of e.filter(s=>oa(s)===null))try{await hu(o,t,n),r.push(o)}catch(s){i.push({fix:o,error:s})}for(let o of e.filter(s=>oa(s)!==null)){let s=oa(o),c=a.get(s);c?c.push(o):a.set(s,[o])}for(let o of a.values()){let s=o[0];if(!s)continue;let c=o.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{s.kind==="prune_file_link"?await xd(s.item_id,{remove:c,message:la},t):await bd(s.item_id,{remove:c,message:la},t),r.push(...o)}catch(l){i.push(...o.map(d=>({fix:d,error:l})))}}return{applied:r,failed:i}}var dT={applyValidateFix:hu,applyValidateFixes:gu,attachValidateFixHints:Jd,buildCommandReferencesCheck:fu,buildDependencyReferencesCheck:nu,buildCloseReasonBackfillRows:Zd,buildFilesCheck:pu,buildLifecycleCheck:mu,buildLifecycleDependencyGraph:tu,buildLifecycleParentGraph:au,buildEstimateBackfillRows:Qd,buildMetadataCounts:Yd,buildMissingFieldOccurrences:Xd,buildOrphanedPathRows:lu,classifyOrphanedPath:su,collectDefaultProjectFileCandidates:ca,collectTrackedGitFileCandidates:Hd,detectLifecycleDependencyCycles:iu,detectLifecycleParentCycles:ou,escapeRegExp:eu,extractItemIds:ru,findLifecycleDependencyCycleComponents:pa,isMetadataFieldMissing:Wd,linkedArtifactPathExceedsFilesystemLimits:uu,listFilesRecursive:ma,resolveDependencyCycleSeverity:zd,resolveParentCycleSeverity:Bd,resolveFileScanMode:Gd,resolveLifecycleDependencyCycleSamplePath:fa,resolveRequestedChecks:Vd,resolveValidateMetadataProfile:Ud,resolveWorkspaceRoot:qd,sharedDirectoryPrefixLength:cu,summarizeOrphanedPathRows:du,summarizeDuplicateIssueCodes:Kd,toMeaningfulString:Re};async function wv(e,t,n,r){let i=await Kl(e,new Set(t.map(g=>g.id)),n,{schema:r.schema,extensionFieldNames:ft(j())}),a=[];i.unreadable_item_files.length>0&&a.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&a.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&a.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&a.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&a.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&a.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let o=a.length,s=await mr(e);s.tracked_path_count>0&&a.push(`validate_storage_tracked_runtime_cache_files:${s.tracked_path_count}`);let c=await Is(e,Kn(r));c.status==="drift"&&a.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await st(e),d=l===null?null:await Yn(l);d!==null&&d.status!=="ok"&&a.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await ln(l,{includeLossless:!0,pmRoot:e}),{pendingDecisions:m,lossless:f}=fr(u);m.length>0&&a.push(`validate_merge_decisions_unreviewed:${m.length}`);let h=o>0?"error":a.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...i,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:m.length,pending_merge_decision_items:[...new Set(m.map(g=>g.item_id))].sort((g,p)=>g.localeCompare(p)),lossless_merge_receipt_count:f.length,lossless_merge_receipt_items:[...new Set(f.map(g=>g.item_id))].sort((g,p)=>g.localeCompare(p)),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}}},warnings:a}}function Ve(e,t,n){n&&Jd(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function vv(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let i=rv(e.items,e.metadataPolicy,e.statusRegistry,r);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,Ve(t,i,n)}if(e.requestedChecks.has("resolution")){let i=iv(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,Ve(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=mu(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,Ve(t,i,n),Ve(t,nu(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await pu(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=i.staleLinkPruneRows,Ve(t,i,n)}return e.requestedChecks.has("command_references")&&Ve(t,fu(e.items,e.settings.id_prefix,r),n),e.requestedChecks.has("history_drift")&&Ve(t,await $d(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&Ve(t,yv(e.items,r),n),e.requestedChecks.has("storage_integrity")&&Ve(t,await wv(e.pmRoot,e.items,G(e.settings,j()).type_to_folder,e.settings),n),t}function bv(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...nd(t.closeReasonBackfillRows)),r.push(...td(t.resolutionBackfillRows)),r.push(...rd(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...id(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...ad(t.staleLinkPruneRows)),r}async function kv(e,t,n,r,i,a){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=bv(e,t,n),{applicable:s,gated:c}=sd(o,r),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await gu(s,i,a);d.push(...m.applied.map(un)),u.push(...m.failed.map(({fix:f,error:h})=>({...un(f),error:h instanceof Error?h.message:String(h)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,f)=>m.localeCompare(f)),planned_count:o.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(un),applied_fixes:d,gated_fixes:c.map(m=>({...un(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function uT(e,t,n={}){ao(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new _("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",y.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new _("--fix-scope requires --auto-fix.",y.USAGE);let i=od(e.fixScope),a=N(process.cwd(),t.path);if(!await R(V(a)))throw new _(`Tracker is not initialized at ${a}. Run pm init first.`,y.NOT_FOUND);let o=await T(a),s=it(o.schema),c=G(o,j()),l=Vd(e),d=[],u=await Td({includeBody:l.has("history_drift"),pmRoot:a,settings:o,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let E=await Vt(a);E.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${E.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",f=Ud(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),h=Gw(f,m,o.validation.metadata_required_fields),g=Bw(o),p=zd(e.dependencyCycleSeverity),w=Bd(e.parentCycleSeverity),v=Gd(e.scanMode),k=qd(a),x=await vv({requestedChecks:l,options:e,global:t,pmRoot:a,workspaceRoot:k,settings:o,items:u,statusRegistry:s,metadataPolicy:h,lifecyclePatternPolicy:g,dependencyCycleSeverity:p,parentCycleSeverity:w,fileScanMode:v,initialWarnings:[...new Set(d)]}),b=r?await kv(e,x,o,i,t,n):void 0,A=[...new Set(x.warnings)].sort((E,F)=>E.localeCompare(F)),C={ok:!x.checks.some(E=>E.status==="error"),has_warnings:A.length>0,checks:x.checks,warnings:A,...b!==void 0?{fixes:b}:{},generated_at:I(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?C:{...zw(C),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as xv}from"node:child_process";import Sv from"node:path";import{promisify as Ev}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 Rv=Ev(xv),Av="@unbrained/pm-cli",Iv="latest";function Cv(e){let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new _('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"}function Ar(e){return e.trim().toLowerCase()}function _u(e,t){let n=Ar(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(i=>typeof i=="string"&&Ar(i)===n)}function Tv(e,t){let n=N(process.cwd(),t.path),r=ht(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function $v(e,t,n){try{let r=await Rv(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:r.stdout,stderr:r.stderr}}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr??""):"",a=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new _(`Command failed: ${e} ${t.join(" ")}
41
+ ${a}`,y.GENERIC_FAILURE)}}async function Ov(){return Ca(import.meta.url,["../../.."])}function Ir(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():Iv}function Rr(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():Av}async function Dv(e,t){let n=e.commandRunner??$v,r=Rr(e),i=Ir(e),a=`${r}@${i}`,o=["npm","install","-g",a];e.repair===!0&&o.push("--force");let s=await Ov(),c={requested:!0,status:"planned",package:r,target:a,command:o,before_version:s,repair:e.repair===!0};if(t)return c;try{await n(o[0],o.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 Pv(e){return Sv.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function Nv(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!Pv(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 Lv(e,t){let n=Nv(e,t);return e.kind!=="local"||await R(n)?n:await R(e.location)?e.location:n}function Mv(e,t,n,r){let i=["pm","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&r&&r.trim().length>0&&i.push("--ref",r.trim()),i}async function yu(e,t){let n=Tv(e,t);return(await de(n.selected_root)).state.entries.filter(i=>i.scope===e)}async function Fv(e,t,n){let r=await yu(e,t);return r.find(i=>_u(i,n.name))??r.find(i=>Ar(i.directory)===Ar(n.directory))}async function jv(e,t,n,r,i){let a=Ir(t),o=await Lv(e.source,a),s=Mv(e.source,o,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(i)return c;try{await ji(o,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let l=await Fv(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 Uv(e,t,n,r){let i=[n?e.status:void 0,...t.map(a=>a.status)].filter(a=>typeof a=="string");return{requested_cli:n,requested_packages:r,planned:i.filter(a=>a==="planned").length,updated:i.filter(a=>a==="updated").length,skipped:i.filter(a=>a==="skipped").length,failed:i.filter(a=>a==="failed").length}}async function yT(e,t,n){if(t.cliOnly===!0&&t.packagesOnly===!0)throw new _('Options "--cli-only" and "--packages-only" are mutually exclusive.',y.USAGE);let r=Cv(t),i=t.dryRun===!0,a=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&a)throw new _('A package target cannot be used with "--cli-only".',y.USAGE);let o=!(t.packagesOnly===!0||a),s=t.cliOnly!==!0,c=o?await Dv(t,i):{requested:!1,status:"skipped",package:Rr(t),target:`${Rr(t)}@${Ir(t)}`,command:["npm","install","-g",`${Rr(t)}@${Ir(t)}`],repair:t.repair===!0,reason:"not_requested"},l=s?await yu(r,n):[];if(a&&(l=l.filter(m=>_u(m,a)),l.length===0))throw new _(`Managed package "${a}" was not found in ${r} scope.`,y.NOT_FOUND);let d=[];for(let m of l)d.push(await jv(m,t,n,r,i));let u=Uv(c,d,o,s);return{ok:u.failed===0,action:"upgrade",dry_run:i,scope:r,target:a,cli:c,packages:d,summary:u}}import jt from"node:fs/promises";import Tr from"node:path";import Cr from"node:fs/promises";import ha 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 zv=864e5;function Bv(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 Wv(e,t){let n;try{n=await Cr.readdir(e,{withFileTypes:!0})}catch(i){if(L(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let a=ha.join(e,i.name),o;try{o=await Cr.readdir(a)}catch(s){L(s)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let s of o)s.endsWith(".json")&&r.push(`${i.name}/${s}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function wu(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*zv,o=ha.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await Wv(o,s.warnings);for(let l of c){let d=ha.join(o,l),u=`checkpoints/${l}`;s.scanned+=1,r?.onRead&&s.warnings.push(...await r.onRead(d));let m;try{m=await Cr.readFile(d,"utf8")}catch(w){if(L(w)){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 f=Bv(m),h=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(h)){s.warnings.push(`checkpoint_unparseable:${l}`),s.retained.push(u),s.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let g=i-h,p={file:u,created_at:f,age_seconds:Math.floor(g/1e3),stale:g>a,reason:g>a?"expired":"active"};if(!p.stale){s.retained.push(u),s.entries.push(p);continue}if(!n){try{await Cr.unlink(d)}catch(w){if(!L(w)){s.warnings.push(`checkpoint_remove_failed:${l}`),s.retained.push(u),s.entries.push(p);continue}}r?.onWrite&&s.warnings.push(...await r.onWrite(d))}s.removed.push(u),s.entries.push(p)}return s}import ga from"node:fs/promises";import vu 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 Gv=1440*60*1e3,qv=new Set(["committed","compensated"]);function Hv(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 Jv(e,t,n,r,i){let a=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(a))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=r-a;return qv.has(t)?o>i?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function Vv(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],a=Hv(await ga.readFile(e,"utf8")),o=Jv(t,a.status,a.updatedAt,r.nowMs,r.retentionMs);return o.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),o.remove&&!r.dryRun&&(await ga.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:o,warnings:i}}async function bu(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*Gv,o=vu.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await ga.readdir(o)).filter(l=>l.endsWith(".json")).sort((l,d)=>l.localeCompare(d))}catch(l){if(L(l))return s;throw l}for(let l of c){let d=vu.join(o,l),u=`transactions/sdk/${l}`,m=await Vv(d,u,l,{dryRun:n,hooks:r,nowMs:i,retentionMs:a});s.warnings.push(...m.warnings),s.scanned+=1;let{decision:f}=m;if(!f.remove){s.retained.push(u),s.entries.push(f.entry);continue}s.removed.push(u),s.entries.push(f.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 hn=["index","embeddings","runtime","locks","checkpoints","transactions"],Kv=1440*60*1e3,Yv=[{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 Xv(e,t,n){let r=t.relativePath,i=Tr.join(e,r),a=await Me({path:i,scope:"project"});try{let o=await jt.stat(i);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...a,`not_a_file:${r}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...a,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:a};t.kind==="file"?await jt.unlink(i):await jt.rm(i,{recursive:!0,force:!0});let s=await te({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...a,...s]}}catch(o){if(L(o))return{removed:!1,warnings:a};throw o}}async function Zv(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],a=[],o=Date.now()-Kv;for(let s of n){let c=Tr.join(e,s.relativePath);if(!await R(c))continue;let l=(await jt.readdir(c)).filter(d=>d.startsWith(s.prefix)).sort();for(let d of l){let u=Tr.posix.join(s.relativePath,d),m=Tr.join(c,d);a.push(...await Me({path:m,scope:"project"}));let f=await jt.stat(m).catch(h=>{if(!L(h))throw h});if(f){if(f.mtimeMs>o){i.push(u);continue}r.push(u),!t&&(await jt.rm(m,{recursive:!0,force:!0}),a.push(...await te({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:a}}function Qv(e){if(!e||e.length===0)return[...hn];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new _(`--scope requires at least one value (${hn.join(",")})`,y.USAGE);let n=new Set;for(let r of t){if(!hn.includes(r))throw new _(`Invalid --scope value "${r}". Expected one or more of: ${hn.join(", ")}`,y.USAGE);n.add(r)}return hn.filter(r=>n.has(r))}function eb(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(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="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(i=>i.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(i=>i.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 UT(e,t={}){let n=N(process.cwd(),e.path);if(!await R(V(n)))throw new _(`Tracker is not initialized at ${n}. Run pm init first.`,y.NOT_FOUND);let r=await T(n),i=t.dryRun===!0,a=Qv(t.scope),o=Yv.filter(h=>a.includes(h.scope)),s=[],c=[],l=[];for(let h of o){let g=await Xv(n,h,i);g.removed?s.push(h.relativePath):c.push(h.relativePath),l.push(...g.warnings)}if(a.includes("runtime")){let h=await Zv(n,i);s.push(...h.removed),c.push(...h.retained),l.push(...h.warnings)}let d;if(a.includes("locks")){let h=await us(n,{dryRun:i,hooks:{onRead:g=>Me({path:g,scope:"project"}),onWrite:g=>te({path:g,scope:"project",op:"gc:lock_remove"})}});s.push(...h.removed),c.push(...h.retained),l.push(...h.warnings),d={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length}}let u;if(a.includes("transactions")){let h=r.checkpoints.retention_days,g=await bu(n,{dryRun:i,retentionDays:h,hooks:{onRead:p=>Me({path:p,scope:"project"}),onWrite:p=>te({path:p,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:h}}let m;if(a.includes("checkpoints")){let h=r.checkpoints.retention_days,g=await wu(n,{dryRun:i,retentionDays:h,hooks:{onRead:p=>Me({path:p,scope:"project"}),onWrite:p=>te({path:p,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:h}}l.push(...await Tn({mode:i?"gc:dry-run":"gc",total_items:o.length}));let f=eb({dryRun:i,scopes:a,removed:s});return{ok:l.length===0,dry_run:i,scope:a,removed:s,retained:c,warnings:l,...d?{locks:d}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:f,generated_at:I()}}import tb from"node:fs/promises";import gn 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 _a="index/manifest.json",ya="search/embeddings.jsonl",nb="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function rb(e){return e.progress===!0||process.stderr.isTTY===!0}function ie(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
42
+ `)}catch{}}function ib(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new _("Reindex mode must be one of keyword|semantic|hybrid",y.USAGE)}async function ab(e,t,n,r){let i=[];return{candidates:await bo(e,t,n,i,r),warnings:i}}async function va(e,t,n,r,i){let a=ft(j()),o=[];for(let s of t)if(!(i&&!i.has(s.metadata.id))){if(typeof s.body=="string"){o.push({metadata:s.metadata,body:s.body});continue}try{let c=await tb.readFile(s.item_path,"utf8"),l=bt(c,{format:s.item_format,schema:n,extensionFieldNames:a,onWarning:d=>r.push(d)});o.push({metadata:s.metadata,body:l.body})}catch{r.push(`item_list_item_read_failed:${gn.relative(e,s.item_path)}`),o.push({metadata:s.metadata,body:""})}}return o}function ob(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:Io(e,{fields:n})}}var Ut=K;function sb(e){let t=j(),n=Ut(e.search?.provider);if(!n)return null;let r=xo(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,a=Ut(i.name)??Ut(r.definition.name);if(!a)return null;let o=i.embedBatch,s=i.embed_batch,c=i.embed,l=typeof o=="function"?o:typeof s=="function"?s:void 0,d=typeof c=="function"?c:void 0;return!l&&!d?null:{name:a,embedBatch:l,embed:d}}function cb(e){let t=j(),n=Ut(e.vector_store?.adapter);if(!n)return null;let r=So(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,a=Ut(i.name)??Ut(r.definition.name);if(!a)return null;let o=i.upsert,s=i.delete;return{adapterName:a,...typeof o=="function"?{upsert:o}:{},...typeof s=="function"?{delete:s}:{}}}function wa(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new _(`Invalid vector returned by ${t}`,y.GENERIC_FAILURE);return e}async function lb(e,t,n){let r=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let a=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:r}));if(!Array.isArray(a))throw new _(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,y.GENERIC_FAILURE);return a.map((o,s)=>wa(o,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new _(`Extension search provider "${e.name}" does not implement embed/embedBatch`,y.GENERIC_FAILURE);let i=[];for(let[a,o]of n.entries()){let s=await Promise.resolve(e.embed({input:o,settings:t,model:r}));i.push(wa(s,`extension search provider "${e.name}" embed output at index ${a}`))}return i}function ku(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function xu(e,t,n){let r=n?ot(n.name,ku(e)):t?ot(t.name,t.model):null;if(!r)throw new _("No embedding identity available for semantic reindex mode",y.USAGE);return r}function db(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function Su(e,t,n,r,i,a,o,s){let c=r?.name??n?.name,l=Co(c,e.search.embedding_corpus_max_characters).maxCharacters,d=Jr(e),u=i.map(h=>To(h,{providerName:c,maxCharacters:l,fields:d})),m=[],f=null;if(r)try{m=await lb(r,e,u),f=ot(r.name,ku(e))}catch(h){if(!n)throw new _(`Extension search provider "${r.name}" failed to generate embeddings: ${h instanceof Error?h.message:String(h)}`,y.GENERIC_FAILURE);a.push(`Extension search provider "${r.name}" failed; falling back to built-in provider (${h instanceof Error?h.message:String(h)})`)}if(m.length===0){if(!n)throw new _(`No embedding executor available for reindex mode '${t}'`,y.USAGE);let h=await $o(n,e,u,{onProgress:g=>{g.phase==="complete"&&(o.batches_completed=g.batch_index),ie(s,`embedding_batch_${g.phase} batch=${g.batch_index}/${g.batch_total} size=${g.batch_size} completed_inputs=${g.completed_inputs}/${g.total_inputs}`)}});a.push(...h.warnings),m=h.vectors,f=ot(n.name,n.model)}if(ie(s,`embedding_complete vectors=${m.length}`),m.length!==i.length)throw new _(`Embedding output size mismatch (expected ${i.length}, received ${m.length})`,y.GENERIC_FAILURE);if(!f)throw new _(`No embedding identity available for reindex mode '${t}'`,y.USAGE);return{vectors:m,embeddingIdentity:f}}async function ub(e,t,n,r,i,a){let o=Object.keys(n);if(t){if(o.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:o.sort((s,c)=>s.localeCompare(c)),settings:r}))}catch(s){throw new _(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,y.GENERIC_FAILURE)}else o.length>0&&i.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${o.length}`);if(!e)return}e&&await Po(e,o,{},a)}async function Eu(e,t,n,r,i){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:r}))}catch(a){throw new _(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${a instanceof Error?a.message:String(a)}`,y.GENERIC_FAILURE)}else i.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Do(e,n)}}function mb(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function pb(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 fb(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Ht(e.settings);if(!t.active&&!e.extensionEmbedding)throw new _(`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`,y.USAGE);let n=jn(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new _(`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`,y.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function hb(e){let t=G(e.settings,j()),n=await ab(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 gb(e){let t=await Et(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 xu(e.settings,Ht(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&St(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(nb))}async function _b(e){let t=await Et(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=xu(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(l=>l.metadata.id)),i=db(t.entries,r),a=St(t.embedding,n);e.forceFullSemantic&&!a&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let o=e.forceFullSemantic||a?e.metadataDocuments:e.metadataDocuments.filter(l=>t.entries[l.metadata.id]!==l.metadata.updated_at),s=new Set(o.map(l=>l.metadata.id)),c=s.size>0?await va(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:i,resetRequired:a,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function yb(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await va(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,ie(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await Su(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:Vr(r.vectors,"Reindex embeddings")}}async function wb(e){let t=await Su(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=Vr(n,"Reindex embeddings");if(!(!e.resetRequired&&(St(e.ledgerEmbedding,r)||Lo(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let o=await yb(e);return n=o.vectors,r=o.embeddingIdentity,i=o.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:o.staleDocuments,vectorDimension:i,resetRequired:!0}}async function vb(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(ie(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new _(`Extension vector adapter "${t}" does not support upserting vectors.`,y.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,ie(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof _)throw t;if(!e.activeVectorStore)throw new _(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,y.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)})`),ie(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){ie(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Oo(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,ie(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new _(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,y.USAGE)}function bb(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:wa(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 kb(e){ie(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await wb({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?(ie(e.progressEnabled,"vector_reset_start"),await ub(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),ie(e.progressEnabled,"vector_reset_complete")):await Eu(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=bb(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await vb({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:No(t.embeddingIdentity,t.vectorDimension)}}async function xb(e){let t=await _b(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(a=>[a.metadata.id,a.metadata.updated_at]));if(ie(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 ie(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await Eu(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await kb({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let i=new Map(r.staleDocuments.map(a=>[a.metadata.id,a]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(a=>i.get(a.metadata.id)??a),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:r.embeddingMetadata}}async function Sb(e){let t=gn.join(e.pmRoot,_a),n=gn.join(e.pmRoot,ya),r=Jr(e.settings),i=e.documentsForKeywordArtifacts.map(o=>JSON.stringify(ob(o,e.mode,r))).join(`
43
+ `);ie(e.progressEnabled,"writing keyword artifacts"),await se(t,`${JSON.stringify(e.manifest,null,2)}
44
+ `),await se(n,`${i}
45
+ `);let a=[];if(e.mode!=="keyword")try{ie(e.progressEnabled,"writing vectorization status ledger"),await Mo(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(o){a.push(`search_vectorization_status_ledger_write_failed:${o instanceof Error?o.message:String(o)}`)}return a}async function qT(e,t){let n=ib(e.mode),r=rb(e),i=e.full===!0;ie(r,`start mode=${n}`);let a=N(process.cwd(),t.path);if(!await R(V(a)))throw new _(`Tracker is not initialized at ${a}. Run pm init first.`,y.NOT_FOUND);let o=Fn(await T(a)).settings,s=null;try{s=await ce(a,Ao,o.locks.ttl_seconds,ne(void 0,"pm-reindex"),!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms)}catch(c){throw c instanceof _&&c.exitCode===y.CONFLICT?new _("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",y.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=sb(o),l=cb(o),d=fb({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:l}),u=n;ie(r,"loading item corpus");let m=await hb({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:h,metadataDocuments:g}=m;ie(r,`loaded_items=${g.length}`);let p=I(),w=pb(u,p,g),v=gn.join(a,_a),k=gn.join(a,ya),x=u==="keyword"?await va(a,h,o.schema,f):g,b=[],A={},U=null,C=mb(u);if(u==="keyword"&&await gb({pmRoot:a,settings:o,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let W=await xb({pmRoot:a,settings:o,requestedMode:n,activeEmbeddingProvider:d.activeEmbeddingProvider,activeVectorStore:d.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:h,metadataDocuments:g,documentsForKeywordArtifacts:x,forceFullSemantic:i,reindexWarnings:f,semanticWarnings:b,semanticSummary:C,progressEnabled:r});x=W.documentsForKeywordArtifacts,A=W.vectorizationLedgerEntries,U=W.vectorizationEmbeddingMetadata}let E=await Sb({pmRoot:a,mode:u,manifest:w,documentsForKeywordArtifacts:x,settings:o,vectorizationLedgerEntries:A,vectorizationEmbeddingMetadata:U,progressEnabled:r}),F=[...await te({path:v,scope:"project",op:"reindex:manifest"}),...await te({path:k,scope:"project",op:"reindex:embeddings"}),...await Tn({mode:u,total_items:g.length})];return ie(r,"done"),{ok:!0,mode:u,total_items:g.length,semantic:C,artifacts:{manifest:_a,embeddings:ya},warnings:[...f,...b,...E,...F],generated_at:p}}finally{await s?.()}}export{Gk as a,js as b,qn as c,M as d,X as e,Iu as f,Kb as g,Yb as h,Xb as i,Ko as j,Zb as k,Qb as l,ek as m,tk as n,nk as o,Qr as p,rk as q,ik as r,Zr as s,ak as t,ok as u,Yo as v,sk as w,Lu as x,Zo as y,gk as z,Vt as A,Uu as B,zu as C,_k as D,Bu as E,fs as F,hm as G,gm as H,st as I,dx as J,xm as K,dp as L,mS as M,pS as N,fS as O,Xt as P,hS as Q,gS as R,_S as S,yS as T,wS as U,vS as V,bS as W,kS as X,xS as Y,SS as Z,ES as _,ji as $,ns as aa,Xg as ba,yA as ca,ln as da,fr as ea,wA as fa,vA as ga,aI as ha,oI as ia,Kl as ja,bd as ka,yI as la,Ql as ma,xd as na,uC as oa,mC as pa,dw as qa,uw as ra,gC as sa,_C as ta,yC as ua,wC as va,pw as wa,fw as xa,hw as ya,vC as za,Rd as Aa,_w as Ba,Ad as Ca,aa as Da,Cd as Ea,yw as Fa,ww as Ga,vw as Ha,zw as Ia,dT as Ja,uT as Ka,yT as La,UT as Ma,qT as Na};
46
+ //# sourceMappingURL=chunk-QK753U3U.js.map