@unbrained/pm-cli 2026.8.10 → 2026.8.11

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 (175) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +102 -80
  3. package/dist/cli/commander-usage.js +79 -7
  4. package/dist/cli/error-guidance.d.ts +10 -0
  5. package/dist/cli/error-guidance.js +76 -25
  6. package/dist/cli/main.js +6 -2
  7. package/dist/cli/register-assurance.d.ts +8 -0
  8. package/dist/cli/register-assurance.js +52 -0
  9. package/dist/cli/register-files-lookup.js +14 -3
  10. package/dist/cli/register-mutation.js +30 -9
  11. package/dist/cli/register-operations.js +16 -11
  12. package/dist/cli-bundle/bundle-manifest.json +159 -159
  13. package/dist/cli-bundle/chunks/{chunk-TRWXF476.js → chunk-2OOU2AFH.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-2RA2YTHJ.js +33 -0
  15. package/dist/cli-bundle/chunks/chunk-A2SJGHSI.js +3 -0
  16. package/dist/cli-bundle/chunks/chunk-DSKYD4LG.js +13 -0
  17. package/dist/cli-bundle/chunks/chunk-HC3GM6YY.js +194 -0
  18. package/dist/cli-bundle/chunks/chunk-IUNRVDAI.js +2 -0
  19. package/dist/cli-bundle/chunks/chunk-W7CPZGSB.js +2 -0
  20. package/dist/cli-bundle/chunks/{chunk-EBO7OUUE.js → chunk-WMEZHCFI.js} +59 -53
  21. package/dist/cli-bundle/chunks/{chunk-ETML5C6H.js → chunk-ZU34C3LH.js} +47 -47
  22. package/dist/cli-bundle/chunks/chunk-ZXOC6HG5.js +5 -0
  23. package/dist/cli-bundle/chunks/{register-list-query-OJ6ZXKV4.js → register-list-query-HAUXVUPY.js} +8 -8
  24. package/dist/cli-bundle/chunks/register-mutation-7Y5U7ABT.js +20 -0
  25. package/dist/cli-bundle/chunks/register-operations-EQX3DLAZ.js +2 -0
  26. package/dist/cli-bundle/chunks/{register-setup-S3KT2LTH.js → register-setup-NOCOOWQY.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-34SX654S.js → chunk-23FTGO3W.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-2COZ67XT.js → chunk-2DL3MRTD.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/chunk-3AYKXMYX.js +2 -0
  30. package/dist/cli-bundle/focused-chunks/chunk-4AHEC74N.js +2 -0
  31. package/dist/cli-bundle/focused-chunks/{chunk-7UN6BHHO.js → chunk-4H5IA6AV.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/chunk-4SV3ZKG3.js +16 -0
  33. package/dist/cli-bundle/focused-chunks/chunk-55BIB6DV.js +2 -0
  34. package/dist/cli-bundle/focused-chunks/chunk-6JW6Z2P5.js +8 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-IW43E4XL.js → chunk-BKPIY34S.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/chunk-D4PIWE6D.js +2 -0
  37. package/dist/cli-bundle/focused-chunks/{chunk-KR5RVXLQ.js → chunk-DPO7TEFX.js} +29 -29
  38. package/dist/cli-bundle/focused-chunks/{chunk-JMVA4HKR.js → chunk-E3KCL7AY.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/chunk-ERAAFLPS.js +153 -0
  40. package/dist/cli-bundle/focused-chunks/{chunk-RIIN5V4N.js → chunk-F6E4JZKG.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-FPSYO5ZG.js +18 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-M6RPIXKC.js → chunk-J5EKAIVD.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-2EXI2DKR.js → chunk-KDH5OX3D.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-OJ3LVVIS.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-DZGAHZZV.js → chunk-TL5M2PAY.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-75774JWP.js → chunk-UDAZWT25.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-VABB4L5Y.js +17 -0
  48. package/dist/cli-bundle/main.js +13 -13
  49. package/dist/cli-bundle/sdk-authoring.js +1 -1
  50. package/dist/cli-bundle/sdk-contracts.js +1 -1
  51. package/dist/cli-bundle/sdk-core.js +41 -39
  52. package/dist/cli-bundle/sdk-governance.js +1 -1
  53. package/dist/cli-bundle/sdk-graph.js +1 -1
  54. package/dist/cli-bundle/sdk-merge.js +1 -1
  55. package/dist/cli-bundle/sdk-query.js +1 -1
  56. package/dist/cli-bundle/sdk-runtime.js +1 -1
  57. package/dist/cli-bundle/sdk-testing.js +1 -1
  58. package/dist/cli-bundle/sdk.js +2 -2
  59. package/dist/core/session/session-state.d.ts +47 -0
  60. package/dist/core/session/session-state.js +207 -6
  61. package/dist/core/shared/author.d.ts +7 -1
  62. package/dist/core/shared/author.js +66 -46
  63. package/dist/core/shared/errors.d.ts +8 -0
  64. package/dist/core/shared/errors.js +2 -2
  65. package/dist/sdk/agent/refusal-reachability.d.ts +40 -0
  66. package/dist/sdk/agent/refusal-reachability.js +72 -0
  67. package/dist/sdk/agent/subcommand-recovery.d.ts +40 -0
  68. package/dist/sdk/agent/subcommand-recovery.js +84 -0
  69. package/dist/sdk/cli-bootstrap.d.ts +8 -0
  70. package/dist/sdk/cli-bootstrap.js +7 -7
  71. package/dist/sdk/cli-contracts/completeness.js +13 -3
  72. package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
  73. package/dist/sdk/cli-contracts/enum-contracts.js +3 -2
  74. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  75. package/dist/sdk/cli-contracts/flag-contracts.js +17 -2
  76. package/dist/sdk/cli-contracts/runtime-contracts.js +4 -3
  77. package/dist/sdk/cli-contracts/schemas/assurance-definition.d.ts +513 -0
  78. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +251 -0
  79. package/dist/sdk/cli-contracts/tool-parameter-tables.js +79 -2
  80. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  81. package/dist/sdk/cli-contracts/tool-schema.js +34 -4
  82. package/dist/sdk/cli-contracts.d.ts +1 -1
  83. package/dist/sdk/cli-contracts.js +3 -3
  84. package/dist/sdk/completion.js +9 -3
  85. package/dist/sdk/config.js +9 -3
  86. package/dist/sdk/context/semantic-session-attribution.d.ts +32 -0
  87. package/dist/sdk/context/semantic-session-attribution.js +83 -0
  88. package/dist/sdk/core-governance.d.ts +3 -1
  89. package/dist/sdk/core-governance.js +5 -3
  90. package/dist/sdk/core.d.ts +1 -1
  91. package/dist/sdk/core.js +2 -2
  92. package/dist/sdk/error-code-catalog.d.ts +13 -0
  93. package/dist/sdk/error-code-catalog.js +35 -2
  94. package/dist/sdk/extension.js +18 -17
  95. package/dist/sdk/files.d.ts +11 -0
  96. package/dist/sdk/files.js +82 -24
  97. package/dist/sdk/generated-error-code-catalog.js +32 -13
  98. package/dist/sdk/governance/assurance-action-contracts.d.ts +7 -0
  99. package/dist/sdk/governance/assurance-action-contracts.js +5 -0
  100. package/dist/sdk/governance/assurance-action.d.ts +70 -0
  101. package/dist/sdk/governance/assurance-action.js +198 -0
  102. package/dist/sdk/governance/assurance-limits.d.ts +7 -0
  103. package/dist/sdk/governance/assurance-limits.js +11 -0
  104. package/dist/sdk/governance/assurance-runtime.d.ts +20 -0
  105. package/dist/sdk/governance/assurance-runtime.js +131 -0
  106. package/dist/sdk/governance/assurance.d.ts +432 -0
  107. package/dist/sdk/governance/assurance.js +689 -0
  108. package/dist/sdk/graph/run.js +8 -3
  109. package/dist/sdk/index.d.ts +6 -1
  110. package/dist/sdk/index.js +8 -3
  111. package/dist/sdk/lifecycle/claim.js +18 -3
  112. package/dist/sdk/lifecycle/focus.js +13 -3
  113. package/dist/sdk/lifecycle/plan.js +8 -3
  114. package/dist/sdk/provenance.d.ts +38 -0
  115. package/dist/sdk/provenance.js +64 -2
  116. package/dist/sdk/query/context.js +19 -8
  117. package/dist/sdk/runtime-extended-actions.js +22 -5
  118. package/dist/sdk/runtime-primitives.d.ts +2 -0
  119. package/dist/sdk/runtime-primitives.js +4 -2
  120. package/dist/sdk/runtime.d.ts +4 -0
  121. package/dist/sdk/runtime.js +31 -27
  122. package/dist/sdk/telemetry.js +7 -4
  123. package/dist/sdk/traceability/runtime-files-lookup.d.ts +8 -0
  124. package/dist/sdk/traceability/runtime-files-lookup.js +33 -0
  125. package/dist/sdk/traceability/source-traceability.d.ts +102 -0
  126. package/dist/sdk/traceability/source-traceability.js +293 -0
  127. package/dist/types.d.ts +8 -2
  128. package/dist/types.js +2 -2
  129. package/docs/ASSURANCE.md +132 -0
  130. package/docs/README.md +1 -0
  131. package/docs/RELEASING.md +9 -5
  132. package/docs/SDK.md +12 -1
  133. package/docs/SDK_AGENT_SESSION_CONTEXT.md +40 -4
  134. package/docs/SDK_EVIDENCE_TRACEABILITY.md +39 -1
  135. package/docs/SDK_RUNTIME_BOUNDARIES.md +36 -1
  136. package/docs/TESTING.md +12 -9
  137. package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -0
  138. package/marketplace.json +2 -2
  139. package/package.json +3 -3
  140. package/packages/pm-beads/package.json +1 -1
  141. package/packages/pm-calendar/package.json +1 -1
  142. package/packages/pm-command-kit/package.json +1 -1
  143. package/packages/pm-digital-twin/package.json +1 -1
  144. package/packages/pm-governance-audit/package.json +1 -1
  145. package/packages/pm-guide-shell/package.json +1 -1
  146. package/packages/pm-kanban/package.json +1 -1
  147. package/packages/pm-lifecycle-hooks/package.json +1 -1
  148. package/packages/pm-linked-test-adapters/package.json +1 -1
  149. package/packages/pm-search-advanced/package.json +1 -1
  150. package/packages/pm-templates/extensions/templates/index.ts +9 -3
  151. package/packages/pm-templates/package.json +1 -1
  152. package/packages/pm-todos/package.json +1 -1
  153. package/packages/pm-vcs/package.json +1 -1
  154. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  155. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  156. package/sdk/public-surface.json +840 -28
  157. package/dist/cli-bundle/chunks/chunk-2QYH4QMI.js +0 -30
  158. package/dist/cli-bundle/chunks/chunk-JUDU4RO4.js +0 -194
  159. package/dist/cli-bundle/chunks/chunk-JZSNADRR.js +0 -5
  160. package/dist/cli-bundle/chunks/chunk-MENWVGJW.js +0 -2
  161. package/dist/cli-bundle/chunks/chunk-S4EITGLA.js +0 -3
  162. package/dist/cli-bundle/chunks/chunk-TIGKWVLA.js +0 -13
  163. package/dist/cli-bundle/chunks/chunk-TSLDTJLQ.js +0 -2
  164. package/dist/cli-bundle/chunks/register-mutation-DKI7QC7O.js +0 -20
  165. package/dist/cli-bundle/chunks/register-operations-P5OGMT6I.js +0 -2
  166. package/dist/cli-bundle/focused-chunks/chunk-36FTZ2NT.js +0 -2
  167. package/dist/cli-bundle/focused-chunks/chunk-3CQECMKR.js +0 -16
  168. package/dist/cli-bundle/focused-chunks/chunk-CHIBMEZR.js +0 -8
  169. package/dist/cli-bundle/focused-chunks/chunk-FF4MNAYB.js +0 -153
  170. package/dist/cli-bundle/focused-chunks/chunk-GHTN2ILR.js +0 -2
  171. package/dist/cli-bundle/focused-chunks/chunk-I4YM2I7S.js +0 -2
  172. package/dist/cli-bundle/focused-chunks/chunk-IMDTEN7K.js +0 -2
  173. package/dist/cli-bundle/focused-chunks/chunk-KSNJG4KI.js +0 -16
  174. package/dist/cli-bundle/focused-chunks/chunk-MXYSIQ56.js +0 -18
  175. package/dist/cli-bundle/focused-chunks/chunk-RKWSCYYN.js +0 -2
@@ -0,0 +1,17 @@
1
+ import{f as Ae,g as nt}from"./chunk-BKPIY34S.js";import{a as Jt,g as tt,i as Xt}from"./chunk-OJ3LVVIS.js";import{g as kn,i as bn}from"./chunk-J5EKAIVD.js";import{s as ge,t as gn,u as ye,ua as wn,v as yn}from"./chunk-FPSYO5ZG.js";import{Ia as ln,La as Z,Ma as dn,Oa as un,Ra as mn,Sa as fn,T as de,U as X,Ua as M,Y as tn,bb as pn,ca as nn,da as rn,ga as on,gb as hn,ha as sn,jb as Ee,k as J,ka as it,kb as Ce,lb as Ie,ma as an,nb as _n,q as en,qb as Te,wa as cn}from"./chunk-ERAAFLPS.js";import{$ as Kt,E as V,J as Ht,K as B,L as _e,N as U,Q as Vt,Qa as Zt,U as L,ca as Ze,h as Gt,o as Je,p as N,r as qt,s as ae,v as Xe,w as Wt}from"./chunk-KDH5OX3D.js";import{i as Qt}from"./chunk-F6E4JZKG.js";import{N as Ut,U as zt,V as xe,Y as h,Z as _,aa as Qe,ba as Yt,ca as et,t as Ye}from"./chunk-D4PIWE6D.js";import Fe from"node:fs/promises";import Pe from"node:path";import{Option as cc}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]="5f92dd0d-4eb1-5a7b-8891-931dd15deb81")}catch{}})();function Or(e,t){let n=[],i=new Set;for(let r of t.keys){if(!Object.hasOwn(e,r))continue;let o=e[r];if(o!=null){if(typeof o=="string"){n.push(o);continue}if(!Array.isArray(o)||!o.every(s=>typeof s=="string"))return;i.has(o)||(i.add(o),n.push(...o))}}return n.length>0?n.join("; "):void 0}function Oe(e,t){return e.find(i=>i.target===t)??{target:t,keys:[t]}}function k(e,t){return e[t]===!0?!0:void 0}function Q(e,t){return e[t]===!1?!0:void 0}function vn(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Rn(e,t){for(let[n,i]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=i)}function Sn(e){let t=r=>tt(e,Oe(Ae,r)),n=r=>Xt(e,Oe(nt,r)),i={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:Or(e,Oe(nt,"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:vn(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:k(e,"replaceDeps"),replaceTests:k(e,"replaceTests"),replaceFiles:k(e,"replaceFiles"),replaceDocs:k(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:k(e,"clearDeps"),clearComments:k(e,"clearComments"),clearNotes:k(e,"clearNotes"),clearLearnings:k(e,"clearLearnings"),clearFiles:k(e,"clearFiles"),clearTests:k(e,"clearTests"),clearDocs:k(e,"clearDocs"),clearReminders:k(e,"clearReminders"),clearEvents:k(e,"clearEvents"),clearTypeOptions:k(e,"clearTypeOptions")};return Rn(i,e),i}function C(e,t){let n=Oe(Jt,t),i=tt(e,n);if(i!==void 0)return i;for(let r of n.keys){let o=e[r];if(Array.isArray(o)){let s=o.filter(a=>typeof a=="string");if(s.length>0)return s.join(",")}if(t==="ids"&&typeof o=="string")return o;if(typeof o=="number"&&Number.isFinite(o))return String(o)}}function Dr(e){let t=k(e,"filterFilesMissing"),n=k(e,"filterDocsMissing");return{filterReviewerMissing:k(e,"filterReviewerMissing"),filterRiskMissing:k(e,"filterRiskMissing"),filterConfidenceMissing:k(e,"filterConfidenceMissing"),filterSprintMissing:k(e,"filterSprintMissing"),filterReleaseMissing:k(e,"filterReleaseMissing"),hasNotes:k(e,"hasNotes"),hasLearnings:k(e,"hasLearnings"),hasFiles:k(e,"hasFiles"),hasDocs:k(e,"hasDocs"),hasTests:k(e,"hasTests"),hasComments:k(e,"hasComments"),hasDeps:k(e,"hasDeps"),hasBody:k(e,"hasBody"),hasLinkedCommand:k(e,"hasLinkedCommand"),noNotes:Q(e,"notes"),noLearnings:Q(e,"learnings"),noFiles:Q(e,"files")??t,filterFilesMissing:t,noDocs:Q(e,"docs")??n,filterDocsMissing:n,noTests:Q(e,"tests"),noComments:Q(e,"comments"),noDeps:Q(e,"deps"),emptyBody:k(e,"emptyBody"),noLinkedCommand:Q(e,"linkedCommand")}}function rt(e){let t={status:C(e,"status"),type:C(e,"type"),tag:C(e,"tag"),priority:C(e,"priority"),deadlineBefore:C(e,"deadlineBefore"),deadlineAfter:C(e,"deadlineAfter"),updatedAfter:C(e,"updatedAfter"),updatedBefore:C(e,"updatedBefore"),createdAfter:C(e,"createdAfter"),createdBefore:C(e,"createdBefore"),today:k(e,"today"),recent:k(e,"recent"),ids:C(e,"ids"),assignee:C(e,"assignee"),assigneeFilter:C(e,"assigneeFilter"),parent:C(e,"parent"),sprint:C(e,"sprint"),release:C(e,"release"),limit:C(e,"limit"),offset:C(e,"offset"),noTruncate:Q(e,"truncate"),includeBody:k(e,"includeBody"),strictRead:k(e,"strictRead"),compact:k(e,"compact"),brief:k(e,"brief"),full:k(e,"full"),fields:C(e,"fields"),sort:C(e,"sort"),order:C(e,"order"),tree:k(e,"tree"),treeDepth:C(e,"treeDepth"),filterAcMissing:k(e,"filterAcMissing"),filterEstimatesMissing:vn(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:k(e,"filterResolutionMissing"),filterMetadataMissing:k(e,"filterMetadataMissing"),...Dr(e)};return Rn(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 R(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function T(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 Fr(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function we(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function gc(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new _(`${t} must be a finite integer.`,h.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.`,h.USAGE);return n}}function yc(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:R(e,"limit")??R(t,"limit")}function wc(e){let t=R(e,"outputFormat");return{json:!0,quiet:!0,author:R(e,"author"),path:R(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:R(e,"outputInclude"),outputLimit:T(e,"outputLimit"),outputBudget:T(e,"outputBudget"),outputSession:R(e,"outputSession"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Pr=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Nr=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"]),Lr=new Set(["files","files-discover","docs","test","test-all"]),Mr=new Set(["claim","release","start-task","pause-task","close-task"]),$r={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"]},jr=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession"];function An(e,t){let n={},i=t!==void 0&&Lr.has(t),r=t==="files"||t==="files-discover"||t==="docs";for(let[o,s]of Object.entries(e)){if(Array.isArray(s)&&Pr.has(o)){n[o]=s.join(",");continue}if(o==="note"&&r){n[o]=s;continue}if(typeof s=="string"&&Nr.has(o)){n[o]=[s];continue}if(typeof s=="string"&&i&&(o==="add"||o==="remove")){n[o]=[s];continue}n[o]=s}return n}function kc(e,t){let n=Kt(e.options),i={},r=c=>{n[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of $r[t??""]??[])r(c);for(let c of jr)r(c);let o=An({...i,...n},t),s=R(e,"author"),a=t!==void 0&&Mr.has(t)?R(e,"assignee")??R(o,"assignee"):void 0;return s&&o.author===void 0?{...o,author:s}:a&&o.author===void 0?{...o,author:a}:o}function bc(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 vc(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 Rc(e){let t=[],n=!0;for(let i of e.trim().toLowerCase()){if(i>="a"&&i<="z"||i>="0"&&i<="9"){t.push(i),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function Sc(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function at(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function xc(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),i={};for(let[o,s]of Object.entries(e))n.has(o)||(i[o]=s);let r={...i,...t};return delete r.args,r}function Ac(e,t){return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:{...t}}}function st(e){return{type:T(e,"filterType"),tag:T(e,"filterTag"),priority:T(e,"filterPriority"),deadlineBefore:T(e,"filterDeadlineBefore"),deadlineAfter:T(e,"filterDeadlineAfter"),updatedAfter:T(e,"filterUpdatedAfter"),updatedBefore:T(e,"filterUpdatedBefore"),createdAfter:T(e,"filterCreatedAfter"),createdBefore:T(e,"filterCreatedBefore"),ids:Fr(e,"ids"),assignee:T(e,"filterAssignee"),assigneeFilter:T(e,"filterAssigneeFilter")??T(e,"filterAssignee_filter"),parent:T(e,"filterParent"),sprint:T(e,"filterSprint"),release:T(e,"filterRelease"),limit:T(e,"limit"),offset:T(e,"offset")}}function ot(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return at(e)}function De(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function Ec(e){let t=ot(e.kind),n=ot(e.exemptIsolate),i=ot(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:De(e.maxDepth),limit:De(e.limit),after:R(e,"after"),direction:R(e,"direction"),maxPaths:De(e.maxPaths),sample:De(e.sample),...n===void 0?{}:{exemptIsolate:n},...i===void 0?{}:{exemptIsolateType:i},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function Cc(e){return{status:R(e,"filterStatus"),list:we(e.list)?rt(e.list):st(e),reason:R(e,"reason"),resolution:R(e,"resolution"),expectedResult:R(e,"expectedResult")??R(e,"expected_result")??R(e,"expected"),actualResult:R(e,"actualResult")??R(e,"actual_result")??R(e,"actual"),validateClose:R(e,"validateClose")??R(e,"validate_close"),author:R(e,"author"),message:R(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:R(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var Br=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 xn(e){let t={};for(let[n,i]of Object.entries(e))Br.has(n)||(t[n]=i);return En(t)}function En(e){let t=An(e,"update-many");for(let n of Ae)for(let i of n.keys){let r=t[i];typeof r=="number"&&Number.isFinite(r)&&(t[i]=String(r))}return Sn(t)}function Ic(e){if(we(e.list)||we(e.update)){let t=we(e.update)?e.update:xn(e);return{status:T(e,"filterStatus"),list:we(e.list)?rt(e.list):st(e),update:En(t),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:R(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:T(e,"filterStatus"),list:st(e),update:xn(e),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:R(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 ee(e,t){throw new _(e,h.USAGE,t)}var Ur="2026-07-15T06:22:12.276Z",zr=Date.parse(Ur),Gr=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Cn=e=>typeof e=="string"?e:"",In=e=>{let t=e??{},n=Cn(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(Cn(t.ts))>=zr);return Gr[i][r]};function Tn(e,t,n=20,i=new Set,r=!1){let o=[],s=[],a={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 p;try{p=JSON.parse(f)}catch{continue}l+=1;let y=In(p);if(y!=="attributed"){if(d+=1,y==="actionable_unknown"&&i.has(`${e}:${m+1}`)){u+=1;continue}a[y]+=1,r&&y==="actionable_unknown"&&s.push({item_id:e,line:m+1}),o.length<c&&o.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:a.legacy_unknown+a.actionable_unknown>o.length,actionable_events:s}}var $c=(e,t,n=20,i=new Set)=>Tn(e,t,n,i);function qr(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let o=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof o!="object"||o===null||!Array.isArray(o.events)))for(let s of o.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var ct=async(e,t=20,n=!1)=>{let i=Pe.join(e,"history"),r;try{r=(await Fe.readdir(i)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{r=[]}let o=new Set,s=[],a=[],c=0,l=0,d=0,u=0,m=0,f=0,p="_workspace.jsonl",y=new Set;if(r.includes(p))try{y=qr(await Fe.readFile(Pe.join(i,p),"utf8"))}catch{y=new Set}for(let w of r){let v;try{v=await Fe.readFile(Pe.join(i,w),"utf8")}catch{continue}let S=w.slice(0,-6),x=Tn(S,v,t-s.length,y,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&&o.add(S),s.push(...x.samples),n&&a.push(...x.actionable_events)}let g=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:[...o].sort((w,v)=>w.localeCompare(v)),samples:s,samples_truncated:g>s.length,...n?{actionable_events:a}:{}}};function Wr(e,t){let n=e.length>0;return n&&t&&ee("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&&ee("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:Hr(e),all_actionable:t}}function Hr(e){return e.map(t=>{let n=t.lastIndexOf(":"),i=t.slice(0,n).trim(),r=Number(t.slice(n+1)),o=i===Z||/^[a-z0-9][a-z0-9-]*$/iu.test(i);return(n<1||!o||!Number.isSafeInteger(r)||r<1)&&ee(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:i,line:r}})}function jc(e,t){let n=Wr(at(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Vr(e,{events:n.events,all_actionable:n.all_actionable,attributed_author:R(t,"attributedAuthor")??R(t,"attributed_author")??"",reviewer:R(t,"reviewer")??"",reason:R(t,"reason")??""})}async function Vr(e,t){let n=t.reviewer.trim(),i=t.attributed_author.trim(),r=t.reason.trim(),o=t.events??[],s=+(t.all_actionable===!0)+ +(o.length>0);s===0&&ee("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),s>1&&ee("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"});let a=t.all_actionable===!0?(await ct(e,0,!0)).actionable_events:o;[a.length>0,n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1)&&ee("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"});let l=[...new Map(a.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===Z||/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1)&&ee(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"});let p;try{let g=(await Fe.readFile(Pe.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];p=JSON.parse(g??"")}catch{ee(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}In(p)!=="actionable_unknown"&&ee(`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 M(e),u=await un({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:l,attributed_author:i}},message:r,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms});return{acknowledged:l.length,history_path:u.historyPath}}import{readFile as Le,realpath as mt,writeFile as eo}from"node:fs/promises";import{execFile as to}from"node:child_process";import O from"node:path";import{promisify as no}from"node:util";import{readFile as Kr,writeFile as Yr}from"node:fs/promises";import ke from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bbfa5b19-d801-582a-98e8-0c4925dd57c0")}catch{}})();var Dn="# pm-cli:runtime-cache:start",lt="# pm-cli:runtime-cache:end",Fn=".agents/pm",dt=["runtime/","search/","locks/","transactions/","checkpoints/"],Jr=["search/eval-queries.json"];async function On(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.",h.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 Pn(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function ut(e){let t=e.replaceAll("\\","/");return ke.isAbsolute(e)||t===".."||t.startsWith("../")}function Xr(e=Fn){let t=Pn(e);return[Dn,...dt.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Jr.map(n=>`!${t}/${n}`),lt].join(`
2
+ `)}async function Wc(e,t={}){let n=ke.join(e,".gitignore"),i=Fn;if(t.pmRoot!==void 0){let d=Pn(ke.relative(ke.resolve(e),ke.resolve(t.pmRoot)));if(ut(d))return{path:n,changed:!1};d.length>0&&(i=d)}let r="";try{r=await On(()=>Kr(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&d.code==="ENOENT"))throw d}let o=r.indexOf(Dn),s=r.indexOf(lt),c=(o>=0&&s>=o?`${r.slice(0,o)}${r.slice(s+lt.length)}`:r).trimEnd(),l=`${c.length>0?`${c}
3
+
4
+ `:""}${Xr(i)}
5
+ `;return l===r?{path:n,changed:!1}:(await On(()=>Yr(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 Zr="PM_SOURCE_CONTEXT_ACCESS",Qr="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Nn(e){let t=e[Zr],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",i=n==="read_only"&&e[Qr]?.trim()==="1";return{access:n,write_override_applied:i,source_writes_allowed:n==="write"||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]="94d2a7a8-ce00-5689-b2f6-3d4813234b55")}catch{}})();var pt=no(to),Ne="# pm-cli:merge-drivers:start",jn="# pm-cli:merge-drivers:end",ue="# pm-cli:merge-drivers:v2:start",ft="# pm-cli:merge-drivers:v2:end",io="merge-fence";function Ln(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Bn(){let e=Wt(import.meta.url,["../../.."]);return`${Ln(process.execPath)} ${Ln(O.join(e,"dist","cli.js"))}`}var Un=[{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 ro(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),i=e.environment.PM_SOURCE_PM_PATH?.trim(),r=Nn(e.environment),o=!!(n&&i),s=t===void 0&&o&&(e.dryRun||r.source_writes_allowed);if(t!==void 0){let a=B(e.cwd,t);return{pm_root:a,workspace_start:a,source_coordinates_available:o,source_context_selected:!1,source_policy:r}}return s?{pm_root:O.resolve(i),workspace_start:O.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:r}:{pm_root:o?B(e.cwd,".agents/pm"):B(e.cwd),workspace_start:e.cwd,source_coordinates_available:o,source_context_selected:!1,source_policy:r}}async function be(e){try{let{stdout:t}=await pt("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await mt(t.trim())}catch{return null}}async function zn(e){let t=await be(e);if(t===null)throw new _("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function ht(e,t){return O.relative(e,t).replaceAll("\\","/")}function K(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Mn(e,t){if(e[t]!=="'")return null;let n="";for(let i=t+1;i<e.length;i+=1){if(e.startsWith(`'"'"'`,i)){n+="'",i+=4;continue}if(e[i]==="'")return{value:n,nextOffset:i+1};n+=e[i]}return null}async function oo(e,t){let n=Mn(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let i=Mn(e,n.nextOffset+1);if(i===null||e.slice(i.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(O.basename(n.value))||O.basename(i.value)!=="cli.js"||O.basename(O.dirname(i.value))!=="dist"||!await N(n.value)||!await N(i.value))return!1;try{let r=O.dirname(O.dirname(i.value)),o=JSON.parse(await Le(O.join(r,"package.json"),"utf8")),s=typeof o.bin=="object"&&o.bin!==null&&"pm"in o.bin?o.bin.pm:void 0;return o.name==="@unbrained/pm-cli"&&(o.bin==="dist/cli.js"||s==="dist/cli.js")}catch{return!1}}function _t(e,t){let n=e.length>0?`${e}/`:"",i=[`${K(`${n}**/*.toon`)} merge=pm-item-toon`,`${K(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)i.push(`${K(`${n}${r}/*.toon`)} merge=pm-item-toon`),i.push(`${K(`${n}${r}/*.md`)} merge=pm-item-markdown`);return i.push(`${K(`${n}**/*.jsonl`)} merge=pm-relationship`),i.push(`${K(`${n}history/*.jsonl`)} merge=pm-history`),i.push(`${K(`${n}settings.json`)} merge=pm-json`),i.push(`${K(`${n}**/*.json`)} merge=pm-json`),i.push(`${K(`${n}extensions/**`)} -merge`),i.push(`${K(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),i}function $n(e,t,n){let i=e.indexOf(t),r=e.indexOf(n);return i>=0&&r>i?`${e.slice(0,i)}${e.slice(r+n.length)}`:e.replace(t,"").replace(n,"")}async function Gn(e,t,n){let i=O.join(e,".gitattributes"),r="";try{r=await Le(i,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&l.code==="ENOENT"))throw l}let o=[ue,...t,ft].join(`
6
+ `),a=$n($n(r,ue,ft),Ne,jn).trimEnd(),c=`${a.length>0?`${a}
7
+
8
+ `:""}${o}
9
+ `;return c===r?{path:i,changed:!1}:(n||await eo(i,c,"utf8"),{path:i,changed:!0})}function Me(e){let t=V(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,i)=>n.localeCompare(i))}async function qn(e,t){let n=O.resolve(e),i=null,r="",o=n;for(let v=0;v<8;v+=1){let S=O.join(o,".gitattributes");try{let A=await Le(S,"utf8");if(A.includes(ue)||A.includes(Ne)){i=o,r=A;break}}catch{}let x=O.dirname(o);if(x===o)break;o=x}if(i===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=O.join(i,".gitattributes"),a=r.includes(ue),c=a?ue:Ne,l=a?ft:jn,d=r.indexOf(c),u=r.indexOf(l),m=u>d?r.slice(d+c.length,u).split(`
10
+ `).map(v=>v.trim()).filter(v=>v.length>0):[],f=_t(ht(i,n),t),p=new Set(m),y=new Set(f),g=f.filter(v=>!p.has(v)),w=m.filter(v=>!y.has(v));return{status:g.length>0||w.length>0?"drift":"ok",path:s,missing_patterns:g,stale_patterns:w,schema_scope:"project"}}async function Wn(e){let t=Bn(),n=[],i=[];for(let r of Un){let o=`merge.${r.key}.driver`,s=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`,a=`${t}${s}`;try{let{stdout:c}=await pt("git",["config","--local","--get",o],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await oo(l,s)&&i.push(o)}catch{n.push(o)}}return{status:n.length>0?"missing":i.length>0?"drift":"ok",missing_keys:n,drifted_keys:i}}async function dl(e){let t;try{t=await zn(O.resolve(e))}catch{return{status:"no_git"}}let n=ht(t,O.resolve(e)),i=await M(e),r=de(void 0,i.author_default),o=await tn(e,io,i.locks.ttl_seconds,r,!1,fn(i).force_required_for_stale_lock,i.locks.wait_ms);try{let s=O.join(t,".gitattributes"),a;try{a=await Le(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&u.code==="ENOENT")return{status:"not_installed",path:s};throw u}if(!a.includes(ue)&&!a.includes(Ne))return{status:"not_installed",path:s};let c=await M(e),l=Me(c),d=await Gn(t,_t(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await o()}}async function ul(e,t){let n=ro({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),i=n.pm_root;if(!await N(U(i)))throw new _(`Tracker is not initialized at ${i}. Run pm init first.`,h.NOT_FOUND);let r=await zn(n.workspace_start);return so({pmRoot:i,workspaceRoot:r,dryRun:e.dryRun===!0})}async function so(e){let t=O.resolve(e.pmRoot),n=O.resolve(e.workspaceRoot),i=e.dryRun===!0,r,o;try{[r,o]=await Promise.all([mt(t),mt(n)])}catch(f){throw new _(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,h.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 s=ht(o,r);if(ut(s))throw new _(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,h.USAGE);let a=await M(r),c=Me(a),l=_t(s,c),d=[],u=Bn();for(let f of Un)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(!i)try{for(let f of d)await pt("git",["config","--local",f.key,f.value],{cwd:o,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new _(`Cannot install repository-local merge drivers in ${o}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,h.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 Gn(o,l,i);return{ok:!0,dry_run:i,workspace_root:o,pm_root:r,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:X()}}import{execFile as ao}from"node:child_process";import{randomUUID as co}from"node:crypto";import{readdir as lo,readFile as Kn}from"node:fs/promises";import j from"node:path";import{promisify as uo}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]="59863597-bf57-5d96-9cba-983443e5b209")}catch{}})();var mo=uo(ao);async function gt(e){try{let{stdout:t}=await mo("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 Yn(e,t){let n=j.dirname(j.resolve(e,t));for(let i=0;i<12;i+=1){if(await N(j.join(n,"settings.json")))return n;let r=j.dirname(n);if(r===n)break;n=r}return null}function yt(e){return j.join(e,"merge-receipts")}function $e(e){return`${e}.json`}function fo(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,preferred:e.preferred,conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Hn(t.retained)??et(Qe(t.retained)),discarded_hash:Hn(t.discarded)??et(Qe(t.discarded))}))}}function Hn(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 bl(e){let t=await gt(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),i=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,r=j.basename(i,j.extname(i)),o={version:1,id:co(),item_path:i.replaceAll("\\","/"),item_id:r,preferred: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:X(),value_availability:"clone_local"};await Je(t),await ae(j.join(t,$e(o.id)),`${JSON.stringify(o,null,2)}
11
+ `);let s=await Yn(e.cwd,o.item_path);if(s!==null){let a=yt(s),c=fo(o),l={...o,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 Je(a),await ae(j.join(a,$e(o.id)),`${JSON.stringify(l,null,2)}
12
+ `)}return o}async function Vn(e,t){if(!await N(e))return[];let n;try{n=await lo(e)}catch{return[]}let i=[];for(let r of n.sort((o,s)=>o.localeCompare(s)))if(r.endsWith(".json"))try{let o=JSON.parse(await Kn(j.join(e,r),"utf8")),s={...o,conflict_resolution:o.conflict_resolution??"preferred_side"};s.version===1&&(t.includeReconciled||s.state==="pending")&&(t.includeLossless!==!1||s.decisions.length>0)&&i.push(s)}catch{}return i}async function wt(e,t={}){let n=await gt(e),i=n===null?[]:await Vn(n,t),r=t.pmRoot??j.join(e,".agents","pm"),o=await Vn(yt(r),t),s=new Map(o.map(a=>[a.id,a]));for(let a of i)s.set(a.id,a);return[...s.values()].sort((a,c)=>a.created_at.localeCompare(c.created_at))}function Jn(e){let t=[],n=[];for(let i of e)(Array.isArray(i.decisions)&&i.decisions.length>0?t:n).push(i);return{pendingDecisions:t,lossless:n}}async function vl(e,t){let n=await gt(e);if(n===null)return;await ae(j.join(n,$e(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:X()},null,2)}
13
+ `);let i=await Yn(e,t.item_path);if(i!==null){let r=j.join(yt(i),$e(t.id));if(await N(r)){let o=JSON.parse(await Kn(r,"utf8"));await ae(r,`${JSON.stringify({...o,state:"reconciled",reconciled_at:X()},null,2)}
14
+ `)}}}async function Rl(e){let t=await wt(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:X()}}import me from"node:fs/promises";import fe 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 po(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let o;try{o=await me.readdir(fe.join(e,r))}catch{return}for(let s of o)for(let a of Ht)if(s.toLowerCase().endsWith(a)){i.push({relativePath:`${r}/${s}`,id:s.slice(0,-a.length)});break}})),i.sort((r,o)=>r.relativePath.localeCompare(o.relativePath))}function ho(e,t){let{id:n,relativePath:i,liveItemIds:r,out:o}=e,s=it(t);if(s){o.conflictMarkers.push({id:n,path:i,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=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");a=d}catch{o.unparseable.push({id:n,path:i,line:l.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&r.has(n)&&o.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(o.repairReconciliations+=1))}function kt(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 _o(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await me.readdir(fe.join(e,"history"))}catch{return n}for(let r of i.sort((o,s)=>o.localeCompare(s))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await me.readFile(fe.join(e,"history",r),"utf8")}catch(s){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:kt("history stream",s)});continue}ho({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},o)}return n}function Xn(e){let t=it(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 go(e){let t=[],n=0,i=null;try{i=await qt(U(e))}catch(o){n+=1,t.push({path:"settings.json",detail:kt("configuration file",o)})}if(i!==null){n+=1;let o=Xn(i);o!==null&&t.push({path:"settings.json",detail:o})}let r;try{r=await me.readdir(fe.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of r.sort((s,a)=>s.localeCompare(a))){if(!o.endsWith(".json"))continue;n+=1;let s;try{s=await me.readFile(fe.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:kt("configuration file",c)});continue}let a=Xn(s);a!==null&&t.push({path:`schema/${o}`,detail:a})}return{scanned:n,unparseable:t}}async function Zn(e,t,n,i={}){let r=await po(e,n),o=new Set(r.map(u=>u.id)),s=new Map;for(let u of r){let m=s.get(u.id);m===void 0?s.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=fe.join(e,u.relativePath);return an(await me.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await _o(e,o),d=await go(e);return{item_files_on_disk:r.length,item_ids_on_disk:o.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,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 yo}from"node:child_process";import Qn 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 ei(e,t){return new Promise((n,i)=>{yo("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(r,o)=>{r?i(r):n(o)})})}function ti(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 Nl(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(ti(n),!n)throw new RangeError("Source line range must use start:end.");return n}function wo(e){let t=new Map;for(let n of e.split(`
15
+ `)){let i=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];i&&t.set(i,(t.get(i)??0)+1)}return t}function ko(e){let t=e.split("\0"),n=new Map;for(let i=0;i+1<t.length;i+=2){let r=t[i]?.trim();if(!r)continue;let o=[...new Set(t[i+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((s,a)=>s.localeCompare(a));n.set(r,o)}return n}async function bo(e){let t=Qn.relative(e.workspaceRoot,Qn.resolve(e.workspaceRoot,e.sourcePath)),n=await ei(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),i=await ei(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:wo(n),commitItems:ko(i),available:!0}}function vo(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,i;for(let r of e.graph.incidentEdges(t)){let o=r.source===t,s=o?r.target:r.source;if((e.visitedDepth.get(s)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(s,n);let a=e.graph.registry().require(r.kind),c={nodes:[...e.current.nodes,s],kinds:[...e.current.kinds,o?r.kind:a.inverse??r.kind]};e.details.get(s)?.type?.toLowerCase()==="decision"?(i=n,e.found.push(c)):e.queue.push(c)}return i}function Ro(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),i=[],r;for(;t.length>0;){let o=t.shift(),s=o.kinds.length;r!==void 0&&s>=r||s>=e.maxDepth||(r=vo({current:o,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:i})??r)}return i.sort((o,s)=>o.nodes.join("\0").localeCompare(s.nodes.join("\0"))),i}function So(e,t,n){let i=bn(t);if(!i.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let r=Ro({itemId:e,maxDepth:n,graph:i.graph,details:new Map(i.details.map(a=>[a.id,a]))}),o=r[0];if(!o)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let s=[...new Set(r.map(a=>a.nodes.at(-1)))];return{status:s.length===1?"found":"ambiguous",nodes:o.nodes,kinds:o.kinds,alternative_decision_ids:s.slice(1)}}async function xo(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await bo({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function Ao(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 Eo(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function ni(e){ti(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 xo(e),i=Eo(n),r=new Map;for(let o of e.candidates){let s=[...n.commitLines.entries()].filter(([d])=>n.commitItems.get(d)?.includes(o.item.id)),a=s.reduce((d,[,u])=>d+u,0),c=So(o.item.id,e.corpus,t),l=Ao({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});r.set(o.item.id,{score:a*100+o.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(o.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...o.files.map(d=>({kind:"linked_file",reference:d.path})),...s.map(([d,u])=>({kind:"git_commit",reference:d.slice(0,12),contribution_lines:u}))],rationale:{value:o.item.value?.trim()||null,why_now:o.item.why_now?.trim()||null,outcome:o.item.outcome?.trim()||null,objective:o.item.objective?.trim()||null},decision_path:c,ambiguities:l})}return{explanations:r,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:i.length,unmapped_commit_count:n.commitLines.size-i.length,decision_depth:t}}}import Nt from"node:fs/promises";import{realpathSync as Vs}from"node:fs";import{execFile as Ks}from"node:child_process";import $ from"node:path";import{promisify as Ys}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]="31d625d8-44be-5298-ab64-c17508ed07d0")}catch{}})();var Co=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 Io(e){if(typeof e!="string")return;let t=e.trim();for(let n of Co)if(t===n.code||t.startsWith(`${n.code}:`))return n}function To(e){let t={};for(let n of e){let i=Io(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function ii(e){return Object.values(To(e))}import pe from"node:fs/promises";import{createHash as Oo}from"node:crypto";import oi 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]="90364096-b94c-591c-9024-e697fa9322a5")}catch{}})();var si=3,Do="history-drift-cache.json";function ai(e){return oi.join(e,"runtime",Do)}async function Fo(e){try{let t=await pe.readFile(ai(e),"utf8"),n=JSON.parse(t);return n.version!==si||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}function ci(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function Po(e,t,n,i,r){let o=dn(e),s;try{s=await pe.stat(o)}catch(l){return ci(l,"ENOENT")||r.unreadableStreams.push(Z),!1}let a=r.missingStreams.length,c=await di({itemId:Z,historyPath:o,stat:s,cached:t[Z],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.chainOk||r.chainMismatches.push(Z),n[Z]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk},c.cacheDirty):(r.missingStreams.splice(a),c.cacheDirty)}function li(e){return Oo("sha256").update(e).digest("hex")}async function No(e){let t=await pe.readFile(e,"utf8");return li(t)}async function Lo(e){let t=await pe.readFile(e,"utf8"),n=li(t);if(t.trim().length===0)return null;let i=[],r=null;for(let o of t.split(/\r?\n/)){let s=o.trim();if(s.length===0)continue;let a=JSON.parse(s);if(typeof a.after_hash!="string"||a.after_hash.trim().length===0)throw new Error("missing after_hash");i.push(a),r=a.after_hash}return r?{latestAfterHash:r,chainOk:ln(i).ok,contentHash:n}:null}function Mo(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function ri(e,t,n){try{let i=await Lo(t);return i||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function di(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Mo(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await ri(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let i;if(e.verifyCacheHitByContent)try{i=await No(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else i=t;return!e.verifyCacheHitByContent||i===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:i},cacheDirty:!1}:{verification:await ri(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function ui(e,t,n={}){let i={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[]},o=(await Fo(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata";for(let u of t){let m=Vt(e,u.id),f;try{f=await pe.stat(m)}catch(S){ci(S,"ENOENT")?i.missingStreams.push(u.id):i.unreadableStreams.push(u.id);continue}let p=o[u.id],y=await di({itemId:u.id,historyPath:m,stat:f,cached:p,verifyCacheHitByContent:c,accumulator:i});if(a||=y.cacheDirty,!y.verification)continue;y.verification.chainOk||i.chainMismatches.push(u.id),s[u.id]={mtime_ms:f.mtimeMs,ctime_ms:f.ctimeMs,size:f.size,content_hash:y.verification.contentHash,latest_after_hash:y.verification.latestAfterHash,chain_ok:y.verification.chainOk};let{body:g,...w}=u;cn({metadata:w,body:g})!==y.verification.latestAfterHash&&i.hashMismatches.push(u.id)}let l=await Po(e,o,s,c,i);if(a||=l,a||Object.keys(o).length!==Object.keys(s).length){let u=ai(e);try{await pe.mkdir(oi.dirname(u),{recursive:!0}),await ae(u,JSON.stringify({version:si,entries:s}))}catch{}}let d=[...new Set([...i.missingStreams,...i.unreadableStreams,...i.hashMismatches,...i.chainMismatches])].sort((u,m)=>u.localeCompare(m));return{...i,driftedItems:d}}(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 $o=["metadata","resolution"],bt=["metadata","resolution","estimates","lifecycle"],jo="completed";function vt(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function mi(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function fi(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=mi(n.close_reason)??jo;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${vt(i)}`,gate:"resolution"})}return t}function pi(e){let t=[];for(let n of e){let i=mi(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${vt(i)}`,gate:"metadata"})}return t}function hi(e,t){return e.map(n=>{let i=mn(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function _i(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 gi(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=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 ${i} ${n.item_id} --remove ${vt(n.path)}`})}return t}function yi(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new _(`--fix-scope values must not be empty. Supported values: ${bt.join(", ")}.`,h.USAGE);return new Set($o)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(bt.includes(r)){n.add(r);continue}throw new _(`Unknown --fix-scope value "${i}". Supported values: ${bt.join(", ")}.`,h.USAGE)}return n}function wi(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function ve(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 Bo=/^([A-Z][A-Z0-9]*-\d+)\b/;function Uo(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=Bo.exec(t);return n?n[1]:null}function ki(e){return typeof e=="string"&&e.trim().length>0}function bi(e){let t=new Map;for(let i of e){if(typeof i.title!="string"||ki(i.duplicate_of))continue;let r=Uo(i.title);if(r===null)continue;let o=t.get(r);o||(o=[],t.set(r,o)),o.some(s=>s.id===i.id)||o.push({id:i.id,title:i.title,parent:ki(i.parent)?i.parent.trim():null})}let n=[];for(let[i,r]of t){if(r.length<2)continue;let o=new Set(r.map(c=>c.id.toLowerCase())),s=r.filter(c=>c.parent===null||!o.has(c.parent.toLowerCase()));if(s.length<2)continue;let a=[...s].sort((c,l)=>c.id.localeCompare(l.id));n.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return n.sort((i,r)=>i.code.localeCompare(r.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 vi(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,o)=>r.localeCompare(o))){let r=t.get(i),o={};for(let s of[...r.keys()].sort((a,c)=>a.localeCompare(c)))o[s]=r.get(s);n[i]=o}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 Ri=3;function Si(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function xi(e,t,n=Ri){let i=Number.isFinite(n)&&n>=1?Math.floor(n):Ri,r=new Map;for(let o of t){let s=Si(o);if(s.length===0)continue;let a=r.get(s);a?a.push(o):r.set(s,[o])}return e.map(o=>{let s=(r.get(Si(o))??[]).filter(a=>a!==o).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:o,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:o,classification:"moved",candidates:s.slice(0,i),candidates_truncated:s.length>i}})}function Ai(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 zo=/^[a-z][a-z0-9+.-]+:\/\//i;function Re(e){return zo.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 Go(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function Ei(e){return`${e.item_id} ${e.link_kind}`}function Ci(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=Go(r.classification,i.classification),r.owners.set(Ei(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[Ei(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(o=>{let s=t(o.item_id);return{id:o.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:o.link_kind}}).sort((o,s)=>{let a=o.id.localeCompare(s.id);return a!==0?a:o.field.localeCompare(s.field)})}))}function qo(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ii(e){let t=[];for(let n of e)for(let i of n.items)t.push(`${n.path}:${n.classification} owner=${i.id} status=${i.status} field=${i.field} title="${qo(i.title)}"`);return t}import{execFile as Wo}from"node:child_process";import{realpath as Ho}from"node:fs/promises";import Ti from"node:path";import{promisify as Vo}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 Ko=Vo(Wo),Yo=32*1024*1024,Jo=1e4,Xo=["search/eval-queries.json"];function Rt(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Zo(e){return`'${e.replaceAll("'","'\\''")}'`}async function Qo(e,t=Ho){return t(e).catch(()=>Ti.resolve(e))}async function Oi(e){let t=await be(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 Qo(e),i=Rt(Ti.relative(t,n));if(i.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let r=dt.map(o=>`${i}/${Rt(o)}`);try{let{stdout:o}=await Ko("git",["ls-files","-z","--",...r.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:Yo,windowsHide:!0,timeout:Jo}),s=new Set(Xo.map(l=>`${i}/${l}`)),a=[...new Set(o.split("\0").filter(l=>l.length>0&&!s.has(Rt(l))))].sort((l,d)=>l.localeCompare(d)),c=r.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>Zo(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import es from"node:fs/promises";import z from"node:path";import ts 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]="3fe80124-596b-591c-9f0d-fbbc129c6bb4")}catch{}})();var ns=["path","scope","note"],is=["pattern","glob","path","scope","note"],rs=["path"],os=["from","to"],ss=new Set(["note","scope"]);function Fi(e){let t=e??"project";if(!Ye.includes(t))throw new _(`Invalid scope "${e}". Valid scopes: ${Ye.join(", ")} (default: project).`,h.USAGE);return t}function Pi(e){return e.startsWith("```")||e.includes(`
16
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:gn(e)}function as(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Pi(n)||!n.includes(",")?[t]:wn(n)})}function cs(e,t){return e?as(e).map(n=>{let i=n.trim(),r=Pi(i)?ge(n,"--add"):{path:i};if(ye(r,"--add",ns),!r.path)throw new _(`--add requires path=<value> or a bare ${t} path`,h.USAGE);return{path:r.path,scope:Fi(r.scope),note:r.note?.trim()||void 0}}):[]}function ls(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--add-glob requires a glob pattern value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=ge(n,"--add-glob");ye(i,"--add-glob",is);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new _("--add-glob key/value form requires pattern=<glob>",h.USAGE);return{pattern:r,scope:Fi(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function ds(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--remove requires a path value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=ge(n,"--remove"),r=Object.keys(i).filter(o=>ss.has(o.toLowerCase()));if(r.length>0)throw new _(`--remove identifies a linked artifact by path only and does not accept ${r.map(o=>`"${o}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,h.USAGE);if(ye(i,"--remove",rs),!i.path)throw new _("--remove key/value form requires path=<value>",h.USAGE);return i.path}return n}):[]}function us(e){return e?e.map(t=>{let n=ge(t,"--migrate");ye(n,"--migrate",os);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new _("--migrate requires from=<value> and to=<value>",h.USAGE);return{from:i,to:r}}):[]}function St(e,t){let n=e;for(let i of t)n.startsWith(i.from)&&(n=`${i.to}${n.slice(i.from.length)}`);return n}function te(e){return e.split(z.sep).join("/")}function xt(e,t,n=process.cwd()){let i=e.trim();if(Re(i))return i;if(z.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return te(i.replaceAll("\\",z.sep));let r=z.relative(t,n);return r.startsWith(`..${z.sep}`)||r===".."||z.isAbsolute(r)?te(z.normalize(i)):te(z.relative(t,z.resolve(n,i)))}async function ms(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){let o=z.isAbsolute(r.pattern),s=await ts(r.pattern,{cwd:n,absolute:o,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>xt(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of a)i.push({path:c,scope:r.scope,note:r.note})}return i}function fs(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)",h.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function ps(e){return`${e.path}::${e.scope}`}function At(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function Et(e){return[...new Map(e.map(t=>[ps(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function hs(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),i=[],r=[],o=[],s=[];for(let a of n){if(Re(a)){s.push(a.trim());continue}let c=z.isAbsolute(a)?a:z.resolve(t,a);try{(await es.stat(c)).isFile()?i.push(a):o.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&l.code==="ENOENT"){r.push(a);continue}o.push(a)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:o,remote_references:s}}function _s(e,t,n,i){let r=0;for(let s=0;s<e.length;s+=1){let a=St(e[s].path,i);a!==e[s].path&&(e[s]={...e[s],path:a},r+=1)}return{adds:t.map(s=>{let a=St(s.path,i);return a!==s.path&&(r+=1),{...s,path:a}}),removes:n.map(s=>St(s,i)),count:r}}function gs(e,t,n,i){for(let o of t)e.some(s=>s.path===o.path&&s.scope===o.scope)||e.push(o);if(n.length>0)for(let o=e.length-1;o>=0;o-=1)n.includes(e[o].path)&&e.splice(o,1);let r=Et(e);return i?r:At(r)}async function Di(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 hs(t,e.workspaceRoot):void 0}}async function je(e,t,n,i){let{metadataKey:r}=i,o=yn(),s=B(process.cwd(),n.path),a=_e(s),c=process.cwd();if(!await N(U(s)))throw new _(`Tracker is not initialized at ${s}. Run pm init first.`,h.NOT_FOUND);let l=await M(s),d=V(l,J()),u=await o.resolveList(t.add,"--add"),m=await o.resolveList(t.addGlob,"--add-glob"),f=await o.resolveList(t.remove,"--remove"),p=await o.resolveList(t.migrate,"--migrate"),y=cs(u,i.bareNoun).map(P=>({...P,path:xt(P.path,a,c)})),g=ls(m),w=await ms(g,a,c),v=fs([...y,...w],t.note,y.length>0||g.length>0),S=ds(f).map(P=>xt(P,a,c)),x=us(p);if(!(v.length>0||S.length>0||x.length>0)){let P=await Ee(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!P)throw new _(`Item ${e} not found`,h.NOT_FOUND);let I=(await Ce(P,{schema:l.schema})).document.metadata[r]??[];return Di({id:P.id,artifacts:I,changed:!1,options:t,workspaceRoot:a})}let Y=de(t.author,l.author_default),W=await Te({pmRoot:s,settings:l,id:e,op:i.op,author:Y,message:t.message,force:t.force,skipNoop:!0,mutate(P){let b=P.metadata,I=b[r]??[],le=[...I],se=_s(le,v,S,x),Ke=gs(le,se.adds,se.removes,i.supportsAppendStable&&t.appendStable===!0);Ke.length>0?b[r]=Ke:delete b[r];let Bt=!Yt(I,Ke);return{changedFields:Bt?[r]:[],warnings:Bt&&se.count>0?[`path_migrations_applied:${se.count}`]:[]}}}),E=W.item[r]??[],F=W.warnings.find(P=>P.startsWith("path_migrations_applied:")),H=F?Number(F.slice(24)):0;return Di({id:W.item.id,artifacts:E,changed:W.changedFields.includes(r),migrationsApplied:H,options:t,workspaceRoot:a})}function Be(e,t){let n={};for(let[i,r]of Object.entries(e))n[i==="artifacts"?t:i]=r;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 Ni(e,t,n){let i=await je(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Be(i,"docs")}import Li from"node:fs/promises";import G 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 ys=32768;function Ct(e){return te(G.normalize(e))}async function Ue(e){try{return await Li.realpath(e)}catch{return G.resolve(e)}}function he(e,t){let n=G.isAbsolute(e.path)?G.resolve(e.path):G.resolve(t,e.path);return`${Ct(n)}::${e.scope}`}function ze(e,t,n){if(typeof e=="string"){let i=e.trim();i.length>0&&n.push({field:t,value:i});return}if(Array.isArray(e)){e.forEach((i,r)=>ze(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))ze(r,t?`${t}.${i}`:i,n)}function ws(e){let t=[];return ze(e.metadata,"metadata",t),ze(e.body,"body",t),t}function ks(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 bs(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,i=/(?:\.{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 r of e){let o=new Set,s=r.value.slice(0,ys);for(let[a,c]of[[n,r.value],[i,s]]){a.lastIndex=0;for(let l of c.matchAll(a)){let d=ks(l[0]);!d||o.has(d)||(o.add(d),t.push({field:r.field,value:d}))}}}return t}async function vs(e,t,n=t){let i=G.isAbsolute(e)?G.resolve(e):G.resolve(n,e),r;try{r=await Li.stat(i)}catch{return}if(!r.isFile())return;let[o,s]=await Promise.all([Ue(t),Ue(i)]);if(Xe(o,s)){let a=G.relative(o,s);return!a||a.startsWith("..")||G.isAbsolute(a)?void 0:{path:Ct(a),scope:"project"}}return{path:Ct(i),scope:"global"}}async function Rs(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>he(c,t))),r=new Map,o=bs(ws(e)),s=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{s.set(c,await vs(c,t,n))}));let a=o.map(c=>({reference:c,resolved:s.get(c.value)}));for(let{reference:c,resolved:l}of a){if(!l)continue;let d=he(l,t),u=r.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,r.set(d,u)}return[...r.entries()].map(([c,l])=>({path:l.path,scope:l.scope,status:i.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 Mi(e,t,n){let i=await je(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Be(i,"files")}async function Ss(e,t){let n=await Ue(t),i=await Promise.all(e.map(async o=>{let s=o.trim();if(!s)throw new _("Files lookup paths must not be empty.",h.USAGE);if(!G.isAbsolute(s))return te(s);let a=await Ue(s);return Xe(n,a)?te(G.relative(n,a)):te(a)})),r=[...new Set(i)].sort((o,s)=>o.localeCompare(s));if(r.length===0)throw new _("Files lookup requires at least one path.",h.USAGE);return r}function xs(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new _(`Files lookup ${i} must be a non-negative integer.`,h.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 $i(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function ji(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let i=t.item.updated_at.localeCompare(e.item.updated_at);return i===0?e.item.id.localeCompare(t.item.id):i}function As(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(te(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,i)=>{let r=n.path.localeCompare(i.path);return r===0?n.scope.localeCompare(i.scope):r})})).filter(t=>t.files.length>0).sort(ji)}async function Es(e){if(e.explain)return ni({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 Cs(e){if([e.strictRead,e.noTruncate,e.explain,en()].includes(!0))return null;let t=await hn(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?pn({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function Is(e){let t=[],n=await Ie(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),i=As({metadata:n,paths:e.paths,scope:e.scope}),r=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&r.length>0)throw new _(`Files lookup could not read every item: ${r.join("; ")}`,h.GENERIC_FAILURE);let o=await Es({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:i,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(o?[...i].sort((c,l)=>{let d=o.explanations.get(l.item.id).score-o.explanations.get(c.item.id).score;return d!==0?d:ji(c,l)}):i).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<i.length,truncated:e.offset+a.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:$i(c.item),files:c.files,...o?{traceability:o.explanations.get(c.item.id)}:{}})),...o?{traceability_receipt:o.receipt}:{}}}async function Wd(e,t){let n=B(process.cwd(),t.path),i=_e(n);if(!await N(U(n)))throw new _(`Tracker is not initialized at ${n}. Run pm init first.`,h.NOT_FOUND);let r=await Ss(e.paths,i);if(e.lineRange&&r.length!==1)throw new _("Files lookup line attribution requires exactly one source path.",h.USAGE);let o=await M(n),s=V(o,J()),{offset:a,limit:c}=xs(e),l=await Cs({pmRoot:n,typeToFolder:s.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return l?{paths:r,total:l.total,count:l.matches.length,offset:a,limit:c,has_more:a+l.matches.length<l.total,truncated:a+l.matches.length<l.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:l.matches.map(d=>({item:$i(d.item),files:d.files}))}:Is({pmRoot:n,settings:o,typeToFolder:s.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:i,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function Hd(e,t,n){let i=B(process.cwd(),n.path),r=_e(i);if(!await N(U(i)))throw new _(`Tracker is not initialized at ${i}. Run pm init first.`,h.NOT_FOUND);let o=await M(i),s=V(o,J()),a=await Ee(i,e,o.id_prefix,o.item_format,s.type_to_folder);if(!a)throw new _(`Item ${e} not found`,h.NOT_FOUND);let c=await Ce(a,{schema:o.schema}),l=await Rs(c.document,r,process.cwd()),d=l.filter(E=>E.status==="addable"),u=l.filter(E=>E.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let E=c.document.metadata.files??[];return{id:a.id,files:E,changed:!1,apply:m,count:E.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let p=de(t.author,o.author_default),y=d.map(E=>({path:E.path,scope:E.scope,note:f})),g=[],w=new Set,v=await Te({pmRoot:i,settings:o,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(E){let F=[...E.metadata.files??[]],H=new Set(F.map(I=>he(I,r)));g=[],w.clear();for(let[I,le]of y.entries()){let se=he(le,r);H.has(se)||(F.push(le),H.add(se),g.push(le),w.add(I))}let P=Et(F),b=t.appendStable?P:At(P);return b.length>0?E.metadata.files=b:delete E.metadata.files,{changedFields:g.length>0?["files"]:[],warnings:g.length!==y.length?[`files_discover_skipped_existing:${y.length-g.length}`]:[]}}}),S=v.item.files??[],x=new Set(g.map(E=>he(E,r))),A=S.filter(E=>x.has(he(E,r))),Y=d.filter((E,F)=>!w.has(F)),W=[...u,...Y];return{id:v.item.id,files:S,changed:A.length>0,apply:!0,count:S.length,candidate_count:l.length,addable_count:d.length,added_count:A.length,skipped_existing_count:W.length,candidates:l,added:A,skipped_existing:W}}import{readFileSync as Ts}from"node:fs";import Ge 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 Os=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),It=new Set(["--pm-path","--path","--author"]),Ds={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"])},Fs=new Set(["-p","--package"]),Ps=new Set(["-c","--call"]),Ns=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Ls=new Set(["-C","--prefix","--userconfig","--cache"]),Jd=new Set(["--cwd"]),Xd=new Set(["--cwd"]),Ms=new Set(["exec","x"]),Zd=new Set(["run","run-script"]),Qd=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function $s(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function js(e,t=process.cwd()){let n=Bs(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[i,...r]=n;if(Bi(i)||Ui(i,t))return r;if(i==="node"&&r[0]&&Ui(r[0],t))return r.slice(1);let o=i==="npx"||i==="bunx"?Tt(r):i==="pnpm"?Gs(r):i==="npm"?qs(r):null;return o&&(Bi(o.command)||zs(o.command))?o.args:null}var zi=(e,t="pm")=>{let n=t.trim().toLowerCase(),i=n.length;for(;i>0&&n[i-1]==="-";)i-=1;let r=n.slice(0,i);if(r.length===0)return[];let o=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of $s(o)){let c=js(a),l=c?Ws(c):null,d=l&&Os.has(l.subcommand)?Hs(l.remaining,Ds[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&s.add(d)}return[...s].sort((a,c)=>a.localeCompare(c))};function Bs(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 eu(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(It.has(n)){t+=2;continue}t+=1;continue}return n}}function Bi(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function Us(e){let t=e.trim();if(!t.startsWith("@")){let r=t.indexOf("@");return r===-1?t:t.slice(0,r)}let n=t.indexOf("/");if(n===-1)return t;let i=t.indexOf("@",n+1);return i===-1?t:t.slice(0,i)}function zs(e){let t=Us(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Ui(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 i=Ge.resolve(t,e);try{return JSON.parse(Ts(Ge.join(Ge.dirname(Ge.dirname(i)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Tt(e){let t=0;for(;t<e.length;){let i=e[t];if(i==="--"){t+=1;break}if(!i.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(i);if(r){let o=r[1];return o?{command:o,args:e.slice(t+1)}:null}if(Ps.has(i)){t+=1;break}t+=Fs.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Gi(e,t){let n=0;for(;n<e.length;){let i=e[n];if(i==="--"){n+=1;continue}if(i.startsWith("-")){if(i.includes("=")){n+=1;continue}if(t.has(i)){n+=2;continue}n+=1;continue}return{subcommand:i,args:e.slice(n+1)}}return null}function Gs(e){let t=Gi(e,Ns);return t?.subcommand!=="dlx"?null:Tt(t.args)}function qs(e){let t=Gi(e,Ls);return!t||!Ms.has(t.subcommand)?null:Tt(t.args)}function Ws(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(It.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Hs(e,t=new Set){for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")return e[n+1];if(!i.startsWith("-"))return i;!i.includes("=")&&(It.has(i)||t.has(i))&&(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]="896ffe11-2cf1-5de0-8d07-5585d4f30c94")}catch{}})();async function qi(e){return e.includeBody?_n(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema):Ie(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]="b5b7e497-f067-5504-9ffa-fd177997c518")}catch{}})();var Js=["src","tests","docs"],Xs=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],Zs=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),Qs=["resolution","expected_result","actual_result"],ea=["default","tracked-all","tracked-all-strict"],Wi=["core","strict","custom"],We=["off","warn","error"];var Dt=["author","acceptance_criteria","estimated_minutes","close_reason"],Ji=[...Dt,"reviewer","risk","confidence","sprint","release"],Lt=Array.from(new Set(Ji)),ta={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"},na={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"},ia={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"},ra={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"},oa={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"},sa=32*1024*1024,aa=1e4,Xi=40,ie=5,ca=4096,la=255,da=Ys(Ks);function Zi(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||(t[n]=typeof i=="object"&&i!==null?Zi(i):i);return t}function ua(e){return{...e,checks:e.checks.map(t=>({...t,details:Zi(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 ce(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Hi(e){return ce(e).replace(/\/+$/,"")}function q(e){let t=L(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Ve(e,t){return sn(e,t)??e}function Se(e,t){return t.terminal_statuses.has(Ve(e,t))}function re(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function qe(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function ma(e){let t=re(zt),n={blocked_reason:re(xe.blocked_reason),resolution:re(xe.resolution),actual_result:re(xe.actual_result)},i=re(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:re(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:re(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:re(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:qe(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:qe(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:qe(r.resolution,n.resolution)?"default":"settings",actual_result:qe(r.actual_result,n.actual_result)?"default":"settings"}}}function Qi(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Wi.includes(t))return t;throw new _(`Unknown --metadata-profile value "${e}". Supported values: ${Wi.join(", ")}.`,h.USAGE)}function er(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(We.includes(t))return t;throw new _(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${We.join(", ")}.`,h.USAGE)}function tr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(We.includes(t))return t;throw new _(`Unknown --parent-cycle-severity value "${e}". Supported values: ${We.join(", ")}.`,h.USAGE)}function fa(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>ta[n]).filter(n=>n!==void 0).sort((n,i)=>n.localeCompare(i))}function pa(e,t,n){let i=fa(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Dt],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Ji],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:i.length>0?{profile:e,profile_source:t,required_fields:i,configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Dt],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var ha=new Set(["acceptance_criteria","estimated_minutes"]);function nr(e,t,n,i){return!i&&ha.has(t)&&Se(e.status,n)?!1:t==="author"?!L(e.author):t==="acceptance_criteria"?!L(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ve(e.status,n)===n.close_status&&!L(e.close_reason):t==="reviewer"?!L(e.reviewer):t==="risk"?!L(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!L(e.confidence):t==="sprint"?!L(e.sprint):!L(e.release)}function ir(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: ${ea.join(", ")}.`,h.USAGE)}function rr(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return $.resolve(t);let n=$.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return $.dirname($.dirname(n));let r=$.resolve(process.cwd()),o=Vi(n),s=Vi(r),a=$.relative(o,s);return a.length===0||!a.startsWith("..")&&!$.isAbsolute(a)?n:r}function Vi(e){try{return Vs.native(e)}catch{return $.resolve(e)}}function or(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Mt(e,t,n){let i=t.length>0?$.join(e,t):e,r;try{r=await Nt.readdir(i,{withFileTypes:!0})}catch(o){if(or(o,["ENOENT"]))return;throw o}for(let o of r){if(o.name.startsWith("."))continue;let s=t.length>0?$.join(t,o.name):o.name;if(o.isDirectory()){if(Zs.has(o.name))continue;await Mt(e,s,n);continue}o.isFile()&&n.push(ce(s))}}async function Ft(e){let t=[];for(let n of Js)await Mt(e,n,t);for(let n of Xs){let i=$.join(e,n);try{(await Nt.stat(i)).isFile()&&t.push(ce(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function sr(e){try{let{stdout:t}=await da("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:sa,windowsHide:!0,timeout:aa}),n=t.split("\0").map(i=>ce(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function _a(e,t){let n=new Set,i=Hi(Ut);i.length>0&&n.add(i);let r=Hi($.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((o,s)=>o.localeCompare(s))}function Ki(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function ga(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await sr(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await Ft(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await Ft(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function D(e,t=ie){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function oe(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=D(e,Xi);return{values:n.values,truncated:n.truncated,total:e.length}}var ya={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},wa={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function ka(e){let t=e.missing_fields.map(n=>`${ya[n]} "${wa[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function ar(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(s=>typeof s=="string"):ii(t);if(r.length===0)return;let o=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...o?{fix_hints_truncated:!0}:{}}}function cr(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 ba="validate_metadata_duplicate_issue_codes";function lr(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:ie,i=e.slice(0,n);return{rows:i.map(o=>({code:o.code,count:o.count,ids:o.ids,titles:o.titles,remediation_hint:`Items ${o.ids.join(", ")} share issue code "${o.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${ba}:${e.length}`]}}function va(){return Object.fromEntries(Lt.map(e=>[e,[]]))}function Ra(e,t,n){let i=va();for(let r of e)for(let o of Lt)nr(r,o,t,n)&&i[o].push(r.id);return i}function Sa(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let o=t[r];o.length>0&&i.push(`${na[r]}:${o.length}`)}return i.push(...n),i}function dr(e,t){let n={};for(let i of e.required_fields){let r=t[i],o=r?r.length:0,s=ia[i];o>0&&s&&(n[s]=o)}return n}function ur(e,t,n){let i=[];for(let r of e.required_fields){let o=t[r];if(o)for(let s of o){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";i.push({item_type:c,field:r})}}return i}function xa(e,t,n,i){for(let r of t.required_fields){let o=n[r];if(!o||o.length===0)continue;let s=ra[r],a=oa[r];if(!s||!a)continue;let c=D(o,i?o.length:ie);e[s]=c.values,e[a]=c.truncated}}function mr(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:L(n.get(r)?.resolution)})):[]}function fr(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:L(n.get(r)?.type)})):[]}function Aa(e,t,n,i){let r=new Map(e.map(g=>[g.id,g])),o=t.profile==="strict",s=Ra(e,n,o),a=bi(e),c=lr(a,i),l=Sa(t,s,c.warnings),d=dr(t,s),u=ur(t,s,r),m=vi(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:[...Lt],counts:d,missing_by_type:m,duplicate_issue_codes_count:a.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]),xa(f,t,s,i);let p=mr(t,s,r),y=fr(t,s,r);return{check:{name:"metadata",status:l.length===0?"ok":"warn",details:f},warnings:l,closeReasonBackfillRows:p,estimateBackfillRows:y}}function Ea(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(m=>i.has(Ve(m.status,t))),o=[],s=[];for(let m of r){let f=Qs.filter(p=>!L(m[p]));f.length!==0&&(o.push({id:m.id,missing_fields:f}),s.push({id:m.id,missing_fields:f,close_reason:L(m.close_reason)}))}let a=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:ie,l=D(o.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=o.map(m=>ka(m)),u=D(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",details:{checked_closed_items:r.length,missing_resolution_items:o.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:a,resolutionBackfillRows:s}}function pr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hr(e,t="pm",n=Ze()){let i=new Set(e.map(o=>o.id)),r=[...e].sort((o,s)=>o.id.localeCompare(s.id));return new Map(r.map(o=>{let s=new Set,a=q(o.blocked_by);a&&i.has(a)&&s.add(a),(o.dependencies??[]).filter(l=>{let d=q(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>q(l.id)).filter(l=>l!==void 0&&i.has(l)).forEach(l=>s.add(l));let c=q(o.definition_of_ready);return gr(c??"",t).filter(l=>i.has(l)).forEach(l=>s.add(l)),[o.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function _r(e,t,n){let i=kn(e,n?d=>Se(d,n):void 0),r=i.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),o=i.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),s=t?Number.POSITIVE_INFINITY:ie,a=D(r,s),c=D(o,s),l=D(i.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>'`),s);return{check:{name:"dependency_references",status:r.length===0?"ok":"warn",details:{checked_items:e.length,dangling_reference_count:r.length+o.length,active_dangling_reference_count:r.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:o.length,legacy_closed_dangling_reference_count:i.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:i.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function gr(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${pr(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,o)=>r.localeCompare(o))}function $t(e){let t=0,n=new Map,i=new Map,r=[],o=new Set,s=[],a=d=>{n.set(d,t),i.set(d,t),t+=1,r.push(d),o.add(d);for(let m of e.get(d)??[])n.has(m)?o.has(m)&&i.set(d,Math.min(i.get(d),n.get(m))):(a(m),i.set(d,Math.min(i.get(d),i.get(m))));if(i.get(d)!==n.get(d))return;let u=[];for(;r.length>0;){let m=r.pop();if(o.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),s.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return s.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 jt(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],o=new Set([n]),s=a=>{let c=(t.get(a)??[]).filter(l=>i.has(l));for(let l of c){if(l===n&&r.length>1)return r.push(n),!0;if(!o.has(l)){if(o.add(l),r.push(l),s(l))return!0;r.pop(),o.delete(l)}}return!1};return s(n)?[...r]:[...e,n]}function yr(e,t="pm"){let n=hr(e,t),i=$t(n),r=[...new Set(i.flat())].sort((s,a)=>s.localeCompare(a)),o=i.map(s=>jt(s,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:o}}function wr(e,t=Ze()){let n=new Map(e.map(o=>[o.id.toLowerCase(),o.id])),i=new Map(e.map(o=>[o.id,[]]));return[...e].sort((o,s)=>o.id.localeCompare(s.id)).forEach(o=>{let s=i.get(o.id),a=q(o.parent),c=a?n.get(a.toLowerCase()):void 0;c&&s.push(c),(o.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"?i.get(u).push(o.id):s.push(u))})}),i.forEach((o,s)=>{i.set(s,[...new Set(o)].sort((a,c)=>a.localeCompare(c)))}),i}function kr(e){let t=wr(e),n=$t(t),i=[...new Set(n.flat())].sort((o,s)=>o.localeCompare(s)),r=n.map(o=>jt(o,t).join("->"));return{cycle_count:n.length,cycle_item_ids:i,cycle_sample_paths:r}}function br(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 He(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function vr(e,t){let n=He(e).split("/").filter(Boolean),i=He(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function Ca(e,t){let n=He(t),i=He(e),r=t.endsWith("/")?t:`${t}/`,o=e.startsWith(r),s=n.length>0&&n===i,a=vr(e,t);return!o&&!s&&a===0?null:o?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function Ia(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function Ta(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(o=>(i==="docs"?o.docs??[]:o.files??[]).map(s=>({item:o,link:s}))).forEach(({item:o,link:s})=>{if(s.scope!=="project")return;let a=ce(s.path);if(a.length===0||a===e)return;let c=Ca(e,a);c!==null&&Ia(r,o,c.score)&&(r={item:o,score:c.score,confidence:c.confidence})}),r?{id:r.item.id,type:r.item.type,title:r.item.title,status:r.item.status,confidence:r.confidence}:null}function Rr(e,t){return e.map(n=>{let i=br(n),r=i==="docs_unowned"?"docs":"files",o=Ta(n,i,t),s=o?.id??"<id>";return{path:n,classification:i,owner_candidate:o,remediation_hint:`pm ${r} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Sr(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function Oa(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=q(e[n]);return r?i.some(o=>r.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function Da(e,t,n,i,r){let o=q(t.parent),s=o?n.get(i.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!Se(s.status,r)}}function Fa(e,t,n,i){let r=q(e.blocked_by),o=q(e.blocked_reason),s=o?.toLowerCase(),a=Ve(e.status,n),c=[];return t.has(a)?(!r&&!o&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&i.stale_blocker_reason_patterns.some(l=>s.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function Pa(e,t,n,i){let r=new Map(e.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!Se(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=Oa(c,i);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=q(c.parent),u=d?r.get(o.get(d.toLowerCase())??d):void 0;if(u&&Se(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(Da(c,u,r,o,n))),t){let m=Fa(c,s,n,i);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,p)=>f.localeCompare(p))})}}return a}function Na(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 Yi(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function La(e,t,n,i,r,o){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=Yi("validate_lifecycle_dependency_cycles",n,r),c=Yi("validate_hierarchy_parent_cycle",i,o);return[...s,...a?[a]:[],...c?[c]:[]]}function xr(e){let t=ce(e);return t.length>ca||t.split(/[\\/]/).some(n=>n.length>la)}async function Ma(e,t){let n=$.isAbsolute(t)?t:$.resolve(e,t);if(xr(n))return!1;try{let i=await Nt.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return or(i,["ENOENT","ENOTDIR"])}}async function $a(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(o=>({item:r,artifact:o,link_kind:"files"})),...(r.docs??[]).map(o=>({item:r,artifact:o,link_kind:"docs"}))]);for(let{item:r,artifact:o,link_kind:s}of i){if(o.scope!=="project")continue;if(Re(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let a=ce(o.path);a.length!==0&&(n.linkedProjectPaths.add(a),await Ma(t,o.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:r.id,path:a,link_kind:s})))}return n}function ja(e,t,n,i,r,o){let s=i==="tracked-all-strict",a=s&&!r,c=r||s,l=c?[]:_a(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>Ki(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Ki(f,l)),m={};if(d.length>0){let f=oe(d,o);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function Ar(e,t,n,i,r,o,s,a="pm"){let c=Pa(e,t,r,o);Na(c);let l=yr(c.activeItems,a),d=kr(e),u=La(c,t,n,i,l.cycle_count,d.cycle_count),m=s?Number.POSITIVE_INFINITY:ie,f=D(c.closureLikeRows.map(A=>`${A.id}:${A.fields.join(",")}`),m),p=D(c.terminalParentRows.map(A=>`${A.id}:${A.parent_id}:${A.parent_status}`),m),y=D(c.staleBlockerRows.map(A=>`${A.id}:${A.status}:${A.reasons.join(",")}`),m),g=D(l.cycle_item_ids,m),w=D(l.cycle_sample_paths,m),v=D(d.cycle_item_ids,m),S=D(d.cycle_sample_paths,m);return{check:{name:"lifecycle",status:l.cycle_count>0&&n==="error"||d.cycle_count>0&&i==="error"?"error":u.length===0?"ok":"warn",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:p.values,active_terminal_parent_rows_truncated:p.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.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:g.values,dependency_cycle_item_ids_truncated:g.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:i,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:S.values,parent_cycle_sample_paths_truncated:S.truncated,stale_blocker_reason_patterns:[...o.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:o.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...o.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:o.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...o.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:o.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...o.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:o.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function Er(e,t,n,i,r,o){let s=await $a(e,t),a=new Map(e.map(b=>[b.id,b])),c=[...new Set(s.missingLinkedPaths)].sort((b,I)=>b.localeCompare(I)),l=await ga(t,i),d=ja(l,n,t,i,r,o),u=d.candidateFiles.filter(b=>!s.linkedProjectPaths.has(b)),m=Rr(u,e),f=xi(c,d.candidateFiles),p=new Map(f.map(b=>[b.path,b.classification])),y=f.filter(b=>b.classification==="moved").length,g=s.staleLinkRows.map(b=>({...b,classification:p.get(b.path)??"deleted"})).sort((b,I)=>b.item_id.localeCompare(I.item_id)||b.path.localeCompare(I.path)||b.link_kind.localeCompare(I.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=[...s.remoteLinkedPaths].sort((b,I)=>b.localeCompare(I)),S=oe(v,o),x=oe(c,o),A=oe(u,o),Y=oe(m.map(b=>`${b.path}:${b.classification}:owner_candidate=${b.owner_candidate?.id??"unowned"}`),o),W=o?m:oe(Sr(m),!1).values,E=oe(Ai(f),o),F=g.map(b=>({item_id:b.item_id,path:b.path,link_kind:b.link_kind,classification:b.classification})),H=Ci(F,b=>{let I=a.get(b);return I?{type:I.type,title:I.title,status:I.status}:void 0}),P=o?H:oe(Ii(H),!1).values;return{check:{name:"files",status:w.length===0?"ok":"warn",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:o?"full":"summary",file_list_summary_limit:Xi,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:r,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:s.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:S.total,remote_linked_paths:S.values,remote_linked_paths_truncated:S.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:y,missing_linked_paths_deleted_count:c.length-y,missing_linked_path_classifications:E.values,missing_linked_path_classifications_truncated:E.truncated,missing_linked_path_rows_count:H.length,missing_linked_path_rows:P,orphaned_paths_count:u.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.truncated,orphaned_path_classifications:Y.values,orphaned_path_classifications_truncated:Y.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:W}},warnings:w,staleLinkPruneRows:g}}async function Ba(e,t,n){let{missingStreams:i,unreadableStreams:r,hashMismatches:o,chainMismatches:s,driftedItems:a}=await ui(e,t),c=[];i.length>0&&c.push(`validate_history_drift_missing_streams:${i.length}`),r.length>0&&c.push(`validate_history_drift_unreadable_streams:${r.length}`),o.length>0&&c.push(`validate_history_drift_hash_mismatches:${o.length}`),s.length>0&&c.push(`validate_history_drift_chain_mismatches:${s.length}`);let l=n?Number.POSITIVE_INFINITY:ie,d=D(a,l);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,drifted_items_count:a.length,drifted_items:d.values,drifted_items_truncated:d.truncated,counts:{missing_streams:i.length,unreadable_streams:r.length,hash_mismatches:o.length,chain_mismatches:s.length}}},warnings:c}}function Ua(e,t,n){let i=n.trim().replaceAll(/\s+/g," "),r=i.length>120?`${i.slice(0,117)}...`:i;return`${e}:${t}:${r}`}function Cr(e,t,n){let i=new Set(e.map(g=>g.id.toLowerCase())),r=0,o=0,s=new Set,a=[],c=e.flatMap(g=>(g.tests??[]).map(w=>({item:g,linkedTest:w})));for(let{item:g,linkedTest:w}of c){if(typeof w.command!="string"||w.command.trim().length===0)continue;r+=1;let v=zi(w.command,t);if(v.length!==0){o+=v.length;for(let S of v)s.add(S),i.has(S.toLowerCase())||a.push(Ua(g.id,S,w.command))}}let l=[...new Set(a)].sort((g,w)=>g.localeCompare(w)),d=[...new Set(l.map(g=>g.split(":")[1]??""))].filter(g=>g.length>0).sort((g,w)=>g.localeCompare(w)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],m=n?Number.POSITIVE_INFINITY:ie,f=D(l,m),p=D(d,m),y=D([...s].sort((g,w)=>g.localeCompare(w)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",details:{checked_items:e.length,linked_commands_scanned:r,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:y.values,unique_referenced_pm_ids_truncated:y.truncated,stale_pm_id_references_count:l.length,stale_pm_ids_count:d.length,stale_pm_ids:p.values,stale_pm_ids_truncated:p.truncated,stale_pm_id_reference_rows:f.values,stale_pm_id_reference_rows_truncated:f.truncated}},warnings:u}}function za(e,t){let n=on(e.map(c=>({ref:c.id,version:rn(c)}))),i=[];n.outdated.length>0&&i.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&i.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:ie,o=D(n.outdated,r),s=D(n.ahead,r);return{check:{name:"format_version",status:n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok",details:{checked_items:e.length,current_format_version:nn,outdated_items_count:n.outdated.length,outdated_items:o.values,outdated_items_truncated:o.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:i}}var Pt="pm validate auto-fix";async function Ir(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:Pt};if(e.kind==="set_resolution"?i.resolution=e.value:e.kind==="set_close_reason"?i.closeReason=e.value:e.kind==="set_estimate"?i.estimatedMinutes=e.value:e.kind==="reparent"?i.parent=e.parent_id:i.unset=["parent"],!n.runUpdate)throw new _("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",h.USAGE);await n.runUpdate(e.item_id,i,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 Ot(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Tr(e,t,n){let i=[],r=[],o=new Map;for(let s of e.filter(a=>Ot(a)===null))try{await Ir(s,t,n),i.push(s)}catch(a){r.push({fix:s,error:a})}for(let s of e.filter(a=>Ot(a)!==null)){let a=Ot(s),c=o.get(a);c?c.push(s):o.set(a,[s])}for(let s of o.values()){let a=s[0];if(!a)continue;let c=s.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await Mi(a.item_id,{remove:c,message:Pt},t):await Ni(a.item_id,{remove:c,message:Pt},t),i.push(...s)}catch(l){r.push(...s.map(d=>({fix:d,error:l})))}}return{applied:i,failed:r}}var zu={applyValidateFix:Ir,applyValidateFixes:Tr,attachValidateFixHints:ar,buildCommandReferencesCheck:Cr,buildDependencyReferencesCheck:_r,buildCloseReasonBackfillRows:mr,buildFilesCheck:Er,buildLifecycleCheck:Ar,buildLifecycleDependencyGraph:hr,buildLifecycleParentGraph:wr,buildEstimateBackfillRows:fr,buildMetadataCounts:dr,buildMissingFieldOccurrences:ur,buildOrphanedPathRows:Rr,classifyOrphanedPath:br,collectDefaultProjectFileCandidates:Ft,collectTrackedGitFileCandidates:sr,detectLifecycleDependencyCycles:yr,detectLifecycleParentCycles:kr,escapeRegExp:pr,extractItemIds:gr,findLifecycleDependencyCycleComponents:$t,isMetadataFieldMissing:nr,linkedArtifactPathExceedsFilesystemLimits:xr,listFilesRecursive:Mt,resolveDependencyCycleSeverity:er,resolveParentCycleSeverity:tr,resolveFileScanMode:ir,resolveLifecycleDependencyCycleSamplePath:jt,resolveRequestedChecks:cr,resolveValidateMetadataProfile:Qi,resolveWorkspaceRoot:rr,sharedDirectoryPrefixLength:vr,summarizeOrphanedPathRows:Sr,summarizeDuplicateIssueCodes:lr,toMeaningfulString:q};async function Ga(e,t,n,i){let r=await Zn(e,new Set(t.map(p=>p.id)),n,{schema:i.schema,extensionFieldNames:Gt(J())}),o=[];r.unreadable_item_files.length>0&&o.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&o.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&o.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&o.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&o.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&o.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let s=o.length,a=await Oi(e);a.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await qn(e,Me(i));c.status==="drift"&&o.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await be(e),d=l===null?null:await Wn(l);d!==null&&d.status!=="ok"&&o.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await wt(l,{includeLossless:!0,pmRoot:e}),{pendingDecisions:m,lossless:f}=Jn(u);return m.length>0&&o.push(`validate_merge_decisions_unreviewed:${m.length}`),{check:{name:"storage_integrity",status:s>0?"error":o.length>0?"warn":"ok",details:{...r,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:m.length,pending_merge_decision_items:[...new Set(m.map(p=>p.item_id))].sort((p,y)=>p.localeCompare(y)),lossless_merge_receipt_count:f.length,lossless_merge_receipt_items:[...new Set(f.map(p=>p.item_id))].sort((p,y)=>p.localeCompare(y)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:o}}function ne(e,t,n){n&&ar(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function qa(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,i=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let r=Aa(e.items,e.metadataPolicy,e.statusRegistry,i);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows,ne(t,r,n)}if(e.requestedChecks.has("resolution")){let r=Ea(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,ne(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=Ar(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,ne(t,r,n),ne(t,_r(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await Er(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=r.staleLinkPruneRows,ne(t,r,n)}return e.requestedChecks.has("command_references")&&ne(t,Cr(e.items,e.settings.id_prefix,i),n),e.requestedChecks.has("history_drift")&&ne(t,await Ba(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&ne(t,za(e.items,i),n),e.requestedChecks.has("storage_integrity")&&ne(t,await Ga(e.pmRoot,e.items,V(e.settings,J()).type_to_folder,e.settings),n),t}function Wa(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...pi(t.closeReasonBackfillRows)),i.push(...fi(t.resolutionBackfillRows)),i.push(...hi(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(..._i(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...gi(t.staleLinkPruneRows)),i}async function Ha(e,t,n,i,r,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=Wa(e,t,n),{applicable:a,gated:c}=wi(s,i),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await Tr(a,r,o);d.push(...m.applied.map(ve)),u.push(...m.failed.map(({fix:f,error:p})=>({...ve(f),error:p instanceof Error?p.message:String(p)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...i].sort((m,f)=>m.localeCompare(f)),planned_count:s.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(ve),applied_fixes:d,gated_fixes:c.map(m=>({...ve(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function Gu(e,t,n={}){Qt(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new _("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",h.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new _("--fix-scope requires --auto-fix.",h.USAGE);let r=yi(e.fixScope),o=B(process.cwd(),t.path);if(!await N(U(o)))throw new _(`Tracker is not initialized at ${o}. Run pm init first.`,h.NOT_FOUND);let s=await M(o),a=Zt(s.schema),c=V(s,J()),l=cr(e),d=[],u=await qi({includeBody:l.has("history_drift"),pmRoot:o,settings:s,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let F=await ct(o);F.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${F.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",f=Qi(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),p=pa(f,m,s.validation.metadata_required_fields),y=ma(s),g=er(e.dependencyCycleSeverity),w=tr(e.parentCycleSeverity),v=ir(e.scanMode),S=rr(o),x=await qa({requestedChecks:l,options:e,global:t,pmRoot:o,workspaceRoot:S,settings:s,items:u,statusRegistry:a,metadataPolicy:p,lifecyclePatternPolicy:y,dependencyCycleSeverity:g,parentCycleSeverity:w,fileScanMode:v,initialWarnings:[...new Set(d)]}),A=i?await Ha(e,x,s,r,t,n):void 0,Y=[...new Set(x.warnings)].sort((F,H)=>F.localeCompare(H)),E={ok:!x.checks.some(F=>F.status==="error"),has_warnings:Y.length>0,checks:x.checks,warnings:Y,...A!==void 0?{fixes:A}:{},generated_at:X(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?E:{...ua(E),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{Wc as a,ui as b,To as c,R as d,T as e,Fr as f,gc as g,yc as h,wc as i,An as j,kc as k,bc as l,vc as m,Rc as n,Sc as o,at as p,xc as q,Ac as r,st as s,Ec as t,Cc as u,En as v,Ic as w,Ur as x,In as y,$c as z,ct as A,Wr as B,Hr as C,jc as D,Vr as E,Zr as F,Qr as G,Ne as H,jn as I,ue as J,ft as K,ro as L,be as M,_t as N,Me as O,qn as P,Wn as Q,dl as R,ul as S,so as T,Oi as U,fo as V,bl as W,wt as X,Jn as Y,vl as Z,Rl as _,Zn as $,Ni as aa,Nl as ba,ni as ca,Mi as da,Wd as ea,Hd as fa,Ns as ga,Ls as ha,Jd as ia,Xd as ja,Zd as ka,Qd as la,$s as ma,js as na,Bs as oa,eu as pa,Bi as qa,zs as ra,Ui as sa,Tt as ta,Gi as ua,Gs as va,qs as wa,Ws as xa,ua as ya,zu as za,Gu as Aa};
17
+ //# sourceMappingURL=chunk-VABB4L5Y.js.map