@unbrained/pm-cli 2026.12.1 → 2026.12.2

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 (267) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli-bundle/bundle-manifest.json +1 -1
  3. package/dist/cli-bundle/chunks/{chunk-CWPR234D.js → chunk-7NAO7I75.js} +2 -2
  4. package/dist/cli-bundle/chunks/{chunk-4YQMQOUO.js → chunk-7V65VACG.js} +52 -52
  5. package/dist/cli-bundle/chunks/{chunk-NA6D75V5.js → chunk-G6TARHFK.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-YSVOXCYH.js → chunk-GOEQXVOI.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-OKEJ4U2I.js → chunk-ROTEELDL.js} +3 -3
  8. package/dist/cli-bundle/chunks/{chunk-U7RBJGLF.js → chunk-SDXCJZKB.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-XME6GIFQ.js → chunk-TKUG2X24.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-Q6GLSAJY.js → chunk-UNBW2LF3.js} +2 -2
  11. package/dist/cli-bundle/chunks/chunk-V2S4XAX3.js +2 -0
  12. package/dist/cli-bundle/chunks/{item-transaction-66RDV7PH.js → item-transaction-56J5OCHA.js} +2 -2
  13. package/dist/cli-bundle/chunks/{linked-resource-value-list-E2DX52LY.js → linked-resource-value-list-ZBIY4H23.js} +2 -2
  14. package/dist/cli-bundle/chunks/{register-mutation-2F6JUBST.js → register-mutation-EK6DVIQK.js} +2 -2
  15. package/dist/cli-bundle/chunks/{register-operations-ET3UKPYK.js → register-operations-6MURXE4V.js} +2 -2
  16. package/dist/cli-bundle/chunks/{register-setup-I63QTFCU.js → register-setup-RW26X3GJ.js} +2 -2
  17. package/dist/cli-bundle/focused-chunks/{chunk-SQ72CVUH.js → chunk-3COWDIPX.js} +54 -54
  18. package/dist/cli-bundle/focused-chunks/{chunk-PT7RT3T6.js → chunk-J72TRWR5.js} +3 -3
  19. package/dist/cli-bundle/focused-chunks/{item-transaction-2K4SFLJ7.js → item-transaction-LQLQLZE7.js} +2 -2
  20. package/dist/cli-bundle/main.js +3 -3
  21. package/dist/cli-bundle/sdk-core.js +1 -1
  22. package/dist/cli-bundle/sdk-governance.js +1 -1
  23. package/dist/cli-bundle/sdk-merge.js +1 -1
  24. package/dist/cli-bundle/sdk-runtime.js +1 -1
  25. package/dist/cli-bundle/sdk-testing.js +1 -1
  26. package/dist/cli-bundle/sdk.js +1 -1
  27. package/dist/sdk/extension/install-sources.d.ts +2 -2
  28. package/dist/sdk/extension/install-sources.js +5 -5
  29. package/marketplace.json +1 -1
  30. package/node_modules/tar/README.md +1792 -1147
  31. package/node_modules/tar/dist/commonjs/bytes.d.ts +21 -0
  32. package/node_modules/tar/dist/commonjs/bytes.js +83 -0
  33. package/node_modules/tar/dist/commonjs/codec.d.ts +53 -0
  34. package/node_modules/tar/dist/commonjs/codec.js +35 -0
  35. package/node_modules/tar/dist/commonjs/concat.d.ts +3 -0
  36. package/node_modules/tar/dist/commonjs/concat.js +20 -0
  37. package/node_modules/tar/dist/commonjs/create.d.ts +39 -2
  38. package/node_modules/tar/dist/commonjs/create.js +150 -64
  39. package/node_modules/tar/dist/commonjs/dealias.d.ts +79 -0
  40. package/node_modules/tar/dist/commonjs/dealias.js +50 -0
  41. package/node_modules/tar/dist/commonjs/delete.d.ts +19 -0
  42. package/node_modules/tar/dist/commonjs/delete.js +121 -0
  43. package/node_modules/tar/dist/commonjs/entries.d.ts +82 -0
  44. package/node_modules/tar/dist/commonjs/entries.js +398 -0
  45. package/node_modules/tar/dist/commonjs/extract.d.ts +14 -2
  46. package/node_modules/tar/dist/commonjs/extract.js +40 -81
  47. package/node_modules/tar/dist/commonjs/fs.d.ts +201 -0
  48. package/node_modules/tar/dist/commonjs/fs.js +5 -0
  49. package/node_modules/tar/dist/commonjs/header.d.ts +4 -4
  50. package/node_modules/tar/dist/commonjs/header.js +71 -53
  51. package/node_modules/tar/dist/commonjs/index.d.ts +25 -18
  52. package/node_modules/tar/dist/commonjs/index.js +46 -18
  53. package/node_modules/tar/dist/commonjs/index.min.js +2 -3
  54. package/node_modules/tar/dist/commonjs/large-numbers.d.ts +2 -2
  55. package/node_modules/tar/dist/commonjs/large-numbers.js +4 -4
  56. package/node_modules/tar/dist/commonjs/list.d.ts +23 -6
  57. package/node_modules/tar/dist/commonjs/list.js +99 -138
  58. package/node_modules/tar/dist/commonjs/mkdir.d.ts +16 -11
  59. package/node_modules/tar/dist/commonjs/mkdir.js +121 -159
  60. package/node_modules/tar/dist/commonjs/normalize-unicode.js +9 -0
  61. package/node_modules/tar/dist/commonjs/options.d.ts +284 -513
  62. package/node_modules/tar/dist/commonjs/options.js +20 -61
  63. package/node_modules/tar/dist/commonjs/pack.d.ts +150 -96
  64. package/node_modules/tar/dist/commonjs/pack.js +752 -445
  65. package/node_modules/tar/dist/commonjs/parser.d.ts +98 -0
  66. package/node_modules/tar/dist/commonjs/parser.js +452 -0
  67. package/node_modules/tar/dist/commonjs/path-reservations.d.ts +17 -7
  68. package/node_modules/tar/dist/commonjs/path-reservations.js +110 -140
  69. package/node_modules/tar/dist/commonjs/path.d.ts +19 -0
  70. package/node_modules/tar/dist/commonjs/path.js +90 -0
  71. package/node_modules/tar/dist/commonjs/pax.d.ts +3 -1
  72. package/node_modules/tar/dist/commonjs/pax.js +67 -36
  73. package/node_modules/tar/dist/commonjs/read-entry.d.ts +97 -11
  74. package/node_modules/tar/dist/commonjs/read-entry.js +251 -97
  75. package/node_modules/tar/dist/commonjs/read-file.d.ts +22 -0
  76. package/node_modules/tar/dist/commonjs/read-file.js +104 -0
  77. package/node_modules/tar/dist/commonjs/replace.d.ts +45 -1
  78. package/node_modules/tar/dist/commonjs/replace.js +164 -211
  79. package/node_modules/tar/dist/commonjs/server/codecs.d.ts +38 -0
  80. package/node_modules/tar/dist/commonjs/server/codecs.js +252 -0
  81. package/node_modules/tar/dist/commonjs/server/index.d.ts +115 -0
  82. package/node_modules/tar/dist/commonjs/server/index.js +166 -0
  83. package/node_modules/tar/dist/commonjs/server/index.min.js +3 -0
  84. package/node_modules/tar/dist/commonjs/strip-absolute-path.d.ts +8 -0
  85. package/node_modules/tar/dist/commonjs/strip-absolute-path.js +17 -20
  86. package/node_modules/tar/dist/commonjs/to-stream.d.ts +7 -0
  87. package/node_modules/tar/dist/commonjs/to-stream.js +22 -0
  88. package/node_modules/tar/dist/commonjs/types.d.ts +4 -3
  89. package/node_modules/tar/dist/commonjs/types.js +4 -3
  90. package/node_modules/tar/dist/commonjs/unpack.d.ts +143 -89
  91. package/node_modules/tar/dist/commonjs/unpack.js +780 -725
  92. package/node_modules/tar/dist/commonjs/update.d.ts +11 -1
  93. package/node_modules/tar/dist/commonjs/update.js +37 -28
  94. package/node_modules/tar/dist/commonjs/warn.d.ts +27 -0
  95. package/node_modules/tar/dist/commonjs/warn.js +36 -0
  96. package/node_modules/tar/dist/commonjs/win32-path.d.ts +16 -0
  97. package/node_modules/tar/dist/commonjs/win32-path.js +67 -0
  98. package/node_modules/tar/dist/commonjs/write-entry.d.ts +64 -111
  99. package/node_modules/tar/dist/commonjs/write-entry.js +108 -672
  100. package/node_modules/tar/dist/commonjs/write-flag.d.ts +18 -0
  101. package/node_modules/tar/dist/commonjs/write-flag.js +29 -0
  102. package/node_modules/tar/dist/esm/bytes.d.ts +21 -0
  103. package/node_modules/tar/dist/esm/bytes.js +72 -0
  104. package/node_modules/tar/dist/esm/codec.d.ts +53 -0
  105. package/node_modules/tar/dist/esm/codec.js +32 -0
  106. package/node_modules/tar/dist/esm/concat.d.ts +3 -0
  107. package/node_modules/tar/dist/esm/concat.js +16 -0
  108. package/node_modules/tar/dist/esm/create.d.ts +39 -2
  109. package/node_modules/tar/dist/esm/create.js +144 -61
  110. package/node_modules/tar/dist/esm/dealias.d.ts +79 -0
  111. package/node_modules/tar/dist/esm/dealias.js +46 -0
  112. package/node_modules/tar/dist/esm/delete.d.ts +19 -0
  113. package/node_modules/tar/dist/esm/delete.js +117 -0
  114. package/node_modules/tar/dist/esm/entries.d.ts +82 -0
  115. package/node_modules/tar/dist/esm/entries.js +388 -0
  116. package/node_modules/tar/dist/esm/extract.d.ts +14 -2
  117. package/node_modules/tar/dist/esm/extract.js +37 -44
  118. package/node_modules/tar/dist/esm/fs.d.ts +201 -0
  119. package/node_modules/tar/dist/esm/fs.js +4 -0
  120. package/node_modules/tar/dist/esm/header.d.ts +4 -4
  121. package/node_modules/tar/dist/esm/header.js +71 -53
  122. package/node_modules/tar/dist/esm/index.d.ts +25 -18
  123. package/node_modules/tar/dist/esm/index.js +23 -18
  124. package/node_modules/tar/dist/esm/index.min.js +2 -3
  125. package/node_modules/tar/dist/esm/large-numbers.d.ts +2 -2
  126. package/node_modules/tar/dist/esm/large-numbers.js +4 -4
  127. package/node_modules/tar/dist/esm/list.d.ts +23 -6
  128. package/node_modules/tar/dist/esm/list.js +96 -101
  129. package/node_modules/tar/dist/esm/mkdir.d.ts +16 -11
  130. package/node_modules/tar/dist/esm/mkdir.js +119 -154
  131. package/node_modules/tar/dist/esm/normalize-unicode.js +9 -0
  132. package/node_modules/tar/dist/esm/options.d.ts +284 -513
  133. package/node_modules/tar/dist/esm/options.js +17 -51
  134. package/node_modules/tar/dist/esm/pack.d.ts +150 -96
  135. package/node_modules/tar/dist/esm/pack.js +750 -441
  136. package/node_modules/tar/dist/esm/parser.d.ts +98 -0
  137. package/node_modules/tar/dist/esm/parser.js +448 -0
  138. package/node_modules/tar/dist/esm/path-reservations.d.ts +17 -7
  139. package/node_modules/tar/dist/esm/path-reservations.js +110 -140
  140. package/node_modules/tar/dist/esm/path.d.ts +19 -0
  141. package/node_modules/tar/dist/esm/path.js +80 -0
  142. package/node_modules/tar/dist/esm/pax.d.ts +3 -1
  143. package/node_modules/tar/dist/esm/pax.js +66 -35
  144. package/node_modules/tar/dist/esm/read-entry.d.ts +97 -11
  145. package/node_modules/tar/dist/esm/read-entry.js +248 -96
  146. package/node_modules/tar/dist/esm/read-file.d.ts +22 -0
  147. package/node_modules/tar/dist/esm/read-file.js +99 -0
  148. package/node_modules/tar/dist/esm/replace.d.ts +45 -1
  149. package/node_modules/tar/dist/esm/replace.js +160 -207
  150. package/node_modules/tar/dist/esm/server/codecs.d.ts +38 -0
  151. package/node_modules/tar/dist/esm/server/codecs.js +214 -0
  152. package/node_modules/tar/dist/esm/server/index.d.ts +115 -0
  153. package/node_modules/tar/dist/esm/server/index.js +102 -0
  154. package/node_modules/tar/dist/esm/server/index.min.js +3 -0
  155. package/node_modules/tar/dist/esm/strip-absolute-path.d.ts +8 -0
  156. package/node_modules/tar/dist/esm/strip-absolute-path.js +17 -20
  157. package/node_modules/tar/dist/esm/to-stream.d.ts +7 -0
  158. package/node_modules/tar/dist/esm/to-stream.js +18 -0
  159. package/node_modules/tar/dist/esm/types.d.ts +4 -3
  160. package/node_modules/tar/dist/esm/types.js +4 -3
  161. package/node_modules/tar/dist/esm/unpack.d.ts +143 -89
  162. package/node_modules/tar/dist/esm/unpack.js +776 -719
  163. package/node_modules/tar/dist/esm/update.d.ts +11 -1
  164. package/node_modules/tar/dist/esm/update.js +35 -28
  165. package/node_modules/tar/dist/esm/warn.d.ts +27 -0
  166. package/node_modules/tar/dist/esm/warn.js +31 -0
  167. package/node_modules/tar/dist/esm/win32-path.d.ts +16 -0
  168. package/node_modules/tar/dist/esm/win32-path.js +60 -0
  169. package/node_modules/tar/dist/esm/write-entry.d.ts +64 -111
  170. package/node_modules/tar/dist/esm/write-entry.js +107 -633
  171. package/node_modules/tar/dist/esm/write-flag.d.ts +18 -0
  172. package/node_modules/tar/dist/esm/write-flag.js +25 -0
  173. package/node_modules/tar/package.json +68 -224
  174. package/package.json +2 -2
  175. package/packages/pm-beads/package.json +1 -1
  176. package/packages/pm-calendar/package.json +1 -1
  177. package/packages/pm-command-kit/package.json +1 -1
  178. package/packages/pm-digital-twin/package.json +1 -1
  179. package/packages/pm-governance-audit/package.json +1 -1
  180. package/packages/pm-guide-shell/package.json +1 -1
  181. package/packages/pm-kanban/package.json +1 -1
  182. package/packages/pm-lifecycle-hooks/package.json +1 -1
  183. package/packages/pm-linked-test-adapters/package.json +1 -1
  184. package/packages/pm-search-advanced/package.json +1 -1
  185. package/packages/pm-templates/package.json +1 -1
  186. package/packages/pm-todos/package.json +1 -1
  187. package/packages/pm-vcs/package.json +1 -1
  188. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  189. package/plugins/pm-claude/package.json +1 -1
  190. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  191. package/plugins/pm-codex/package.json +1 -1
  192. package/plugins/pm-codex/plugin.json +1 -1
  193. package/runtime-dependencies.json +1 -1
  194. package/dist/cli-bundle/chunks/chunk-AJLU6KLW.js +0 -2
  195. package/node_modules/@isaacs/fs-minipass/LICENSE +0 -15
  196. package/node_modules/@isaacs/fs-minipass/README.md +0 -71
  197. package/node_modules/@isaacs/fs-minipass/dist/commonjs/index.d.ts +0 -118
  198. package/node_modules/@isaacs/fs-minipass/dist/commonjs/index.js +0 -430
  199. package/node_modules/@isaacs/fs-minipass/dist/commonjs/package.json +0 -3
  200. package/node_modules/@isaacs/fs-minipass/dist/esm/index.d.ts +0 -118
  201. package/node_modules/@isaacs/fs-minipass/dist/esm/index.js +0 -420
  202. package/node_modules/@isaacs/fs-minipass/dist/esm/package.json +0 -3
  203. package/node_modules/@isaacs/fs-minipass/package.json +0 -72
  204. package/node_modules/chownr/LICENSE.md +0 -63
  205. package/node_modules/chownr/README.md +0 -3
  206. package/node_modules/chownr/dist/commonjs/index.d.ts +0 -3
  207. package/node_modules/chownr/dist/commonjs/index.js +0 -93
  208. package/node_modules/chownr/dist/commonjs/package.json +0 -3
  209. package/node_modules/chownr/dist/esm/index.d.ts +0 -3
  210. package/node_modules/chownr/dist/esm/index.js +0 -85
  211. package/node_modules/chownr/dist/esm/package.json +0 -3
  212. package/node_modules/chownr/package.json +0 -69
  213. package/node_modules/minipass/LICENSE.md +0 -55
  214. package/node_modules/minipass/README.md +0 -825
  215. package/node_modules/minipass/dist/commonjs/index.d.ts +0 -545
  216. package/node_modules/minipass/dist/commonjs/index.js +0 -1038
  217. package/node_modules/minipass/dist/commonjs/package.json +0 -3
  218. package/node_modules/minipass/dist/esm/index.d.ts +0 -545
  219. package/node_modules/minipass/dist/esm/index.js +0 -1020
  220. package/node_modules/minipass/dist/esm/package.json +0 -3
  221. package/node_modules/minipass/package.json +0 -77
  222. package/node_modules/minizlib/LICENSE +0 -26
  223. package/node_modules/minizlib/README.md +0 -64
  224. package/node_modules/minizlib/dist/commonjs/constants.d.ts +0 -2
  225. package/node_modules/minizlib/dist/commonjs/constants.js +0 -123
  226. package/node_modules/minizlib/dist/commonjs/index.d.ts +0 -99
  227. package/node_modules/minizlib/dist/commonjs/index.js +0 -416
  228. package/node_modules/minizlib/dist/commonjs/package.json +0 -3
  229. package/node_modules/minizlib/dist/esm/constants.d.ts +0 -2
  230. package/node_modules/minizlib/dist/esm/constants.js +0 -117
  231. package/node_modules/minizlib/dist/esm/index.d.ts +0 -99
  232. package/node_modules/minizlib/dist/esm/index.js +0 -363
  233. package/node_modules/minizlib/dist/esm/package.json +0 -3
  234. package/node_modules/minizlib/package.json +0 -80
  235. package/node_modules/tar/dist/commonjs/get-write-flag.d.ts +0 -2
  236. package/node_modules/tar/dist/commonjs/get-write-flag.js +0 -32
  237. package/node_modules/tar/dist/commonjs/make-command.d.ts +0 -49
  238. package/node_modules/tar/dist/commonjs/make-command.js +0 -52
  239. package/node_modules/tar/dist/commonjs/normalize-windows-path.d.ts +0 -2
  240. package/node_modules/tar/dist/commonjs/normalize-windows-path.js +0 -12
  241. package/node_modules/tar/dist/commonjs/parse.d.ts +0 -92
  242. package/node_modules/tar/dist/commonjs/parse.js +0 -655
  243. package/node_modules/tar/dist/commonjs/process-umask.d.ts +0 -2
  244. package/node_modules/tar/dist/commonjs/process-umask.js +0 -7
  245. package/node_modules/tar/dist/commonjs/warn-method.d.ts +0 -24
  246. package/node_modules/tar/dist/commonjs/warn-method.js +0 -31
  247. package/node_modules/tar/dist/esm/get-write-flag.d.ts +0 -2
  248. package/node_modules/tar/dist/esm/get-write-flag.js +0 -26
  249. package/node_modules/tar/dist/esm/make-command.d.ts +0 -49
  250. package/node_modules/tar/dist/esm/make-command.js +0 -48
  251. package/node_modules/tar/dist/esm/normalize-windows-path.d.ts +0 -2
  252. package/node_modules/tar/dist/esm/normalize-windows-path.js +0 -9
  253. package/node_modules/tar/dist/esm/parse.d.ts +0 -92
  254. package/node_modules/tar/dist/esm/parse.js +0 -651
  255. package/node_modules/tar/dist/esm/process-umask.d.ts +0 -2
  256. package/node_modules/tar/dist/esm/process-umask.js +0 -3
  257. package/node_modules/tar/dist/esm/warn-method.d.ts +0 -24
  258. package/node_modules/tar/dist/esm/warn-method.js +0 -27
  259. package/node_modules/yallist/LICENSE.md +0 -63
  260. package/node_modules/yallist/README.md +0 -205
  261. package/node_modules/yallist/dist/commonjs/index.d.ts +0 -39
  262. package/node_modules/yallist/dist/commonjs/index.js +0 -384
  263. package/node_modules/yallist/dist/commonjs/package.json +0 -3
  264. package/node_modules/yallist/dist/esm/index.d.ts +0 -39
  265. package/node_modules/yallist/dist/esm/index.js +0 -379
  266. package/node_modules/yallist/dist/esm/package.json +0 -3
  267. package/node_modules/yallist/package.json +0 -68
@@ -161,7 +161,7 @@ ${r(t.theirsRaw)}>>>>>>> pm theirs
161
161
  Agent guidance check
162
162
  `),Gu.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
163
163
  `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return Gu.write(`
164
- `),lX(n,!0)}finally{t.close()}}function ZR(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:gy,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function QR(e){let t=[],n=await XR(e);for(let r of XY){let i=it.join(e,r),o=await H(i);if(!o){t.push({file_path:i,exists:o,has_guidance:!1,has_marker:!1});continue}let s=await hy.readFile(i,"utf8"),a=s.toLowerCase(),c=ZY.filter(d=>a.includes(d)),l=iX(s);t.push({file_path:i,exists:o,has_guidance:l||c.length>=QY,has_marker:l,outdated:l&&YR(s,n).changed})}return t}function Ji(e,t){e.includes(t)||e.push(t)}function uX(e,t){let n=ZR(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function eI(e,t=it.dirname(e)){let r=await H(e)?await hy.readFile(e,"utf8"):"",i=YR(r,await XR(t));return i.changed?(await V(e,i.next_content),{changed:!0,warnings:await et({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function fX(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>hs(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>hs(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>hs(e.projectRoot,t.file_path))}}async function pX(e,t,n){return e?await QR(n):t}function fc(e,t,n){e.state={...e.state,...n,template_version:gy,last_checked_files:t}}async function tI(e,t){if(t.presentBefore)return;let n=await eI(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function mX(e,t){t||(e.warnings.push("agent_guidance:missing"),Ji(e.nextSteps,pc))}function _X(e,t){e.skipped=!0,fc(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Ji(e.nextSteps,pc)}async function hX(e,t){await tI(e,t),fc(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function gX(e,t){e.state.declined&&fc(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function yX(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ji(e.nextSteps,pc)}async function wX(e,t){if(e.prompted=!0,await dX(t.targetRelativePath)){await tI(e,t),fc(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,fc(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ji(e.nextSteps,pc)}function vX(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ji(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Ji(e.nextSteps,pc)}async function bX(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(mX(n,t.presentBefore),n):t.mode==="skip"?(_X(n,t.checkedFiles),n):t.mode==="add"?(await hX(n,t),n):t.presentBefore?(gX(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(yX(n),n):t.interactive?(await wX(n,t),n):(vX(n),n)}async function nI(e){let t=aX(e.pm_root,e.cwd),n=await QR(t),r=cX(n,t),i=hs(t,r),o=n.map(u=>hs(t,u.file_path)),s=n.some(u=>u.has_guidance),a=await bX(ZR(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:i,checkedFiles:o,presentBefore:s,projectRoot:t});if(e.mode==="add")for(let u of n.filter(f=>f.outdated)){let f=await eI(u.file_path,t);a.applied||=f.changed,a.warnings.push(...f.warnings)}let c=uX(e.settings,a.state);n=await pX(a.applied,n,t);let l=n.filter(u=>u.outdated).map(u=>hs(t,u.file_path));return l.length>0&&(a.warnings.push(`agent_guidance_outdated:${l.join(",")}`),Ji(a.nextSteps,"pm init --agent-guidance add")),{summary:fX({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:a.prompted,applied:a.applied,skipped:a.skipped,state:a.state}),warnings:a.warnings,next_steps:a.nextSteps,settings_changed:c.changed}}or();function Wu(e){let t=/^extension_(disabled_)?pm_(min|max)_version_([a-z_]+):(project|global):([^:]+):(.+)$/u.exec(e);if(!t)return;let[,n,r,i,o,s,a]=t,c=a.split(":")[0].replace(r==="min"?"required=":"allowed=",""),l=i==="invalid"?`a valid pm_${r}_version instead of ${c}`:`pm ${r==="min"?">=":"<="} ${c}`;return n?`Package ${s} is disabled and requires ${l} before activation. After satisfying the bound, run ${re(["package","activate",s,`--${o}`])}.`:`Package ${s} requires ${l}. Use a compatible host or package version, or keep it disabled with ${re(["package","deactivate",s,`--${o}`])}.`}import gr from"node:fs/promises";import ot from"node:path";yn();Xn();De();at();P();Z();Mr();nr();Um();od();Qe();P();import rI from"node:fs/promises";import iI from"node:path";function oI(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:o,ttl_seconds:s}=n;return typeof r!="string"||typeof i!="string"||typeof o!="string"||typeof s!="number"||!Number.isFinite(s)?null:{id:r,owner:i,created_at:o,ttl_seconds:s,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function EX(e,t,n){let r=oI(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let o=n-i,s=Math.floor(o/1e3),a=o>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:s,stale:a,reason:a?"expired":"active"}}}async function kX(e,t,n){let r=EX(e,t,n);if(r.detail!=="active")return r;let i=oI(t),o=await Fo(i);return o==="unknown"?r:{detail:o==="dead"?"owner_dead":"active",entry:{...r.entry,owner_state:o,pid:i.pid,...o==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}function xX(e,t,n){t==="owner_dead"&&(e.owner_dead_lock_samples??=[],e.owner_dead_lock_samples.length<20&&e.owner_dead_lock_samples.push(n)),t==="active"?e.active_lock_count+=1:t==="expired"||t==="owner_dead"?e.stale_lock_count+=1:e.unparseable_lock_count+=1}async function sI(e,t){let n=t??Date.now(),r=iI.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await rI.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(s){if(D(s))return i;throw s}for(let s of o){let a;try{a=await rI.readFile(iI.join(r,s),"utf8")}catch(d){if(D(d))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c,entry:l}=await kX(s,a,n);xX(i,c,l)}return i}function yy(e,t){let n=t??{};return e.filter(r=>n[r.id]!==r.updated_at).map(r=>r.id).sort((r,i)=>r.localeCompare(i))}k();oi();x();xe();J();ln();ii();q();me();var SX=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:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{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_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{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 record; the repair rebuilds the stream as one audited baseline from the on-disk item, and earlier versions stay unrecorded. When the stream was deleted by mistake, restore it from version control first (pm history-repair --all, with or without --append-only, rebuilds every missing stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"The item's history stream cannot be read; preview salvage, which removes lines that cannot hold a record and an invalid tail after a verified prefix, then apply it without --dry-run. Salvage refuses interior corruption, which needs recovery from version control, and a permission error needs the file's access fixed."},{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> --append-only",summary:"The item's history chain is broken; append one record that bridges every break in the stream and keeps every recorded line byte-identical (pm history-repair <id> re-anchors the recorded entries instead). pm health previews the bridge for every chain mismatch, so a break a bridge cannot repair is reported as history_drift_chain_unbridgeable, and a stream no repair can keep as history_drift_unrepairable_stream, instead."},{code:"history_drift_chain_unbridgeable",command:"pm history-repair <id>",summary:"The item's history chain is broken in a way an append-only bridge cannot repair, for example a recorded patch that applies only on top of the unrecorded change (details.repair_refusals names the refusal reason); re-anchor the recorded entries instead (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unrepairable_stream",command:"pm history <id> --verify --full",summary:"Neither history repair can keep this stream (details.repair_refusals names both refusal reasons). Inspect it: a record that no longer matches its seal, or a malformed chain, needs the item's own stream restored from version control or a backup; a stream entry that is a link (reason stream_not_regular_file) needs the item's own stream restored as a regular file. Then run pm history <id> --verify --strict-exit."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{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:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{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_schema_field_option_collision",command:"pm schema rename-field <key> --to <new-key>",summary:"A custom field shadows a built-in option of a command it is registered for; rename it (item values move with it), or re-register the same key with another flag or a narrower --commands list."},{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:"Rebuild the history streams of the items without a history record as one audited baseline from each on-disk item."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"Preview salvage of the unreadable history streams, then apply it without --dry-run; interior corruption needs recovery from version control."},{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_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{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 wy(e){if(typeof e!="string")return;let t=e.trim();for(let n of SX)if(t===n.code||t.startsWith(`${n.code}:`))return n}function vy(e){let t={};for(let n of e){let r=wy(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function aI(e){return Object.values(vy(e))}en();import dI from"node:fs/promises";import{createRequire as AX}from"node:module";import Vt from"node:path";function cI(e,t){let n=Vt.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Vt.sep}`)&&!Vt.isAbsolute(n))return n.split(Vt.sep).join("/");let r=Vt.resolve(e),i=0xcbf29ce484222325n;for(let s=0;s<r.length;s+=1)i^=BigInt(r.charCodeAt(s)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Vt.basename(Vt.dirname(e))}/package.json`}function TX(e){return e.includes(`${Vt.sep}.pnpm${Vt.sep}`)?"pnpm":e.includes(`${Vt.sep}node_modules${Vt.sep}`)?"npm":"other"}async function lI(e){try{let t=JSON.parse(await dI.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function by(e){try{return await dI.realpath(e)}catch{return Vt.resolve(e)}}async function uI(e,t,n=Ht(import.meta.url,["../../.."])){let r=await by(t),i=await by(Vt.join(n,"package.json")),o=await lI(i),s=new Map;o!==void 0&&s.set(i,{version:o,path:cI(i,r),layout:"host",consumers:["pm-cli-host"]});for(let l of e)try{let d=AX(l.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await by(d),f=await lI(u);if(f===void 0)continue;let p=u,m=s.get(p);if(m){m.consumers.includes(l.name)||(m.consumers.push(l.name),m.consumers.sort((g,y)=>g.localeCompare(y)));continue}s.set(p,{version:f,path:cI(u,r),layout:TX(u),consumers:[l.name]})}catch{}let a=[...s.values()].sort((l,d)=>l.path.localeCompare(d.path)),c=o===void 0?[]:a.filter(l=>l.version!==o);return{host_version:o??null,copies:a,mismatches:c,warnings:c.map(l=>`extension_host_pm_cli_version_skew:${o}:${l.version}:${l.consumers.join("+")}`)}}Lt();me();k();x();import zy from"node:fs/promises";import Hy from"node:path";k();x();xe();k();x();xe();var gs=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Item title [required] (or first positional argument)"},{target:"id",keys:["id"],option:"--id <value>",description:"Explicit id (normalized with id_prefix)"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Item description (allow empty string)"},{target:"type",keys:["type"],option:"--type <value>",description:"Built-in or custom item type"},{target:"template",keys:["template"],option:"--template <value>",description:"Named template defaults; explicit flags override"},{target:"createMode",keys:["createMode","create_mode"],option:"--create-mode <value>",description:"Required fields: strict|progressive",aliasOptions:[{option:"--create_mode <value>",description:"Alias for --create-mode"}]},{target:"defer",keys:["defer"],option:"--defer <field>",description:"Defer an unknown strict field: deadline|assignee|ac|estimate (repeatable)",repeatable:!0},{target:"deferReason",keys:["deferReason","defer_reason"],option:"--defer-reason <value>",description:"Why deferred values are unknown (required with --defer)",aliasOptions:[{option:"--defer_reason <value>",description:"Alias for --defer-reason"}]},{target:"schedulePreset",keys:["schedulePreset","schedule_preset"],option:"--schedule-preset <value>",description:"Reminder/Meeting/Event defaults: lightweight",aliasOptions:[{option:"--schedule_preset <value>",description:"Alias for --schedule-preset"}]},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Item status"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Reason for a directly terminal item",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Actual completion time for terminal imports",aliasOptions:[{option:"--completed_at <value>",description:"Alias for --completed-at"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Priority 0..4"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Comma-separated tags"},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags additively on top of --tags (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Item markdown body (allow empty string)"},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Deadline (ISO/date string or relative +6h/+1d/+2w/+6m)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Acceptance criteria (repeatable; values join with '; '; allow empty string)",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Definition of ready (allow empty string)",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"History message (allow empty string)"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Item assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow creating with an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Seed dependency entry (key=value CSV, markdown key:value lines, or - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Type option key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar fields by name (repeatable or csv)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Seed reminder entry at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Seed event entry start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Seed comment entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Seed note entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Seed learning entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Seed linked file entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Seed linked test entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Seed linked doc entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0}],Ey=gs.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),ky=gs.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),Yi=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Set title"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Set description"},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Set body (allow empty string)"},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Set status (use close command for closed)"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Set close reason",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Set priority"},{target:"type",keys:["type"],option:"--type <value>",description:"Set type"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Set comma-separated tags (replaces existing). Use --add-tags / --remove-tags to mutate additively."},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags to the existing list without replacing it (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"removeTags",keys:["removeTags","remove_tags"],option:"--remove-tags <value>",description:"Remove tags from the existing list (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--remove_tags <value>",description:"Alias for --remove-tags"}]},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Set deadline (ISO/date string or relative)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Set estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Replace the complete acceptance-criteria list (repeatable values join with '; '); use --remove-ac plus --add-ac for one-entry repair",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"addAc",keys:["addAc","add_ac"],option:"--add-ac <value>",description:"Add one semicolon-free acceptance criterion without replacing the existing list (repeatable)",repeatable:!0,aliasOptions:[{option:"--add_ac <value>",description:"Alias for --add-ac"}]},{target:"removeAc",keys:["removeAc","remove_ac"],option:"--remove-ac <value>",description:"Remove one semicolon-free acceptance criterion by exact text match; fails if any selector is unmatched (repeatable)",repeatable:!0,aliasOptions:[{option:"--remove_ac <value>",description:"Alias for --remove-ac"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Set definition of ready",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Set planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Set goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Set objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Set business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Set business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Set expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Set why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"Mutation message"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Set assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Set parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow updating to an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Correct the actual completion timestamp on a terminal item"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Set reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Set risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Set confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Set sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Set release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Set blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Set unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Set issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Set issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Set issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Set issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Set issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Set issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Set issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Set affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Set fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Set issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Set regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Set customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Add dependency entries id=<id>,kind=<value>,author=<value>,created_at=<iso|now>,source_kind=<value> (repeatable)",repeatable:!0},{target:"depRemove",keys:["depRemove","dep_remove"],option:"--dep-remove <value>",description:"Remove by id, row signature, or kind=<kind> alone (repeatable)",repeatable:!0,aliasOptions:[{option:"--dep_remove <value>",description:"Alias for --dep-remove"}]},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Append comment seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Append note seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Append learning seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Append linked file path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Append test command=<value>,path=<value>,scope=<project|global>,timeout_seconds=<n>,pm_context_mode=<schema|tracker|auto|none> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Append linked doc path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Set reminders at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Set events start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Set type options key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar fields by name (repeatable or csv)",repeatable:!0}],xy=Yi.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),Sy=Yi.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys}));function pt(e){return e.map(t=>({...t}))}var Ay=[{param:"status",flag:"--status"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"deadlineBefore",flag:"--deadline-before"},{param:"deadlineAfter",flag:"--deadline-after"}],fI=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],OX=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},...fI],pI=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],CX=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],RX=[...Ay,...pI],mI=[{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"}],IX=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],_I=[{param:"hasNotes",flag:"--has-notes"},{param:"noNotes",flag:"--no-notes"},{param:"hasLearnings",flag:"--has-learnings"},{param:"noLearnings",flag:"--no-learnings"},{param:"hasFiles",flag:"--has-files"},{param:"noFiles",flag:"--no-files"},{param:"filterFilesMissing",flag:"--filter-files-missing"},{param:"hasDocs",flag:"--has-docs"},{param:"noDocs",flag:"--no-docs"},{param:"filterDocsMissing",flag:"--filter-docs-missing"},{param:"hasTests",flag:"--has-tests"},{param:"noTests",flag:"--no-tests"},{param:"hasComments",flag:"--has-comments"},{param:"noComments",flag:"--no-comments"},{param:"hasDeps",flag:"--has-deps"},{param:"noDeps",flag:"--no-deps"},{param:"hasBody",flag:"--has-body"},{param:"emptyBody",flag:"--empty-body"},{param:"hasLinkedCommand",flag:"--has-linked-command"},{param:"noLinkedCommand",flag:"--no-linked-command"}],Ty=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...pt(Ay),...pt(OX),{param:"ids",flag:"--ids"},...pt(pI),...pt(IX),...pt(mI),...pt(_I),{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"},{param:"after",flag:"--after"},{param:"fields",flag:"--fields"},{param:"sort",flag:"--sort"},{param:"order",flag:"--order"},{param:"tree",flag:"--tree"},{param:"treeDepth",flag:"--tree-depth"}],Oy=[{param:"groupBy",flag:"--group-by"},{param:"setMode",flag:"--set-mode"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...pt(RX)],Cy=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},{param:"matchMode",flag:"--match-mode"},{param:"minScore",flag:"--min-score"},{param:"count",flag:"--count",booleanish:!0},{param:"semanticWeight",flag:"--semantic-weight"},...pt(Ay),...pt(fI),...pt(CX),...pt(mI),...pt(_I),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],hI=[{param:"parent",flag:"--parent"},{param:"reviewer",flag:"--reviewer"},{param:"risk",flag:"--risk"},{param:"confidence",flag:"--confidence"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"blockedBy",flag:"--blocked-by"},{param:"blockedReason",flag:"--blocked-reason"},{param:"unblockNote",flag:"--unblock-note"},{param:"reporter",flag:"--reporter"},{param:"severity",flag:"--severity"},{param:"environment",flag:"--environment"},{param:"reproSteps",flag:"--repro-steps"},{param:"resolution",flag:"--resolution"},{param:"expectedResult",flag:"--expected-result"},{param:"actualResult",flag:"--actual-result"},{param:"affectedVersion",flag:"--affected-version"},{param:"fixedVersion",flag:"--fixed-version"},{param:"component",flag:"--component"},{param:"regression",flag:"--regression",booleanish:!0},{param:"customerImpact",flag:"--customer-impact"},{param:"definitionOfReady",flag:"--definition-of-ready",allowEmpty:!0},{param:"order",flag:"--order"},{param:"rank",flag:"--rank"},{param:"goal",flag:"--goal"},{param:"objective",flag:"--objective"},{param:"value",flag:"--value"},{param:"impact",flag:"--impact"},{param:"outcome",flag:"--outcome"},{param:"whyNow",flag:"--why-now"}],ys=pt(hI),gI=[{param:"inheritFocus",flag:"--inherit-focus",booleanish:!0},{param:"id",flag:"--id"},{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"type",flag:"--type"},{param:"template",flag:"--template"},{param:"createMode",flag:"--create-mode"},{param:"defer",flag:"--defer",repeatable:!0},{param:"deferReason",flag:"--defer-reason"},{param:"schedulePreset",flag:"--schedule-preset"},{param:"status",flag:"--status"},{param:"closeReason",flag:"--close-reason"},{param:"completedAt",flag:"--completed-at"},{param:"priority",flag:"--priority"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"allowDuplicate",flag:"--allow-duplicate",booleanish:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"dep",flag:"--dep",repeatable:!0},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],mc=pt(gI),yI=[{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"status",flag:"--status"},{param:"closeReason",flag:"--close-reason"},{param:"completedAt",flag:"--completed-at"},{param:"priority",flag:"--priority"},{param:"type",flag:"--type"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"removeTags",flag:"--remove-tags",repeatable:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"addAc",flag:"--add-ac",repeatable:!0},{param:"removeAc",flag:"--remove-ac",repeatable:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"dep",flag:"--dep",repeatable:!0},{param:"depRemove",flag:"--dep-remove",repeatable:!0},{param:"replaceDeps",flag:"--replace-deps"},{param:"replaceTests",flag:"--replace-tests"},{param:"replaceFiles",flag:"--replace-files"},{param:"replaceDocs",flag:"--replace-docs"},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],_c=pt(yI),Ry=[{param:"filterStatus",flag:"--filter-status"},{param:"filterType",flag:"--filter-type"},{param:"filterTag",flag:"--filter-tag"},{param:"filterPriority",flag:"--filter-priority"},{param:"filterDeadlineBefore",flag:"--filter-deadline-before"},{param:"filterDeadlineAfter",flag:"--filter-deadline-after"},{param:"filterUpdatedAfter",flag:"--filter-updated-after"},{param:"filterUpdatedBefore",flag:"--filter-updated-before"},{param:"filterCreatedAfter",flag:"--filter-created-after"},{param:"filterCreatedBefore",flag:"--filter-created-before"},{param:"filterAssignee",flag:"--filter-assignee"},{param:"filterAssigneeFilter",flag:"--filter-assignee-filter"},{param:"filterParent",flag:"--filter-parent"},{param:"filterSprint",flag:"--filter-sprint"},{param:"filterRelease",flag:"--filter-release"},{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"},{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"},{param:"filterHasNotes",flag:"--filter-has-notes"},{param:"filterNoNotes",flag:"--filter-no-notes"},{param:"filterHasLearnings",flag:"--filter-has-learnings"},{param:"filterNoLearnings",flag:"--filter-no-learnings"},{param:"filterHasFiles",flag:"--filter-has-files"},{param:"filterNoFiles",flag:"--filter-no-files"},{param:"filterHasDocs",flag:"--filter-has-docs"},{param:"filterNoDocs",flag:"--filter-no-docs"},{param:"filterHasTests",flag:"--filter-has-tests"},{param:"filterNoTests",flag:"--filter-no-tests"},{param:"filterHasComments",flag:"--filter-has-comments"},{param:"filterNoComments",flag:"--filter-no-comments"},{param:"filterHasDeps",flag:"--filter-has-deps"},{param:"filterNoDeps",flag:"--filter-no-deps"},{param:"filterHasBody",flag:"--filter-has-body"},{param:"filterEmptyBody",flag:"--filter-empty-body"},{param:"filterHasLinkedCommand",flag:"--filter-has-linked-command"},{param:"filterNoLinkedCommand",flag:"--filter-no-linked-command"},{param:"ids",flag:"--ids"},{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"}],Iy=pt(Ry),Ny=pt(Ry);var Py=[{param:"id",flag:"--id"},{param:"op",flag:"--op"},{param:"author",flag:"--author"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"unbounded",flag:"--unbounded"},{param:"compact",flag:"--compact"},{param:"raw",flag:"--raw"},{param:"full",flag:"--full"},{param:"provenance",flag:"--provenance"},{param:"provenanceSummary",flag:"--provenance-summary"},{param:"harness",flag:"--harness",repeatable:!0},{param:"agentInstance",flag:"--agent-instance",repeatable:!0},{param:"provenanceFilter",flag:"--provenance-filter",repeatable:!0}],Ly=[{param:"for",flag:"--for"},{param:"date",flag:"--date"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"format",flag:"--format"},{param:"depth",flag:"--depth"},{param:"fields",flag:"--fields"},{param:"section",flag:"--section",repeatable:!0},{param:"activityLimit",flag:"--activity-limit"},{param:"staleThreshold",flag:"--stale-threshold"},{param:"tokenBudget",flag:"--token-budget"},{param:"explainRanking",flag:"--explain-ranking"},{param:"noTags",flag:"--no-tags"},{param:"noExtensionHealth",flag:"--no-extension-health"}];Yt();A_();ye();J();var wI=["production_defect","nightly_regression","scanner_finding","review_caught_late"];var Vu={type:"string",pattern:"\\S"},My={type:"array",minItems:1,items:Vu},bI={type:"object",properties:Object.fromEntries(["files","package_names","item_ids","tags","error_codes"].map(e=>[e,{type:"array",items:{type:"string"}}]))},NX={type:"object",required:["id","version","title","owner_item_id","escape_class","triggers","checks","negative_control","historical_item_ids","budget"],properties:{id:Vu,version:{type:"integer",minimum:1},title:Vu,owner_item_id:Vu,escape_class:{enum:wI},triggers:{type:"object",properties:{...Object.fromEntries(["package_names","item_ids","tags","error_codes"].map(e=>[e,{type:"array",items:{type:"string"}}])),file_patterns:{type:"array",items:{type:"string",maxLength:256}}}},checks:{type:"object",required:["local","hosted"],properties:{local:My,hosted:My}},negative_control:{...bI,minProperties:1},historical_item_ids:My,budget:{type:"object",required:["max_escape_rate","max_false_positive_rate"],properties:Object.fromEntries(["max_escape_rate","max_false_positive_rate"].map(e=>[e,{type:"number",minimum:0,maximum:1}]))}}},vI={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},EI={if:{required:["field"]}};Reflect.set(EI,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var kI={oneOf:[...[!0,!1].map(e=>({type:"object",additionalProperties:!1,required:e?["policy","change"]:["policy"],properties:{policy:{type:"object",required:["version","evidence_epoch","families"],properties:{version:{const:1},evidence_epoch:{type:"string",format:"date-time"},families:{type:"array",items:NX}},additionalProperties:!1},...e?{change:{...bI,additionalProperties:!1}}:{uncoveredOnly:{type:"boolean"}},limit:{type:"integer",minimum:1,maximum:100},cursor:{type:"string",minLength:1}}})),{type:"object",additionalProperties:!1,required:["id","source"],properties:{id:{type:"string",minLength:1},description:{type:"string"},max_cost:{type:"number",minimum:0},source:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],allOf:[EI],properties:{kind:{const:"items"},statuses:{type:"array",items:{type:"string"}},types:{type:"array",items:{type:"string"}},tags:{type:"array",items:{type:"string"}},field:{type:"string"},equals:{type:["string","number","boolean","null"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","dependency_kind"],properties:{kind:{const:"dependency_kind"},dependency_kind:{type:"string",minLength:1}}},{type:"object",required:["kind","operation","field"],properties:{kind:{const:"graph"},operation:{type:"string",minLength:1},field:{type:"string",minLength:1},parameters:{type:"object"}},additionalProperties:!1},...["validate","health"].map(e=>({type:"object",required:["kind","check","field"],properties:{kind:{const:e},check:{type:"string",minLength:1},field:{type:"string",minLength:1}},additionalProperties:!1})),{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"history"},op:{type:"string"},author:{type:"string"},harness:{type:"string"},model:{type:"string"}}},{type:"object",additionalProperties:!1,required:["kind","link","state"],properties:{kind:{const:"links"},link:{enum:["files","tests","docs"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","provider","key"],properties:{kind:{const:"provider"},provider:{type:"string",minLength:1},key:{type:"string",minLength:1},parameters:{type:"object"}}},{type:"object",additionalProperties:!1,required:["kind","expression"],properties:{kind:{const:"derived"},expression:{type:"object",minProperties:1}}}]}}},{type:"object",additionalProperties:!1,required:["id","measurement_id","owner_item_id","scope","enforcement","negative_control"],oneOf:[{required:["ceiling"]},{required:["floor"]},{required:["equals"]},{required:["zero"]},{required:["monotone_nondecreasing"]},{required:["monotone_nonincreasing"]},{required:["subset_of"]}],allOf:[{oneOf:[{not:{required:["lifetime"],properties:{lifetime:{const:"retire"}}}},{required:["lifetime","retire_reason"],properties:{lifetime:{const:"retire"},retire_reason:{type:"string",minLength:1}}}]}],properties:{id:{type:"string",minLength:1},measurement_id:{type:"string",minLength:1},owner_item_id:{type:"string",minLength:1},scope:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{enum:["all","active"]}}},{type:"object",additionalProperties:!1,required:["kind","measurement_id"],properties:{kind:{const:"filter"},measurement_id:{type:"string",minLength:1}}}]},ceiling:{type:"number"},floor:{type:"number"},equals:vI,zero:{const:!0},monotone_nondecreasing:{type:"number"},monotone_nonincreasing:{type:"number"},subset_of:{type:"array",items:{type:"string"}},lifetime:{enum:["hold","retire"]},retire_reason:{type:"string",minLength:1},enforcement:{enum:["block","warn","observe"]},authorization_decision:{type:"string",minLength:1},negative_control:{type:"object",additionalProperties:!1,required:["cases"],properties:{cases:{type:"array",minItems:2,items:{type:"object",additionalProperties:!1,required:["observed","expected"],properties:{observed:vI,expected:{enum:["pass","fail"]}}}}}}}},{type:"object",additionalProperties:!1,required:["id","assertion_ids","triggers"],properties:{id:{type:"string",minLength:1},description:{type:"string"},assertion_ids:{type:"array",minItems:1,items:{type:"string",minLength:1}},triggers:{type:"array",minItems:1,items:{enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]}},provider_policy:{type:"object",additionalProperties:!1,required:["allowed_providers","triggers"],properties:{allowed_providers:{type:"array",items:{type:"string",minLength:1}},triggers:{type:"object",additionalProperties:{type:"object",additionalProperties:!1,required:["max_cost_class","allow_network"],properties:{max_cost_class:{enum:["low","medium","high"]},allow_network:{type:"boolean"}}}}}}}}]};var hc={json:{type:"boolean",default:!0},quiet:{type:"boolean"},profile:{type:"boolean"},noExtensions:{type:"boolean"},noPager:{type:"boolean"},tokenAccounting:{type:"boolean"},outputInclude:{type:"string",minLength:1},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputFormat:{type:"string",enum:["json","toon"]},outputSession:{anyOf:[{type:"string",minLength:1},{type:"object",additionalProperties:!1,required:["version","id","token_budget","spent_tokens","seen_item_ids"],properties:{version:{const:1},id:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$"},token_budget:{type:"integer",minimum:256},spent_tokens:{type:"integer",minimum:0},seen_item_ids:{type:"array",maxItems:Rd,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"}}}}]},outputCursor:{type:"string",minLength:1},outputRowContract:{type:"boolean"},path:{type:"string"},pmExecutable:{type:"string"},timeoutMs:{type:"number"},id:{type:"string"},target:{type:"string"},snapshotAction:{type:"string",enum:["create","list","inspect","restore","delete"]},artifact:{type:"string",enum:["item","history","relationship","json"]},basePath:{type:"string"},oursPath:{type:"string"},theirsPath:{type:"string"},outputPath:{type:"string"},itemPath:{type:"string"},prefer:{type:"string",enum:["ours","theirs"]},includeReconciled:{type:"boolean"},preCommitHook:{type:"boolean"},stage:{type:"boolean"},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"},capability:{type:"string",minLength:1},declarative:{type:"boolean"},output:{type:"string",minLength:1},markdown:{type:"boolean"},init:{type:"boolean"},install:{type:"boolean"},uninstall:{type:"boolean"},explore:{type:"boolean"},manage:{type:"boolean"},describe:{type:"boolean"},doctor:{type:"boolean"},catalog:{type:"boolean"},adopt:{type:"boolean"},adoptAll:{type:"boolean"},activate:{type:"boolean"},deactivate:{type:"boolean"},filterFilesMissing:{type:"boolean"},filterDocsMissing:{type:"boolean"},matchMode:{type:"string",enum:["all","any","phrase"]},minScore:{anyOf:[{type:"number"},{type:"string",pattern:"^\\d+(\\.\\d+)?$"}]},rank:{anyOf:[{type:"number"},{type:"string",pattern:"^-?\\d+$"}]},exemptIsolateType:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},saveBaseline:{type:"boolean"},rebuild:{type:"boolean"},github:{type:"string"},ref:{type:"string"},query:{type:"string"},queries:{type:"string"},k:{anyOf:[{type:"number"},{type:"string"}]},failUnder:{anyOf:[{type:"number"},{type:"string"}]},for:{type:"string",minLength:1},keywords:{type:"string"},fields:{type:"string"},sort:{type:"string",enum:["priority","deadline","updated_at","created_at","title","parent"]},prefix:{type:"string"},idPrefix:{type:"string"},workspace:{type:"string"},preset:{type:"string",enum:["minimal","default","strict","custom"]},typePreset:{type:"string",enum:["agile","ops","research"]},defaults:{type:"boolean"},verbose:{type:"boolean"},agentGuidance:{type:"string",enum:["ask","add","skip","status"]},withPackages:{type:"boolean"},mergeFence:{type:"boolean"},scope:{type:"string",enum:["project","global"]},allOver:{type:"number"},minEntries:{type:"number"},closed:{type:"boolean"},allStreams:{type:"boolean"},contractAction:{type:"string"},command:{type:"string"},summary:{type:"boolean"},schemaOnly:{type:"boolean"},flagsOnly:{type:"boolean"},availabilityOnly:{type:"boolean"},runtimeOnly:{type:"boolean"},activeOnly:{type:"boolean"},eagerTags:{type:"boolean"},fullChangedFields:{type:"boolean"},provenance:{type:"boolean"},provenanceSummary:{type:"boolean"},agentInstance:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},provenanceFilter:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},idOnly:{type:"boolean"},expectHash:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},allowMissingParent:{type:"boolean"},allowUnresolvedDeps:{type:"boolean"},allowDuplicate:{type:"boolean"},inheritFocus:{type:"boolean",description:"Opt into saved session focus as parent; SDK/MCP default false, CLI default true. Explicit parent or unset-parent takes precedence."},duplicateOf:{type:"string"},configAction:{type:"string",enum:["get","set","list","export"]},key:{type:"string"},title:{type:"string"},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},start:{type:"string"},duration:{type:"string"},end:{type:"string"},location:{type:"string"},timezone:{type:"string"},allDay:{type:"boolean"},description:{type:"string"},type:{type:"string"},template:{type:"string"},createMode:{type:"string",enum:["strict","progressive"]},defer:{type:"array",items:{type:"string"}},deferReason:{type:"string"},schedulePreset:{type:"string",enum:["lightweight"]},status:{type:"string"},since:{type:"string",format:"date-time"},cursorMode:{type:"string",enum:["batch","row"]},exhaustive:{type:"boolean"},threshold:{type:"number",minimum:0,maximum:1},filterStatus:{type:"string"},filterType:{type:"string"},filterTag:{type:"string"},filterPriority:{anyOf:[{type:"string"},{type:"number"}]},filterDeadlineBefore:{type:"string"},filterDeadlineAfter:{type:"string"},filterUpdatedAfter:{type:"string"},filterUpdatedBefore:{type:"string"},filterCreatedAfter:{type:"string"},filterCreatedBefore:{type:"string"},filterAssignee:{type:"string"},filterAssigneeFilter:{type:"string",enum:["assigned","unassigned"]},filterParent:{type:"string"},filterSprint:{type:"string"},filterRelease:{type:"string"},closeReason:{type:"string"},completedAt:{type:"string",format:"date-time"},reason:{type:"string"},priority:{anyOf:[{type:"string"},{type:"number"}]},tags:{type:"string"},addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}},addAc:{type:"array",items:{type:"string"}},removeAc:{type:"array",items:{type:"string"}},body:{type:"string"},deadline:{type:"string"},estimate:{anyOf:[{type:"string"},{type:"number"}]},acceptanceCriteria:{type:"string"},author:{type:"string"},message:{type:"string"},owner:{type:"string"},enforcement:{type:"string"},assignee:{type:"string"},assigneeFilter:{type:"string",enum:["assigned","unassigned"]},parent:{type:"string"},reviewer:{type:"string"},attributedAuthor:{type:"string"},planFingerprint:{type:"string",pattern:"^[a-f0-9]{64}$"},historyEvent:{type:"array",items:{type:"string"}},risk:{type:"string"},confidence:{anyOf:[{type:"string"},{type:"number"}]},sprint:{type:"string"},release:{type:"string"},blockedBy:{type:"string"},blockedReason:{type:"string"},unblockNote:{type:"string"},reporter:{type:"string"},severity:{type:"string"},environment:{type:"string"},reproSteps:{type:"string"},resolution:{type:"string"},expectedResult:{type:"string"},actualResult:{type:"string"},affectedVersion:{type:"string"},fixedVersion:{type:"string"},component:{type:"string"},regression:{anyOf:[{type:"boolean"},{type:"string"},{type:"number"}]},customerImpact:{type:"string"},definitionOfReady:{type:"string"},order:{anyOf:[{type:"string"},{type:"number"}]},goal:{type:"string"},objective:{type:"string"},value:{type:"string"},impact:{type:"string"},outcome:{type:"string"},whyNow:{type:"string"},mode:{type:"string",enum:["keyword","semantic","hybrid"]},semanticWeight:{anyOf:[{type:"string"},{type:"number"}]},op:{type:"string"},compact:{type:"boolean"},raw:{type:"boolean"},brief:{type:"boolean"},full:{type:"boolean"},includeEmpty:{type:"boolean"},view:{type:"string",enum:["agenda","day","week","month"]},date:{type:"string"},from:{type:"string"},before:{type:"string"},at:{type:"string"},to:{type:"string"},migrationId:{type:"string"},fieldTypeScope:{type:"string"},past:{type:"boolean"},fullPeriod:{type:"boolean"},include:{type:"string"},recurrenceLookaheadDays:{anyOf:[{type:"string"},{type:"number"}]},recurrenceLookbackDays:{anyOf:[{type:"string"},{type:"number"}]},occurrenceLimit:{anyOf:[{type:"string"},{type:"number"}]},includeLinked:{type:"boolean"},semantic:{type:"boolean"},hybrid:{type:"boolean"},titleExact:{type:"boolean"},phraseExact:{type:"boolean"},highlight:{type:"boolean"},includeBody:{type:"boolean"},noTruncate:{type:"boolean"},strictRead:{type:"boolean"},tag:{type:"string"},deadlineBefore:{type:"string"},deadlineAfter:{type:"string"},today:{type:"boolean"},recent:{type:"boolean"},updatedAfter:{type:"string"},updatedBefore:{type:"string"},createdAfter:{type:"string"},createdBefore:{type:"string"},filterAcMissing:{type:"boolean"},filterEstimatesMissing:{type:"boolean"},filterResolutionMissing:{type:"boolean"},filterMetadataMissing:{type:"boolean"},filterReviewerMissing:{type:"boolean"},filterRiskMissing:{type:"boolean"},filterConfidenceMissing:{type:"boolean"},filterSprintMissing:{type:"boolean"},filterReleaseMissing:{type:"boolean"},hasNotes:{type:"boolean"},noNotes:{type:"boolean"},hasLearnings:{type:"boolean"},noLearnings:{type:"boolean"},hasFiles:{type:"boolean"},noFiles:{type:"boolean"},hasDocs:{type:"boolean"},noDocs:{type:"boolean"},hasTests:{type:"boolean"},noTests:{type:"boolean"},hasComments:{type:"boolean"},noComments:{type:"boolean"},hasDeps:{type:"boolean"},noDeps:{type:"boolean"},hasBody:{type:"boolean"},emptyBody:{type:"boolean"},hasLinkedCommand:{type:"boolean"},noLinkedCommand:{type:"boolean"},filterHasNotes:{type:"boolean"},filterNoNotes:{type:"boolean"},filterHasLearnings:{type:"boolean"},filterNoLearnings:{type:"boolean"},filterHasFiles:{type:"boolean"},filterNoFiles:{type:"boolean"},filterHasDocs:{type:"boolean"},filterNoDocs:{type:"boolean"},filterHasTests:{type:"boolean"},filterNoTests:{type:"boolean"},filterHasComments:{type:"boolean"},filterNoComments:{type:"boolean"},filterHasDeps:{type:"boolean"},filterNoDeps:{type:"boolean"},filterHasBody:{type:"boolean"},filterEmptyBody:{type:"boolean"},filterHasLinkedCommand:{type:"boolean"},filterNoLinkedCommand:{type:"boolean"},ids:{type:"string"},limit:{anyOf:[{type:"string"},{type:"number"}]},blockedLimit:{anyOf:[{type:"string"},{type:"number"}]},readyOnly:{type:"boolean"},offset:{anyOf:[{type:"string"},{type:"number"}]},progress:{type:"boolean"},background:{type:"boolean"},runId:{type:"string"},stream:{anyOf:[{type:"boolean"},{type:"string",enum:["stdout","stderr","both","rows","ndjson","jsonl"]}]},tail:{anyOf:[{type:"string"},{type:"number"}]},addJson:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},eventType:{type:"string"},includeMeta:{type:"boolean"},allActionable:{type:"boolean"},verboseAuthorEvents:{type:"boolean"},match:{type:"string"},onlyIndex:{anyOf:[{type:"string"},{type:"number"}]},removeIndex:{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}},updateIndex:{anyOf:[{type:"string"},{type:"number"}]},setJson:{type:"string"},update:{type:"string"},onlyLast:{type:"boolean"},envSet:{type:"array",items:{type:"string"}},envClear:{type:"array",items:{type:"string"}},sharedHostSafe:{type:"boolean"},detail:{type:"string",enum:["summary","deep"]},trace:{type:"boolean"},reload:{type:"boolean"},watch:{type:"boolean"},runtimeProbe:{type:"boolean"},offline:{type:"boolean"},fixManagedState:{type:"boolean"},isolated:{type:"boolean"},ignoreGlobal:{type:"boolean"},pmContext:{type:"string",enum:["schema","tracker","auto","none"]},overrideLinkedPmContext:{type:"boolean"},workspaceContext:{type:"string",enum:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{type:"boolean"},allowUntrustedLinkedTests:{type:"boolean"},acknowledgeLinkedTests:{type:"boolean"},failOnContextMismatch:{type:"boolean"},failOnSkipped:{type:"boolean"},failOnEmptyTestRun:{type:"boolean"},requireAssertionsForPm:{type:"boolean"},checkContext:{type:"boolean"},fullOutput:{type:"boolean"},autoPmContext:{type:"boolean"},measure:{type:"array",items:{type:"string"}},metricBelow:{type:"string"},metricDiff:{type:"string"},diff:{type:"boolean"},storage:{type:"boolean"},metadataCoverage:{type:"boolean"},fieldUtilization:{type:"boolean"},byAssignee:{type:"boolean"},byTag:{type:"boolean"},byPriority:{type:"boolean"},tagPrefix:{type:"string"},measurements:{type:"boolean"},metric:{type:"string"},measurementLimit:{type:"integer",minimum:0,maximum:1e3},observe:{type:"array",items:{type:"string"}},improvementDirection:{type:"string",enum:["higher","lower","target"]},measurementSource:{type:"string"},measurementItem:{type:"string"},measurementRevision:{type:"string"},provenanceCoverage:{type:"boolean"},fleetAttribution:{type:"boolean"},eventLimit:{type:"integer",minimum:1,maximum:1e5},minimumSample:{type:"integer",minimum:1,maximum:1e4},verify:{type:"boolean"},literal:{type:"array",items:{type:"string"}},regex:{type:"array",items:{type:"string"}},replacement:{type:"string"},timeout:{anyOf:[{type:"string"},{type:"number"}]},validateClose:{type:"string",enum:["off","warn","strict"]},checkMetadata:{type:"boolean"},metadataProfile:{type:"string",enum:["core","strict","custom"]},checkResolution:{type:"boolean"},checkCompleteness:{type:"boolean"},checkLifecycle:{type:"boolean"},checkStaleBlockers:{type:"boolean"},dependencyCycleSeverity:{type:"string",enum:["off","warn","error"]},parentCycleSeverity:{type:"string",enum:["off","warn","error"]},checkFiles:{type:"boolean"},checkStorageIntegrity:{type:"boolean"},strictDirectories:{type:"boolean"},requireMergeDrivers:{type:"boolean"},checkOnly:{type:"boolean"},checkTelemetry:{type:"boolean"},noRefresh:{type:"boolean"},refreshVectors:{type:"boolean"},verboseStaleItems:{type:"boolean"},skipVectors:{type:"boolean"},skipIntegrity:{type:"boolean"},skipDrift:{type:"boolean"},verboseDiagnostics:{type:"boolean"},allAffectedIds:{type:"boolean"},scanMode:{type:"string",enum:["default","tracked-all","tracked-all-strict"]},includePmInternals:{type:"boolean"},verboseFileLists:{type:"boolean"},strictExit:{type:"boolean"},failOnWarn:{type:"boolean"},fixHints:{type:"boolean"},autoFix:{type:"boolean"},fixScope:{type:"array",items:{type:"string",enum:["metadata","resolution","estimates","lifecycle"]}},pruneMissing:{type:"boolean"},checkHistoryDrift:{type:"boolean"},checkCommandReferences:{type:"boolean"},counts:{type:"boolean"},edit:{type:"integer",minimum:1},delete:{type:"integer",minimum:1},dryRun:{type:"boolean"},normalizeProvenance:{type:"boolean"},salvageTail:{type:"boolean"},appendOnly:{type:"boolean"},all:{type:"boolean"},clear:{type:"boolean"},cliOnly:{type:"boolean"},packagesOnly:{type:"boolean"},repair:{type:"boolean"},packageName:{type:"string"},rollback:{type:"string"},noCheckpoint:{type:"boolean"},force:{type:"boolean"},ifAvailable:{type:"boolean"},takeoverStale:{type:"boolean"},ifAbsent:{type:"boolean"},expectAt:{type:"string",minLength:1},next:{type:"boolean"},maxAttempts:{anyOf:[{type:"integer",minimum:1,maximum:100},{type:"string",pattern:"^(?:[1-9]|[1-9][0-9]|100)$"}]},includeDecisions:{type:"boolean"},includeGates:{type:"boolean"},includeContainers:{type:"boolean"},explainRanking:{type:"boolean"},noTags:{type:"boolean"},noExtensionHealth:{type:"boolean"},run:{type:"boolean"},count:{type:"boolean"},sum:{type:"string"},avg:{type:"string"},tree:{type:"boolean"},treeId:{type:"string",minLength:1},definition:{type:"object"},trigger:{type:"string",enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]},gate:{type:"string",minLength:1},treeDepth:{anyOf:[{type:"string"},{type:"number"}]},includeUnparented:{type:"boolean"},gcScope:{type:"array",items:{type:"string",enum:["index","embeddings","runtime","locks"]}},maxDepth:{anyOf:[{type:"string"},{type:"number"}]},nodeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},edgeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},tokenBudget:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},cursor:{type:"string"},direction:{type:"string",enum:["outgoing","incoming","both"]},kind:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},after:{type:"string"},maxPaths:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},sample:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},exemptIsolate:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},collapse:{type:"string",enum:["none","repeated"]},shell:{type:"string",enum:["bash","zsh","fish"]},stdin:{type:"boolean"},file:{type:"string"},preserveSourceIds:{type:"boolean"},folder:{type:"string"},subcommand:{type:"string"},name:{type:"string"},defaultStatus:{type:"string"},alias:{type:"array",items:{type:"string"}},role:{type:"array",items:{type:"string"}},fieldType:{type:"string",enum:["string","number","boolean","string_array"]},commands:{type:"array",items:{type:"string"}},cliFlag:{type:"string"},required:{type:"boolean"},requiredOnCreate:{type:"boolean"},allowUnset:{type:"boolean"},requiredTypes:{type:"array",items:{type:"string"}},infer:{type:"boolean"},minCount:{type:"number"},text:{type:"string"},add:{type:"array",items:{type:"string"}},addGlob:{type:"array",items:{type:"string"}},remove:{type:"array",items:{type:"string"}},migrate:{type:"array",items:{type:"string"}},discover:{type:"boolean"},apply:{type:"boolean"},discoveryNote:{type:"string"},lookupPath:{type:"array",items:{type:"string"}},explain:{type:"boolean"},lines:{type:"string",pattern:"^[1-9]\\d*:[1-9]\\d*$"},decisionDepth:{type:"integer",minimum:1,maximum:32},addNote:{type:"string"},noteConflict:{type:"string",enum:["refuse","replace","append"]},list:{type:"boolean"},appendStable:{type:"boolean"},validatePaths:{type:"boolean"},dep:{type:"array",items:{type:"string"}},depRemove:{type:"array",items:{type:"string"}},replaceDeps:{type:"boolean"},replaceTests:{type:"boolean"},replaceFiles:{type:"boolean"},replaceDocs:{type:"boolean"},comment:{type:"array",items:{type:"string"}},note:{type:"array",items:{type:"string"}},learning:{type:"array",items:{type:"string"}},linkedFile:{type:"array",items:{type:"string"}},linkedTest:{type:"array",items:{type:"string"}},doc:{type:"array",items:{type:"string"}},reminder:{type:"array",items:{type:"string"}},event:{type:"array",items:{type:"string"}},typeOption:{type:"array",items:{type:"string"}},field:{type:"array",items:{type:"string"}},unset:{type:"array",items:{type:"string"}},clearDeps:{type:"boolean"},clearComments:{type:"boolean"},clearNotes:{type:"boolean"},clearLearnings:{type:"boolean"},clearFiles:{type:"boolean"},clearTests:{type:"boolean"},clearDocs:{type:"boolean"},clearReminders:{type:"boolean"},clearEvents:{type:"boolean"},clearTypeOptions:{type:"boolean"},criterion:{type:"array",items:{type:"string"}},clearCriteria:{type:"boolean"},groupBy:{type:"string"},setMode:{type:"string",enum:["element","tuple"]},completion:{type:"boolean"},format:{type:"string"},unbounded:{type:"boolean"},depth:{type:"string",enum:["brief","standard","deep","full"]},section:{type:"array",items:{type:"string",enum:["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]}},activityLimit:{anyOf:[{type:"string"},{type:"number"}]},staleThreshold:{type:"string"},policy:{type:"string"}},xI={schema:{definition:{type:["object","string"]}},assurance:{definition:kI,kind:{type:"string",enum:["measurement","assertion","gate"]},subcommand:{type:"string",enum:["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"]},preset:{type:"string",enum:["software-delivery","research","agent-evaluation","operations"]},enforcement:{type:"string",enum:["warn","block"]},limit:{type:"integer",minimum:1,maximum:1e3}},activity:{harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},"update-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"close-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"history-compact":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},events:{verify:{type:"boolean"},since:{type:"string",minLength:1},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},history:{order:{type:"string",enum:["oldest_first","newest_first"]},harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},remind:{at:{type:"string",minLength:1}}},PX=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],$y={subcommand:{type:"string",enum:[...PX]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...Ww]},mode:{type:"string",enum:[...Gw]},resumeContext:{type:"string"},related:{type:"string"},blocks:{type:"string"},claim:{type:"boolean"},fromSearch:{type:"string"},stepTitle:{type:"string"},step:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},stepBody:{type:"string"},stepOwner:{type:"string"},stepStatus:{type:"string",enum:[...Hc]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...Vw]},linkNote:{type:"string"},promoteToItemDep:{type:"boolean"},allowMultipleActive:{type:"boolean"},file:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},test:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},doc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},decisionText:{type:"string"},decision:{type:"string"},decisionRationale:{type:"string"},decisionEvidence:{type:"string"},discoveryText:{type:"string"},discovery:{type:"string"},validationText:{type:"string"},validation:{type:"string"},validationCommand:{type:"string"},validationExpected:{type:"string"},steps:{type:"array",items:{type:"string"}},materializeType:{type:"string"},materializeParent:{type:"string"},materializeTags:{type:"string"},field:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},Dy={subcommand:{description:"Plan workflow operation to run.",examples:["create","show","add-step","approve"]},stepRef:{description:"Plan step id or order for step lifecycle subcommands.",examples:["plan-step-001","1"]},reorderTo:{description:"New integer order for reorder-step.",examples:[1,"2"]},scope:{description:"Short free-text scope statement describing what the Plan covers.",examples:["Release readiness audit","Search package migration"]},mode:{description:"Plan lifecycle mode.",examples:["draft","research","approved"]},step:{description:"Ordered initial step titles for create (string or array, never comma-split; stepTitle, when also set, becomes the first step). For step subcommands a single value aliases stepTitle.",examples:[["Read the code","Write the fix","Run the tests"]]},file:{description:"File link to attach while creating or materializing a Plan.",examples:["path=src/cli.ts,note=implementation surface"]},test:{description:"Test command link to attach while creating or materializing a Plan.",examples:["command=pnpm build,timeout_seconds=300"]},doc:{description:"Documentation link to attach while creating or materializing a Plan.",examples:["path=docs/SDK.md,note=public API reference"]}},SI={includeGates:{description:"Opt next or claim-next into outcome gates. Blocker and ownership restrictions still apply."},includeContainers:{description:"Opt next or claim-next into containers with unfinished descendants. Blocker and ownership restrictions still apply."},action:{description:"Tool action to execute."},pmExecutable:{description:"Override the pm executable used by actions that invoke or verify an external CLI process.",examples:["pm","node dist/cli.js"]},force:{description:"Allow the selected action to override its supported ownership, terminal-state, or destructive-operation guard."},takeoverStale:{description:"Take over another holder's claim only when it has been idle for mutation_guard.stale_in_progress_hours; an active claim is refused with stale_claim_takeover_refused. Not combinable with force or next."},limit:{description:"Maximum number of rows returned by the selected action.",examples:[10,"25"]},text:{description:"Text payload used by append, comment, note, or learning mutations."},path:{description:"Optional PM data root override for this invocation.",examples:[".agents/pm"]},scope:{description:"Scope selector for commands that operate on project or global state. Linked files, docs, and tests default to project scope when omitted.",examples:["project","global"]},detail:{description:"Detail mode for commands that support concise and deep diagnostics.",examples:["summary","deep"]},trace:{description:"When true for extension-doctor, include actionable registration traces in deep diagnostics."},reload:{description:"When true for extension action payloads, trigger cache-busted extension module reload."},watch:{description:"When true for extension-reload/extension action payloads, enable watch mode semantics."},runtimeProbe:{description:"When true for extension-manage, run a doctor-like runtime activation probe for parity fields."},offline:{description:"Skip remote GitHub and npm freshness checks during package or extension manage; update availability remains unknown."},fixManagedState:{description:"When true for extension-manage/extension-doctor, adopt unmanaged extensions before diagnostics/update checks."},isolated:{description:"When true for extension-doctor/package-doctor, ignore global registrations for hermetic project diagnostics."},ignoreGlobal:{description:"Alias for isolated on extension-doctor/package-doctor action payloads."},target:{description:"Positional target argument for the selected action (ID, source, package source, or extension name).",examples:["pm-a1b2",".agents/pm/extensions/sample","sample-extension"]},capability:{description:"Starter capability selected by extension-init or package-init scaffolding.",examples:["commands","hooks","search","schema"]},declarative:{description:"Generate the package composeExtension declarative blueprint starter."},output:{description:"File path for commands that write generated output, such as package/extension describe Markdown references.",examples:["docs/pm-package-reference.md"]},markdown:{description:"Render the package or extension description as Markdown instead of structured output.",examples:[!0]},github:{description:"GitHub shorthand owner/repo[/path] source for package/extension install actions.",examples:["org/repo/extensions/sample"]},ref:{description:"Git ref/branch/tag used when installing from GitHub shorthand/URL sources.",examples:["main","v1.0.0"]},cliOnly:{description:"Restrict upgrade to the pm CLI/SDK npm package."},packagesOnly:{description:"Restrict upgrade to managed installable pm packages."},repair:{description:"Force npm global reinstall semantics when upgrading the pm CLI/SDK."},tag:{description:"npm version or dist-tag used for CLI and registry package upgrades.",examples:["latest","next","2026.5.11"]},today:{description:"When true for list actions, include only items updated since local midnight today."},recent:{description:"When true for list actions, include only items updated in the last seven days."},packageName:{description:"Override the pm CLI package name for self-upgrade automation and tests.",examples:["@unbrained/pm-cli"]},json:{description:"Emit machine-readable JSON output."},quiet:{description:"Suppress stdout payload output."},noExtensions:{description:"Disable extension loading for this invocation."},noPager:{description:"Disable pager integration for help and long output."},tokenAccounting:{description:"Request a bounded transport-level receipt for output emitted by a compatible CLI or MCP host."},outputInclude:{description:"Comma-separated fields or sections retained by any built-in read action.",examples:["id,title,status","summary,counts"]},outputLimit:{description:"Universal read row ceiling, or unbounded to disable the shared ceiling.",examples:[10,"unbounded"]},outputBudget:{description:"Universal estimated-token ceiling for a read result, or unbounded to disable the shared ceiling.",examples:[600,1200,"unbounded"]},outputFormat:{description:"Universal read-result encoding selector.",examples:["toon","json"]},outputSession:{description:"Caller-carried JSON session state that enforces a token ceiling across read calls and replaces repeated item facts with resolvable context references.",examples:[{version:1,id:"orientation",token_budget:4e3,spent_tokens:0,seen_item_ids:[]}]},outputCursor:{description:"Opaque continuation cursor returned when a declared row collection is compacted by the output budget."},outputRowContract:{description:"Include the row selector and TOON row-encoding contract on a read result."},profile:{description:"Emit deterministic timing diagnostics to stderr."},timeoutMs:{description:"Tool execution timeout in milliseconds.",examples:[12e4]},id:{description:"Item identifier for read or mutation actions.",examples:["pm-a1b2"]},treeId:{description:"Commit, tree, snapshot, or immutable workspace identity judged by an assurance gate.",examples:["0123456789abcdef","release-candidate-3"]},definition:{description:"Structured measurement, assertion, or gate declaration used by assurance put."},trigger:{description:"Lifecycle trigger used to evaluate an assurance gate.",examples:["ci","pre-release"]},gate:{description:"Stable assurance gate id used to filter durable verdict history.",examples:["release-readiness"]},owner:{description:"pm item that owns preset or observation-derived assurance assertions.",examples:["pm-a1b2"]},enforcement:{description:"Explicit next assurance enforcement level.",examples:["warn","block"]},runId:{description:"Background test run identifier.",examples:["tr-kq9x3f-93acde"]},title:{description:"Item title text."},description:{description:"Item description text."},type:{description:"Item type name from the active runtime type registry.",examples:["Task","Feature"]},subcommand:{description:"Subcommand selector for schema, profile, telemetry, and graph actions."},name:{description:"Custom definition name, schema migration source name, or profile name.",examples:["Spike","review","component"]},defaultStatus:{description:"Default status hint recorded for a custom item type.",examples:["open"]},alias:{description:"Aliases for the custom item type or status (repeatable).",examples:[["spike","research"]]},role:{description:"Lifecycle roles for a custom status (schema add-status): draft, active, blocked, terminal, terminal_done, terminal_canceled, default_open, default_close, default_cancel.",examples:[["active"],["terminal","terminal_done"]]},fieldType:{description:"Value type for a custom field (schema add-field): string, number, boolean, or string_array.",examples:["string","number","string_array"]},fieldTypeScope:{description:"Optional item type restricting which records participate in schema rename-field.",examples:["Issue","Feature"]},migrationId:{description:"Optional stable idempotency override used to persist and resume a schema migration plan; omitted values are derived from the workspace and normalized request.",examples:["severity-to-impact-v2"]},commands:{description:"Commands a custom field is wired onto (schema add-field): create, update, update_many, list, search, calendar, context.",examples:[["create","update"],["create","update","list"]]},cliFlag:{description:"Override the auto-derived CLI flag for a custom field (schema add-field).",examples:["--owner"]},required:{description:"Mark a custom field as always required (schema add-field)."},requiredOnCreate:{description:"Mark a custom field as required at create time (schema add-field)."},allowUnset:{description:"Whether a custom field may be cleared via --unset (schema add-field); defaults to true."},allowDuplicate:{description:"Explicitly proceed when strict similarity governance finds likely duplicate items."},allowUnresolvedDeps:{description:"Permit unresolved local dependency targets while returning dependency_target_unresolved warning receipts. Cross-workspace references should use source_kind=external instead.",examples:[!0]},requiredTypes:{description:"Restrict a custom field's requirement to specific item types (schema add-field).",examples:[["Bug"],["Story","Spike"]]},infer:{description:"Infer custom item types from title-prefix conventions (schema add-type); previews unless apply is true."},minCount:{description:"Minimum number of items sharing a title prefix for schema add-type inference (default 10).",examples:[10,25]},preset:{description:"Governance preset for initialization flows.",examples:["minimal","default","strict"]},idPrefix:{description:"Tracker item identifier prefix used by initialization; overrides the positional compatibility prefix.",examples:["pm","work"]},workspace:{description:"Workspace directory where initialization resolves or creates the tracker.",examples:[".","packages/app"]},typePreset:{description:"Domain item-type preset registered during initialization.",examples:["agile","ops","research"]},defaults:{description:"Use non-interactive setup defaults during initialization."},verbose:{description:"Include the full resolved settings tree in init output."},agentGuidance:{description:"Control AGENTS.md/CLAUDE.md guidance behavior during init: ask, add, skip, or status.",examples:["ask","add","skip","status"]},withPackages:{description:"Install all bundled first-party pm packages during initialization."},mergeFence:{description:"Install the repository merge-driver fence for a fresh Git-backed tracker; set false to opt out."},createMode:{description:"Create required-option policy mode.",examples:["strict","progressive"]},defer:{description:"Strict-required create fields whose values are not known yet (GH-1713): deadline, assignee, acceptance_criteria or estimated_minutes. Each is recorded in deferred_fields with deferReason; strict close validation refuses the item until every deferred field holds a value, and warn mode only warns.",examples:[["deadline","assignee"],["acceptance_criteria"]]},deferReason:{description:"Why the deferred values are not known yet, for example the external system the record was imported from. Required with defer.",examples:["Imported from GitHub issue 42"]},schedulePreset:{description:"Schedule-centric create preset for Reminder, Meeting, and Event types.",examples:["lightweight"]},status:{description:"Item status value. Statuses are project-configurable via .agents/pm/settings.json (schema block); the built-in defaults are draft, open, in_progress, blocked, closed, canceled. Custom statuses defined for the project are accepted \u2014 discover the active set with the pm_contracts tool (workspace.statuses) or `pm contracts`. Unknown statuses are rejected at runtime with a did-you-mean hint rather than blocked by a fixed schema enum.",examples:["open","in_progress"]},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for duplicate discovery.",examples:["2026-01-01T00:00:00.000Z"]},exhaustive:{description:"Compare every duplicate pair within the disclosed safety bound; default prefix filtering preserves exact recall."},threshold:{description:"Minimum duplicate similarity score from zero through one.",examples:[.85]},priority:{description:"Priority value in range 0..4.",examples:[0,1,"2"]},order:{description:"Planning order/rank value for create/update, or sort direction (asc|desc) for list-family sorting.",examples:[0,1,"2","asc","desc"]},sort:{description:"List-family sort field selector.",examples:["priority","deadline","updated_at","created_at","title","parent"]},tags:{description:"Comma-delimited tag list.",examples:["pm-cli,agent-ux"]},addTags:{description:"Tags to add to the existing list without replacing it. Each entry may be CSV or a JSON array.",examples:[["agent-ux"],["fix","security"]]},addAc:{description:"Acceptance criteria appended individually without replacing the existing list (one criterion per entry).",examples:[["error path covered by a regression test"]]},removeAc:{description:"Acceptance criteria removed individually by exact text match; the mutation fails atomically if any selector is unmatched (one criterion per entry).",examples:[["superseded manual QA step"]]},removeTags:{description:"Tags to remove from the existing list. Each entry may be CSV or a JSON array.",examples:[["stale"],["legacy","wontfix"]]},deadline:{description:"ISO/date timestamp or relative offset (+6h/+1d/+2w/+6m).",examples:["2026-04-01T00:00:00.000Z","+1d"]},reminder:{description:"Repeatable reminder seed entries at=<iso|relative>,text=<text>.",examples:[["at=+2d,text=Review PR"]]},event:{description:"Repeatable event seed entries start=<iso|relative> with end=<iso|relative> or duration=<relative|30min|PT30M>. Bare `m` remains months for backward compatibility.",examples:[["start=2026-07-01T10:00:00Z,duration=2h,title=planning"],["start=2026-07-01T10:00:00Z,duration=30min,title=standup"],["start=2026-07-01T10:00:00Z,duration=PT30M,title=window"]]},historyEvent:{description:"Unknown-author history target in <item-id>:<one-based-line> form.",examples:[["pm-example:4","pm-example:5"]]},planFingerprint:{description:"Exact SHA-256 returned by a history-author-acknowledge dry-run preview; apply refuses stale or changed source coordinates.",examples:["0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"]},estimate:{description:"Estimated effort in minutes.",examples:[60,"120"]},acceptanceCriteria:{description:"Complete acceptance-criteria text supplied while creating or replacing an item field."},author:{description:"Intentional mutation-author override. Agent harness identity is automatic when omitted."},expectHash:{description:"Expected item revision: the item_hash from get. Each locked write refuses with item_revision_conflict when the item changed since; a bare hash binds to id, <id>=<item_hash> names other items."},attributedAuthor:{description:"Principal attributed to the immutable unknown-author history events after review.",examples:["reviewed-principal"]},message:{description:"History message for mutation audit trail."},ifAbsent:{description:"For annotations, append only when no existing entry has the same resolved author and exact stored text; retries return changed false without a history event."},expectAt:{description:"For annotation edit or delete, the created_at of the entry read at that index; the write is refused with annotation_entry_mismatch when the addressed entry has a different created_at. It compares timestamps, not entry identities.",examples:["2026-11-06T06:02:01.768Z"]},assignee:{description:"Assignee identity."},assigneeFilter:{description:"Assignee presence selector for list, calendar, and context filters.",examples:["assigned","unassigned"]},parent:{description:"Parent item ID filter for hierarchical list queries.",examples:["pm-epic01"]},blockedLimit:{description:"Cap blocked rows returned by the next action (defaults to the ready --limit).",examples:["3"]},readyOnly:{description:"When true, the next action omits the blocked companion list."},unset:{description:"Repeatable list of item-metadata fields to clear explicitly during create/update mutations; each entry may also be a comma-separated field list.",examples:[["deadline","assignee"],["close-reason"]]},clearDeps:{description:"When true, clear linked dependencies."},replaceDeps:{description:"When true for update, atomically replace dependencies with the supplied --dep values."},replaceTests:{description:"When true for update, atomically replace linked tests with the supplied --test values."},replaceFiles:{description:"When true for update, atomically replace linked files with the supplied --file values."},replaceDocs:{description:"When true for update, atomically replace linked docs with the supplied --doc values."},lookupPath:{description:"One or more source paths whose referencing pm items should be returned by files lookup.",examples:[["src/sdk/files.ts"],["README.md","docs/SDK.md"]]},explain:{description:"Include ranked linked-file, rationale, and governing-decision evidence for a files lookup."},lines:{description:"Inclusive start:end source-line range for Git contribution attribution; requires one lookup path.",examples:["10:24"]},decisionDepth:{description:"Maximum typed relationship depth searched for a governing Decision during files lookup.",examples:[8]},clearComments:{description:"When true, clear item comments."},clearNotes:{description:"When true, clear item notes."},clearLearnings:{description:"When true, clear item learnings."},clearFiles:{description:"When true, clear linked files."},clearTests:{description:"When true, clear linked tests."},clearDocs:{description:"When true, clear linked docs."},clearReminders:{description:"When true, clear reminders."},clearEvents:{description:"When true, clear events."},clearTypeOptions:{description:"When true, clear type option metadata."},clearCriteria:{description:"When true for config set criteria-list keys (definition-of-done, metadata-required-fields, lifecycle pattern lists), clear the criteria list."},mode:{description:"Mode selector for search and reindex (keyword|semantic|hybrid).",examples:["keyword","hybrid"]},semanticWeight:{description:"Per-query hybrid semantic weight override in [0,1] for search action; invalid values fall back to settings.",examples:[.2,"0.7"]},op:{description:"History operation filter for activity output.",examples:["create","update","close","update_ownership_bypass"]},fullPeriod:{description:"For day/week/month calendar views, include the full anchored period instead of clipping the start to now."},progress:{description:"Emit progress diagnostics to stderr for long-running operations."},background:{description:"Run linked tests in managed background mode."},addJson:{description:"JSON input: one structured context event for notes, or repeatable linked-test entries for test.",examples:[['{"command":"node scripts/run-tests.mjs test -- tests/unit/output.spec.ts","timeout_seconds":240}']]},eventType:{description:"For notes action, return structured context events whose top-level type matches this value."},includeMeta:{description:"Include structured-event counts for notes reads; filtered reads also include total, returned, limit, and has-more metadata."},allActionable:{description:"For history-author-acknowledge, select every currently actionable undispositioned event."},match:{description:"Run only linked tests whose command or path contains this case-insensitive substring.",examples:["output.spec.ts","coverage"]},onlyIndex:{description:"Run only the 1-based linked-test index from pm test <id> --list order.",examples:[1,"2"]},removeIndex:{description:"Remove linked tests by their 1-based positions from pm test <id> --list order; repeatable and lossless for commands containing commas or equals signs.",examples:[[1],["2","4"]]},update:{description:"Edit one linked test by exact command, command=<value>, or path=<value>, with setJson; ambiguous matches refuse without changes.",examples:["node scripts/run-tests.mjs test","path=tests/example.spec.ts"]},updateIndex:{description:"Edit one linked test at its current 1-based list position with setJson, preserving order and original command provenance.",examples:[1,"2"]},setJson:{description:"Explicit JSON metadata patch for update or updateIndex. Null clears optional fields; command and provenance are immutable.",examples:['{"note":"focused regression","timeout_seconds":120}']},onlyLast:{description:"Run only the most recently added linked-test entry."},envSet:{description:"Repeatable runtime environment KEY=VALUE overrides for linked-test execution.",examples:[["PORT=0","PLAYWRIGHT_HTML_OPEN=never"]]},envClear:{description:"Repeatable runtime environment variable names to clear before linked-test execution.",examples:[["PLAYWRIGHT_BASE_URL"]]},sharedHostSafe:{description:"Apply additive shared-host-safe runtime defaults during linked-test execution."},pmContext:{description:"PM linked-test context mode (schema keeps isolated tracker data; tracker seeds source tracker data; auto uses tracker for PM tracker-read commands; none omits PM_PATH for self-isolating SDK tests in isolated or snapshot workspaces).",examples:["schema","tracker","auto","none"]},overrideLinkedPmContext:{description:"Force run-level --pm-context to override per-linked-test pm_context_mode metadata for all linked-test entries."},workspaceContext:{description:"Source-workspace mode: source preserves read-only source context, isolated omits it for self-sandboxing commands, and snapshot runs from a temporary workspace paired with the selected tracker sandbox.",examples:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{description:"Force run-level --workspace-context over per-linked-test workspace_context_mode metadata."},allowUntrustedLinkedTests:{description:"Explicitly execute commands not yet trusted by this clone when testing.allow_untrusted_linked_tests is also enabled."},acknowledgeLinkedTests:{description:"Record clone-local trust for the item's current linked commands without executing them."},failOnContextMismatch:{description:"Fail linked PM command runs when source and sandbox tracker item counts differ."},failOnSkipped:{description:"Treat skipped linked tests as dependency-failed policy violations."},failOnEmptyTestRun:{description:"Treat successful linked-test commands that report zero executed tests as failures."},requireAssertionsForPm:{description:"Require assertion metadata for linked PM command test entries during run execution."},checkContext:{description:"Run linked PM command context preflight diagnostics before command execution."},fullOutput:{description:"Keep every linked-test row's complete stdout and stderr in the CLI rendering, which otherwise keeps an escape-free tail on a quiet passing run; MCP and SDK results always carry the complete streams."},autoPmContext:{description:"Auto-remediate PM tracker-read linked commands by routing those entries through tracker context regardless of linked-test pm_context_mode overrides."},measure:{description:"Repeatable numeric run evidence in name=value[,unit=...][,threshold=...] form; requires run=true.",examples:[["coverage=100,unit=percent,threshold=100"]]},metricBelow:{description:"Return recorded evidence below a name=value threshold.",examples:["coverage=100"]},metricDiff:{description:"Compare the latest and previous values for one metric.",examples:["coverage"]},dryRun:{description:"Preview command effects without mutating storage artifacts."},normalizeProvenance:{description:"For history-repair: remove invalid legacy provenance observations and emit only aggregate privacy-safe repair evidence."},salvageTail:{description:"For history-repair with one explicit id: remove lines that cannot hold a record (a JSON null, boolean or number) and an invalid trailing suffix after a verified prefix; refuses interior corruption."},appendOnly:{description:"For history-repair: bridge each chain break with one appended, sealed record instead of re-anchoring recorded entries, so every earlier line stays byte-identical."},all:{description:"For history-repair action: scan every stream for drift and repair each drifted stream in one audited pass (mutually exclusive with id)."},clear:{description:"For focus action: clear the session focused item instead of setting it (mutually exclusive with id)."},gcScope:{description:"Repeatable gc scope selector values (index, embeddings, runtime, locks, checkpoints, transactions).",examples:[["index","embeddings"],["runtime"],["locks"],["checkpoints"]]},storage:{description:"For stats action: include aggregate history-stream storage metrics (total streams/lines/bytes, largest + deepest streams, oldest/newest entries) for compaction and storage planning."},fieldUtilization:{description:"For stats action: include a field_utilization block reporting present/total/percent for content fields (notes, learnings, files, docs, tests, comments, deps, body, linked_command) across all items so under-documented dimensions are visible at a glance."},measurements:{description:"For stats action: include the audited append-only improvement ledger and baseline-to-latest trends."},metric:{description:"Exact improvement metric name used to filter ledger reads.",examples:["quality.coverage.lines"]},measurementLimit:{description:"Maximum newest improvement observations returned by stats.",examples:[50]},observe:{description:"Repeatable audited observation in name=value[,unit=...][,threshold=...] form.",examples:[["quality.coverage.lines=100,unit=percent,threshold=100"]]},improvementDirection:{description:"Improvement direction for newly recorded observations.",examples:["higher","lower","target"]},measurementSource:{description:"Producing gate or instrument for a new observation.",examples:["pnpm coverage"]},measurementItem:{description:"Tracked item that owns an improvement observation.",examples:["pm-123abc"]},measurementRevision:{description:"Explicit source revision for a new observation.",examples:["0123456789abcdef"]},provenanceCoverage:{description:"For stats action: compare configured provenance descriptors with bounded immutable-history observations."},fleetAttribution:{description:"For stats action: derive observational throughput, rework, and defect-escape rates by harness, model, and author source."},eventLimit:{description:"Maximum immutable history events consumed by an analytics projection.",examples:[1e4]},minimumSample:{description:"Minimum denominator before analytics rates are reported.",examples:[5]},offset:{description:"Number of matching rows to skip before limit is applied.",examples:[0,50,"100"]},provenance:{description:"Return patch-free immutable author, harness, instance, and extensible provenance rows."},provenanceSummary:{description:"Include bounded observed, unavailable, legacy-missing, and unresolved-author counts."},agentInstance:{description:"Privacy-safe agent invocation fingerprint filter, supplied once or as a list.",examples:["a1b2c3d4",["a1b2c3d4","e5f6g7h8"]]},provenanceFilter:{description:"Exact extensible provenance predicate in dimension=value form, supplied once or as a list.",examples:["model=gpt-5.6-sol",["effort=xhigh","role=reviewer"]]},before:{description:"For history-compact, compact entries strictly before this boundary (version number or ISO timestamp). Single-id mode only.",examples:["5","2026-06-01T00:00:00.000Z"]},at:{description:"Read-only historical projection boundary as an item version or ISO timestamp.",examples:["3","2026-07-01T12:00:00.000Z"]},allOver:{description:"For history-compact bulk mode, compact every stream with more than N entries. When history.compact_policy is enabled and this is omitted, the policy's max_entries is used.",examples:[200,"500"]},minEntries:{description:"For history-compact bulk mode, skip streams with at most N entries as already-compact (default 3).",examples:[3,"10"]},closed:{description:"For history-compact bulk mode, compact only closed (terminal) items' history streams."},allStreams:{description:"For history-compact bulk mode, compact every history stream regardless of lifecycle state."},literal:{description:"Repeatable literal matcher used by history-redact to scrub exact string values.",examples:["[redacted_path_prefix]/private/path"]},regex:{description:"Repeatable regex matcher used by history-redact. Accepts either /pattern/flags or a raw pattern (global mode is auto-enabled).",examples:["/192\\\\.168\\\\.[0-9.]+/g","token=[A-Za-z0-9_-]+"]},replacement:{description:'Replacement text used by history-redact (defaults to "[redacted]").',examples:["[scrubbed_path]"]},validateClose:{description:'Close-time metadata validation mode ("off", "warn", or "strict").',examples:["off","warn","strict"]},checkMetadata:{description:"Run metadata completeness checks."},metadataProfile:{description:"Select metadata validation profile for --check-metadata.",examples:["core","strict","custom"]},checkResolution:{description:"Run closed-item resolution metadata checks."},checkCompleteness:{description:"Evaluate declarative lifecycle field requirements, with per-type counts and bounded missing-field diagnostics."},checkLifecycle:{description:"Run active-item lifecycle governance drift checks."},checkStaleBlockers:{description:"Include stale blocker-pattern diagnostics in lifecycle checks."},dependencyCycleSeverity:{description:"Set dependency-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},parentCycleSeverity:{description:"Set parent-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},checkFiles:{description:"Run linked-file and orphaned-file checks."},checkStorageIntegrity:{description:"Run deep item, history, index, and vector storage integrity checks."},strictDirectories:{description:"Treat optional item-type directories as required health failures."},requireMergeDrivers:{description:"Treat never-installed clone-local semantic merge drivers as required health failures."},checkOnly:{description:"For health action, run read-only diagnostics without refreshing vectors."},checkTelemetry:{description:"For health action, probe telemetry endpoint health and include network diagnostics."},noRefresh:{description:"For health action, skip vector refresh while still running checks."},refreshVectors:{description:"For health action, explicitly refresh stale vectors."},verboseStaleItems:{description:"For health action, include full stale-item arrays in vectorization details."},verboseAuthorEvents:{description:"For health action, include every actionable unknown-author event coordinate."},skipVectors:{description:"For health action, skip vectorization checks for a faster diagnostic run."},skipIntegrity:{description:"For health action, skip item/history file integrity checks for a faster diagnostic run."},skipDrift:{description:"For health action, skip history drift hash checks for a faster diagnostic run."},scanMode:{description:"Select file candidate scan mode for --check-files.",examples:["default","tracked-all","tracked-all-strict"]},includePmInternals:{description:"Include PM storage internals in tracked-all candidate scans."},verboseFileLists:{description:"For validate action, include full file-path lists for --check-files details."},verboseDiagnostics:{description:"For validate action, include full diagnostic ID lists instead of compact summaries."},strictExit:{description:"Apply the selected capability's strict exit policy; health also requires merge drivers."},failOnWarn:{description:"Alias for strictExit in health, validation, history, and managed doctor actions."},fixHints:{description:"For validate action, add a machine-executable fix_hints[] of pm commands to each failing check's details."},autoFix:{description:"For validate action, apply the safe, deterministic subset of fix-hint remediations (field backfills) automatically; combine with dryRun to preview and fixScope to grant gated scopes."},fixScope:{description:"For validate action, grant --auto-fix scopes (metadata, resolution, estimates, lifecycle). Defaults to the safe scopes metadata and resolution; estimates (per-type default estimated_minutes backfill) and lifecycle must be named explicitly.",examples:[["estimates"],["lifecycle"],["metadata","resolution"]]},pruneMissing:{description:"For validate action, remove stale linked-file/doc LINKS whose paths classified as deleted (link removal only \u2014 never touches real files); honors dryRun."},checkHistoryDrift:{description:"Run item/history hash drift checks."},checkCommandReferences:{description:"Run linked-command PM-ID reference checks."},edit:{description:"For comments, notes, and learnings actions, replace the annotation at this 1-based index with supplied replacement text."},delete:{description:"For comments, notes, and learnings actions, delete the annotation at this 1-based index."},stdin:{description:"For comments, notes, and learnings actions, read annotation text from piped stdin (supports multiline markdown)."},file:{description:"CLI-only path to an input file for commands that read payload text; tool actions exclude host file access.",examples:["notes/comment.md"]},preserveSourceIds:{description:"Preserve explicit source IDs during Beads imports instead of normalizing to tracker prefix.",examples:[!0]},appendStable:{description:"When true for files action, preserve existing linked-file order and append new links without full-array resorting."},discover:{description:"When true for files action, use `pm files discover <id>` to scan item text for referenced file paths."},apply:{description:"Persist changes instead of returning a dry-run preview: for files discovery, add the missing discovered file links; for schema add-type --infer, register the inferred custom item types."},discoveryNote:{description:"Note attached to file links added by files discovery.",examples:["discovered from item text"]},addNote:{description:"Note attached to every link added by add/addGlob in this call (per-entry embedded note= wins; requires add or addGlob). Maps to the CLI --note flag on pm files/pm docs.",examples:["command wiring"]},noteConflict:{description:"How add/addGlob treat a link that already has a different note: refuse (default, keeps the stored note), replace, or append (requires add or addGlob). Maps to the CLI --note-conflict flag on pm files/pm docs.",examples:["append"]},list:{description:"When true, list command-specific entries without mutating state (for example linked paths for files/docs or topics for guide).",examples:[!0]},stream:{description:"Stream selector: test-runs logs accepts stdout|stderr|both; activity accepts boolean/rows|ndjson|jsonl for line-delimited output.",examples:["stderr","stdout","both","rows","ndjson","jsonl",!0]},tail:{description:"Number of lines to tail for background run logs.",examples:[100]},query:{description:"Search query text for search action."},for:{description:"Named context intent projection declared for the selected read action.",examples:["orient","inspect","triage","execute","discover"]},keywords:{description:"Alias for query in search action payloads."},includeLinked:{description:"Include readable linked docs/files/tests content in keyword and hybrid lexical scoring."},titleExact:{description:"For search action, require exact normalized title match for the full query string."},phraseExact:{description:"For search action, require exact normalized query phrase match in item text fields."},highlight:{description:"For search action, emit per-field matched-text snippets (wrapped in \xAB\u2026\xBB) on each hit. Off by default."},includeBody:{description:"When true for list-family actions, include item body text in projected rows."},noTruncate:{description:"When true for list-family actions, return every matched row, overriding any limit (surfaces total when rows were dropped)."},strictRead:{description:"When true for list-family actions, fail if any source item or item directory cannot be read."},compact:{description:"Render compact projection output for search and list-family actions."},raw:{description:"For activity, restore the compact per-event stream instead of the default item digest."},brief:{description:"Emit compact low-token output for commands that support terse projections or health details.",examples:[!0]},full:{description:"Enable command-specific full/detail output mode when supported, such as deep item reads for get or full payload mode for search/history."},includeEmpty:{description:"For stats, restore zero-count registered type and lifecycle-status buckets."},fields:{description:"Comma-separated projection fields for get, search, list-family, context, or package listing outputs. Valid field names are command-specific (e.g. score/matched_fields apply to search; context projects focus-row fields such as priority/deadline/completion_pct; package explore/manage rows take package keys such as name/version/activation_status/update_available, and package catalog rows take alias/installed/install_command).",examples:["id,title,status,parent,type","id,title,score,matched_fields","id,title,priority,deadline","name,version,activation_status"]},groupBy:{description:"Comma-separated aggregate grouping fields (supported: parent,type,priority,status,assignee,tags,sprint,release).",examples:["parent,type","type,status","priority,assignee","tags","sprint,release"]},setMode:{description:"Aggregate array dimensions by distinct element (default), or by the complete normalized tuple. Empty sets retain a null group.",examples:["element","tuple"]},count:{description:"Enable grouped count output for aggregate action."},completion:{description:"For aggregate action, add open/in_progress/closed/other counts and completion_pct per group."},sum:{description:"Numeric field to sum per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},avg:{description:"Numeric field to average per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},tree:{description:"When true for list/get actions, render recursive parent/child tree ordering."},treeDepth:{description:"Maximum recursion depth for tree output (0 keeps root rows only).",examples:[0,1,"2"]},includeUnparented:{description:"Include unparented rows when aggregate grouping includes parent."},maxDepth:{description:"Maximum dependency traversal depth for deps action (0 keeps only the root node).",examples:[0,1,"2"]},nodeLimit:{description:"Maximum related nodes returned by deps --format context.",examples:[10,"20"]},edgeLimit:{description:"Maximum related edges returned by deps --format context.",examples:[20,"40"]},tokenBudget:{description:"Maximum estimated output tokens for the command output.",examples:[600,"1200"]},cursor:{description:"Opaque continuation cursor returned by deps --format context."},direction:{description:'Graph-context traversal direction for deps action ("outgoing", "incoming", or "both").',examples:["both","incoming"]},kind:{description:"Registered relationship kinds narrowing deps --format context traversal (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},after:{description:"Opaque action-specific continuation cursor returned by the preceding bounded query.",examples:["pm-x1y2"]},maxPaths:{description:"Maximum enumerated paths for graph paths queries.",examples:[5,"10"]},sample:{description:"Maximum evidence sample entries per graph audit finding.",examples:[10,"25"]},exemptIsolate:{description:"Item ids the graph audit treats as explicitly valid isolates (string, comma-separated, or array).",examples:["pm-x1y2",["pm-x1y2","pm-a3b4"]]},exemptIsolateType:{description:"Item types whose active isolates the graph audit treats as policy-valid (string, comma-separated, or array).",examples:["Reminder",["Reminder","Event"]]},saveBaseline:{description:"When true, persist the graph audit census as the change-since-baseline comparison point (audit only)."},rebuild:{description:"When true, rebuild and warm the durable graph index (graph index only)."},collapse:{description:'Dependency tree collapse mode for deps action ("none" or "repeated").',examples:["none","repeated"]},summary:{description:"When true, return the command's compact summary projection (deps counts, health rollup, or contracts command intents)."},shell:{description:"Shell target for completion generation.",examples:["bash"]},eagerTags:{description:"When true for completion, eagerly embed current tracker tags into generated scripts (legacy mode)."},contractAction:{description:"Filter contracts schema to one tool action.",examples:["create","update"]},command:{description:"Scope contracts output to one CLI command name; action/schema surfaces narrow by default.",examples:["create","search","list"]},schemaOnly:{description:"When true, contracts action returns schema-focused payloads (mutually exclusive with flagsOnly/availabilityOnly)."},flagsOnly:{description:"When true, contracts action returns only command flag surface payloads (mutually exclusive projection mode)."},availabilityOnly:{description:"When true, contracts action returns only action availability payloads (mutually exclusive projection mode)."},runtimeOnly:{description:"When true, contracts action only includes actions invocable in the current runtime."},activeOnly:{description:"Alias for runtimeOnly in contracts action payloads."},depth:{description:"Context depth level controlling how many sections are included (brief=focus+agenda, standard=+hierarchy/activity/progress/workload, deep=all sections, full=every section with no per-section row cap).",examples:["brief","standard","deep","full"]},section:{description:"Repeatable section selector for context; overrides --depth when provided.",examples:[["hierarchy","activity"],["blockers","files","staleness"]]},activityLimit:{description:"Maximum number of recent activity entries to include in context output.",examples:[5,10,"20"]},staleThreshold:{description:"Staleness cutoff in days for context staleness section (e.g. 7 or 7d).",examples:["7","14d","30"]}},AI={health:{strictExit:{description:"Return non-zero for a failing health verdict; also require merge drivers."}},validate:{strictExit:{description:"Return non-zero when validation reports warnings."}},"extension-doctor":{strictExit:{description:"Return non-zero when extension diagnostics report warnings or a non-ok summary."}},"package-doctor":{strictExit:{description:"Return non-zero when package diagnostics report warnings or a non-ok summary."}},history:{strictExit:{description:"Return non-zero for history verification failures when verify is enabled."},order:{description:"Display direction after selecting the latest matching entries; defaults to newest_first for compact/provenance and oldest_first for full history.",examples:["oldest_first","newest_first"]}},extension:{strictExit:{description:"For doctor operations, return non-zero on warnings or a non-ok diagnostic summary."}},package:{strictExit:{description:"For doctor operations, return non-zero on warnings or a non-ok diagnostic summary."}},assurance:{subcommand:{description:"Assurance operation: list, show, put, remove, run, verdicts, presets, apply, derive, promote, risk, or lineages.",examples:["list","run","risk","lineages"]},kind:{description:"Assurance declaration kind for registry operations: measurement, assertion, or gate.",examples:["measurement","assertion","gate"]},id:{description:"Stable assurance declaration id or gate id, depending on subcommand.",examples:["active-issues","release-readiness"]},limit:{description:"Maximum number of newest assurance verdicts returned.",examples:[10,25]},preset:{description:"Built-in assurance project shape to preview or apply.",examples:["software-delivery","agent-evaluation"]}},update:{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},"update-many":{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},stats:{since:{description:"Inclusive ISO 8601 timestamp or negative duration lower bound for provenance and fleet analytics.",examples:["2026-08-01T00:00:00.000Z","-30d"]}},events:{verify:{description:"Verify complete selected authoritative chains before filtering and pagination."},since:{description:"Durable event cursor returned as next_cursor, or an inclusive event timestamp.",examples:["eyJmaW5nZXJwcmludCI6Ii4uLiJ9","2026-08-01T00:00:00.000Z"]},type:{description:"Mutation event type filter, supplied once or as a list.",examples:["create",["create","update"]]},author:{description:"Mutation author filter, supplied once or as a list.",examples:["agent-a",["agent-a","agent-b"]]},item:{description:"Tracked item id filter, supplied once or as a list.",examples:["pm-a1b2",["pm-a1b2","pm-c3d4"]]},limit:{description:"Maximum mutation events returned, from 0 through 1000.",examples:[0,100]},cursorMode:{description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event.",examples:["batch","row"]}},remind:{at:{description:"Reminder time as an ISO 8601 timestamp or supported relative expression.",examples:["2026-08-02T09:00:00+02:00","tomorrow 09:00"]}},deps:{tokenBudget:{description:"Maximum estimated output tokens for deps --format context.",examples:[600,"1200"]}},comments:{full:{description:"Return the complete post-mutation comment history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a comment only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},notes:{full:{description:"Return the complete post-mutation note history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a note only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for structured note event filtering.",examples:["2026-01-01T00:00:00.000Z"]}},learnings:{full:{description:"Return the complete post-mutation learning history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a learning only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},next:{tag:{description:"Only recommend items carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the recommendation context.",examples:[600,"1200"]}},claim:{tag:{description:"When claiming the next item, only consider work carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the next-item context returned with the claim.",examples:[600,"1200"]}},close:{text:{description:"Backward-compatible alias for the item close reason when reason is not provided."}},"close-task":{text:{description:"Close reason used before releasing the item's active assignment."}},schema:{definition:{description:"Workflow policy declaration for policy-put, or proposed item fields for policy-check."},policy:{description:"Declared approval rule id for policy-approve."},name:{description:"Custom item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse.",examples:["Spike","review","component"]}},profile:{name:{description:"Profile name for show/apply/lint. Built-in profiles are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too.",examples:["agile","ops","research"]}},graph:{subcommand:{description:"Graph query selector: ancestors|descendants|predecessors|successors|paths|impact|analyze|audit|communities|redundancy|dominators|slack|centrality|articulation|plan|index. Traversals, paths, impact, and dominators require id; paths also requires target; slack reports critical-path float, centrality ranks betweenness/closeness/degree, articulation reports cut points and bridges; plan derives dry-run remediation proposals from the governance audit; index reports, rebuilds, or clears the durable cross-process graph index.",examples:["successors","audit"]},clear:{description:"When true, delete the durable graph index (graph index only)."},id:{description:"Root item id for traversal, paths, impact, and dominators graph queries.",examples:["pm-x1y2"]},target:{description:"Target item id for graph paths queries.",examples:["pm-a3b4"]},direction:{description:'Edge orientation for graph paths/impact/dominators queries ("outgoing", "incoming", or "both"; default "both").',examples:["incoming"]},kind:{description:"Registered relationship kinds narrowing the graph query (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},maxDepth:{description:"Maximum graph traversal depth (non-negative integer).",examples:[2,"4"]},after:{description:"Resume a hierarchy/ordering graph traversal after this previously returned node id.",examples:["pm-x1y2"]},limit:{description:"Maximum returned rows per bounded graph collection (traversal ids, impact rows, analyze/communities samples, redundancy rows, dominator bottlenecks).",examples:[10,"25"]},summary:{description:"When true, return counts-first graph envelopes without row collections."}}};Nr();Go();var LX={...xI,"history-attest":{verify:{type:"object",additionalProperties:!0},output:{not:{}}}},Ku={...hc,pause:{type:"boolean"},handoff:{type:"string"},releaseAssignment:{type:"boolean"},hashAlgorithm:{type:"string",enum:["sha256","sha512"]}},Yu={...SI,pause:{description:"Return work to its configured open status before releasing ownership."},handoff:{description:"Release into a configured non-terminal queue with a required evidence message."},releaseAssignment:{description:"Release assignment after recording closure evidence."},hashAlgorithm:{description:"Digest for detached history bundles; defaults to sha256."}},MX=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],$X=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],DX=new Set(["action","cwd","options",...Object.keys(Ku).filter(e=>e!=="severity")]);var FX={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],claim:["fullChangedFields","idOnly"],release:["fullChangedFields","idOnly"],"start-task":["fullChangedFields","idOnly"],"pause-task":["fullChangedFields","idOnly"],"close-task":["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},PI=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],ETe=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(tn.filter(e=>e==="upgrade"||e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function Kt(e){return as(e)}var jX=Kt([...mc.map(e=>e.param),...ys.map(e=>e.param)]),LI=Kt([..._c.map(e=>e.param),...ys.map(e=>e.param),"force"]),UX=Kt([...Iy.map(e=>e.param),...LI.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),zX=Kt([...Ny.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),TI=Kt([...Ly.map(e=>e.param),"past","section"]),HX=Kt([...Py.map(e=>e.param),"stream"]),Fy=Kt([...Ty.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),ws=Fy.filter(e=>e!=="all"&&e!=="status"),Jr=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],qX=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],BX=Kt([...Oy.map(e=>e.param),"count","completion","includeUnparented"]),GX=Kt(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...Cy.map(e=>e.param)]),OI=Kt(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","includeGates","includeContainers","tokenBudget","explainRanking"]),$t=["author","message","force"],MI=["releaseAssignment","text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],gc=["author","assignee","message","force"],WX=["dryRun","target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","offline","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn","fields"];function CI(e){return{[`${e}-init`]:{required:["target"],optional:["scope","capability",...e==="package"?["declarative"]:[]]},[`${e}-install`]:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},[`${e}-uninstall`]:{required:["target"],optional:["scope"]},[`${e}-explore`]:{optional:["scope","fields"]},[`${e}-manage`]:{optional:["scope","runtimeProbe","fixManagedState","offline","fields"]},[`${e}-describe`]:{optional:["target","scope","markdown","output"]},[`${e}-reload`]:{optional:["scope","watch"]},[`${e}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${e}-catalog`]:{optional:["scope","fields"]},[`${e}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${e}-adopt-all`]:{optional:["scope"]},[`${e}-activate`]:{required:["target"],optional:["scope"]},[`${e}-deactivate`]:{required:["target"],optional:["scope"]},[e]:{optional:WX,dependentAnyOfRequired:[{property:"dryRun",value:!0,anyOfRequired:[["install","target"],["install","github"]]}],mutuallyExclusiveWhen:[[{property:"dryRun",schema:{const:!0}},{property:"install",schema:{const:!1}}]]}}}var RI={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},II={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},Ju={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...CI("extension"),...CI("package"),"package-upgrade":II,install:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},upgrade:II,create:{required:["title","description","type","status","priority","message"],optional:jX},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:Fy,mutuallyExclusiveWhen:Jr},"list-all":{optional:Fy,mutuallyExclusiveWhen:Jr},"list-draft":{optional:ws,mutuallyExclusiveWhen:Jr},"list-open":{optional:ws,mutuallyExclusiveWhen:Jr},"list-in-progress":{optional:ws,mutuallyExclusiveWhen:Jr},"list-blocked":{optional:ws,mutuallyExclusiveWhen:Jr},"list-closed":{optional:ws,mutuallyExclusiveWhen:Jr},"list-canceled":{optional:ws,mutuallyExclusiveWhen:Jr},aggregate:{optional:BX},guide:{optional:["list","format","depth"]},context:{optional:TI},ctx:{optional:TI},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:GX,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["verify","since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","preCommitHook","stage","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:RI,event:RI,remind:{required:["title"],optional:["at","text","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...OI,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","order","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-attest":{optional:["verify","output","hashAlgorithm"],mutuallyExclusive:[["verify","hashAlgorithm"]]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...$t],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance","salvageTail","appendOnly",...$t],oneOfRequired:[["id"],["all"]],mutuallyExclusiveWhen:[[{property:"appendOnly",schema:{const:!0}},{property:"salvageTail",schema:{const:!0}}],[{property:"appendOnly",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"all",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...$t]},schema:{mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"policy-mode"}},{property:"name",schema:{not:{enum:["advise","refuse"]}}}]],required:["subcommand"],optional:["definition","policy","message","name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"policy-put",required:["definition"]},{property:"subcommand",value:"policy-remove",required:["name"]},{property:"subcommand",value:"policy-mode",required:["name"]},{property:"subcommand",value:"policy-check",required:["name"]},{property:"subcommand",value:"policy-approve",required:["name","policy"]},{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","inheritFocus","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...PI,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...$t]},activity:{optional:HX},restore:{required:["id","target"],optional:$t},update:{required:["id"],optional:LI,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:UX,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...MI,...$t]},"close-many":{optional:zX},delete:{required:["id"],optional:["dryRun",...$t]},append:{required:["id","body"],optional:$t},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent","expectAt",...$t],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent","expectAt",...$t],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent","expectAt",...$t],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","noteConflict","discover","apply","discoveryNote","appendStable","validatePaths","full","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...$t],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]},{property:"noteConflict",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","noteConflict","list","validatePaths","full",...$t],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]},{property:"noteConflict",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["list","add","addJson","remove","removeIndex","update","updateIndex","setJson","run","match","onlyIndex","onlyLast","full","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","fullOutput","autoPmContext","measure","metricBelow","metricDiff",...$t],dependentAnyOfRequired:[{property:"update",anyOfRequired:[["setJson"]]},{property:"updateIndex",anyOfRequired:[["setJson"]]},{property:"setJson",anyOfRequired:[["update"],["updateIndex"]]}],mutuallyExclusive:[["update","updateIndex"],["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","fullOutput","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit","exhaustive"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkCompleteness","checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"risk",required:["definition"]},{property:"subcommand",value:"lineages",required:["definition"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}],mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"risk"}},{property:"definition",schema:{not:{required:["policy","change"]}}}],[{property:"subcommand",schema:{const:"lineages"}},{property:"definition",schema:{anyOf:[{required:["change"]},{not:{required:["policy"]}}]}}]]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:qX},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["start","id","next","ifAvailable","takeoverStale","maxAttempts","includeDecisions",...OI,...gc],oneOfRequired:[["id"],["next"]],mutuallyExclusiveWhen:[[{property:"start",schema:{const:!0}},{property:"ifAvailable",schema:{const:!0}},{property:"id",schema:{type:"string"}}],[{property:"takeoverStale",schema:{const:!0}},{property:"force",schema:{const:!0}}],[{property:"takeoverStale",schema:{const:!0}},{property:"next",schema:{const:!0}}]]},release:{required:["id"],optional:["pause","handoff",...gc],dependentAnyOfRequired:[{property:"handoff",anyOfRequired:[["message"]]}],mutuallyExclusiveWhen:[[{property:"pause",schema:{const:!0}},{property:"handoff",schema:{type:"string"}}]]},"start-task":{required:["id"],optional:[...gc,"takeoverStale"],mutuallyExclusiveWhen:[[{property:"takeoverStale",schema:{const:!0}},{property:"force",schema:{const:!0}}]]},"pause-task":{required:["id"],optional:gc},"close-task":{required:["id"],optional:["text","validateClose",...gc]},"item-reopen":{required:["id","reason"],optional:["status","expectedResult","author","message","force"]}},jy=Object.freeze(Object.fromEntries(tn.map(e=>[e,Ju[e]])));function $I(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function VX(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=Yu[e];return{...n,description:r?.description??$I(e),...r?.examples?{examples:r.examples}:{}}}function KX(e,t){if(e==="history-attest"&&t==="verify")return{description:"Compare all retained history streams with a detached JSON proof object. Server-local proof paths are not accepted over MCP."};if(e==="history-attest"&&t==="output")return{description:"Local CLI/SDK only. MCP rejects this field; save the returned JSON bundle on the client."};if(e==="claim"&&t==="start")return{description:"Move the claimed item to its configured in-progress status; with next, the selected item is claimed and started in one locked write."};if((e==="list"||e.startsWith("list-"))&&t==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(e==="plan"&&Object.prototype.hasOwnProperty.call(Dy,t))return Dy[t];let n=AI[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:Yu[t]}function JX(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},i=KX(e,t);return{...r,description:i?.description??$I(t),...i?.examples?{examples:i.examples}:{}}}function YX(e,t){if(e==="claim"&&t==="start")return{type:"boolean"};let n=LX[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call($y,t)?$y[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:t==="pause"||t==="handoff"||t==="releaseAssignment"||t==="hashAlgorithm"?Ku[t]:hc[t]}function XX(e,t){let n={action:{const:e,description:Yu.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let i=YX(e,r);i&&(n[r]=JX(e,r,i))}return n}function ZX(e,t){let n=t.flat();return t.map(r=>{let i=n.filter(o=>!r.includes(o));return{required:[...r],...i.length>0?{not:{anyOf:i.map(o=>({required:[o]}))}}:{},...e==="history-repair"&&r.includes("all")?{properties:{all:{const:!0}}}:e==="claim"&&r.includes("next")?{properties:{next:{const:!0}}}:{}}})}function NI(e,t){return{...t===void 0?{}:{properties:{[e]:{const:t}}},required:[e]}}function QX(e){let t=[];if(e.conditionalRequired&&e.conditionalRequired.length>0)for(let n of e.conditionalRequired)t.push({if:NI(n.property,n.value),then:{required:n.required}});if(e.dependentAnyOfRequired&&e.dependentAnyOfRequired.length>0)for(let n of e.dependentAnyOfRequired)t.push({if:NI(n.property,n.value),then:{anyOf:n.anyOfRequired.map(r=>({required:[...r]}))}});if(e.mutuallyExclusive&&e.mutuallyExclusive.length>0)for(let n of e.mutuallyExclusive)t.push({not:{required:Kt(n)}});if(e.mutuallyExclusiveWhen&&e.mutuallyExclusiveWhen.length>0)for(let n of e.mutuallyExclusiveWhen)t.push({not:{allOf:n.map(r=>({properties:{[r.property]:r.schema},required:[r.property]}))}});return t}function DI(e){if(!Object.prototype.hasOwnProperty.call(Ju,e))return;let t=Ju[e],n=FX[e]??[];return Kt(["action",...MX,...Bo(e)!==void 0?$X:[],...n,...Zp.has(e)?["expectHash"]:[],...t.required??[],...t.optional??[]])}function e6(e){let t=Ju[e],n=Kt(t.required??[]),r=DI(e),i={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:XX(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(i.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(i.oneOf=ZX(e,t.oneOfRequired));let o=QX(t);return o.length>0&&(i.allOf=o),i}function FI(e){let t,n=()=>t??=e();return new Proxy({},{get:(r,i)=>n()[i],has:(r,i)=>i in n(),ownKeys:()=>Reflect.ownKeys(n()),getOwnPropertyDescriptor:(r,i)=>{let o=Reflect.getOwnPropertyDescriptor(n(),i);return o&&(o.configurable=!0),o}})}var Uy="4.28.1",jI=Uy.split(".")[0],UI="1.12.0",t6=FI(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${jI}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":Uy,type:"object",oneOf:tn.map(e=>e6(e))}));function n6(e,t){let n=VX(e,t);if(typeof n.type=="string")return n;let i=(Array.isArray(n.anyOf)?n.anyOf:[]).find(a=>typeof a.type=="string");if(i){let{anyOf:a,...c}=n;return{...i,...c}}let{anyOf:o,...s}=n;return{...s,type:"string"}}function r6(){let e={action:{type:"string",description:Yu.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(let t of Object.keys(Ku).sort())e[t]=n6(t,Ku[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":UI,type:"object",additionalProperties:!1,required:["action"],properties:e}}var i6=FI(r6);var o6=["close_reason","close-reason"],zI=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],HI=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],s6=[...zI,...HI],qI=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}],BI=[...s6,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...qI],ITe=[...zI,{canonical:"close-reason",aliases:o6,optionKey:"closeReason",metadataKey:"close_reason"},...HI,...qI];var NTe=(()=>{let e=new Map;for(let t of BI)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),PTe=BI.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");On();import{Option as qOe}from"commander";On();Nr();Nr();Go();var ZTe=new Set([...mx,..._x]);Td();var h6=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"]),gCe=new Set([...h6].filter(e=>e!=="file"));var yCe=new Map(Yi.flatMap(({target:e,keys:t})=>t.map(n=>[n,e])));var g6="2026-07-15T06:22:12.276Z",y6=Date.parse(g6),w6=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],WI=e=>typeof e=="string"?e:"",v6=e=>{let t=e??{},n=WI(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(WI(t.ts))>=y6);return w6[r][i]};function b6(e,t,n=20,r=new Set,i=!1){let o=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[f,p]of t.split(/\r?\n/).entries()){let m;try{m=JSON.parse(p)}catch{continue}l+=1;let g=v6(m);if(g!=="attributed"){if(d+=1,g==="actionable_unknown"&&r.has(`${e}:${f+1}`)){u+=1;continue}a[g]+=1,i&&g==="actionable_unknown"&&s.push({item_id:e,line:f+1}),o.length<c&&o.push({item_id:e,line:f+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}}function E6(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let o=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.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 Xu=async(e,t=20,n=!1)=>{let r=Hy.join(e,"history"),i;try{i=(await zy.readdir(r)).filter(v=>v.endsWith(".jsonl")).sort((v,E)=>v.localeCompare(E))}catch{i=[]}let o=new Set,s=[],a=[],c=0,l=0,d=0,u=0,f=0,p=0,m="_workspace.jsonl",g=new Set;if(i.includes(m))try{g=E6(await zy.readFile(Hy.join(r,m),"utf8"))}catch{g=new Set}for(let v of i){let E;try{E=await zy.readFile(Hy.join(r,v),"utf8")}catch{continue}let T=v.slice(0,-6),R=b6(T,E,t-s.length,g,n);c+=1,l+=R.checked_events,d+=R.unknown_event_count,u+=R.legacy_unknown_event_count,f+=R.actionable_unknown_event_count,p+=R.acknowledged_actionable_event_count,R.unknown_event_count>0&&o.add(T),s.push(...R.samples),n&&a.push(...R.actionable_events)}let y=u+f;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:f,acknowledged_actionable_event_count:p,affected_item_ids:[...o].sort((v,E)=>v.localeCompare(E)),samples:s,samples_truncated:y>s.length,...n?{actionable_events:a}:{}}};Z();Dm();Ys();nr();P();en();k();x();Pr();J();q();me();or();yn();We();P();Lt();Qe();Mn();Yt();at();Vn();Vn();var $Ce=new Set(co),k6=new Set(fl.map(e=>Me(e.id)).filter(e=>e.length>0));Rs();at();De();k();x();J();Z();q();me();Rs();k();x();ho();at();ip();function KI(e){return e.trim().toLowerCase().replace(/^-+/u,"")}function JI(e){let t=KI(e),n=Sv({key:t,cli_flag:t,cli_aliases:[]});return[...new Set([...n,sp(t)])]}var S6=new Set(ze.filter(e=>!Qc.has(e))),YI={flag:"--help",short:"-h"},VI=new Map;function A6(e){let t=VI.get(e);if(t===void 0){let n=new Map,r=new Map;for(let i of[...Nu(e),...yg,YI]){for(let o of[i.flag,...i.aliases??[]].flatMap(JI))n.has(o)||n.set(o,i.flag);i.short!==void 0&&!r.has(i.short)&&r.set(i.short,i.flag)}t={long:n,short:r},VI.set(e,t)}return t}function T6(e,t){return $s(e)?t.short.get(e.trim()):JI(e).map(n=>t.long.get(n)).find(n=>n!==void 0)}function O6(e){let t=[];for(let n of e){let r=s=>$s(s)?s.trim():KI(s),i=[...new Set([n.cli_flag,...n.cli_aliases].map(r))],o=r(n.key);for(let s of n.commands)t.push(...C6(n.key,i,i.includes(o)?void 0:o,s.replaceAll("_","-")))}return t.sort((n,r)=>n.field.localeCompare(r.field)||n.command.localeCompare(r.command)||n.option.localeCompare(r.option))}function C6(e,t,n,r){let i=A6(r),o=new Map;for(let s of n===void 0?t:[...t,n]){if(S6.has(e)&&s.replaceAll("-","_")===e)continue;let a=T6(s,i);a===void 0||o.has(a)||s===n&&a===YI.flag||o.set(a,{field:e,command:r,field_flag:$s(s)?s:`--${s.replaceAll("_","-")}`,option:a})}return[...o.values()]}function R6(e){return e.flatMap(t=>[...new Set([t.cli_flag,...t.cli_aliases])].flatMap(n=>{let r=Ev(n);return r===void 0?[]:[{field:t.key,spelling:n,reason:r}]}))}function XI(e,t){let n=_o(e).definitions,r=O6(n),i=R6(n),o=i.length===0?{details:{},warnings:[]}:{details:{schema_field_flag_invalid_count:i.length,schema_field_flag_invalid:i.slice(0,t),schema_field_flag_invalid_truncated:i.length>t,schema_field_flag_invalid_fix_hint:"Re-register the field with one flag and one spelling per alias: pm schema add-field <key> --cli-flag <flag> --alias <alias>. A short alias is one dash and one character. Edit a field defined inline in settings.json there."},warnings:[`validate_schema_field_flag_invalid:${i.length}`]};return r.length===0?o:{details:{...o.details,schema_field_option_collision_count:r.length,schema_field_option_collisions:r.slice(0,t),schema_field_option_collisions_truncated:r.length>t,schema_field_option_collision_fix_hint:"Rename a file-backed field without losing item values: pm schema rename-field <key> --to <new-key>. For a colliding flag, alias or command list, re-register the same key: pm schema add-field <key> --cli-flag <flag> --commands <commands>. Edit a field defined inline in settings.json there."},warnings:[...o.warnings,`validate_schema_field_option_collision:${r.length}`]}}yn();q();me();We();x();k();Lt();De();Z();hi();hi();hi();var yc={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Zu={type:"array",minItems:1,maxItems:To,items:yc},ZI={...Zu,items:{...yc,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},QCe={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Zu])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:yc,id:yc}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:ZI}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Zu}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:ZI,authors:Zu}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:To,items:{type:"array",minItems:2,maxItems:2,items:yc}}}}]}}};hi();async function QI(e,t,n,r){let i=await Ua(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:eN(i,t,n,r)}function I6(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function eN(e,t,n=5,r=!1){let i=[],o=new Map,s=e.policies.filter(y=>y.rule.kind==="require_fields"),a=s.filter(y=>y.subject?.operations===void 0),c=new Set,l=0,d=0,u=0,f=0,p=0,m=Sb(e);for(let y of t){let v=m({operation:"",author:"",before:y,after:y,completeness_only:!0});l+=+(v.decisions.length>0),d+=v.decisions.length,v.decisions.forEach(R=>c.add(R.policy_id));let E=v.decisions.filter(R=>!R.satisfied);if(E.length===0)continue;f+=1;let T=o.get(y.type)??{items:0,violations:0,missing_fields:0};T.items+=1;for(let R of E)u+=1,T.violations+=1,T.missing_fields+=R.missing_fields.length,R.effect==="refuse"&&(p+=1),i.length<n&&i.push({id:y.id,type:y.type,status:y.status,decision:R});o.set(y.type,T)}let g=r||p>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:g,ok:g==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:s.length,state_requirement_count:a.length,applicable_requirement_count:c.size,requirement_application_count:d,governed_items:l,ungoverned_items:t.length-l,contract_status:I6(s.length,t.length,l),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:f,violation_count:u,refused_violations:p,missing_by_type:Object.fromEntries(o),violations:i,violations_truncated:i.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}yn();P();Lt();De();Rs();at();Vn();Z();q();me();k();x();We();xe();Lt();Wn();yn();Z();fn();Xe();tt();De();k();x();q();me();Cc();function nN(e,t){let n=be(e),r=e.length>0?e[e.length-1].after_hash:H_(),i=t===void 0||n.item_hash_version===void 0?void 0:Vo(t,n.item_hash_version,Re(e.at(-1)?.hash_algorithm)),o=t===void 0?void 0:i===void 0?li(t):i[Math.max(0,i.indexOf(r))],s=o===void 0?void 0:o===r,a=[...n.errors];return s===!1&&a.push("verify_failed:current_item_hash_mismatch"),{ok:a.length===0,entries:e.length,errors:a,latest_after_hash:e.length>0?e[e.length-1].after_hash:void 0,current_item_hash:o,current_matches_latest:s}}Qe();P();J();k();x();import{AsyncLocalStorage as L6}from"node:async_hooks";var BRe=new L6;var mNe=[...Oo,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"];P();An();k();x();nr();function qy(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}P();k();x();J();Ys();import z6 from"node:fs/promises";import H6 from"node:path";var q6=".managed-extensions.json",By=1;function Qu(e){return H6.join(e,q6)}function B6(){return{version:By,updated_at:z(),entries:[]}}function rN(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function Dt(e){return typeof e=="string"?e:void 0}var G6=/^(?:npm_registry|github_remote)_lookup_timed_out$/u;function W6(e,t){let n=Dt(t);return n===void 0||e.kind!=="github"||n.trim().length===0||/^[a-z0-9_]+$/u.test(n.trim())?n:"github_remote_lookup_failed"}function iN(e){return typeof e=="string"&&G6.test(e.trim())}function V6(e,t){return iN(e)&&typeof t=="number"&&Number.isSafeInteger(t)&&t>0?{update_check_timeout_ms:t}:{}}function K6(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function J6(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:Dt(t.name),package:Dt(t.package),version:Dt(t.version),repository:Dt(t.repository),owner:Dt(t.owner),repo:Dt(t.repo),ref:Dt(t.ref),subpath:Dt(t.subpath),commit:Dt(t.commit)}}function Y6(e){if(typeof e!="object"||e===null)return null;let t=e;if(!K6(t))return null;let n=J6(t.source);if(!n)return null;let r=No(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:qy(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Dt(t.last_update_check_at),last_update_remote_commit:Dt(t.last_update_remote_commit),last_update_remote_version:Dt(t.last_update_remote_version),update_available:iN(t.update_error)?null:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:W6(n,t.update_error),...V6(t.update_error,t.update_check_timeout_ms)}}function oN(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==By||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=Y6(r);i&&n.push(i)}return{version:By,updated_at:Dt(t.updated_at)??z(),entries:rN(n)}}async function wc(e){let t=Qu(e),n=B6();try{let r=await z6.readFile(t,"utf8"),i=JSON.parse(r),o=oN(i);if(!o)throw new _(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:o,warnings:[]}}catch(r){if(r instanceof _)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&D(r))return{path:t,state:n,warnings:[]};throw new _(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}import{execFile as e4}from"node:child_process";import{promisify as t4}from"node:util";import i0e from"npm-package-arg";import{extract as s0e,list as a0e}from"tar";P();An();k();x();var FNe=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});en();P();An();k();x();en();P();k();x();nr();q();var _0e=t4(e4);var h0e={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024};P();k();x();var k0e=new Set([...Co.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Xp).map(e=>e.toLowerCase()),"scaffold"]);Z();nr();k();x();var aN=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function i4(e){return aN.has(a4(e))}function sN(e){return e==="project"||e==="global"}function o4(e){let t=e.split(":"),n=t[0];if(!n||!aN.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),o=t.at(-2),s=t.at(-1)?.trim();return!sN(r)||!sN(o)||!i||!s?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:o,name:s}}}function s4(e){let t=new Set;for(let n of e){let r=o4(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function cN(e,t){let n=e.filter(i4);if(n.length===0)return null;let r=s4(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function a4(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Gy(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let o=im(r);return o?[o]:om(r)})();for(let o of i){let s=`${o.layer}:${o.name}:${o.capability}`;t.has(s)||(t.add(s),n.push(o))}}return n}function Wy(){return{version:Ic.version,capabilities:[...Ic.capabilities],legacy_aliases:{...Ic.legacy_aliases}}}Vl();An();P();An();k();x();en();J();J();import{AsyncLocalStorage as d4}from"node:async_hooks";import pPe from"npm-package-arg";import rPe from"npm-package-arg";import oPe from"semver";var gPe=new d4;Vc();Qe();P();P();var MPe=64*1024,$Pe=16*1024*1024,DPe=1024*1024,FPe=300*1e3;var jPe=64*1024;P();Z();Lt();me();import p4 from"node:fs/promises";import m4 from"node:path";function _4(e){return m4.join(e,"extension-migrations.json")}function h4(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function g4(e,t){return`${e.layer}:${e.name}:${t}`}async function y4(e){let t=_4(e);if(!await H(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await p4.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function dN(e,t){let n=await y4(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let s=h4(i,o),a=r.get(g4(i,s));a&&(i.definition.status=a.status,a.status==="failed"?i.definition.reason=a.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}An();x();k();P();P();wm();q();import v4 from"node:fs/promises";import b4 from"node:path";function E4(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function k4(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function fN(e){let t=b4.join(e,"manifest.json"),n;try{n=await v4.readFile(t,"utf8")}catch(a){if(ke(a))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw a}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=r,o=ym(i),s=E4(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:o.findings,warnings:o.findings.map(a=>k4(s,a)),remediation:o.findings.map(a=>a.message)}}import fLe from"npm-package-arg";P();Vl();q();P();x();k();or();Lt();me();Pa();We();var T4=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],i$e=T4.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", ");var o$e=ed();or();var pN=25;function O4(e,t,n=[]){let r=["list","--status",e,...n],i=["--assignee-filter","unassigned"],o=["--updated-before",`-${t}h`];return{unowned:re([...r,...i]),idle:re([...r,...o]),stale:re([...r,...i,...o])}}function mN(e,t){let n=e.items.length>pN;return{count:e.count,items:e.items.slice(0,pN),...n?{truncated:!0}:{},sweep:t}}function _N(e,t,n=[]){let r=O4(t.in_progress,e.threshold_hours,n),i=(s,...a)=>`pm ${s} <id>${[...a,...n].map(c=>` ${Tr(c)}`).join("")}`,o=[...e.unowned.count>0?[`in_progress_unowned:${e.unowned.count}`]:[],...e.idle.count>0?[`in_progress_idle:${e.idle.count}`]:[]];return{warnings:o,details:o.length===0?void 0:{threshold_hours:e.threshold_hours,threshold_setting:"mutation_guard.stale_in_progress_hours",unowned:mN(e.unowned,r.unowned),idle:mN(e.idle,r.idle),item_remedies:{claim:i("claim"),take_over_idle:i("claim","--takeover-stale"),return_to_open:i("update","--status",t.open)}},remediation:{stale_in_progress_items:r.stale,in_progress_unowned:r.unowned,in_progress_idle:r.idle}}}or();Sa();Mn();Jn();import{execFile as C4}from"node:child_process";import{realpath as R4}from"node:fs/promises";import hN from"node:path";import{promisify as I4}from"node:util";var N4=I4(C4),P4=32*1024*1024,L4=1e4,M4=["search/eval-queries.json"];function Vy(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}async function $4(e,t=R4){return t(e).catch(()=>hN.resolve(e))}async function ef(e){let t=await Mt(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 $4(e),r=Vy(hN.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=RS.map(o=>`${r}/${Vy(o)}`);try{let{stdout:o}=await N4("git",["ls-files","-z","--",...i.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:P4,windowsHide:!0,timeout:L4}),s=new Set(M4.map(l=>`${r}/${l}`)),a=[...new Set(o.split("\0").filter(l=>l.length>0&&!s.has(Vy(l))))].sort((l,d)=>l.localeCompare(d)),c=i.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>Tr(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}Ky();Mn();import gN from"node:path";import{realpath as U4}from"node:fs/promises";async function yN(e,t){let n=t===null?[]:await tf(t,[gN.relative(t,gN.join(await U4(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function wN(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await $a(e,is(n),{gitWorkspaceRoot:t});if(i.status==="ok")return{audit:i,count:0,warnings:[]};let o=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:o,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${o}`]:[]}}function vN(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}Mn();J();import{createHash as z4}from"node:crypto";import nf from"node:path";var Yy="2026-08-09T16:15:18.000Z",EN=Symbol("pre-durable-disposition-eligible");function _r(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jy(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function bN(e){return _r(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function kN(e,t){if(typeof e!="string")return!1;let n=nf.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!nf.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(nf.posix.basename(n)===`${t}.toon`||nf.posix.basename(n)===`${t}.md`)}function H4(e,t){return typeof e.receipt_id=="string"&&lr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&kN(e.item_path,t)}function xN(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,o=Array.isArray(i)?new Set(i.flatMap(s=>bN(s)?[s.field]:[])):new Set;return Jy(t)&&Jy(n)&&Jy(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(bN)&&o.size===i.length&&t.length===o.size&&t.every(s=>o.has(s))}function q4(e,t){return H4(e,t)&&xN(e)}function B4(e,t){return typeof e.receipt_id=="string"&&lr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&kN(e.item_path,t)&&xN(e)}function Xy(e){return e[EN]===!0}function rf(e,t){if(!_r(e)||!_r(e.context))return[];let n=e.context.merge;return!_r(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!_r(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:q4(r,t),[EN]:B4(r,t),...typeof e.ts=="string"&&Xt(e.ts)?{eventTimestamp:e.ts}:{}}])}function SN(e,t,n){if(!_r(e)||e.op!=="merge_reconcile")return[];if(!_r(e.context)||!_r(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!_r(i)||typeof i.receipt_id!="string"||!lr(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!Xt(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function AN(e,t,n=[]){let r=new Map;for(let s of n){let a=`${s.itemId}\0${s.originalHistoryLine}\0${s.receiptId}\0${s.originalEventTimestamp}`;r.set(a,Math.max(r.get(a)??0,s.auditHistoryLine))}let i=s=>Xy(s)&&s.eventTimestamp!==void 0&&He(s.eventTimestamp,Yy)<0&&(r.get(`${s.itemId}\0${s.line}\0${s.receiptId}\0${s.eventTimestamp}`)??0)>s.line;return{missing:e.filter(s=>!s.legacySummaryAccepted&&!t.has(s.receiptId)&&!i(s)).map(s=>({item_id:s.itemId,history_line:s.line,...lr(s.receiptId)?{receipt_id:s.receiptId}:{receipt_reference_hash:z4("sha256").update(s.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(s=>s.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}x();q();import{lstat as G4}from"node:fs/promises";var Zy="history_drift_chain_mismatch",W4="history_drift_chain_unbridgeable",CN="history_drift_unrepairable_stream",TN="history_drift_hash_mismatch",RN="history_drift_missing_stream",V4=["history_drift_unreadable_stream",CN,"history_drift_version_skew","history_drift_merge_receipt"],K4=new Set([Zy,RN]);function of(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function J4(e,t){return e instanceof _?typeof e.context.reason=="string"?e.context.reason:e.code??t:t}async function ON(e,t,n){try{await vn(e,{appendOnly:t,dryRun:!0},n);return}catch(r){return J4(r,t?"append_only_preview_failed":"rewrite_preview_failed")}}async function Y4(e,t){let n=[];for(let r of of(e.check.details.missing_streams)){let[i]=await Promise.allSettled([G4(Ae(t,r))]);i.status==="fulfilled"&&i.value.isSymbolicLink()&&n.push({id:r,reason:"stream_not_regular_file",rewrite_refusal:"stream_not_regular_file"})}return n}async function IN(e,t,n){let r=[],i=new Set(of(e.check.details.version_skews));for(let o of of(e.check.details.chain_mismatches)){if(i.has(o))continue;let s=await ON(o,!0,t);if(s===void 0)continue;let a=await ON(o,!1,t);r.push({id:o,reason:s,...a===void 0?{}:{rewrite_refusal:a}})}return[...r,...await Y4(e,n)]}function X4(e,t,n){for(let r of[Zy,RN]){if(!e.startsWith(`${r}:`))continue;let i=e.slice(r.length+1),o=t.get(i);return o===null?[]:[o===void 0?e:`${o}:${i}`]}return e.startsWith(`${TN}:`)?n.has(e.slice(TN.length+1))?[]:[e]:[e]}function NN(e,t){let n=of(e.check.details.version_skews),r=new Map([...n.map(o=>[o,null]),...t.map(o=>[o.id,o.rewrite_refusal===void 0?W4:CN])]),i=new Set([...n,...t.filter(o=>o.rewrite_refusal!==void 0).map(o=>o.id)]);e.warnings=e.warnings.flatMap(o=>X4(o,r,i)).sort((o,s)=>o.localeCompare(s)),t.length!==0&&(e.check.details={...e.check.details,repair_refusals:t})}function PN(e){if(V4.some(r=>Object.hasOwn(e,r)))return;let t=Object.keys(e),n=t.every(r=>K4.has(r));for(let r of t)n?e[r]="pm history-repair --all --append-only":r!==Zy&&(e[r]="pm history-repair --all")}Ds();var Z4=5;function sf(e,t){let n=[],r={};for(let o of e){let s=lp(o);if(s.length!==0){for(let a of s)r[a.field]=(r[a.field]??0)+1;n.push({id:o.id,fields:s.map(a=>a.field),reasons:[...new Set(s.map(a=>a.reason))]})}}if(n.length===0)return;n.sort((o,s)=>o.id.localeCompare(s.id));let i=t?n.length:Z4;return{details:{items:n.length,by_field:Object.fromEntries(Object.entries(r).sort(([o],[s])=>o.localeCompare(s))),rows:n.slice(0,i),truncated:n.length>i},warning:`validate_metadata_deferred_fields:${n.length}`}}ui();k();x();Z();ui();function hr(){let e=di();for(let t of ee()?.relationship_kinds??[])for(let n of t.definitions)e.register(n);return e}function cf(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function af(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function Q4(e,t){let n=new Set,r=[];for(let i of[...e].sort()){if(n.has(i))continue;n.add(i);let o=[{nodeId:i,children:[...t.get(i)??[]].sort(),nextChild:0}];for(;o.length>0;){let s=o.at(-1),a=s.children[s.nextChild];a===void 0?(r.push(s.nodeId),o.pop()):(s.nextChild+=1,n.has(a)||(n.add(a),o.push({nodeId:a,children:[...t.get(a)??[]].sort(),nextChild:0})))}}return r}function e5(e,t){let n=[...e].sort(),r=Q4(n,t),i=new Set,o=t5(n,t),s=[];for(let a of r.reverse()){if(i.has(a))continue;let c=n5(a,o,i);(c.length>1||t.get(c[0])?.has(c[0]))&&s.push(c)}return s.sort((a,c)=>a.join("\0").localeCompare(c.join("\0")))}function t5(e,t){let n=new Map(e.map(r=>[r,new Set]));for(let[r,i]of t)for(let o of i)n.get(o)?.add(r);return n}function n5(e,t,n){let r=[],i=[e];for(n.add(e);i.length>0;){let o=i.pop();r.push(o);for(let s of[...t.get(o)].sort())n.has(s)||(n.add(s),i.push(s))}return r.sort()}function r5(e){let t=new Map;for(let n of e){let r=cf(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function i5(e,t,n){let r=cf(t.parent);if(!(!r||!n.has(r)))return{parent_id:r,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function o5(e,t,n,r){let i=cf(t?.id),o=r.resolve(t?.kind);if(!i||!n.has(i)||!o?.hierarchy)return;let s=o.hierarchyDirection==="source_parent";return{parent_id:s?e:i,child_id:s?i:e,source:"dependency",kind:o.kind,holder_id:e,target_id:i,child_cardinality:s?o.incoming:o.outgoing}}function s5(e,t){let n=new Map;for(let[r,i]of e){let o=i5(r,i,e);o&&n.set(af(o),o);for(let s of i.dependencies??[]){let a=o5(r,s,e,t);a&&n.set(af(a),a)}}return[...n.values()].sort((r,i)=>af(r).localeCompare(af(i)))}function a5(e,t,n){let r=new Set(e.filter(i=>i.child_cardinality==="one").map(i=>i.child_id));return[...t].filter(([i,o])=>o.length>1&&r.has(i)).map(([i,o])=>({child_id:i,parent_ids:[...o],legacy_terminal:n.has(i)&&o.every(s=>n.has(s))})).sort((i,o)=>i.child_id.localeCompare(o.child_id))}function c5(e,t,n){let r=new Map;for(let o of t){if(o.source!=="dependency")continue;let s=r.get(o.child_id)??new Set;s.add(o.parent_id),r.set(o.child_id,s)}let i=[];for(let[o,s]of e){let a=cf(s.parent);if(!a||!e.has(a))continue;let c=[...r.get(o)??[]].filter(l=>l!==a).sort();c.length!==0&&i.push({child_id:o,scalar_parent_id:a,dependency_parent_ids:c,legacy_terminal:n.has(o)&&n.has(a)&&c.every(l=>n.has(l))})}return i.sort((o,s)=>o.child_id.localeCompare(s.child_id))}function vc(e,t=r=>r==="closed"||r==="canceled",n=hr()){let r=r5(e),i=s5(r,n),o=l5(i),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=e5([...r.keys()],new Map([...o.children_by_parent].map(([c,l])=>[c,new Set(l)]))).map(c=>({item_ids:c,legacy_terminal:c.every(l=>s.has(l))}));return{relations:i,cycles:a,cardinality_violations:a5(i,o.parents_by_child,s),divergences:c5(r,i,s)}}function l5(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.child_id)??new Set;i.add(r.parent_id),t.set(r.child_id,i);let o=n.get(r.parent_id)??new Set;o.add(r.child_id),n.set(r.parent_id,o)}return{parents_by_child:new Map([...t].map(([r,i])=>[r,[...i].sort()])),children_by_parent:new Map([...n].map(([r,i])=>[r,[...i].sort()]))}}function LN(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function d5(e,t,n=!0){let r=LN(e);return n&&(Kr(t)||r!==void 0&&Gi(r))}function MN(e,t=n=>n==="closed"||n==="canceled"){let n=e.filter(c=>typeof c?.id=="string"&&c.id.trim().length>0),r=new Set(n.map(c=>c.id.trim().toLowerCase())),i=new Map,o=(c,l,d,u,f)=>{let p=LN(l);if(!p||r.has(p.toLowerCase())||d5(p,void 0,f))return;let m={holder_id:c.id.trim(),target_id:p,kind:d,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:p.toLowerCase()==="no-active-blocker"};i.set(`${m.holder_id}::${m.target_id}::${m.kind}::${m.source}`,m)};for(let c of n){o(c,c.parent,"parent","parent",!1),o(c,c.blocked_by,"blocked_by","blocked_by",!0);for(let l of c.dependencies??[]){if(typeof l!="object"||l===null)continue;let d=l;Kr(d.source_kind)||o(c,d.id,typeof d.kind=="string"?d.kind:"related","dependency",!0)}}let s=[...i.values()].sort((c,l)=>c.holder_id.localeCompare(l.holder_id)||c.target_id.localeCompare(l.target_id)||c.kind.localeCompare(l.kind)||c.source.localeCompare(l.source)),a=s.filter(c=>c.legacy_terminal);return{active:s.filter(c=>!c.legacy_terminal),legacy_terminal:a,no_active_blocker_sentinels:s.filter(c=>c.no_active_blocker_sentinel)}}at();function lf(e,t,n=25){let r=e.definitions.filter(s=>s.roles.length===0).map(s=>s.id).sort((s,a)=>s.localeCompare(a)),i=new Set(r),o=t.filter(s=>{let a=mo(s.status,e);return a!==void 0&&i.has(a)}).map(s=>s.id).sort((s,a)=>s.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:o.length,affected_item_ids:o.slice(0,n),affected_item_ids_truncated:o.length>n}}function df(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}var zN=25,f5=ot.join("runtime","telemetry","events.jsonl"),p5=ot.join("runtime","telemetry","state.json"),m5=2500,_5=500,HN=QC-3,h5=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function qN(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("extension_disabled_pm_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("in_progress_unowned:")||e.startsWith("in_progress_idle:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function BN(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function bc(e){return e.trim().toLowerCase()}function DN(e,t){let n=bc(e),r=bc(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function GN(e){try{return(await gr.stat(e)).isDirectory()}catch{return!1}}async function g5(e){let t=(await gr.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>gr.readdir(ot.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>Zn.some(o=>i.name.endsWith(o))).map(i=>ot.parse(i.name).name)))}async function y5(e,t,n,r){let i=await lt({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:i,overThreshold:!1,classification:"live"};let s;try{s=await gr.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(o){let l=s.split(/\r?\n/).map(d=>d.trim()).filter(Boolean).at(-1);try{a=JSON.parse(l??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?s.split(/\r?\n/).filter(l=>l.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function w5(e,t,n){let r=ot.join(e,"history");if(!await GN(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await gr.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,f)=>u.localeCompare(f)),s=t.enabled?t.max_entries:null,a=[],c=[],l=[],d=[];for(let u of i){let f=ot.join(r,u),p=u.slice(0,-6),m=await y5(f,p,t,n);a.push(...m.warnings),m.classification==="tombstone"&&l.push(p),m.classification==="orphaned"&&d.push(p),m.overThreshold&&c.push(p)}return{count:i.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...d.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:s,tombstones:l,orphaned:d}}function nw(e,t){return ot.relative(e,t).replaceAll("\\","/")}async function v5(e,t){let n=[...new Set(Object.values(t))].sort((i,o)=>i.localeCompare(o)),r=[];for(let i of n){let o=ot.join(e,i),s=[];try{s=await gr.readdir(o)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&D(a))continue;continue}for(let a of s)Zn.some(c=>a.toLowerCase().endsWith(c))&&r.push(ot.join(o,a))}return r.sort((i,o)=>nw(e,i).localeCompare(nw(e,o))),r}function b5(e){return!(typeof e=="object"&&e!==null&&"code"in e&&D(e))}function E5(e){let t=sf(e,!1);return t===void 0?{}:{curation:{deferred_fields:t.details}}}async function k5(e,t,n){let r=await v5(e,t),i=[],o=[],s=[],a=[],c=dn(ee());for(let l of r){let d=nw(e,l),u;try{u=await gr.readFile(l,"utf8")}catch{i.push(d);continue}let f=_t(u);if(f){o.push({path:d,...f});continue}try{let p=Et(u,{format:Ao(l),schema:n,extensionFieldNames:c});a.push({ref:d,version:Yn(p.metadata)})}catch{s.push(d)}}return{paths:r,unreadable:i,conflictMarkers:o,parseFailures:s,formatVersions:a}}async function x5(e){let t=ot.join(e,"history"),n=[],r=[],i=[],o=[],s=[],a=[];try{a=(await gr.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,l)=>c.localeCompare(l))}catch(c){b5(c)&&n.push("history")}for(let c of a){let l=c.slice(0,-6),d;try{d=await gr.readFile(ot.join(t,c),"utf8")}catch{n.push(l);continue}let u=_t(d);if(u){r.push({id:l,...u});continue}d.split(/\r?\n/).forEach((f,p)=>{if(f.trim())try{let m=JSON.parse(f);o.push(...rf(m,l).map(g=>({itemId:l,line:p+1,...g}))),s.push(...SN(m,l,p+1))}catch{i.push({id:l,line:p+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:o,mergeReceiptDispositions:s}}function S5(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function A5(e,t,n,r,i,o){let s=await k5(e,t,n),a=await x5(e),c=wl(s.formatVersions,4,1),l=Ot(n),d=vc(o,L=>vl(L,l),hr()),u=await ef(e),f=await Mt(e),p=await yN(e,f),m=await wN(e,f,r,i),g=f===null?null:await Da(f),y=await hn(f??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),v=new Set(y.durable_receipt_ids),E=AN(a.mergeReceiptReferences,v,a.mergeReceiptDispositions),T=E.missing,R=y.receipts.filter(L=>L.state==="pending"),{pendingDecisions:C,lossless:F}=tu(R),O=g?.status==="missing"&&g.missing_keys.length===5&&g.drifted_keys.length===0,U=[...s.unreadable.map(L=>`integrity_item_unreadable:${L}`),...s.conflictMarkers.map(L=>`integrity_item_conflict_marker:${L.path}:L${L.line}`),...s.parseFailures.map(L=>`integrity_item_parse_failed:${L}`),...a.unreadable.map(L=>`integrity_history_unreadable:${L}`),...a.conflictMarkers.map(L=>`integrity_history_conflict_marker:${L.id}:L${L.line}`),...a.invalidJson.map(L=>`integrity_history_invalid_json:${L.id}:L${L.line}`),...c.outdated.map(L=>`integrity_item_outdated_format_version:${L}`),...c.ahead.map(L=>`integrity_item_ahead_format_version:${L}`),...S5(d),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...g!==null&&g.status!=="ok"?[`merge_driver_configuration_${O?"missing":"drift"}:${g.missing_keys.length+g.drifted_keys.length}`]:[],...m.warnings,...p.warnings,...C.length>0?[`merge_decisions_unreviewed:${C.length}`]:[],...F.length>0?[`merge_receipts_pending:${F.length}`]:[],...vN({invalidEvidenceCount:y.invalid_evidence_count,missingHistoryReferenceCount:T.length})],Y=[...new Set(U)].sort((L,I)=>L.localeCompare(I)),W=Y.filter(L=>!L.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:W.length===0?"ok":"warn",ok:W.length===0,details:{checked_item_files:s.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:s.unreadable.length,item_conflict_markers:s.conflictMarkers.length,item_parse_failures:s.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:d.cycles.length,hierarchy_cardinality_violations:d.cardinality_violations.length,hierarchy_parent_divergences:d.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:g===null||g.status==="ok"?0:g.missing_keys.length+g.drifted_keys.length,merge_fence:m.count,ignored_merge_artifacts:p.rules.length,pending_merge_decisions:C.length,lossless_merge_receipts:F.length,invalid_merge_receipt_evidence:y.invalid_evidence_count,missing_merge_receipt_history_references:T.length,accepted_legacy_merge_receipt_references:E.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:E.acceptedDispositionCount},item_unreadable:s.unreadable,item_conflict_markers:s.conflictMarkers,item_parse_failures:s.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,...E5(o),hierarchy_integrity:{...d,relations:Hn(d.relations,8)},history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:g===null?null:{...g,required:i},merge_fence:m.audit,ignored_merge_artifacts:p.rules,pending_merge_decision_items:[...new Set(C.map(L=>L.item_id))].sort((L,I)=>L.localeCompare(I)),lossless_merge_receipt_items:[...new Set(F.map(L=>L.item_id))].sort((L,I)=>L.localeCompare(I)),invalid_merge_receipt_evidence_details:y.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:y.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:T.slice(0,100),missing_merge_receipt_history_reference_details_truncated:T.length>100}},warnings:Y,gitWorkspaceRoot:f,pendingMergeReceipts:R}}function T5(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function O5(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:T5(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function C5(e,t){let n=Ie(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function R5(e){let n=Ie(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function I5(e){return Ie(e.reason)??Ie(e.error)??Ie(e.message)}function Qy(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function N5(e){let t=[],n=[],r=[];e.forEach((o,s)=>{let a=C5(o.definition,s),c=R5(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:a,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:a,status:c,reason:I5(o.definition)});return}n.push({layer:o.layer,name:o.name,id:a,status:c})}),t.sort(Qy),n.sort(Qy),r.sort(Qy);let i=[...r.map(o=>`extension_migration_failed:${o.layer}:${o.name}:${o.id}`),...n.map(o=>`extension_migration_pending:${o.layer}:${o.name}:${o.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function P5(e,t,n,r,i,o,s,a,c){let l=[...new Set(e)].sort((y,v)=>y.localeCompare(v)),d=[...new Set(l.map(y=>BN(y)))].sort((y,v)=>y.localeCompare(v)),u=l.filter(y=>y.startsWith("extension_capability_unknown:")).length,f=c.length>0,p=f?"partial":"full",m=l.map(Wu).filter(y=>y!==void 0),g=cN(l,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return g&&m.push(g),t>0&&m.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&m.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&m.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&m.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&m.push(`Unknown extension capabilities detected. Allowed capabilities: ${Ut.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),l.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&m.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),l.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&m.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),f?m.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):s.length>0&&m.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),m.length===0&&m.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:l.length===0?"ok":"warn",warning_count:l.length,warning_codes:d,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:o,unmanaged_loaded_extension_count:s.length,unmanaged_loaded_extensions:s,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:p,update_health_partial:f,unknown_capability_count:u,top_warnings:l.slice(0,8),remediation:m}}async function L5(e,t,n){let r=await fN(qt(e)),i=await aa({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),o=i.loaded.map(O=>O5(O)),s=await uI(i.loaded,qt(e)),a=await ca({...i,loaded:i.loaded}),[c,l]=await Promise.all([wc(i.roots.project),wc(i.roots.global)]);await dN(e,a.registrations.migrations);let d=N5(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:d.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:l.path,count:l.state.entries.length,entries:l.state.entries}}},f=new Set(c.state.entries.map(O=>bc(O.name))),p=new Set(l.state.entries.map(O=>bc(O.name))),m=[...new Map(i.loaded.filter(O=>!(O.layer==="project"?f:p).has(bc(O.name))).map(O=>[`${O.layer}:${O.name}`,{layer:O.layer,name:O.name,directory:O.directory}])).values()].sort((O,U)=>{let Y=`${O.layer}:${O.name}`,W=`${U.layer}:${U.name}`;return Y.localeCompare(W)}),g=m.map(O=>`${O.layer}:${O.name}`).sort((O,U)=>O.localeCompare(U)),y=m.filter(O=>DN(O.name,O.directory)).map(O=>`${O.layer}:${O.name}`).sort((O,U)=>O.localeCompare(U)),v=m.filter(O=>!DN(O.name,O.directory)).map(O=>`${O.layer}:${O.name}`).sort((O,U)=>O.localeCompare(U)),E=v.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${v.length}`]:[],T=[...r.warnings,...i.warnings,...u.warnings,...d.warnings,...c.warnings,...l.warnings,...E,...s.warnings],R=Gy(T),C=Wy(),F=P5(T,i.failed.length,a.failed.length,d.summary,c.warnings.length+l.warnings.length,c.state.entries.length+l.state.entries.length,g,y,v);return{check:{name:"extensions",status:T.length===0?"ok":"warn",ok:T.length===0,details:{...i,loaded:o,warnings:T,activation:u,author_manifest:r,triage:F,...d.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:C,capability_guidance:R,host_version_census:s}},warnings:T}}function FN(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=BR(e,zN);return{values:n.values,truncated:n.truncated,total:e.length}}function ew(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function M5(){let e=dc();return e.source_context_source==="env_override"?e.source_context:null}function $5(e){let t=0,n=0,r=0,i=0,o=0;for(let s of e.split(`
164
+ `),lX(n,!0)}finally{t.close()}}function ZR(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:gy,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function QR(e){let t=[],n=await XR(e);for(let r of XY){let i=it.join(e,r),o=await H(i);if(!o){t.push({file_path:i,exists:o,has_guidance:!1,has_marker:!1});continue}let s=await hy.readFile(i,"utf8"),a=s.toLowerCase(),c=ZY.filter(d=>a.includes(d)),l=iX(s);t.push({file_path:i,exists:o,has_guidance:l||c.length>=QY,has_marker:l,outdated:l&&YR(s,n).changed})}return t}function Ji(e,t){e.includes(t)||e.push(t)}function uX(e,t){let n=ZR(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function eI(e,t=it.dirname(e)){let r=await H(e)?await hy.readFile(e,"utf8"):"",i=YR(r,await XR(t));return i.changed?(await V(e,i.next_content),{changed:!0,warnings:await et({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function fX(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>hs(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>hs(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>hs(e.projectRoot,t.file_path))}}async function pX(e,t,n){return e?await QR(n):t}function fc(e,t,n){e.state={...e.state,...n,template_version:gy,last_checked_files:t}}async function tI(e,t){if(t.presentBefore)return;let n=await eI(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function mX(e,t){t||(e.warnings.push("agent_guidance:missing"),Ji(e.nextSteps,pc))}function _X(e,t){e.skipped=!0,fc(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Ji(e.nextSteps,pc)}async function hX(e,t){await tI(e,t),fc(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function gX(e,t){e.state.declined&&fc(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function yX(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ji(e.nextSteps,pc)}async function wX(e,t){if(e.prompted=!0,await dX(t.targetRelativePath)){await tI(e,t),fc(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,fc(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ji(e.nextSteps,pc)}function vX(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ji(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Ji(e.nextSteps,pc)}async function bX(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(mX(n,t.presentBefore),n):t.mode==="skip"?(_X(n,t.checkedFiles),n):t.mode==="add"?(await hX(n,t),n):t.presentBefore?(gX(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(yX(n),n):t.interactive?(await wX(n,t),n):(vX(n),n)}async function nI(e){let t=aX(e.pm_root,e.cwd),n=await QR(t),r=cX(n,t),i=hs(t,r),o=n.map(u=>hs(t,u.file_path)),s=n.some(u=>u.has_guidance),a=await bX(ZR(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:i,checkedFiles:o,presentBefore:s,projectRoot:t});if(e.mode==="add")for(let u of n.filter(f=>f.outdated)){let f=await eI(u.file_path,t);a.applied||=f.changed,a.warnings.push(...f.warnings)}let c=uX(e.settings,a.state);n=await pX(a.applied,n,t);let l=n.filter(u=>u.outdated).map(u=>hs(t,u.file_path));return l.length>0&&(a.warnings.push(`agent_guidance_outdated:${l.join(",")}`),Ji(a.nextSteps,"pm init --agent-guidance add")),{summary:fX({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:a.prompted,applied:a.applied,skipped:a.skipped,state:a.state}),warnings:a.warnings,next_steps:a.nextSteps,settings_changed:c.changed}}or();function Wu(e){let t=/^extension_(disabled_)?pm_(min|max)_version_([a-z_]+):(project|global):([^:]+):(.+)$/u.exec(e);if(!t)return;let[,n,r,i,o,s,a]=t,c=a.split(":")[0].replace(r==="min"?"required=":"allowed=",""),l=i==="invalid"?`a valid pm_${r}_version instead of ${c}`:`pm ${r==="min"?">=":"<="} ${c}`;return n?`Package ${s} is disabled and requires ${l} before activation. After satisfying the bound, run ${re(["package","activate",s,`--${o}`])}.`:`Package ${s} requires ${l}. Use a compatible host or package version, or keep it disabled with ${re(["package","deactivate",s,`--${o}`])}.`}import gr from"node:fs/promises";import ot from"node:path";yn();Xn();De();at();P();Z();Mr();nr();Um();od();Qe();P();import rI from"node:fs/promises";import iI from"node:path";function oI(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:o,ttl_seconds:s}=n;return typeof r!="string"||typeof i!="string"||typeof o!="string"||typeof s!="number"||!Number.isFinite(s)?null:{id:r,owner:i,created_at:o,ttl_seconds:s,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function EX(e,t,n){let r=oI(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let o=n-i,s=Math.floor(o/1e3),a=o>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:s,stale:a,reason:a?"expired":"active"}}}async function kX(e,t,n){let r=EX(e,t,n);if(r.detail!=="active")return r;let i=oI(t),o=await Fo(i);return o==="unknown"?r:{detail:o==="dead"?"owner_dead":"active",entry:{...r.entry,owner_state:o,pid:i.pid,...o==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}function xX(e,t,n){t==="owner_dead"&&(e.owner_dead_lock_samples??=[],e.owner_dead_lock_samples.length<20&&e.owner_dead_lock_samples.push(n)),t==="active"?e.active_lock_count+=1:t==="expired"||t==="owner_dead"?e.stale_lock_count+=1:e.unparseable_lock_count+=1}async function sI(e,t){let n=t??Date.now(),r=iI.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await rI.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(s){if(D(s))return i;throw s}for(let s of o){let a;try{a=await rI.readFile(iI.join(r,s),"utf8")}catch(d){if(D(d))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c,entry:l}=await kX(s,a,n);xX(i,c,l)}return i}function yy(e,t){let n=t??{};return e.filter(r=>n[r.id]!==r.updated_at).map(r=>r.id).sort((r,i)=>r.localeCompare(i))}k();oi();x();xe();J();ln();ii();q();me();var SX=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:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{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_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{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 record; the repair rebuilds the stream as one audited baseline from the on-disk item, and earlier versions stay unrecorded. When the stream was deleted by mistake, restore it from version control first (pm history-repair --all, with or without --append-only, rebuilds every missing stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"The item's history stream cannot be read; preview salvage, which removes lines that cannot hold a record and an invalid tail after a verified prefix, then apply it without --dry-run. Salvage refuses interior corruption, which needs recovery from version control, and a permission error needs the file's access fixed."},{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> --append-only",summary:"The item's history chain is broken; append one record that bridges every break in the stream and keeps every recorded line byte-identical (pm history-repair <id> re-anchors the recorded entries instead). pm health previews the bridge for every chain mismatch, so a break a bridge cannot repair is reported as history_drift_chain_unbridgeable, and a stream no repair can keep as history_drift_unrepairable_stream, instead."},{code:"history_drift_chain_unbridgeable",command:"pm history-repair <id>",summary:"The item's history chain is broken in a way an append-only bridge cannot repair, for example a recorded patch that applies only on top of the unrecorded change (details.repair_refusals names the refusal reason); re-anchor the recorded entries instead (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unrepairable_stream",command:"pm history <id> --verify --full",summary:"Neither history repair can keep this stream (details.repair_refusals names both refusal reasons). Inspect it: a record that no longer matches its seal, or a malformed chain, needs the item's own stream restored from version control or a backup; a stream entry that is a link (reason stream_not_regular_file) needs the item's own stream restored as a regular file. Then run pm history <id> --verify --strict-exit."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{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:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{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_schema_field_option_collision",command:"pm schema rename-field <key> --to <new-key>",summary:"A custom field shadows a built-in option of a command it is registered for; rename it (item values move with it), or re-register the same key with another flag or a narrower --commands list."},{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:"Rebuild the history streams of the items without a history record as one audited baseline from each on-disk item."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"Preview salvage of the unreadable history streams, then apply it without --dry-run; interior corruption needs recovery from version control."},{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_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{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 wy(e){if(typeof e!="string")return;let t=e.trim();for(let n of SX)if(t===n.code||t.startsWith(`${n.code}:`))return n}function vy(e){let t={};for(let n of e){let r=wy(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function aI(e){return Object.values(vy(e))}en();import dI from"node:fs/promises";import{createRequire as AX}from"node:module";import Vt from"node:path";function cI(e,t){let n=Vt.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Vt.sep}`)&&!Vt.isAbsolute(n))return n.split(Vt.sep).join("/");let r=Vt.resolve(e),i=0xcbf29ce484222325n;for(let s=0;s<r.length;s+=1)i^=BigInt(r.charCodeAt(s)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Vt.basename(Vt.dirname(e))}/package.json`}function TX(e){return e.includes(`${Vt.sep}.pnpm${Vt.sep}`)?"pnpm":e.includes(`${Vt.sep}node_modules${Vt.sep}`)?"npm":"other"}async function lI(e){try{let t=JSON.parse(await dI.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function by(e){try{return await dI.realpath(e)}catch{return Vt.resolve(e)}}async function uI(e,t,n=Ht(import.meta.url,["../../.."])){let r=await by(t),i=await by(Vt.join(n,"package.json")),o=await lI(i),s=new Map;o!==void 0&&s.set(i,{version:o,path:cI(i,r),layout:"host",consumers:["pm-cli-host"]});for(let l of e)try{let d=AX(l.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await by(d),f=await lI(u);if(f===void 0)continue;let p=u,m=s.get(p);if(m){m.consumers.includes(l.name)||(m.consumers.push(l.name),m.consumers.sort((g,y)=>g.localeCompare(y)));continue}s.set(p,{version:f,path:cI(u,r),layout:TX(u),consumers:[l.name]})}catch{}let a=[...s.values()].sort((l,d)=>l.path.localeCompare(d.path)),c=o===void 0?[]:a.filter(l=>l.version!==o);return{host_version:o??null,copies:a,mismatches:c,warnings:c.map(l=>`extension_host_pm_cli_version_skew:${o}:${l.version}:${l.consumers.join("+")}`)}}Lt();me();k();x();import zy from"node:fs/promises";import Hy from"node:path";k();x();xe();k();x();xe();var gs=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Item title [required] (or first positional argument)"},{target:"id",keys:["id"],option:"--id <value>",description:"Explicit id (normalized with id_prefix)"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Item description (allow empty string)"},{target:"type",keys:["type"],option:"--type <value>",description:"Built-in or custom item type"},{target:"template",keys:["template"],option:"--template <value>",description:"Named template defaults; explicit flags override"},{target:"createMode",keys:["createMode","create_mode"],option:"--create-mode <value>",description:"Required fields: strict|progressive",aliasOptions:[{option:"--create_mode <value>",description:"Alias for --create-mode"}]},{target:"defer",keys:["defer"],option:"--defer <field>",description:"Defer an unknown strict field: deadline|assignee|ac|estimate (repeatable)",repeatable:!0},{target:"deferReason",keys:["deferReason","defer_reason"],option:"--defer-reason <value>",description:"Why deferred values are unknown (required with --defer)",aliasOptions:[{option:"--defer_reason <value>",description:"Alias for --defer-reason"}]},{target:"schedulePreset",keys:["schedulePreset","schedule_preset"],option:"--schedule-preset <value>",description:"Reminder/Meeting/Event defaults: lightweight",aliasOptions:[{option:"--schedule_preset <value>",description:"Alias for --schedule-preset"}]},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Item status"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Reason for a directly terminal item",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Actual completion time for terminal imports",aliasOptions:[{option:"--completed_at <value>",description:"Alias for --completed-at"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Priority 0..4"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Comma-separated tags"},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags additively on top of --tags (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Item markdown body (allow empty string)"},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Deadline (ISO/date string or relative +6h/+1d/+2w/+6m)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Acceptance criteria (repeatable; values join with '; '; allow empty string)",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Definition of ready (allow empty string)",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"History message (allow empty string)"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Item assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow creating with an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Seed dependency entry (key=value CSV, markdown key:value lines, or - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Type option key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar fields by name (repeatable or csv)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Seed reminder entry at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Seed event entry start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Seed comment entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Seed note entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Seed learning entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Seed linked file entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Seed linked test entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Seed linked doc entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0}],Ey=gs.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),ky=gs.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),Yi=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Set title"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Set description"},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Set body (allow empty string)"},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Set status (use close command for closed)"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Set close reason",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Set priority"},{target:"type",keys:["type"],option:"--type <value>",description:"Set type"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Set comma-separated tags (replaces existing). Use --add-tags / --remove-tags to mutate additively."},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags to the existing list without replacing it (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"removeTags",keys:["removeTags","remove_tags"],option:"--remove-tags <value>",description:"Remove tags from the existing list (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--remove_tags <value>",description:"Alias for --remove-tags"}]},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Set deadline (ISO/date string or relative)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Set estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Replace the complete acceptance-criteria list (repeatable values join with '; '); use --remove-ac plus --add-ac for one-entry repair",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"addAc",keys:["addAc","add_ac"],option:"--add-ac <value>",description:"Add one semicolon-free acceptance criterion without replacing the existing list (repeatable)",repeatable:!0,aliasOptions:[{option:"--add_ac <value>",description:"Alias for --add-ac"}]},{target:"removeAc",keys:["removeAc","remove_ac"],option:"--remove-ac <value>",description:"Remove one semicolon-free acceptance criterion by exact text match; fails if any selector is unmatched (repeatable)",repeatable:!0,aliasOptions:[{option:"--remove_ac <value>",description:"Alias for --remove-ac"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Set definition of ready",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Set planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Set goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Set objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Set business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Set business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Set expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Set why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"Mutation message"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Set assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Set parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow updating to an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Correct the actual completion timestamp on a terminal item"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Set reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Set risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Set confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Set sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Set release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Set blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Set unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Set issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Set issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Set issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Set issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Set issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Set issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Set issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Set affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Set fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Set issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Set regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Set customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Add dependency entries id=<id>,kind=<value>,author=<value>,created_at=<iso|now>,source_kind=<value> (repeatable)",repeatable:!0},{target:"depRemove",keys:["depRemove","dep_remove"],option:"--dep-remove <value>",description:"Remove by id, row signature, or kind=<kind> alone (repeatable)",repeatable:!0,aliasOptions:[{option:"--dep_remove <value>",description:"Alias for --dep-remove"}]},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Append comment seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Append note seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Append learning seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Append linked file path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Append test command=<value>,path=<value>,scope=<project|global>,timeout_seconds=<n>,pm_context_mode=<schema|tracker|auto|none> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Append linked doc path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Set reminders at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Set events start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Set type options key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar fields by name (repeatable or csv)",repeatable:!0}],xy=Yi.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),Sy=Yi.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys}));function pt(e){return e.map(t=>({...t}))}var Ay=[{param:"status",flag:"--status"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"deadlineBefore",flag:"--deadline-before"},{param:"deadlineAfter",flag:"--deadline-after"}],fI=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],OX=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},...fI],pI=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],CX=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],RX=[...Ay,...pI],mI=[{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"}],IX=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],_I=[{param:"hasNotes",flag:"--has-notes"},{param:"noNotes",flag:"--no-notes"},{param:"hasLearnings",flag:"--has-learnings"},{param:"noLearnings",flag:"--no-learnings"},{param:"hasFiles",flag:"--has-files"},{param:"noFiles",flag:"--no-files"},{param:"filterFilesMissing",flag:"--filter-files-missing"},{param:"hasDocs",flag:"--has-docs"},{param:"noDocs",flag:"--no-docs"},{param:"filterDocsMissing",flag:"--filter-docs-missing"},{param:"hasTests",flag:"--has-tests"},{param:"noTests",flag:"--no-tests"},{param:"hasComments",flag:"--has-comments"},{param:"noComments",flag:"--no-comments"},{param:"hasDeps",flag:"--has-deps"},{param:"noDeps",flag:"--no-deps"},{param:"hasBody",flag:"--has-body"},{param:"emptyBody",flag:"--empty-body"},{param:"hasLinkedCommand",flag:"--has-linked-command"},{param:"noLinkedCommand",flag:"--no-linked-command"}],Ty=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...pt(Ay),...pt(OX),{param:"ids",flag:"--ids"},...pt(pI),...pt(IX),...pt(mI),...pt(_I),{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"},{param:"after",flag:"--after"},{param:"fields",flag:"--fields"},{param:"sort",flag:"--sort"},{param:"order",flag:"--order"},{param:"tree",flag:"--tree"},{param:"treeDepth",flag:"--tree-depth"}],Oy=[{param:"groupBy",flag:"--group-by"},{param:"setMode",flag:"--set-mode"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...pt(RX)],Cy=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},{param:"matchMode",flag:"--match-mode"},{param:"minScore",flag:"--min-score"},{param:"count",flag:"--count",booleanish:!0},{param:"semanticWeight",flag:"--semantic-weight"},...pt(Ay),...pt(fI),...pt(CX),...pt(mI),...pt(_I),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],hI=[{param:"parent",flag:"--parent"},{param:"reviewer",flag:"--reviewer"},{param:"risk",flag:"--risk"},{param:"confidence",flag:"--confidence"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"blockedBy",flag:"--blocked-by"},{param:"blockedReason",flag:"--blocked-reason"},{param:"unblockNote",flag:"--unblock-note"},{param:"reporter",flag:"--reporter"},{param:"severity",flag:"--severity"},{param:"environment",flag:"--environment"},{param:"reproSteps",flag:"--repro-steps"},{param:"resolution",flag:"--resolution"},{param:"expectedResult",flag:"--expected-result"},{param:"actualResult",flag:"--actual-result"},{param:"affectedVersion",flag:"--affected-version"},{param:"fixedVersion",flag:"--fixed-version"},{param:"component",flag:"--component"},{param:"regression",flag:"--regression",booleanish:!0},{param:"customerImpact",flag:"--customer-impact"},{param:"definitionOfReady",flag:"--definition-of-ready",allowEmpty:!0},{param:"order",flag:"--order"},{param:"rank",flag:"--rank"},{param:"goal",flag:"--goal"},{param:"objective",flag:"--objective"},{param:"value",flag:"--value"},{param:"impact",flag:"--impact"},{param:"outcome",flag:"--outcome"},{param:"whyNow",flag:"--why-now"}],ys=pt(hI),gI=[{param:"inheritFocus",flag:"--inherit-focus",booleanish:!0},{param:"id",flag:"--id"},{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"type",flag:"--type"},{param:"template",flag:"--template"},{param:"createMode",flag:"--create-mode"},{param:"defer",flag:"--defer",repeatable:!0},{param:"deferReason",flag:"--defer-reason"},{param:"schedulePreset",flag:"--schedule-preset"},{param:"status",flag:"--status"},{param:"closeReason",flag:"--close-reason"},{param:"completedAt",flag:"--completed-at"},{param:"priority",flag:"--priority"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"allowDuplicate",flag:"--allow-duplicate",booleanish:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"dep",flag:"--dep",repeatable:!0},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],mc=pt(gI),yI=[{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"status",flag:"--status"},{param:"closeReason",flag:"--close-reason"},{param:"completedAt",flag:"--completed-at"},{param:"priority",flag:"--priority"},{param:"type",flag:"--type"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"removeTags",flag:"--remove-tags",repeatable:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"addAc",flag:"--add-ac",repeatable:!0},{param:"removeAc",flag:"--remove-ac",repeatable:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"dep",flag:"--dep",repeatable:!0},{param:"depRemove",flag:"--dep-remove",repeatable:!0},{param:"replaceDeps",flag:"--replace-deps"},{param:"replaceTests",flag:"--replace-tests"},{param:"replaceFiles",flag:"--replace-files"},{param:"replaceDocs",flag:"--replace-docs"},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],_c=pt(yI),Ry=[{param:"filterStatus",flag:"--filter-status"},{param:"filterType",flag:"--filter-type"},{param:"filterTag",flag:"--filter-tag"},{param:"filterPriority",flag:"--filter-priority"},{param:"filterDeadlineBefore",flag:"--filter-deadline-before"},{param:"filterDeadlineAfter",flag:"--filter-deadline-after"},{param:"filterUpdatedAfter",flag:"--filter-updated-after"},{param:"filterUpdatedBefore",flag:"--filter-updated-before"},{param:"filterCreatedAfter",flag:"--filter-created-after"},{param:"filterCreatedBefore",flag:"--filter-created-before"},{param:"filterAssignee",flag:"--filter-assignee"},{param:"filterAssigneeFilter",flag:"--filter-assignee-filter"},{param:"filterParent",flag:"--filter-parent"},{param:"filterSprint",flag:"--filter-sprint"},{param:"filterRelease",flag:"--filter-release"},{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"},{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"},{param:"filterHasNotes",flag:"--filter-has-notes"},{param:"filterNoNotes",flag:"--filter-no-notes"},{param:"filterHasLearnings",flag:"--filter-has-learnings"},{param:"filterNoLearnings",flag:"--filter-no-learnings"},{param:"filterHasFiles",flag:"--filter-has-files"},{param:"filterNoFiles",flag:"--filter-no-files"},{param:"filterHasDocs",flag:"--filter-has-docs"},{param:"filterNoDocs",flag:"--filter-no-docs"},{param:"filterHasTests",flag:"--filter-has-tests"},{param:"filterNoTests",flag:"--filter-no-tests"},{param:"filterHasComments",flag:"--filter-has-comments"},{param:"filterNoComments",flag:"--filter-no-comments"},{param:"filterHasDeps",flag:"--filter-has-deps"},{param:"filterNoDeps",flag:"--filter-no-deps"},{param:"filterHasBody",flag:"--filter-has-body"},{param:"filterEmptyBody",flag:"--filter-empty-body"},{param:"filterHasLinkedCommand",flag:"--filter-has-linked-command"},{param:"filterNoLinkedCommand",flag:"--filter-no-linked-command"},{param:"ids",flag:"--ids"},{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"}],Iy=pt(Ry),Ny=pt(Ry);var Py=[{param:"id",flag:"--id"},{param:"op",flag:"--op"},{param:"author",flag:"--author"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"unbounded",flag:"--unbounded"},{param:"compact",flag:"--compact"},{param:"raw",flag:"--raw"},{param:"full",flag:"--full"},{param:"provenance",flag:"--provenance"},{param:"provenanceSummary",flag:"--provenance-summary"},{param:"harness",flag:"--harness",repeatable:!0},{param:"agentInstance",flag:"--agent-instance",repeatable:!0},{param:"provenanceFilter",flag:"--provenance-filter",repeatable:!0}],Ly=[{param:"for",flag:"--for"},{param:"date",flag:"--date"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"format",flag:"--format"},{param:"depth",flag:"--depth"},{param:"fields",flag:"--fields"},{param:"section",flag:"--section",repeatable:!0},{param:"activityLimit",flag:"--activity-limit"},{param:"staleThreshold",flag:"--stale-threshold"},{param:"tokenBudget",flag:"--token-budget"},{param:"explainRanking",flag:"--explain-ranking"},{param:"noTags",flag:"--no-tags"},{param:"noExtensionHealth",flag:"--no-extension-health"}];Yt();A_();ye();J();var wI=["production_defect","nightly_regression","scanner_finding","review_caught_late"];var Vu={type:"string",pattern:"\\S"},My={type:"array",minItems:1,items:Vu},bI={type:"object",properties:Object.fromEntries(["files","package_names","item_ids","tags","error_codes"].map(e=>[e,{type:"array",items:{type:"string"}}]))},NX={type:"object",required:["id","version","title","owner_item_id","escape_class","triggers","checks","negative_control","historical_item_ids","budget"],properties:{id:Vu,version:{type:"integer",minimum:1},title:Vu,owner_item_id:Vu,escape_class:{enum:wI},triggers:{type:"object",properties:{...Object.fromEntries(["package_names","item_ids","tags","error_codes"].map(e=>[e,{type:"array",items:{type:"string"}}])),file_patterns:{type:"array",items:{type:"string",maxLength:256}}}},checks:{type:"object",required:["local","hosted"],properties:{local:My,hosted:My}},negative_control:{...bI,minProperties:1},historical_item_ids:My,budget:{type:"object",required:["max_escape_rate","max_false_positive_rate"],properties:Object.fromEntries(["max_escape_rate","max_false_positive_rate"].map(e=>[e,{type:"number",minimum:0,maximum:1}]))}}},vI={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},EI={if:{required:["field"]}};Reflect.set(EI,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var kI={oneOf:[...[!0,!1].map(e=>({type:"object",additionalProperties:!1,required:e?["policy","change"]:["policy"],properties:{policy:{type:"object",required:["version","evidence_epoch","families"],properties:{version:{const:1},evidence_epoch:{type:"string",format:"date-time"},families:{type:"array",items:NX}},additionalProperties:!1},...e?{change:{...bI,additionalProperties:!1}}:{uncoveredOnly:{type:"boolean"}},limit:{type:"integer",minimum:1,maximum:100},cursor:{type:"string",minLength:1}}})),{type:"object",additionalProperties:!1,required:["id","source"],properties:{id:{type:"string",minLength:1},description:{type:"string"},max_cost:{type:"number",minimum:0},source:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],allOf:[EI],properties:{kind:{const:"items"},statuses:{type:"array",items:{type:"string"}},types:{type:"array",items:{type:"string"}},tags:{type:"array",items:{type:"string"}},field:{type:"string"},equals:{type:["string","number","boolean","null"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","dependency_kind"],properties:{kind:{const:"dependency_kind"},dependency_kind:{type:"string",minLength:1}}},{type:"object",required:["kind","operation","field"],properties:{kind:{const:"graph"},operation:{type:"string",minLength:1},field:{type:"string",minLength:1},parameters:{type:"object"}},additionalProperties:!1},...["validate","health"].map(e=>({type:"object",required:["kind","check","field"],properties:{kind:{const:e},check:{type:"string",minLength:1},field:{type:"string",minLength:1}},additionalProperties:!1})),{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"history"},op:{type:"string"},author:{type:"string"},harness:{type:"string"},model:{type:"string"}}},{type:"object",additionalProperties:!1,required:["kind","link","state"],properties:{kind:{const:"links"},link:{enum:["files","tests","docs"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","provider","key"],properties:{kind:{const:"provider"},provider:{type:"string",minLength:1},key:{type:"string",minLength:1},parameters:{type:"object"}}},{type:"object",additionalProperties:!1,required:["kind","expression"],properties:{kind:{const:"derived"},expression:{type:"object",minProperties:1}}}]}}},{type:"object",additionalProperties:!1,required:["id","measurement_id","owner_item_id","scope","enforcement","negative_control"],oneOf:[{required:["ceiling"]},{required:["floor"]},{required:["equals"]},{required:["zero"]},{required:["monotone_nondecreasing"]},{required:["monotone_nonincreasing"]},{required:["subset_of"]}],allOf:[{oneOf:[{not:{required:["lifetime"],properties:{lifetime:{const:"retire"}}}},{required:["lifetime","retire_reason"],properties:{lifetime:{const:"retire"},retire_reason:{type:"string",minLength:1}}}]}],properties:{id:{type:"string",minLength:1},measurement_id:{type:"string",minLength:1},owner_item_id:{type:"string",minLength:1},scope:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{enum:["all","active"]}}},{type:"object",additionalProperties:!1,required:["kind","measurement_id"],properties:{kind:{const:"filter"},measurement_id:{type:"string",minLength:1}}}]},ceiling:{type:"number"},floor:{type:"number"},equals:vI,zero:{const:!0},monotone_nondecreasing:{type:"number"},monotone_nonincreasing:{type:"number"},subset_of:{type:"array",items:{type:"string"}},lifetime:{enum:["hold","retire"]},retire_reason:{type:"string",minLength:1},enforcement:{enum:["block","warn","observe"]},authorization_decision:{type:"string",minLength:1},negative_control:{type:"object",additionalProperties:!1,required:["cases"],properties:{cases:{type:"array",minItems:2,items:{type:"object",additionalProperties:!1,required:["observed","expected"],properties:{observed:vI,expected:{enum:["pass","fail"]}}}}}}}},{type:"object",additionalProperties:!1,required:["id","assertion_ids","triggers"],properties:{id:{type:"string",minLength:1},description:{type:"string"},assertion_ids:{type:"array",minItems:1,items:{type:"string",minLength:1}},triggers:{type:"array",minItems:1,items:{enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]}},provider_policy:{type:"object",additionalProperties:!1,required:["allowed_providers","triggers"],properties:{allowed_providers:{type:"array",items:{type:"string",minLength:1}},triggers:{type:"object",additionalProperties:{type:"object",additionalProperties:!1,required:["max_cost_class","allow_network"],properties:{max_cost_class:{enum:["low","medium","high"]},allow_network:{type:"boolean"}}}}}}}}]};var hc={json:{type:"boolean",default:!0},quiet:{type:"boolean"},profile:{type:"boolean"},noExtensions:{type:"boolean"},noPager:{type:"boolean"},tokenAccounting:{type:"boolean"},outputInclude:{type:"string",minLength:1},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputFormat:{type:"string",enum:["json","toon"]},outputSession:{anyOf:[{type:"string",minLength:1},{type:"object",additionalProperties:!1,required:["version","id","token_budget","spent_tokens","seen_item_ids"],properties:{version:{const:1},id:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$"},token_budget:{type:"integer",minimum:256},spent_tokens:{type:"integer",minimum:0},seen_item_ids:{type:"array",maxItems:Rd,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"}}}}]},outputCursor:{type:"string",minLength:1},outputRowContract:{type:"boolean"},path:{type:"string"},pmExecutable:{type:"string"},timeoutMs:{type:"number"},id:{type:"string"},target:{type:"string"},snapshotAction:{type:"string",enum:["create","list","inspect","restore","delete"]},artifact:{type:"string",enum:["item","history","relationship","json"]},basePath:{type:"string"},oursPath:{type:"string"},theirsPath:{type:"string"},outputPath:{type:"string"},itemPath:{type:"string"},prefer:{type:"string",enum:["ours","theirs"]},includeReconciled:{type:"boolean"},preCommitHook:{type:"boolean"},stage:{type:"boolean"},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"},capability:{type:"string",minLength:1},declarative:{type:"boolean"},output:{type:"string",minLength:1},markdown:{type:"boolean"},init:{type:"boolean"},install:{type:"boolean"},uninstall:{type:"boolean"},explore:{type:"boolean"},manage:{type:"boolean"},describe:{type:"boolean"},doctor:{type:"boolean"},catalog:{type:"boolean"},adopt:{type:"boolean"},adoptAll:{type:"boolean"},activate:{type:"boolean"},deactivate:{type:"boolean"},filterFilesMissing:{type:"boolean"},filterDocsMissing:{type:"boolean"},matchMode:{type:"string",enum:["all","any","phrase"]},minScore:{anyOf:[{type:"number"},{type:"string",pattern:"^\\d+(\\.\\d+)?$"}]},rank:{anyOf:[{type:"number"},{type:"string",pattern:"^-?\\d+$"}]},exemptIsolateType:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},saveBaseline:{type:"boolean"},rebuild:{type:"boolean"},github:{type:"string"},ref:{type:"string"},query:{type:"string"},queries:{type:"string"},k:{anyOf:[{type:"number"},{type:"string"}]},failUnder:{anyOf:[{type:"number"},{type:"string"}]},for:{type:"string",minLength:1},keywords:{type:"string"},fields:{type:"string"},sort:{type:"string",enum:["priority","deadline","updated_at","created_at","title","parent"]},prefix:{type:"string"},idPrefix:{type:"string"},workspace:{type:"string"},preset:{type:"string",enum:["minimal","default","strict","custom"]},typePreset:{type:"string",enum:["agile","ops","research"]},defaults:{type:"boolean"},verbose:{type:"boolean"},agentGuidance:{type:"string",enum:["ask","add","skip","status"]},withPackages:{type:"boolean"},mergeFence:{type:"boolean"},scope:{type:"string",enum:["project","global"]},allOver:{type:"number"},minEntries:{type:"number"},closed:{type:"boolean"},allStreams:{type:"boolean"},contractAction:{type:"string"},command:{type:"string"},summary:{type:"boolean"},schemaOnly:{type:"boolean"},flagsOnly:{type:"boolean"},availabilityOnly:{type:"boolean"},runtimeOnly:{type:"boolean"},activeOnly:{type:"boolean"},eagerTags:{type:"boolean"},fullChangedFields:{type:"boolean"},provenance:{type:"boolean"},provenanceSummary:{type:"boolean"},agentInstance:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},provenanceFilter:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},idOnly:{type:"boolean"},expectHash:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},allowMissingParent:{type:"boolean"},allowUnresolvedDeps:{type:"boolean"},allowDuplicate:{type:"boolean"},inheritFocus:{type:"boolean",description:"Opt into saved session focus as parent; SDK/MCP default false, CLI default true. Explicit parent or unset-parent takes precedence."},duplicateOf:{type:"string"},configAction:{type:"string",enum:["get","set","list","export"]},key:{type:"string"},title:{type:"string"},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},start:{type:"string"},duration:{type:"string"},end:{type:"string"},location:{type:"string"},timezone:{type:"string"},allDay:{type:"boolean"},description:{type:"string"},type:{type:"string"},template:{type:"string"},createMode:{type:"string",enum:["strict","progressive"]},defer:{type:"array",items:{type:"string"}},deferReason:{type:"string"},schedulePreset:{type:"string",enum:["lightweight"]},status:{type:"string"},since:{type:"string",format:"date-time"},cursorMode:{type:"string",enum:["batch","row"]},exhaustive:{type:"boolean"},threshold:{type:"number",minimum:0,maximum:1},filterStatus:{type:"string"},filterType:{type:"string"},filterTag:{type:"string"},filterPriority:{anyOf:[{type:"string"},{type:"number"}]},filterDeadlineBefore:{type:"string"},filterDeadlineAfter:{type:"string"},filterUpdatedAfter:{type:"string"},filterUpdatedBefore:{type:"string"},filterCreatedAfter:{type:"string"},filterCreatedBefore:{type:"string"},filterAssignee:{type:"string"},filterAssigneeFilter:{type:"string",enum:["assigned","unassigned"]},filterParent:{type:"string"},filterSprint:{type:"string"},filterRelease:{type:"string"},closeReason:{type:"string"},completedAt:{type:"string",format:"date-time"},reason:{type:"string"},priority:{anyOf:[{type:"string"},{type:"number"}]},tags:{type:"string"},addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}},addAc:{type:"array",items:{type:"string"}},removeAc:{type:"array",items:{type:"string"}},body:{type:"string"},deadline:{type:"string"},estimate:{anyOf:[{type:"string"},{type:"number"}]},acceptanceCriteria:{type:"string"},author:{type:"string"},message:{type:"string"},owner:{type:"string"},enforcement:{type:"string"},assignee:{type:"string"},assigneeFilter:{type:"string",enum:["assigned","unassigned"]},parent:{type:"string"},reviewer:{type:"string"},attributedAuthor:{type:"string"},planFingerprint:{type:"string",pattern:"^[a-f0-9]{64}$"},historyEvent:{type:"array",items:{type:"string"}},risk:{type:"string"},confidence:{anyOf:[{type:"string"},{type:"number"}]},sprint:{type:"string"},release:{type:"string"},blockedBy:{type:"string"},blockedReason:{type:"string"},unblockNote:{type:"string"},reporter:{type:"string"},severity:{type:"string"},environment:{type:"string"},reproSteps:{type:"string"},resolution:{type:"string"},expectedResult:{type:"string"},actualResult:{type:"string"},affectedVersion:{type:"string"},fixedVersion:{type:"string"},component:{type:"string"},regression:{anyOf:[{type:"boolean"},{type:"string"},{type:"number"}]},customerImpact:{type:"string"},definitionOfReady:{type:"string"},order:{anyOf:[{type:"string"},{type:"number"}]},goal:{type:"string"},objective:{type:"string"},value:{type:"string"},impact:{type:"string"},outcome:{type:"string"},whyNow:{type:"string"},mode:{type:"string",enum:["keyword","semantic","hybrid"]},semanticWeight:{anyOf:[{type:"string"},{type:"number"}]},op:{type:"string"},compact:{type:"boolean"},raw:{type:"boolean"},brief:{type:"boolean"},full:{type:"boolean"},includeEmpty:{type:"boolean"},view:{type:"string",enum:["agenda","day","week","month"]},date:{type:"string"},from:{type:"string"},before:{type:"string"},at:{type:"string"},to:{type:"string"},migrationId:{type:"string"},fieldTypeScope:{type:"string"},past:{type:"boolean"},fullPeriod:{type:"boolean"},include:{type:"string"},recurrenceLookaheadDays:{anyOf:[{type:"string"},{type:"number"}]},recurrenceLookbackDays:{anyOf:[{type:"string"},{type:"number"}]},occurrenceLimit:{anyOf:[{type:"string"},{type:"number"}]},includeLinked:{type:"boolean"},semantic:{type:"boolean"},hybrid:{type:"boolean"},titleExact:{type:"boolean"},phraseExact:{type:"boolean"},highlight:{type:"boolean"},includeBody:{type:"boolean"},noTruncate:{type:"boolean"},strictRead:{type:"boolean"},tag:{type:"string"},deadlineBefore:{type:"string"},deadlineAfter:{type:"string"},today:{type:"boolean"},recent:{type:"boolean"},updatedAfter:{type:"string"},updatedBefore:{type:"string"},createdAfter:{type:"string"},createdBefore:{type:"string"},filterAcMissing:{type:"boolean"},filterEstimatesMissing:{type:"boolean"},filterResolutionMissing:{type:"boolean"},filterMetadataMissing:{type:"boolean"},filterReviewerMissing:{type:"boolean"},filterRiskMissing:{type:"boolean"},filterConfidenceMissing:{type:"boolean"},filterSprintMissing:{type:"boolean"},filterReleaseMissing:{type:"boolean"},hasNotes:{type:"boolean"},noNotes:{type:"boolean"},hasLearnings:{type:"boolean"},noLearnings:{type:"boolean"},hasFiles:{type:"boolean"},noFiles:{type:"boolean"},hasDocs:{type:"boolean"},noDocs:{type:"boolean"},hasTests:{type:"boolean"},noTests:{type:"boolean"},hasComments:{type:"boolean"},noComments:{type:"boolean"},hasDeps:{type:"boolean"},noDeps:{type:"boolean"},hasBody:{type:"boolean"},emptyBody:{type:"boolean"},hasLinkedCommand:{type:"boolean"},noLinkedCommand:{type:"boolean"},filterHasNotes:{type:"boolean"},filterNoNotes:{type:"boolean"},filterHasLearnings:{type:"boolean"},filterNoLearnings:{type:"boolean"},filterHasFiles:{type:"boolean"},filterNoFiles:{type:"boolean"},filterHasDocs:{type:"boolean"},filterNoDocs:{type:"boolean"},filterHasTests:{type:"boolean"},filterNoTests:{type:"boolean"},filterHasComments:{type:"boolean"},filterNoComments:{type:"boolean"},filterHasDeps:{type:"boolean"},filterNoDeps:{type:"boolean"},filterHasBody:{type:"boolean"},filterEmptyBody:{type:"boolean"},filterHasLinkedCommand:{type:"boolean"},filterNoLinkedCommand:{type:"boolean"},ids:{type:"string"},limit:{anyOf:[{type:"string"},{type:"number"}]},blockedLimit:{anyOf:[{type:"string"},{type:"number"}]},readyOnly:{type:"boolean"},offset:{anyOf:[{type:"string"},{type:"number"}]},progress:{type:"boolean"},background:{type:"boolean"},runId:{type:"string"},stream:{anyOf:[{type:"boolean"},{type:"string",enum:["stdout","stderr","both","rows","ndjson","jsonl"]}]},tail:{anyOf:[{type:"string"},{type:"number"}]},addJson:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},eventType:{type:"string"},includeMeta:{type:"boolean"},allActionable:{type:"boolean"},verboseAuthorEvents:{type:"boolean"},match:{type:"string"},onlyIndex:{anyOf:[{type:"string"},{type:"number"}]},removeIndex:{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}},updateIndex:{anyOf:[{type:"string"},{type:"number"}]},setJson:{type:"string"},update:{type:"string"},onlyLast:{type:"boolean"},envSet:{type:"array",items:{type:"string"}},envClear:{type:"array",items:{type:"string"}},sharedHostSafe:{type:"boolean"},detail:{type:"string",enum:["summary","deep"]},trace:{type:"boolean"},reload:{type:"boolean"},watch:{type:"boolean"},runtimeProbe:{type:"boolean"},offline:{type:"boolean"},fixManagedState:{type:"boolean"},isolated:{type:"boolean"},ignoreGlobal:{type:"boolean"},pmContext:{type:"string",enum:["schema","tracker","auto","none"]},overrideLinkedPmContext:{type:"boolean"},workspaceContext:{type:"string",enum:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{type:"boolean"},allowUntrustedLinkedTests:{type:"boolean"},acknowledgeLinkedTests:{type:"boolean"},failOnContextMismatch:{type:"boolean"},failOnSkipped:{type:"boolean"},failOnEmptyTestRun:{type:"boolean"},requireAssertionsForPm:{type:"boolean"},checkContext:{type:"boolean"},fullOutput:{type:"boolean"},autoPmContext:{type:"boolean"},measure:{type:"array",items:{type:"string"}},metricBelow:{type:"string"},metricDiff:{type:"string"},diff:{type:"boolean"},storage:{type:"boolean"},metadataCoverage:{type:"boolean"},fieldUtilization:{type:"boolean"},byAssignee:{type:"boolean"},byTag:{type:"boolean"},byPriority:{type:"boolean"},tagPrefix:{type:"string"},measurements:{type:"boolean"},metric:{type:"string"},measurementLimit:{type:"integer",minimum:0,maximum:1e3},observe:{type:"array",items:{type:"string"}},improvementDirection:{type:"string",enum:["higher","lower","target"]},measurementSource:{type:"string"},measurementItem:{type:"string"},measurementRevision:{type:"string"},provenanceCoverage:{type:"boolean"},fleetAttribution:{type:"boolean"},eventLimit:{type:"integer",minimum:1,maximum:1e5},minimumSample:{type:"integer",minimum:1,maximum:1e4},verify:{type:"boolean"},literal:{type:"array",items:{type:"string"}},regex:{type:"array",items:{type:"string"}},replacement:{type:"string"},timeout:{anyOf:[{type:"string"},{type:"number"}]},validateClose:{type:"string",enum:["off","warn","strict"]},checkMetadata:{type:"boolean"},metadataProfile:{type:"string",enum:["core","strict","custom"]},checkResolution:{type:"boolean"},checkCompleteness:{type:"boolean"},checkLifecycle:{type:"boolean"},checkStaleBlockers:{type:"boolean"},dependencyCycleSeverity:{type:"string",enum:["off","warn","error"]},parentCycleSeverity:{type:"string",enum:["off","warn","error"]},checkFiles:{type:"boolean"},checkStorageIntegrity:{type:"boolean"},strictDirectories:{type:"boolean"},requireMergeDrivers:{type:"boolean"},checkOnly:{type:"boolean"},checkTelemetry:{type:"boolean"},noRefresh:{type:"boolean"},refreshVectors:{type:"boolean"},verboseStaleItems:{type:"boolean"},skipVectors:{type:"boolean"},skipIntegrity:{type:"boolean"},skipDrift:{type:"boolean"},verboseDiagnostics:{type:"boolean"},allAffectedIds:{type:"boolean"},scanMode:{type:"string",enum:["default","tracked-all","tracked-all-strict"]},includePmInternals:{type:"boolean"},verboseFileLists:{type:"boolean"},strictExit:{type:"boolean"},failOnWarn:{type:"boolean"},fixHints:{type:"boolean"},autoFix:{type:"boolean"},fixScope:{type:"array",items:{type:"string",enum:["metadata","resolution","estimates","lifecycle"]}},pruneMissing:{type:"boolean"},checkHistoryDrift:{type:"boolean"},checkCommandReferences:{type:"boolean"},counts:{type:"boolean"},edit:{type:"integer",minimum:1},delete:{type:"integer",minimum:1},dryRun:{type:"boolean"},normalizeProvenance:{type:"boolean"},salvageTail:{type:"boolean"},appendOnly:{type:"boolean"},all:{type:"boolean"},clear:{type:"boolean"},cliOnly:{type:"boolean"},packagesOnly:{type:"boolean"},repair:{type:"boolean"},packageName:{type:"string"},rollback:{type:"string"},noCheckpoint:{type:"boolean"},force:{type:"boolean"},ifAvailable:{type:"boolean"},takeoverStale:{type:"boolean"},ifAbsent:{type:"boolean"},expectAt:{type:"string",minLength:1},next:{type:"boolean"},maxAttempts:{anyOf:[{type:"integer",minimum:1,maximum:100},{type:"string",pattern:"^(?:[1-9]|[1-9][0-9]|100)$"}]},includeDecisions:{type:"boolean"},includeGates:{type:"boolean"},includeContainers:{type:"boolean"},explainRanking:{type:"boolean"},noTags:{type:"boolean"},noExtensionHealth:{type:"boolean"},run:{type:"boolean"},count:{type:"boolean"},sum:{type:"string"},avg:{type:"string"},tree:{type:"boolean"},treeId:{type:"string",minLength:1},definition:{type:"object"},trigger:{type:"string",enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]},gate:{type:"string",minLength:1},treeDepth:{anyOf:[{type:"string"},{type:"number"}]},includeUnparented:{type:"boolean"},gcScope:{type:"array",items:{type:"string",enum:["index","embeddings","runtime","locks"]}},maxDepth:{anyOf:[{type:"string"},{type:"number"}]},nodeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},edgeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},tokenBudget:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},cursor:{type:"string"},direction:{type:"string",enum:["outgoing","incoming","both"]},kind:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},after:{type:"string"},maxPaths:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},sample:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},exemptIsolate:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},collapse:{type:"string",enum:["none","repeated"]},shell:{type:"string",enum:["bash","zsh","fish"]},stdin:{type:"boolean"},file:{type:"string"},preserveSourceIds:{type:"boolean"},folder:{type:"string"},subcommand:{type:"string"},name:{type:"string"},defaultStatus:{type:"string"},alias:{type:"array",items:{type:"string"}},role:{type:"array",items:{type:"string"}},fieldType:{type:"string",enum:["string","number","boolean","string_array"]},commands:{type:"array",items:{type:"string"}},cliFlag:{type:"string"},required:{type:"boolean"},requiredOnCreate:{type:"boolean"},allowUnset:{type:"boolean"},requiredTypes:{type:"array",items:{type:"string"}},infer:{type:"boolean"},minCount:{type:"number"},text:{type:"string"},add:{type:"array",items:{type:"string"}},addGlob:{type:"array",items:{type:"string"}},remove:{type:"array",items:{type:"string"}},migrate:{type:"array",items:{type:"string"}},discover:{type:"boolean"},apply:{type:"boolean"},discoveryNote:{type:"string"},lookupPath:{type:"array",items:{type:"string"}},explain:{type:"boolean"},lines:{type:"string",pattern:"^[1-9]\\d*:[1-9]\\d*$"},decisionDepth:{type:"integer",minimum:1,maximum:32},addNote:{type:"string"},noteConflict:{type:"string",enum:["refuse","replace","append"]},list:{type:"boolean"},appendStable:{type:"boolean"},validatePaths:{type:"boolean"},dep:{type:"array",items:{type:"string"}},depRemove:{type:"array",items:{type:"string"}},replaceDeps:{type:"boolean"},replaceTests:{type:"boolean"},replaceFiles:{type:"boolean"},replaceDocs:{type:"boolean"},comment:{type:"array",items:{type:"string"}},note:{type:"array",items:{type:"string"}},learning:{type:"array",items:{type:"string"}},linkedFile:{type:"array",items:{type:"string"}},linkedTest:{type:"array",items:{type:"string"}},doc:{type:"array",items:{type:"string"}},reminder:{type:"array",items:{type:"string"}},event:{type:"array",items:{type:"string"}},typeOption:{type:"array",items:{type:"string"}},field:{type:"array",items:{type:"string"}},unset:{type:"array",items:{type:"string"}},clearDeps:{type:"boolean"},clearComments:{type:"boolean"},clearNotes:{type:"boolean"},clearLearnings:{type:"boolean"},clearFiles:{type:"boolean"},clearTests:{type:"boolean"},clearDocs:{type:"boolean"},clearReminders:{type:"boolean"},clearEvents:{type:"boolean"},clearTypeOptions:{type:"boolean"},criterion:{type:"array",items:{type:"string"}},clearCriteria:{type:"boolean"},groupBy:{type:"string"},setMode:{type:"string",enum:["element","tuple"]},completion:{type:"boolean"},format:{type:"string"},unbounded:{type:"boolean"},depth:{type:"string",enum:["brief","standard","deep","full"]},section:{type:"array",items:{type:"string",enum:["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]}},activityLimit:{anyOf:[{type:"string"},{type:"number"}]},staleThreshold:{type:"string"},policy:{type:"string"}},xI={schema:{definition:{type:["object","string"]}},assurance:{definition:kI,kind:{type:"string",enum:["measurement","assertion","gate"]},subcommand:{type:"string",enum:["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"]},preset:{type:"string",enum:["software-delivery","research","agent-evaluation","operations"]},enforcement:{type:"string",enum:["warn","block"]},limit:{type:"integer",minimum:1,maximum:1e3}},activity:{harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},"update-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"close-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"history-compact":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},events:{verify:{type:"boolean"},since:{type:"string",minLength:1},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},history:{order:{type:"string",enum:["oldest_first","newest_first"]},harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},remind:{at:{type:"string",minLength:1}}},PX=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],$y={subcommand:{type:"string",enum:[...PX]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...Ww]},mode:{type:"string",enum:[...Gw]},resumeContext:{type:"string"},related:{type:"string"},blocks:{type:"string"},claim:{type:"boolean"},fromSearch:{type:"string"},stepTitle:{type:"string"},step:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},stepBody:{type:"string"},stepOwner:{type:"string"},stepStatus:{type:"string",enum:[...Hc]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...Vw]},linkNote:{type:"string"},promoteToItemDep:{type:"boolean"},allowMultipleActive:{type:"boolean"},file:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},test:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},doc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},decisionText:{type:"string"},decision:{type:"string"},decisionRationale:{type:"string"},decisionEvidence:{type:"string"},discoveryText:{type:"string"},discovery:{type:"string"},validationText:{type:"string"},validation:{type:"string"},validationCommand:{type:"string"},validationExpected:{type:"string"},steps:{type:"array",items:{type:"string"}},materializeType:{type:"string"},materializeParent:{type:"string"},materializeTags:{type:"string"},field:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},Dy={subcommand:{description:"Plan workflow operation to run.",examples:["create","show","add-step","approve"]},stepRef:{description:"Plan step id or order for step lifecycle subcommands.",examples:["plan-step-001","1"]},reorderTo:{description:"New integer order for reorder-step.",examples:[1,"2"]},scope:{description:"Short free-text scope statement describing what the Plan covers.",examples:["Release readiness audit","Search package migration"]},mode:{description:"Plan lifecycle mode.",examples:["draft","research","approved"]},step:{description:"Ordered initial step titles for create (string or array, never comma-split; stepTitle, when also set, becomes the first step). For step subcommands a single value aliases stepTitle.",examples:[["Read the code","Write the fix","Run the tests"]]},file:{description:"File link to attach while creating or materializing a Plan.",examples:["path=src/cli.ts,note=implementation surface"]},test:{description:"Test command link to attach while creating or materializing a Plan.",examples:["command=pnpm build,timeout_seconds=300"]},doc:{description:"Documentation link to attach while creating or materializing a Plan.",examples:["path=docs/SDK.md,note=public API reference"]}},SI={includeGates:{description:"Opt next or claim-next into outcome gates. Blocker and ownership restrictions still apply."},includeContainers:{description:"Opt next or claim-next into containers with unfinished descendants. Blocker and ownership restrictions still apply."},action:{description:"Tool action to execute."},pmExecutable:{description:"Override the pm executable used by actions that invoke or verify an external CLI process.",examples:["pm","node dist/cli.js"]},force:{description:"Allow the selected action to override its supported ownership, terminal-state, or destructive-operation guard."},takeoverStale:{description:"Take over another holder's claim only when it has been idle for mutation_guard.stale_in_progress_hours; an active claim is refused with stale_claim_takeover_refused. Not combinable with force or next."},limit:{description:"Maximum number of rows returned by the selected action.",examples:[10,"25"]},text:{description:"Text payload used by append, comment, note, or learning mutations."},path:{description:"Optional PM data root override for this invocation.",examples:[".agents/pm"]},scope:{description:"Scope selector for commands that operate on project or global state. Linked files, docs, and tests default to project scope when omitted.",examples:["project","global"]},detail:{description:"Detail mode for commands that support concise and deep diagnostics.",examples:["summary","deep"]},trace:{description:"When true for extension-doctor, include actionable registration traces in deep diagnostics."},reload:{description:"When true for extension action payloads, trigger cache-busted extension module reload."},watch:{description:"When true for extension-reload/extension action payloads, enable watch mode semantics."},runtimeProbe:{description:"When true for extension-manage, run a doctor-like runtime activation probe for parity fields."},offline:{description:"Skip remote GitHub and npm freshness checks during package or extension manage; update availability remains unknown."},fixManagedState:{description:"When true for extension-manage/extension-doctor, adopt unmanaged extensions before diagnostics/update checks."},isolated:{description:"When true for extension-doctor/package-doctor, ignore global registrations for hermetic project diagnostics."},ignoreGlobal:{description:"Alias for isolated on extension-doctor/package-doctor action payloads."},target:{description:"Positional target argument for the selected action (ID, source, package source, or extension name).",examples:["pm-a1b2",".agents/pm/extensions/sample","sample-extension"]},capability:{description:"Starter capability selected by extension-init or package-init scaffolding.",examples:["commands","hooks","search","schema"]},declarative:{description:"Generate the package composeExtension declarative blueprint starter."},output:{description:"File path for commands that write generated output, such as package/extension describe Markdown references.",examples:["docs/pm-package-reference.md"]},markdown:{description:"Render the package or extension description as Markdown instead of structured output.",examples:[!0]},github:{description:"GitHub shorthand owner/repo[/path] source for package/extension install actions.",examples:["org/repo/extensions/sample"]},ref:{description:"Git ref/branch/tag used when installing from GitHub shorthand/URL sources.",examples:["main","v1.0.0"]},cliOnly:{description:"Restrict upgrade to the pm CLI/SDK npm package."},packagesOnly:{description:"Restrict upgrade to managed installable pm packages."},repair:{description:"Force npm global reinstall semantics when upgrading the pm CLI/SDK."},tag:{description:"npm version or dist-tag used for CLI and registry package upgrades.",examples:["latest","next","2026.5.11"]},today:{description:"When true for list actions, include only items updated since local midnight today."},recent:{description:"When true for list actions, include only items updated in the last seven days."},packageName:{description:"Override the pm CLI package name for self-upgrade automation and tests.",examples:["@unbrained/pm-cli"]},json:{description:"Emit machine-readable JSON output."},quiet:{description:"Suppress stdout payload output."},noExtensions:{description:"Disable extension loading for this invocation."},noPager:{description:"Disable pager integration for help and long output."},tokenAccounting:{description:"Request a bounded transport-level receipt for output emitted by a compatible CLI or MCP host."},outputInclude:{description:"Comma-separated fields or sections retained by any built-in read action.",examples:["id,title,status","summary,counts"]},outputLimit:{description:"Universal read row ceiling, or unbounded to disable the shared ceiling.",examples:[10,"unbounded"]},outputBudget:{description:"Universal estimated-token ceiling for a read result, or unbounded to disable the shared ceiling.",examples:[600,1200,"unbounded"]},outputFormat:{description:"Universal read-result encoding selector.",examples:["toon","json"]},outputSession:{description:"Caller-carried JSON session state that enforces a token ceiling across read calls and replaces repeated item facts with resolvable context references.",examples:[{version:1,id:"orientation",token_budget:4e3,spent_tokens:0,seen_item_ids:[]}]},outputCursor:{description:"Opaque continuation cursor returned when a declared row collection is compacted by the output budget."},outputRowContract:{description:"Include the row selector and TOON row-encoding contract on a read result."},profile:{description:"Emit deterministic timing diagnostics to stderr."},timeoutMs:{description:"Tool execution timeout in milliseconds.",examples:[12e4]},id:{description:"Item identifier for read or mutation actions.",examples:["pm-a1b2"]},treeId:{description:"Commit, tree, snapshot, or immutable workspace identity judged by an assurance gate.",examples:["0123456789abcdef","release-candidate-3"]},definition:{description:"Structured measurement, assertion, or gate declaration used by assurance put."},trigger:{description:"Lifecycle trigger used to evaluate an assurance gate.",examples:["ci","pre-release"]},gate:{description:"Stable assurance gate id used to filter durable verdict history.",examples:["release-readiness"]},owner:{description:"pm item that owns preset or observation-derived assurance assertions.",examples:["pm-a1b2"]},enforcement:{description:"Explicit next assurance enforcement level.",examples:["warn","block"]},runId:{description:"Background test run identifier.",examples:["tr-kq9x3f-93acde"]},title:{description:"Item title text."},description:{description:"Item description text."},type:{description:"Item type name from the active runtime type registry.",examples:["Task","Feature"]},subcommand:{description:"Subcommand selector for schema, profile, telemetry, and graph actions."},name:{description:"Custom definition name, schema migration source name, or profile name.",examples:["Spike","review","component"]},defaultStatus:{description:"Default status hint recorded for a custom item type.",examples:["open"]},alias:{description:"Aliases for the custom item type or status (repeatable).",examples:[["spike","research"]]},role:{description:"Lifecycle roles for a custom status (schema add-status): draft, active, blocked, terminal, terminal_done, terminal_canceled, default_open, default_close, default_cancel.",examples:[["active"],["terminal","terminal_done"]]},fieldType:{description:"Value type for a custom field (schema add-field): string, number, boolean, or string_array.",examples:["string","number","string_array"]},fieldTypeScope:{description:"Optional item type restricting which records participate in schema rename-field.",examples:["Issue","Feature"]},migrationId:{description:"Optional stable idempotency override used to persist and resume a schema migration plan; omitted values are derived from the workspace and normalized request.",examples:["severity-to-impact-v2"]},commands:{description:"Commands a custom field is wired onto (schema add-field): create, update, update_many, list, search, calendar, context.",examples:[["create","update"],["create","update","list"]]},cliFlag:{description:"Override the auto-derived CLI flag for a custom field (schema add-field).",examples:["--owner"]},required:{description:"Mark a custom field as always required (schema add-field)."},requiredOnCreate:{description:"Mark a custom field as required at create time (schema add-field)."},allowUnset:{description:"Whether a custom field may be cleared via --unset (schema add-field); defaults to true."},allowDuplicate:{description:"Explicitly proceed when strict similarity governance finds likely duplicate items."},allowUnresolvedDeps:{description:"Permit unresolved local dependency targets while returning dependency_target_unresolved warning receipts. Cross-workspace references should use source_kind=external instead.",examples:[!0]},requiredTypes:{description:"Restrict a custom field's requirement to specific item types (schema add-field).",examples:[["Bug"],["Story","Spike"]]},infer:{description:"Infer custom item types from title-prefix conventions (schema add-type); previews unless apply is true."},minCount:{description:"Minimum number of items sharing a title prefix for schema add-type inference (default 10).",examples:[10,25]},preset:{description:"Governance preset for initialization flows.",examples:["minimal","default","strict"]},idPrefix:{description:"Tracker item identifier prefix used by initialization; overrides the positional compatibility prefix.",examples:["pm","work"]},workspace:{description:"Workspace directory where initialization resolves or creates the tracker.",examples:[".","packages/app"]},typePreset:{description:"Domain item-type preset registered during initialization.",examples:["agile","ops","research"]},defaults:{description:"Use non-interactive setup defaults during initialization."},verbose:{description:"Include the full resolved settings tree in init output."},agentGuidance:{description:"Control AGENTS.md/CLAUDE.md guidance behavior during init: ask, add, skip, or status.",examples:["ask","add","skip","status"]},withPackages:{description:"Install all bundled first-party pm packages during initialization."},mergeFence:{description:"Install the repository merge-driver fence for a fresh Git-backed tracker; set false to opt out."},createMode:{description:"Create required-option policy mode.",examples:["strict","progressive"]},defer:{description:"Strict-required create fields whose values are not known yet (GH-1713): deadline, assignee, acceptance_criteria or estimated_minutes. Each is recorded in deferred_fields with deferReason; strict close validation refuses the item until every deferred field holds a value, and warn mode only warns.",examples:[["deadline","assignee"],["acceptance_criteria"]]},deferReason:{description:"Why the deferred values are not known yet, for example the external system the record was imported from. Required with defer.",examples:["Imported from GitHub issue 42"]},schedulePreset:{description:"Schedule-centric create preset for Reminder, Meeting, and Event types.",examples:["lightweight"]},status:{description:"Item status value. Statuses are project-configurable via .agents/pm/settings.json (schema block); the built-in defaults are draft, open, in_progress, blocked, closed, canceled. Custom statuses defined for the project are accepted \u2014 discover the active set with the pm_contracts tool (workspace.statuses) or `pm contracts`. Unknown statuses are rejected at runtime with a did-you-mean hint rather than blocked by a fixed schema enum.",examples:["open","in_progress"]},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for duplicate discovery.",examples:["2026-01-01T00:00:00.000Z"]},exhaustive:{description:"Compare every duplicate pair within the disclosed safety bound; default prefix filtering preserves exact recall."},threshold:{description:"Minimum duplicate similarity score from zero through one.",examples:[.85]},priority:{description:"Priority value in range 0..4.",examples:[0,1,"2"]},order:{description:"Planning order/rank value for create/update, or sort direction (asc|desc) for list-family sorting.",examples:[0,1,"2","asc","desc"]},sort:{description:"List-family sort field selector.",examples:["priority","deadline","updated_at","created_at","title","parent"]},tags:{description:"Comma-delimited tag list.",examples:["pm-cli,agent-ux"]},addTags:{description:"Tags to add to the existing list without replacing it. Each entry may be CSV or a JSON array.",examples:[["agent-ux"],["fix","security"]]},addAc:{description:"Acceptance criteria appended individually without replacing the existing list (one criterion per entry).",examples:[["error path covered by a regression test"]]},removeAc:{description:"Acceptance criteria removed individually by exact text match; the mutation fails atomically if any selector is unmatched (one criterion per entry).",examples:[["superseded manual QA step"]]},removeTags:{description:"Tags to remove from the existing list. Each entry may be CSV or a JSON array.",examples:[["stale"],["legacy","wontfix"]]},deadline:{description:"ISO/date timestamp or relative offset (+6h/+1d/+2w/+6m).",examples:["2026-04-01T00:00:00.000Z","+1d"]},reminder:{description:"Repeatable reminder seed entries at=<iso|relative>,text=<text>.",examples:[["at=+2d,text=Review PR"]]},event:{description:"Repeatable event seed entries start=<iso|relative> with end=<iso|relative> or duration=<relative|30min|PT30M>. Bare `m` remains months for backward compatibility.",examples:[["start=2026-07-01T10:00:00Z,duration=2h,title=planning"],["start=2026-07-01T10:00:00Z,duration=30min,title=standup"],["start=2026-07-01T10:00:00Z,duration=PT30M,title=window"]]},historyEvent:{description:"Unknown-author history target in <item-id>:<one-based-line> form.",examples:[["pm-example:4","pm-example:5"]]},planFingerprint:{description:"Exact SHA-256 returned by a history-author-acknowledge dry-run preview; apply refuses stale or changed source coordinates.",examples:["0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"]},estimate:{description:"Estimated effort in minutes.",examples:[60,"120"]},acceptanceCriteria:{description:"Complete acceptance-criteria text supplied while creating or replacing an item field."},author:{description:"Intentional mutation-author override. Agent harness identity is automatic when omitted."},expectHash:{description:"Expected item revision: the item_hash from get. Each locked write refuses with item_revision_conflict when the item changed since; a bare hash binds to id, <id>=<item_hash> names other items."},attributedAuthor:{description:"Principal attributed to the immutable unknown-author history events after review.",examples:["reviewed-principal"]},message:{description:"History message for mutation audit trail."},ifAbsent:{description:"For annotations, append only when no existing entry has the same resolved author and exact stored text; retries return changed false without a history event."},expectAt:{description:"For annotation edit or delete, the created_at of the entry read at that index; the write is refused with annotation_entry_mismatch when the addressed entry has a different created_at. It compares timestamps, not entry identities.",examples:["2026-11-06T06:02:01.768Z"]},assignee:{description:"Assignee identity."},assigneeFilter:{description:"Assignee presence selector for list, calendar, and context filters.",examples:["assigned","unassigned"]},parent:{description:"Parent item ID filter for hierarchical list queries.",examples:["pm-epic01"]},blockedLimit:{description:"Cap blocked rows returned by the next action (defaults to the ready --limit).",examples:["3"]},readyOnly:{description:"When true, the next action omits the blocked companion list."},unset:{description:"Repeatable list of item-metadata fields to clear explicitly during create/update mutations; each entry may also be a comma-separated field list.",examples:[["deadline","assignee"],["close-reason"]]},clearDeps:{description:"When true, clear linked dependencies."},replaceDeps:{description:"When true for update, atomically replace dependencies with the supplied --dep values."},replaceTests:{description:"When true for update, atomically replace linked tests with the supplied --test values."},replaceFiles:{description:"When true for update, atomically replace linked files with the supplied --file values."},replaceDocs:{description:"When true for update, atomically replace linked docs with the supplied --doc values."},lookupPath:{description:"One or more source paths whose referencing pm items should be returned by files lookup.",examples:[["src/sdk/files.ts"],["README.md","docs/SDK.md"]]},explain:{description:"Include ranked linked-file, rationale, and governing-decision evidence for a files lookup."},lines:{description:"Inclusive start:end source-line range for Git contribution attribution; requires one lookup path.",examples:["10:24"]},decisionDepth:{description:"Maximum typed relationship depth searched for a governing Decision during files lookup.",examples:[8]},clearComments:{description:"When true, clear item comments."},clearNotes:{description:"When true, clear item notes."},clearLearnings:{description:"When true, clear item learnings."},clearFiles:{description:"When true, clear linked files."},clearTests:{description:"When true, clear linked tests."},clearDocs:{description:"When true, clear linked docs."},clearReminders:{description:"When true, clear reminders."},clearEvents:{description:"When true, clear events."},clearTypeOptions:{description:"When true, clear type option metadata."},clearCriteria:{description:"When true for config set criteria-list keys (definition-of-done, metadata-required-fields, lifecycle pattern lists), clear the criteria list."},mode:{description:"Mode selector for search and reindex (keyword|semantic|hybrid).",examples:["keyword","hybrid"]},semanticWeight:{description:"Per-query hybrid semantic weight override in [0,1] for search action; invalid values fall back to settings.",examples:[.2,"0.7"]},op:{description:"History operation filter for activity output.",examples:["create","update","close","update_ownership_bypass"]},fullPeriod:{description:"For day/week/month calendar views, include the full anchored period instead of clipping the start to now."},progress:{description:"Emit progress diagnostics to stderr for long-running operations."},background:{description:"Run linked tests in managed background mode."},addJson:{description:"JSON input: one structured context event for notes, or repeatable linked-test entries for test.",examples:[['{"command":"node scripts/run-tests.mjs test -- tests/unit/output.spec.ts","timeout_seconds":240}']]},eventType:{description:"For notes action, return structured context events whose top-level type matches this value."},includeMeta:{description:"Include structured-event counts for notes reads; filtered reads also include total, returned, limit, and has-more metadata."},allActionable:{description:"For history-author-acknowledge, select every currently actionable undispositioned event."},match:{description:"Run only linked tests whose command or path contains this case-insensitive substring.",examples:["output.spec.ts","coverage"]},onlyIndex:{description:"Run only the 1-based linked-test index from pm test <id> --list order.",examples:[1,"2"]},removeIndex:{description:"Remove linked tests by their 1-based positions from pm test <id> --list order; repeatable and lossless for commands containing commas or equals signs.",examples:[[1],["2","4"]]},update:{description:"Edit one linked test by exact command, command=<value>, or path=<value>, with setJson; ambiguous matches refuse without changes.",examples:["node scripts/run-tests.mjs test","path=tests/example.spec.ts"]},updateIndex:{description:"Edit one linked test at its current 1-based list position with setJson, preserving order and original command provenance.",examples:[1,"2"]},setJson:{description:"Explicit JSON metadata patch for update or updateIndex. Null clears optional fields; command and provenance are immutable.",examples:['{"note":"focused regression","timeout_seconds":120}']},onlyLast:{description:"Run only the most recently added linked-test entry."},envSet:{description:"Repeatable runtime environment KEY=VALUE overrides for linked-test execution.",examples:[["PORT=0","PLAYWRIGHT_HTML_OPEN=never"]]},envClear:{description:"Repeatable runtime environment variable names to clear before linked-test execution.",examples:[["PLAYWRIGHT_BASE_URL"]]},sharedHostSafe:{description:"Apply additive shared-host-safe runtime defaults during linked-test execution."},pmContext:{description:"PM linked-test context mode (schema keeps isolated tracker data; tracker seeds source tracker data; auto uses tracker for PM tracker-read commands; none omits PM_PATH for self-isolating SDK tests in isolated or snapshot workspaces).",examples:["schema","tracker","auto","none"]},overrideLinkedPmContext:{description:"Force run-level --pm-context to override per-linked-test pm_context_mode metadata for all linked-test entries."},workspaceContext:{description:"Source-workspace mode: source preserves read-only source context, isolated omits it for self-sandboxing commands, and snapshot runs from a temporary workspace paired with the selected tracker sandbox.",examples:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{description:"Force run-level --workspace-context over per-linked-test workspace_context_mode metadata."},allowUntrustedLinkedTests:{description:"Explicitly execute commands not yet trusted by this clone when testing.allow_untrusted_linked_tests is also enabled."},acknowledgeLinkedTests:{description:"Record clone-local trust for the item's current linked commands without executing them."},failOnContextMismatch:{description:"Fail linked PM command runs when source and sandbox tracker item counts differ."},failOnSkipped:{description:"Treat skipped linked tests as dependency-failed policy violations."},failOnEmptyTestRun:{description:"Treat successful linked-test commands that report zero executed tests as failures."},requireAssertionsForPm:{description:"Require assertion metadata for linked PM command test entries during run execution."},checkContext:{description:"Run linked PM command context preflight diagnostics before command execution."},fullOutput:{description:"Keep every linked-test row's complete stdout and stderr in the CLI rendering, which otherwise keeps an escape-free tail on a quiet passing run; MCP and SDK results always carry the complete streams."},autoPmContext:{description:"Auto-remediate PM tracker-read linked commands by routing those entries through tracker context regardless of linked-test pm_context_mode overrides."},measure:{description:"Repeatable numeric run evidence in name=value[,unit=...][,threshold=...] form; requires run=true.",examples:[["coverage=100,unit=percent,threshold=100"]]},metricBelow:{description:"Return recorded evidence below a name=value threshold.",examples:["coverage=100"]},metricDiff:{description:"Compare the latest and previous values for one metric.",examples:["coverage"]},dryRun:{description:"Preview command effects without mutating storage artifacts."},normalizeProvenance:{description:"For history-repair: remove invalid legacy provenance observations and emit only aggregate privacy-safe repair evidence."},salvageTail:{description:"For history-repair with one explicit id: remove lines that cannot hold a record (a JSON null, boolean or number) and an invalid trailing suffix after a verified prefix; refuses interior corruption."},appendOnly:{description:"For history-repair: bridge each chain break with one appended, sealed record instead of re-anchoring recorded entries, so every earlier line stays byte-identical."},all:{description:"For history-repair action: scan every stream for drift and repair each drifted stream in one audited pass (mutually exclusive with id)."},clear:{description:"For focus action: clear the session focused item instead of setting it (mutually exclusive with id)."},gcScope:{description:"Repeatable gc scope selector values (index, embeddings, runtime, locks, checkpoints, transactions).",examples:[["index","embeddings"],["runtime"],["locks"],["checkpoints"]]},storage:{description:"For stats action: include aggregate history-stream storage metrics (total streams/lines/bytes, largest + deepest streams, oldest/newest entries) for compaction and storage planning."},fieldUtilization:{description:"For stats action: include a field_utilization block reporting present/total/percent for content fields (notes, learnings, files, docs, tests, comments, deps, body, linked_command) across all items so under-documented dimensions are visible at a glance."},measurements:{description:"For stats action: include the audited append-only improvement ledger and baseline-to-latest trends."},metric:{description:"Exact improvement metric name used to filter ledger reads.",examples:["quality.coverage.lines"]},measurementLimit:{description:"Maximum newest improvement observations returned by stats.",examples:[50]},observe:{description:"Repeatable audited observation in name=value[,unit=...][,threshold=...] form.",examples:[["quality.coverage.lines=100,unit=percent,threshold=100"]]},improvementDirection:{description:"Improvement direction for newly recorded observations.",examples:["higher","lower","target"]},measurementSource:{description:"Producing gate or instrument for a new observation.",examples:["pnpm coverage"]},measurementItem:{description:"Tracked item that owns an improvement observation.",examples:["pm-123abc"]},measurementRevision:{description:"Explicit source revision for a new observation.",examples:["0123456789abcdef"]},provenanceCoverage:{description:"For stats action: compare configured provenance descriptors with bounded immutable-history observations."},fleetAttribution:{description:"For stats action: derive observational throughput, rework, and defect-escape rates by harness, model, and author source."},eventLimit:{description:"Maximum immutable history events consumed by an analytics projection.",examples:[1e4]},minimumSample:{description:"Minimum denominator before analytics rates are reported.",examples:[5]},offset:{description:"Number of matching rows to skip before limit is applied.",examples:[0,50,"100"]},provenance:{description:"Return patch-free immutable author, harness, instance, and extensible provenance rows."},provenanceSummary:{description:"Include bounded observed, unavailable, legacy-missing, and unresolved-author counts."},agentInstance:{description:"Privacy-safe agent invocation fingerprint filter, supplied once or as a list.",examples:["a1b2c3d4",["a1b2c3d4","e5f6g7h8"]]},provenanceFilter:{description:"Exact extensible provenance predicate in dimension=value form, supplied once or as a list.",examples:["model=gpt-5.6-sol",["effort=xhigh","role=reviewer"]]},before:{description:"For history-compact, compact entries strictly before this boundary (version number or ISO timestamp). Single-id mode only.",examples:["5","2026-06-01T00:00:00.000Z"]},at:{description:"Read-only historical projection boundary as an item version or ISO timestamp.",examples:["3","2026-07-01T12:00:00.000Z"]},allOver:{description:"For history-compact bulk mode, compact every stream with more than N entries. When history.compact_policy is enabled and this is omitted, the policy's max_entries is used.",examples:[200,"500"]},minEntries:{description:"For history-compact bulk mode, skip streams with at most N entries as already-compact (default 3).",examples:[3,"10"]},closed:{description:"For history-compact bulk mode, compact only closed (terminal) items' history streams."},allStreams:{description:"For history-compact bulk mode, compact every history stream regardless of lifecycle state."},literal:{description:"Repeatable literal matcher used by history-redact to scrub exact string values.",examples:["[redacted_path_prefix]/private/path"]},regex:{description:"Repeatable regex matcher used by history-redact. Accepts either /pattern/flags or a raw pattern (global mode is auto-enabled).",examples:["/192\\\\.168\\\\.[0-9.]+/g","token=[A-Za-z0-9_-]+"]},replacement:{description:'Replacement text used by history-redact (defaults to "[redacted]").',examples:["[scrubbed_path]"]},validateClose:{description:'Close-time metadata validation mode ("off", "warn", or "strict").',examples:["off","warn","strict"]},checkMetadata:{description:"Run metadata completeness checks."},metadataProfile:{description:"Select metadata validation profile for --check-metadata.",examples:["core","strict","custom"]},checkResolution:{description:"Run closed-item resolution metadata checks."},checkCompleteness:{description:"Evaluate declarative lifecycle field requirements, with per-type counts and bounded missing-field diagnostics."},checkLifecycle:{description:"Run active-item lifecycle governance drift checks."},checkStaleBlockers:{description:"Include stale blocker-pattern diagnostics in lifecycle checks."},dependencyCycleSeverity:{description:"Set dependency-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},parentCycleSeverity:{description:"Set parent-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},checkFiles:{description:"Run linked-file and orphaned-file checks."},checkStorageIntegrity:{description:"Run deep item, history, index, and vector storage integrity checks."},strictDirectories:{description:"Treat optional item-type directories as required health failures."},requireMergeDrivers:{description:"Treat never-installed clone-local semantic merge drivers as required health failures."},checkOnly:{description:"For health action, run read-only diagnostics without refreshing vectors."},checkTelemetry:{description:"For health action, probe telemetry endpoint health and include network diagnostics."},noRefresh:{description:"For health action, skip vector refresh while still running checks."},refreshVectors:{description:"For health action, explicitly refresh stale vectors."},verboseStaleItems:{description:"For health action, include full stale-item arrays in vectorization details."},verboseAuthorEvents:{description:"For health action, include every actionable unknown-author event coordinate."},skipVectors:{description:"For health action, skip vectorization checks for a faster diagnostic run."},skipIntegrity:{description:"For health action, skip item/history file integrity checks for a faster diagnostic run."},skipDrift:{description:"For health action, skip history drift hash checks for a faster diagnostic run."},scanMode:{description:"Select file candidate scan mode for --check-files.",examples:["default","tracked-all","tracked-all-strict"]},includePmInternals:{description:"Include PM storage internals in tracked-all candidate scans."},verboseFileLists:{description:"For validate action, include full file-path lists for --check-files details."},verboseDiagnostics:{description:"For validate action, include full diagnostic ID lists instead of compact summaries."},strictExit:{description:"Apply the selected capability's strict exit policy; health also requires merge drivers."},failOnWarn:{description:"Alias for strictExit in health, validation, history, and managed doctor actions."},fixHints:{description:"For validate action, add a machine-executable fix_hints[] of pm commands to each failing check's details."},autoFix:{description:"For validate action, apply the safe, deterministic subset of fix-hint remediations (field backfills) automatically; combine with dryRun to preview and fixScope to grant gated scopes."},fixScope:{description:"For validate action, grant --auto-fix scopes (metadata, resolution, estimates, lifecycle). Defaults to the safe scopes metadata and resolution; estimates (per-type default estimated_minutes backfill) and lifecycle must be named explicitly.",examples:[["estimates"],["lifecycle"],["metadata","resolution"]]},pruneMissing:{description:"For validate action, remove stale linked-file/doc LINKS whose paths classified as deleted (link removal only \u2014 never touches real files); honors dryRun."},checkHistoryDrift:{description:"Run item/history hash drift checks."},checkCommandReferences:{description:"Run linked-command PM-ID reference checks."},edit:{description:"For comments, notes, and learnings actions, replace the annotation at this 1-based index with supplied replacement text."},delete:{description:"For comments, notes, and learnings actions, delete the annotation at this 1-based index."},stdin:{description:"For comments, notes, and learnings actions, read annotation text from piped stdin (supports multiline markdown)."},file:{description:"CLI-only path to an input file for commands that read payload text; tool actions exclude host file access.",examples:["notes/comment.md"]},preserveSourceIds:{description:"Preserve explicit source IDs during Beads imports instead of normalizing to tracker prefix.",examples:[!0]},appendStable:{description:"When true for files action, preserve existing linked-file order and append new links without full-array resorting."},discover:{description:"When true for files action, use `pm files discover <id>` to scan item text for referenced file paths."},apply:{description:"Persist changes instead of returning a dry-run preview: for files discovery, add the missing discovered file links; for schema add-type --infer, register the inferred custom item types."},discoveryNote:{description:"Note attached to file links added by files discovery.",examples:["discovered from item text"]},addNote:{description:"Note attached to every link added by add/addGlob in this call (per-entry embedded note= wins; requires add or addGlob). Maps to the CLI --note flag on pm files/pm docs.",examples:["command wiring"]},noteConflict:{description:"How add/addGlob treat a link that already has a different note: refuse (default, keeps the stored note), replace, or append (requires add or addGlob). Maps to the CLI --note-conflict flag on pm files/pm docs.",examples:["append"]},list:{description:"When true, list command-specific entries without mutating state (for example linked paths for files/docs or topics for guide).",examples:[!0]},stream:{description:"Stream selector: test-runs logs accepts stdout|stderr|both; activity accepts boolean/rows|ndjson|jsonl for line-delimited output.",examples:["stderr","stdout","both","rows","ndjson","jsonl",!0]},tail:{description:"Number of lines to tail for background run logs.",examples:[100]},query:{description:"Search query text for search action."},for:{description:"Named context intent projection declared for the selected read action.",examples:["orient","inspect","triage","execute","discover"]},keywords:{description:"Alias for query in search action payloads."},includeLinked:{description:"Include readable linked docs/files/tests content in keyword and hybrid lexical scoring."},titleExact:{description:"For search action, require exact normalized title match for the full query string."},phraseExact:{description:"For search action, require exact normalized query phrase match in item text fields."},highlight:{description:"For search action, emit per-field matched-text snippets (wrapped in \xAB\u2026\xBB) on each hit. Off by default."},includeBody:{description:"When true for list-family actions, include item body text in projected rows."},noTruncate:{description:"When true for list-family actions, return every matched row, overriding any limit (surfaces total when rows were dropped)."},strictRead:{description:"When true for list-family actions, fail if any source item or item directory cannot be read."},compact:{description:"Render compact projection output for search and list-family actions."},raw:{description:"For activity, restore the compact per-event stream instead of the default item digest."},brief:{description:"Emit compact low-token output for commands that support terse projections or health details.",examples:[!0]},full:{description:"Enable command-specific full/detail output mode when supported, such as deep item reads for get or full payload mode for search/history."},includeEmpty:{description:"For stats, restore zero-count registered type and lifecycle-status buckets."},fields:{description:"Comma-separated projection fields for get, search, list-family, context, or package listing outputs. Valid field names are command-specific (e.g. score/matched_fields apply to search; context projects focus-row fields such as priority/deadline/completion_pct; package explore/manage rows take package keys such as name/version/activation_status/update_available, and package catalog rows take alias/installed/install_command).",examples:["id,title,status,parent,type","id,title,score,matched_fields","id,title,priority,deadline","name,version,activation_status"]},groupBy:{description:"Comma-separated aggregate grouping fields (supported: parent,type,priority,status,assignee,tags,sprint,release).",examples:["parent,type","type,status","priority,assignee","tags","sprint,release"]},setMode:{description:"Aggregate array dimensions by distinct element (default), or by the complete normalized tuple. Empty sets retain a null group.",examples:["element","tuple"]},count:{description:"Enable grouped count output for aggregate action."},completion:{description:"For aggregate action, add open/in_progress/closed/other counts and completion_pct per group."},sum:{description:"Numeric field to sum per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},avg:{description:"Numeric field to average per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},tree:{description:"When true for list/get actions, render recursive parent/child tree ordering."},treeDepth:{description:"Maximum recursion depth for tree output (0 keeps root rows only).",examples:[0,1,"2"]},includeUnparented:{description:"Include unparented rows when aggregate grouping includes parent."},maxDepth:{description:"Maximum dependency traversal depth for deps action (0 keeps only the root node).",examples:[0,1,"2"]},nodeLimit:{description:"Maximum related nodes returned by deps --format context.",examples:[10,"20"]},edgeLimit:{description:"Maximum related edges returned by deps --format context.",examples:[20,"40"]},tokenBudget:{description:"Maximum estimated output tokens for the command output.",examples:[600,"1200"]},cursor:{description:"Opaque continuation cursor returned by deps --format context."},direction:{description:'Graph-context traversal direction for deps action ("outgoing", "incoming", or "both").',examples:["both","incoming"]},kind:{description:"Registered relationship kinds narrowing deps --format context traversal (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},after:{description:"Opaque action-specific continuation cursor returned by the preceding bounded query.",examples:["pm-x1y2"]},maxPaths:{description:"Maximum enumerated paths for graph paths queries.",examples:[5,"10"]},sample:{description:"Maximum evidence sample entries per graph audit finding.",examples:[10,"25"]},exemptIsolate:{description:"Item ids the graph audit treats as explicitly valid isolates (string, comma-separated, or array).",examples:["pm-x1y2",["pm-x1y2","pm-a3b4"]]},exemptIsolateType:{description:"Item types whose active isolates the graph audit treats as policy-valid (string, comma-separated, or array).",examples:["Reminder",["Reminder","Event"]]},saveBaseline:{description:"When true, persist the graph audit census as the change-since-baseline comparison point (audit only)."},rebuild:{description:"When true, rebuild and warm the durable graph index (graph index only)."},collapse:{description:'Dependency tree collapse mode for deps action ("none" or "repeated").',examples:["none","repeated"]},summary:{description:"When true, return the command's compact summary projection (deps counts, health rollup, or contracts command intents)."},shell:{description:"Shell target for completion generation.",examples:["bash"]},eagerTags:{description:"When true for completion, eagerly embed current tracker tags into generated scripts (legacy mode)."},contractAction:{description:"Filter contracts schema to one tool action.",examples:["create","update"]},command:{description:"Scope contracts output to one CLI command name; action/schema surfaces narrow by default.",examples:["create","search","list"]},schemaOnly:{description:"When true, contracts action returns schema-focused payloads (mutually exclusive with flagsOnly/availabilityOnly)."},flagsOnly:{description:"When true, contracts action returns only command flag surface payloads (mutually exclusive projection mode)."},availabilityOnly:{description:"When true, contracts action returns only action availability payloads (mutually exclusive projection mode)."},runtimeOnly:{description:"When true, contracts action only includes actions invocable in the current runtime."},activeOnly:{description:"Alias for runtimeOnly in contracts action payloads."},depth:{description:"Context depth level controlling how many sections are included (brief=focus+agenda, standard=+hierarchy/activity/progress/workload, deep=all sections, full=every section with no per-section row cap).",examples:["brief","standard","deep","full"]},section:{description:"Repeatable section selector for context; overrides --depth when provided.",examples:[["hierarchy","activity"],["blockers","files","staleness"]]},activityLimit:{description:"Maximum number of recent activity entries to include in context output.",examples:[5,10,"20"]},staleThreshold:{description:"Staleness cutoff in days for context staleness section (e.g. 7 or 7d).",examples:["7","14d","30"]}},AI={health:{strictExit:{description:"Return non-zero for a failing health verdict; also require merge drivers."}},validate:{strictExit:{description:"Return non-zero when validation reports warnings."}},"extension-doctor":{strictExit:{description:"Return non-zero when extension diagnostics report warnings or a non-ok summary."}},"package-doctor":{strictExit:{description:"Return non-zero when package diagnostics report warnings or a non-ok summary."}},history:{strictExit:{description:"Return non-zero for history verification failures when verify is enabled."},order:{description:"Display direction after selecting the latest matching entries; defaults to newest_first for compact/provenance and oldest_first for full history.",examples:["oldest_first","newest_first"]}},extension:{strictExit:{description:"For doctor operations, return non-zero on warnings or a non-ok diagnostic summary."}},package:{strictExit:{description:"For doctor operations, return non-zero on warnings or a non-ok diagnostic summary."}},assurance:{subcommand:{description:"Assurance operation: list, show, put, remove, run, verdicts, presets, apply, derive, promote, risk, or lineages.",examples:["list","run","risk","lineages"]},kind:{description:"Assurance declaration kind for registry operations: measurement, assertion, or gate.",examples:["measurement","assertion","gate"]},id:{description:"Stable assurance declaration id or gate id, depending on subcommand.",examples:["active-issues","release-readiness"]},limit:{description:"Maximum number of newest assurance verdicts returned.",examples:[10,25]},preset:{description:"Built-in assurance project shape to preview or apply.",examples:["software-delivery","agent-evaluation"]}},update:{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},"update-many":{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},stats:{since:{description:"Inclusive ISO 8601 timestamp or negative duration lower bound for provenance and fleet analytics.",examples:["2026-08-01T00:00:00.000Z","-30d"]}},events:{verify:{description:"Verify complete selected authoritative chains before filtering and pagination."},since:{description:"Durable event cursor returned as next_cursor, or an inclusive event timestamp.",examples:["eyJmaW5nZXJwcmludCI6Ii4uLiJ9","2026-08-01T00:00:00.000Z"]},type:{description:"Mutation event type filter, supplied once or as a list.",examples:["create",["create","update"]]},author:{description:"Mutation author filter, supplied once or as a list.",examples:["agent-a",["agent-a","agent-b"]]},item:{description:"Tracked item id filter, supplied once or as a list.",examples:["pm-a1b2",["pm-a1b2","pm-c3d4"]]},limit:{description:"Maximum mutation events returned, from 0 through 1000.",examples:[0,100]},cursorMode:{description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event.",examples:["batch","row"]}},remind:{at:{description:"Reminder time as an ISO 8601 timestamp or supported relative expression.",examples:["2026-08-02T09:00:00+02:00","tomorrow 09:00"]}},deps:{tokenBudget:{description:"Maximum estimated output tokens for deps --format context.",examples:[600,"1200"]}},comments:{full:{description:"Return the complete post-mutation comment history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a comment only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},notes:{full:{description:"Return the complete post-mutation note history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a note only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for structured note event filtering.",examples:["2026-01-01T00:00:00.000Z"]}},learnings:{full:{description:"Return the complete post-mutation learning history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a learning only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},next:{tag:{description:"Only recommend items carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the recommendation context.",examples:[600,"1200"]}},claim:{tag:{description:"When claiming the next item, only consider work carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the next-item context returned with the claim.",examples:[600,"1200"]}},close:{text:{description:"Backward-compatible alias for the item close reason when reason is not provided."}},"close-task":{text:{description:"Close reason used before releasing the item's active assignment."}},schema:{definition:{description:"Workflow policy declaration for policy-put, or proposed item fields for policy-check."},policy:{description:"Declared approval rule id for policy-approve."},name:{description:"Custom item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse.",examples:["Spike","review","component"]}},profile:{name:{description:"Profile name for show/apply/lint. Built-in profiles are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too.",examples:["agile","ops","research"]}},graph:{subcommand:{description:"Graph query selector: ancestors|descendants|predecessors|successors|paths|impact|analyze|audit|communities|redundancy|dominators|slack|centrality|articulation|plan|index. Traversals, paths, impact, and dominators require id; paths also requires target; slack reports critical-path float, centrality ranks betweenness/closeness/degree, articulation reports cut points and bridges; plan derives dry-run remediation proposals from the governance audit; index reports, rebuilds, or clears the durable cross-process graph index.",examples:["successors","audit"]},clear:{description:"When true, delete the durable graph index (graph index only)."},id:{description:"Root item id for traversal, paths, impact, and dominators graph queries.",examples:["pm-x1y2"]},target:{description:"Target item id for graph paths queries.",examples:["pm-a3b4"]},direction:{description:'Edge orientation for graph paths/impact/dominators queries ("outgoing", "incoming", or "both"; default "both").',examples:["incoming"]},kind:{description:"Registered relationship kinds narrowing the graph query (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},maxDepth:{description:"Maximum graph traversal depth (non-negative integer).",examples:[2,"4"]},after:{description:"Resume a hierarchy/ordering graph traversal after this previously returned node id.",examples:["pm-x1y2"]},limit:{description:"Maximum returned rows per bounded graph collection (traversal ids, impact rows, analyze/communities samples, redundancy rows, dominator bottlenecks).",examples:[10,"25"]},summary:{description:"When true, return counts-first graph envelopes without row collections."}}};Nr();Go();var LX={...xI,"history-attest":{verify:{type:"object",additionalProperties:!0},output:{not:{}}}},Ku={...hc,pause:{type:"boolean"},handoff:{type:"string"},releaseAssignment:{type:"boolean"},hashAlgorithm:{type:"string",enum:["sha256","sha512"]}},Yu={...SI,pause:{description:"Return work to its configured open status before releasing ownership."},handoff:{description:"Release into a configured non-terminal queue with a required evidence message."},releaseAssignment:{description:"Release assignment after recording closure evidence."},hashAlgorithm:{description:"Digest for detached history bundles; defaults to sha256."}},MX=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],$X=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],DX=new Set(["action","cwd","options",...Object.keys(Ku).filter(e=>e!=="severity")]);var FX={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],claim:["fullChangedFields","idOnly"],release:["fullChangedFields","idOnly"],"start-task":["fullChangedFields","idOnly"],"pause-task":["fullChangedFields","idOnly"],"close-task":["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},PI=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],ETe=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(tn.filter(e=>e==="upgrade"||e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function Kt(e){return as(e)}var jX=Kt([...mc.map(e=>e.param),...ys.map(e=>e.param)]),LI=Kt([..._c.map(e=>e.param),...ys.map(e=>e.param),"force"]),UX=Kt([...Iy.map(e=>e.param),...LI.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),zX=Kt([...Ny.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),TI=Kt([...Ly.map(e=>e.param),"past","section"]),HX=Kt([...Py.map(e=>e.param),"stream"]),Fy=Kt([...Ty.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),ws=Fy.filter(e=>e!=="all"&&e!=="status"),Jr=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],qX=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],BX=Kt([...Oy.map(e=>e.param),"count","completion","includeUnparented"]),GX=Kt(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...Cy.map(e=>e.param)]),OI=Kt(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","includeGates","includeContainers","tokenBudget","explainRanking"]),$t=["author","message","force"],MI=["releaseAssignment","text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],gc=["author","assignee","message","force"],WX=["dryRun","target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","offline","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn","fields"];function CI(e){return{[`${e}-init`]:{required:["target"],optional:["scope","capability",...e==="package"?["declarative"]:[]]},[`${e}-install`]:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},[`${e}-uninstall`]:{required:["target"],optional:["scope"]},[`${e}-explore`]:{optional:["scope","fields"]},[`${e}-manage`]:{optional:["scope","runtimeProbe","fixManagedState","offline","fields"]},[`${e}-describe`]:{optional:["target","scope","markdown","output"]},[`${e}-reload`]:{optional:["scope","watch"]},[`${e}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${e}-catalog`]:{optional:["scope","fields"]},[`${e}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${e}-adopt-all`]:{optional:["scope"]},[`${e}-activate`]:{required:["target"],optional:["scope"]},[`${e}-deactivate`]:{required:["target"],optional:["scope"]},[e]:{optional:WX,dependentAnyOfRequired:[{property:"dryRun",value:!0,anyOfRequired:[["install","target"],["install","github"]]}],mutuallyExclusiveWhen:[[{property:"dryRun",schema:{const:!0}},{property:"install",schema:{const:!1}}]]}}}var RI={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},II={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},Ju={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...CI("extension"),...CI("package"),"package-upgrade":II,install:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},upgrade:II,create:{required:["title","description","type","status","priority","message"],optional:jX},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:Fy,mutuallyExclusiveWhen:Jr},"list-all":{optional:Fy,mutuallyExclusiveWhen:Jr},"list-draft":{optional:ws,mutuallyExclusiveWhen:Jr},"list-open":{optional:ws,mutuallyExclusiveWhen:Jr},"list-in-progress":{optional:ws,mutuallyExclusiveWhen:Jr},"list-blocked":{optional:ws,mutuallyExclusiveWhen:Jr},"list-closed":{optional:ws,mutuallyExclusiveWhen:Jr},"list-canceled":{optional:ws,mutuallyExclusiveWhen:Jr},aggregate:{optional:BX},guide:{optional:["list","format","depth"]},context:{optional:TI},ctx:{optional:TI},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:GX,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["verify","since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","preCommitHook","stage","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:RI,event:RI,remind:{required:["title"],optional:["at","text","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...OI,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","order","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-attest":{optional:["verify","output","hashAlgorithm"],mutuallyExclusive:[["verify","hashAlgorithm"]]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...$t],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance","salvageTail","appendOnly",...$t],oneOfRequired:[["id"],["all"]],mutuallyExclusiveWhen:[[{property:"appendOnly",schema:{const:!0}},{property:"salvageTail",schema:{const:!0}}],[{property:"appendOnly",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"all",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...$t]},schema:{mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"policy-mode"}},{property:"name",schema:{not:{enum:["advise","refuse"]}}}]],required:["subcommand"],optional:["definition","policy","message","name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"policy-put",required:["definition"]},{property:"subcommand",value:"policy-remove",required:["name"]},{property:"subcommand",value:"policy-mode",required:["name"]},{property:"subcommand",value:"policy-check",required:["name"]},{property:"subcommand",value:"policy-approve",required:["name","policy"]},{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","inheritFocus","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...PI,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...$t]},activity:{optional:HX},restore:{required:["id","target"],optional:$t},update:{required:["id"],optional:LI,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:UX,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...MI,...$t]},"close-many":{optional:zX},delete:{required:["id"],optional:["dryRun",...$t]},append:{required:["id","body"],optional:$t},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent","expectAt",...$t],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent","expectAt",...$t],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent","expectAt",...$t],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","noteConflict","discover","apply","discoveryNote","appendStable","validatePaths","full","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...$t],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]},{property:"noteConflict",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","noteConflict","list","validatePaths","full",...$t],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]},{property:"noteConflict",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["list","add","addJson","remove","removeIndex","update","updateIndex","setJson","run","match","onlyIndex","onlyLast","full","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","fullOutput","autoPmContext","measure","metricBelow","metricDiff",...$t],dependentAnyOfRequired:[{property:"update",anyOfRequired:[["setJson"]]},{property:"updateIndex",anyOfRequired:[["setJson"]]},{property:"setJson",anyOfRequired:[["update"],["updateIndex"]]}],mutuallyExclusive:[["update","updateIndex"],["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","fullOutput","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit","exhaustive"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkCompleteness","checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"risk",required:["definition"]},{property:"subcommand",value:"lineages",required:["definition"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}],mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"risk"}},{property:"definition",schema:{not:{required:["policy","change"]}}}],[{property:"subcommand",schema:{const:"lineages"}},{property:"definition",schema:{anyOf:[{required:["change"]},{not:{required:["policy"]}}]}}]]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:qX},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["start","id","next","ifAvailable","takeoverStale","maxAttempts","includeDecisions",...OI,...gc],oneOfRequired:[["id"],["next"]],mutuallyExclusiveWhen:[[{property:"start",schema:{const:!0}},{property:"ifAvailable",schema:{const:!0}},{property:"id",schema:{type:"string"}}],[{property:"takeoverStale",schema:{const:!0}},{property:"force",schema:{const:!0}}],[{property:"takeoverStale",schema:{const:!0}},{property:"next",schema:{const:!0}}]]},release:{required:["id"],optional:["pause","handoff",...gc],dependentAnyOfRequired:[{property:"handoff",anyOfRequired:[["message"]]}],mutuallyExclusiveWhen:[[{property:"pause",schema:{const:!0}},{property:"handoff",schema:{type:"string"}}]]},"start-task":{required:["id"],optional:[...gc,"takeoverStale"],mutuallyExclusiveWhen:[[{property:"takeoverStale",schema:{const:!0}},{property:"force",schema:{const:!0}}]]},"pause-task":{required:["id"],optional:gc},"close-task":{required:["id"],optional:["text","validateClose",...gc]},"item-reopen":{required:["id","reason"],optional:["status","expectedResult","author","message","force"]}},jy=Object.freeze(Object.fromEntries(tn.map(e=>[e,Ju[e]])));function $I(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function VX(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=Yu[e];return{...n,description:r?.description??$I(e),...r?.examples?{examples:r.examples}:{}}}function KX(e,t){if(e==="history-attest"&&t==="verify")return{description:"Compare all retained history streams with a detached JSON proof object. Server-local proof paths are not accepted over MCP."};if(e==="history-attest"&&t==="output")return{description:"Local CLI/SDK only. MCP rejects this field; save the returned JSON bundle on the client."};if(e==="claim"&&t==="start")return{description:"Move the claimed item to its configured in-progress status; with next, the selected item is claimed and started in one locked write."};if((e==="list"||e.startsWith("list-"))&&t==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(e==="plan"&&Object.prototype.hasOwnProperty.call(Dy,t))return Dy[t];let n=AI[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:Yu[t]}function JX(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},i=KX(e,t);return{...r,description:i?.description??$I(t),...i?.examples?{examples:i.examples}:{}}}function YX(e,t){if(e==="claim"&&t==="start")return{type:"boolean"};let n=LX[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call($y,t)?$y[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:t==="pause"||t==="handoff"||t==="releaseAssignment"||t==="hashAlgorithm"?Ku[t]:hc[t]}function XX(e,t){let n={action:{const:e,description:Yu.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let i=YX(e,r);i&&(n[r]=JX(e,r,i))}return n}function ZX(e,t){let n=t.flat();return t.map(r=>{let i=n.filter(o=>!r.includes(o));return{required:[...r],...i.length>0?{not:{anyOf:i.map(o=>({required:[o]}))}}:{},...e==="history-repair"&&r.includes("all")?{properties:{all:{const:!0}}}:e==="claim"&&r.includes("next")?{properties:{next:{const:!0}}}:{}}})}function NI(e,t){return{...t===void 0?{}:{properties:{[e]:{const:t}}},required:[e]}}function QX(e){let t=[];if(e.conditionalRequired&&e.conditionalRequired.length>0)for(let n of e.conditionalRequired)t.push({if:NI(n.property,n.value),then:{required:n.required}});if(e.dependentAnyOfRequired&&e.dependentAnyOfRequired.length>0)for(let n of e.dependentAnyOfRequired)t.push({if:NI(n.property,n.value),then:{anyOf:n.anyOfRequired.map(r=>({required:[...r]}))}});if(e.mutuallyExclusive&&e.mutuallyExclusive.length>0)for(let n of e.mutuallyExclusive)t.push({not:{required:Kt(n)}});if(e.mutuallyExclusiveWhen&&e.mutuallyExclusiveWhen.length>0)for(let n of e.mutuallyExclusiveWhen)t.push({not:{allOf:n.map(r=>({properties:{[r.property]:r.schema},required:[r.property]}))}});return t}function DI(e){if(!Object.prototype.hasOwnProperty.call(Ju,e))return;let t=Ju[e],n=FX[e]??[];return Kt(["action",...MX,...Bo(e)!==void 0?$X:[],...n,...Zp.has(e)?["expectHash"]:[],...t.required??[],...t.optional??[]])}function e6(e){let t=Ju[e],n=Kt(t.required??[]),r=DI(e),i={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:XX(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(i.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(i.oneOf=ZX(e,t.oneOfRequired));let o=QX(t);return o.length>0&&(i.allOf=o),i}function FI(e){let t,n=()=>t??=e();return new Proxy({},{get:(r,i)=>n()[i],has:(r,i)=>i in n(),ownKeys:()=>Reflect.ownKeys(n()),getOwnPropertyDescriptor:(r,i)=>{let o=Reflect.getOwnPropertyDescriptor(n(),i);return o&&(o.configurable=!0),o}})}var Uy="4.28.1",jI=Uy.split(".")[0],UI="1.12.0",t6=FI(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${jI}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":Uy,type:"object",oneOf:tn.map(e=>e6(e))}));function n6(e,t){let n=VX(e,t);if(typeof n.type=="string")return n;let i=(Array.isArray(n.anyOf)?n.anyOf:[]).find(a=>typeof a.type=="string");if(i){let{anyOf:a,...c}=n;return{...i,...c}}let{anyOf:o,...s}=n;return{...s,type:"string"}}function r6(){let e={action:{type:"string",description:Yu.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(let t of Object.keys(Ku).sort())e[t]=n6(t,Ku[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":UI,type:"object",additionalProperties:!1,required:["action"],properties:e}}var i6=FI(r6);var o6=["close_reason","close-reason"],zI=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],HI=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],s6=[...zI,...HI],qI=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}],BI=[...s6,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...qI],ITe=[...zI,{canonical:"close-reason",aliases:o6,optionKey:"closeReason",metadataKey:"close_reason"},...HI,...qI];var NTe=(()=>{let e=new Map;for(let t of BI)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),PTe=BI.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");On();import{Option as qOe}from"commander";On();Nr();Nr();Go();var ZTe=new Set([...mx,..._x]);Td();var h6=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"]),gCe=new Set([...h6].filter(e=>e!=="file"));var yCe=new Map(Yi.flatMap(({target:e,keys:t})=>t.map(n=>[n,e])));var g6="2026-07-15T06:22:12.276Z",y6=Date.parse(g6),w6=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],WI=e=>typeof e=="string"?e:"",v6=e=>{let t=e??{},n=WI(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(WI(t.ts))>=y6);return w6[r][i]};function b6(e,t,n=20,r=new Set,i=!1){let o=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[f,p]of t.split(/\r?\n/).entries()){let m;try{m=JSON.parse(p)}catch{continue}l+=1;let g=v6(m);if(g!=="attributed"){if(d+=1,g==="actionable_unknown"&&r.has(`${e}:${f+1}`)){u+=1;continue}a[g]+=1,i&&g==="actionable_unknown"&&s.push({item_id:e,line:f+1}),o.length<c&&o.push({item_id:e,line:f+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}}function E6(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let o=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.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 Xu=async(e,t=20,n=!1)=>{let r=Hy.join(e,"history"),i;try{i=(await zy.readdir(r)).filter(v=>v.endsWith(".jsonl")).sort((v,E)=>v.localeCompare(E))}catch{i=[]}let o=new Set,s=[],a=[],c=0,l=0,d=0,u=0,f=0,p=0,m="_workspace.jsonl",g=new Set;if(i.includes(m))try{g=E6(await zy.readFile(Hy.join(r,m),"utf8"))}catch{g=new Set}for(let v of i){let E;try{E=await zy.readFile(Hy.join(r,v),"utf8")}catch{continue}let T=v.slice(0,-6),R=b6(T,E,t-s.length,g,n);c+=1,l+=R.checked_events,d+=R.unknown_event_count,u+=R.legacy_unknown_event_count,f+=R.actionable_unknown_event_count,p+=R.acknowledged_actionable_event_count,R.unknown_event_count>0&&o.add(T),s.push(...R.samples),n&&a.push(...R.actionable_events)}let y=u+f;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:f,acknowledged_actionable_event_count:p,affected_item_ids:[...o].sort((v,E)=>v.localeCompare(E)),samples:s,samples_truncated:y>s.length,...n?{actionable_events:a}:{}}};Z();Dm();Ys();nr();P();en();k();x();Pr();J();q();me();or();yn();We();P();Lt();Qe();Mn();Yt();at();Vn();Vn();var $Ce=new Set(co),k6=new Set(fl.map(e=>Me(e.id)).filter(e=>e.length>0));Rs();at();De();k();x();J();Z();q();me();Rs();k();x();ho();at();ip();function KI(e){return e.trim().toLowerCase().replace(/^-+/u,"")}function JI(e){let t=KI(e),n=Sv({key:t,cli_flag:t,cli_aliases:[]});return[...new Set([...n,sp(t)])]}var S6=new Set(ze.filter(e=>!Qc.has(e))),YI={flag:"--help",short:"-h"},VI=new Map;function A6(e){let t=VI.get(e);if(t===void 0){let n=new Map,r=new Map;for(let i of[...Nu(e),...yg,YI]){for(let o of[i.flag,...i.aliases??[]].flatMap(JI))n.has(o)||n.set(o,i.flag);i.short!==void 0&&!r.has(i.short)&&r.set(i.short,i.flag)}t={long:n,short:r},VI.set(e,t)}return t}function T6(e,t){return $s(e)?t.short.get(e.trim()):JI(e).map(n=>t.long.get(n)).find(n=>n!==void 0)}function O6(e){let t=[];for(let n of e){let r=s=>$s(s)?s.trim():KI(s),i=[...new Set([n.cli_flag,...n.cli_aliases].map(r))],o=r(n.key);for(let s of n.commands)t.push(...C6(n.key,i,i.includes(o)?void 0:o,s.replaceAll("_","-")))}return t.sort((n,r)=>n.field.localeCompare(r.field)||n.command.localeCompare(r.command)||n.option.localeCompare(r.option))}function C6(e,t,n,r){let i=A6(r),o=new Map;for(let s of n===void 0?t:[...t,n]){if(S6.has(e)&&s.replaceAll("-","_")===e)continue;let a=T6(s,i);a===void 0||o.has(a)||s===n&&a===YI.flag||o.set(a,{field:e,command:r,field_flag:$s(s)?s:`--${s.replaceAll("_","-")}`,option:a})}return[...o.values()]}function R6(e){return e.flatMap(t=>[...new Set([t.cli_flag,...t.cli_aliases])].flatMap(n=>{let r=Ev(n);return r===void 0?[]:[{field:t.key,spelling:n,reason:r}]}))}function XI(e,t){let n=_o(e).definitions,r=O6(n),i=R6(n),o=i.length===0?{details:{},warnings:[]}:{details:{schema_field_flag_invalid_count:i.length,schema_field_flag_invalid:i.slice(0,t),schema_field_flag_invalid_truncated:i.length>t,schema_field_flag_invalid_fix_hint:"Re-register the field with one flag and one spelling per alias: pm schema add-field <key> --cli-flag <flag> --alias <alias>. A short alias is one dash and one character. Edit a field defined inline in settings.json there."},warnings:[`validate_schema_field_flag_invalid:${i.length}`]};return r.length===0?o:{details:{...o.details,schema_field_option_collision_count:r.length,schema_field_option_collisions:r.slice(0,t),schema_field_option_collisions_truncated:r.length>t,schema_field_option_collision_fix_hint:"Rename a file-backed field without losing item values: pm schema rename-field <key> --to <new-key>. For a colliding flag, alias or command list, re-register the same key: pm schema add-field <key> --cli-flag <flag> --commands <commands>. Edit a field defined inline in settings.json there."},warnings:[...o.warnings,`validate_schema_field_option_collision:${r.length}`]}}yn();q();me();We();x();k();Lt();De();Z();hi();hi();hi();var yc={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Zu={type:"array",minItems:1,maxItems:To,items:yc},ZI={...Zu,items:{...yc,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},QCe={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Zu])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:yc,id:yc}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:ZI}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Zu}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:ZI,authors:Zu}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:To,items:{type:"array",minItems:2,maxItems:2,items:yc}}}}]}}};hi();async function QI(e,t,n,r){let i=await Ua(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:eN(i,t,n,r)}function I6(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function eN(e,t,n=5,r=!1){let i=[],o=new Map,s=e.policies.filter(y=>y.rule.kind==="require_fields"),a=s.filter(y=>y.subject?.operations===void 0),c=new Set,l=0,d=0,u=0,f=0,p=0,m=Sb(e);for(let y of t){let v=m({operation:"",author:"",before:y,after:y,completeness_only:!0});l+=+(v.decisions.length>0),d+=v.decisions.length,v.decisions.forEach(R=>c.add(R.policy_id));let E=v.decisions.filter(R=>!R.satisfied);if(E.length===0)continue;f+=1;let T=o.get(y.type)??{items:0,violations:0,missing_fields:0};T.items+=1;for(let R of E)u+=1,T.violations+=1,T.missing_fields+=R.missing_fields.length,R.effect==="refuse"&&(p+=1),i.length<n&&i.push({id:y.id,type:y.type,status:y.status,decision:R});o.set(y.type,T)}let g=r||p>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:g,ok:g==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:s.length,state_requirement_count:a.length,applicable_requirement_count:c.size,requirement_application_count:d,governed_items:l,ungoverned_items:t.length-l,contract_status:I6(s.length,t.length,l),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:f,violation_count:u,refused_violations:p,missing_by_type:Object.fromEntries(o),violations:i,violations_truncated:i.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}yn();P();Lt();De();Rs();at();Vn();Z();q();me();k();x();We();xe();Lt();Wn();yn();Z();fn();Xe();tt();De();k();x();q();me();Cc();function nN(e,t){let n=be(e),r=e.length>0?e[e.length-1].after_hash:H_(),i=t===void 0||n.item_hash_version===void 0?void 0:Vo(t,n.item_hash_version,Re(e.at(-1)?.hash_algorithm)),o=t===void 0?void 0:i===void 0?li(t):i[Math.max(0,i.indexOf(r))],s=o===void 0?void 0:o===r,a=[...n.errors];return s===!1&&a.push("verify_failed:current_item_hash_mismatch"),{ok:a.length===0,entries:e.length,errors:a,latest_after_hash:e.length>0?e[e.length-1].after_hash:void 0,current_item_hash:o,current_matches_latest:s}}Qe();P();J();k();x();import{AsyncLocalStorage as L6}from"node:async_hooks";var BRe=new L6;var mNe=[...Oo,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"];P();An();k();x();nr();function qy(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}P();k();x();J();Ys();import z6 from"node:fs/promises";import H6 from"node:path";var q6=".managed-extensions.json",By=1;function Qu(e){return H6.join(e,q6)}function B6(){return{version:By,updated_at:z(),entries:[]}}function rN(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function Dt(e){return typeof e=="string"?e:void 0}var G6=/^(?:npm_registry|github_remote)_lookup_timed_out$/u;function W6(e,t){let n=Dt(t);return n===void 0||e.kind!=="github"||n.trim().length===0||/^[a-z0-9_]+$/u.test(n.trim())?n:"github_remote_lookup_failed"}function iN(e){return typeof e=="string"&&G6.test(e.trim())}function V6(e,t){return iN(e)&&typeof t=="number"&&Number.isSafeInteger(t)&&t>0?{update_check_timeout_ms:t}:{}}function K6(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function J6(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:Dt(t.name),package:Dt(t.package),version:Dt(t.version),repository:Dt(t.repository),owner:Dt(t.owner),repo:Dt(t.repo),ref:Dt(t.ref),subpath:Dt(t.subpath),commit:Dt(t.commit)}}function Y6(e){if(typeof e!="object"||e===null)return null;let t=e;if(!K6(t))return null;let n=J6(t.source);if(!n)return null;let r=No(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:qy(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Dt(t.last_update_check_at),last_update_remote_commit:Dt(t.last_update_remote_commit),last_update_remote_version:Dt(t.last_update_remote_version),update_available:iN(t.update_error)?null:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:W6(n,t.update_error),...V6(t.update_error,t.update_check_timeout_ms)}}function oN(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==By||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=Y6(r);i&&n.push(i)}return{version:By,updated_at:Dt(t.updated_at)??z(),entries:rN(n)}}async function wc(e){let t=Qu(e),n=B6();try{let r=await z6.readFile(t,"utf8"),i=JSON.parse(r),o=oN(i);if(!o)throw new _(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:o,warnings:[]}}catch(r){if(r instanceof _)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&D(r))return{path:t,state:n,warnings:[]};throw new _(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}import{execFile as e4}from"node:child_process";import{promisify as t4}from"node:util";import i0e from"npm-package-arg";import{extract as s0e,Parser as a0e}from"tar";P();An();k();x();var FNe=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});en();P();An();k();x();en();P();k();x();nr();q();var _0e=t4(e4);var h0e={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024};P();k();x();var k0e=new Set([...Co.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Xp).map(e=>e.toLowerCase()),"scaffold"]);Z();nr();k();x();var aN=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function i4(e){return aN.has(a4(e))}function sN(e){return e==="project"||e==="global"}function o4(e){let t=e.split(":"),n=t[0];if(!n||!aN.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),o=t.at(-2),s=t.at(-1)?.trim();return!sN(r)||!sN(o)||!i||!s?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:o,name:s}}}function s4(e){let t=new Set;for(let n of e){let r=o4(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function cN(e,t){let n=e.filter(i4);if(n.length===0)return null;let r=s4(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function a4(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Gy(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let o=im(r);return o?[o]:om(r)})();for(let o of i){let s=`${o.layer}:${o.name}:${o.capability}`;t.has(s)||(t.add(s),n.push(o))}}return n}function Wy(){return{version:Ic.version,capabilities:[...Ic.capabilities],legacy_aliases:{...Ic.legacy_aliases}}}Vl();An();P();An();k();x();en();J();J();import{AsyncLocalStorage as d4}from"node:async_hooks";import pPe from"npm-package-arg";import rPe from"npm-package-arg";import oPe from"semver";var gPe=new d4;Vc();Qe();P();P();var MPe=64*1024,$Pe=16*1024*1024,DPe=1024*1024,FPe=300*1e3;var jPe=64*1024;P();Z();Lt();me();import p4 from"node:fs/promises";import m4 from"node:path";function _4(e){return m4.join(e,"extension-migrations.json")}function h4(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function g4(e,t){return`${e.layer}:${e.name}:${t}`}async function y4(e){let t=_4(e);if(!await H(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await p4.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function dN(e,t){let n=await y4(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let s=h4(i,o),a=r.get(g4(i,s));a&&(i.definition.status=a.status,a.status==="failed"?i.definition.reason=a.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}An();x();k();P();P();wm();q();import v4 from"node:fs/promises";import b4 from"node:path";function E4(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function k4(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function fN(e){let t=b4.join(e,"manifest.json"),n;try{n=await v4.readFile(t,"utf8")}catch(a){if(ke(a))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw a}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=r,o=ym(i),s=E4(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:o.findings,warnings:o.findings.map(a=>k4(s,a)),remediation:o.findings.map(a=>a.message)}}import fLe from"npm-package-arg";P();Vl();q();P();x();k();or();Lt();me();Pa();We();var T4=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],i$e=T4.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", ");var o$e=ed();or();var pN=25;function O4(e,t,n=[]){let r=["list","--status",e,...n],i=["--assignee-filter","unassigned"],o=["--updated-before",`-${t}h`];return{unowned:re([...r,...i]),idle:re([...r,...o]),stale:re([...r,...i,...o])}}function mN(e,t){let n=e.items.length>pN;return{count:e.count,items:e.items.slice(0,pN),...n?{truncated:!0}:{},sweep:t}}function _N(e,t,n=[]){let r=O4(t.in_progress,e.threshold_hours,n),i=(s,...a)=>`pm ${s} <id>${[...a,...n].map(c=>` ${Tr(c)}`).join("")}`,o=[...e.unowned.count>0?[`in_progress_unowned:${e.unowned.count}`]:[],...e.idle.count>0?[`in_progress_idle:${e.idle.count}`]:[]];return{warnings:o,details:o.length===0?void 0:{threshold_hours:e.threshold_hours,threshold_setting:"mutation_guard.stale_in_progress_hours",unowned:mN(e.unowned,r.unowned),idle:mN(e.idle,r.idle),item_remedies:{claim:i("claim"),take_over_idle:i("claim","--takeover-stale"),return_to_open:i("update","--status",t.open)}},remediation:{stale_in_progress_items:r.stale,in_progress_unowned:r.unowned,in_progress_idle:r.idle}}}or();Sa();Mn();Jn();import{execFile as C4}from"node:child_process";import{realpath as R4}from"node:fs/promises";import hN from"node:path";import{promisify as I4}from"node:util";var N4=I4(C4),P4=32*1024*1024,L4=1e4,M4=["search/eval-queries.json"];function Vy(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}async function $4(e,t=R4){return t(e).catch(()=>hN.resolve(e))}async function ef(e){let t=await Mt(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 $4(e),r=Vy(hN.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=RS.map(o=>`${r}/${Vy(o)}`);try{let{stdout:o}=await N4("git",["ls-files","-z","--",...i.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:P4,windowsHide:!0,timeout:L4}),s=new Set(M4.map(l=>`${r}/${l}`)),a=[...new Set(o.split("\0").filter(l=>l.length>0&&!s.has(Vy(l))))].sort((l,d)=>l.localeCompare(d)),c=i.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>Tr(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}Ky();Mn();import gN from"node:path";import{realpath as U4}from"node:fs/promises";async function yN(e,t){let n=t===null?[]:await tf(t,[gN.relative(t,gN.join(await U4(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function wN(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await $a(e,is(n),{gitWorkspaceRoot:t});if(i.status==="ok")return{audit:i,count:0,warnings:[]};let o=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:o,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${o}`]:[]}}function vN(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}Mn();J();import{createHash as z4}from"node:crypto";import nf from"node:path";var Yy="2026-08-09T16:15:18.000Z",EN=Symbol("pre-durable-disposition-eligible");function _r(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jy(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function bN(e){return _r(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function kN(e,t){if(typeof e!="string")return!1;let n=nf.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!nf.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(nf.posix.basename(n)===`${t}.toon`||nf.posix.basename(n)===`${t}.md`)}function H4(e,t){return typeof e.receipt_id=="string"&&lr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&kN(e.item_path,t)}function xN(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,o=Array.isArray(i)?new Set(i.flatMap(s=>bN(s)?[s.field]:[])):new Set;return Jy(t)&&Jy(n)&&Jy(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(bN)&&o.size===i.length&&t.length===o.size&&t.every(s=>o.has(s))}function q4(e,t){return H4(e,t)&&xN(e)}function B4(e,t){return typeof e.receipt_id=="string"&&lr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&kN(e.item_path,t)&&xN(e)}function Xy(e){return e[EN]===!0}function rf(e,t){if(!_r(e)||!_r(e.context))return[];let n=e.context.merge;return!_r(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!_r(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:q4(r,t),[EN]:B4(r,t),...typeof e.ts=="string"&&Xt(e.ts)?{eventTimestamp:e.ts}:{}}])}function SN(e,t,n){if(!_r(e)||e.op!=="merge_reconcile")return[];if(!_r(e.context)||!_r(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!_r(i)||typeof i.receipt_id!="string"||!lr(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!Xt(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function AN(e,t,n=[]){let r=new Map;for(let s of n){let a=`${s.itemId}\0${s.originalHistoryLine}\0${s.receiptId}\0${s.originalEventTimestamp}`;r.set(a,Math.max(r.get(a)??0,s.auditHistoryLine))}let i=s=>Xy(s)&&s.eventTimestamp!==void 0&&He(s.eventTimestamp,Yy)<0&&(r.get(`${s.itemId}\0${s.line}\0${s.receiptId}\0${s.eventTimestamp}`)??0)>s.line;return{missing:e.filter(s=>!s.legacySummaryAccepted&&!t.has(s.receiptId)&&!i(s)).map(s=>({item_id:s.itemId,history_line:s.line,...lr(s.receiptId)?{receipt_id:s.receiptId}:{receipt_reference_hash:z4("sha256").update(s.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(s=>s.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}x();q();import{lstat as G4}from"node:fs/promises";var Zy="history_drift_chain_mismatch",W4="history_drift_chain_unbridgeable",CN="history_drift_unrepairable_stream",TN="history_drift_hash_mismatch",RN="history_drift_missing_stream",V4=["history_drift_unreadable_stream",CN,"history_drift_version_skew","history_drift_merge_receipt"],K4=new Set([Zy,RN]);function of(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function J4(e,t){return e instanceof _?typeof e.context.reason=="string"?e.context.reason:e.code??t:t}async function ON(e,t,n){try{await vn(e,{appendOnly:t,dryRun:!0},n);return}catch(r){return J4(r,t?"append_only_preview_failed":"rewrite_preview_failed")}}async function Y4(e,t){let n=[];for(let r of of(e.check.details.missing_streams)){let[i]=await Promise.allSettled([G4(Ae(t,r))]);i.status==="fulfilled"&&i.value.isSymbolicLink()&&n.push({id:r,reason:"stream_not_regular_file",rewrite_refusal:"stream_not_regular_file"})}return n}async function IN(e,t,n){let r=[],i=new Set(of(e.check.details.version_skews));for(let o of of(e.check.details.chain_mismatches)){if(i.has(o))continue;let s=await ON(o,!0,t);if(s===void 0)continue;let a=await ON(o,!1,t);r.push({id:o,reason:s,...a===void 0?{}:{rewrite_refusal:a}})}return[...r,...await Y4(e,n)]}function X4(e,t,n){for(let r of[Zy,RN]){if(!e.startsWith(`${r}:`))continue;let i=e.slice(r.length+1),o=t.get(i);return o===null?[]:[o===void 0?e:`${o}:${i}`]}return e.startsWith(`${TN}:`)?n.has(e.slice(TN.length+1))?[]:[e]:[e]}function NN(e,t){let n=of(e.check.details.version_skews),r=new Map([...n.map(o=>[o,null]),...t.map(o=>[o.id,o.rewrite_refusal===void 0?W4:CN])]),i=new Set([...n,...t.filter(o=>o.rewrite_refusal!==void 0).map(o=>o.id)]);e.warnings=e.warnings.flatMap(o=>X4(o,r,i)).sort((o,s)=>o.localeCompare(s)),t.length!==0&&(e.check.details={...e.check.details,repair_refusals:t})}function PN(e){if(V4.some(r=>Object.hasOwn(e,r)))return;let t=Object.keys(e),n=t.every(r=>K4.has(r));for(let r of t)n?e[r]="pm history-repair --all --append-only":r!==Zy&&(e[r]="pm history-repair --all")}Ds();var Z4=5;function sf(e,t){let n=[],r={};for(let o of e){let s=lp(o);if(s.length!==0){for(let a of s)r[a.field]=(r[a.field]??0)+1;n.push({id:o.id,fields:s.map(a=>a.field),reasons:[...new Set(s.map(a=>a.reason))]})}}if(n.length===0)return;n.sort((o,s)=>o.id.localeCompare(s.id));let i=t?n.length:Z4;return{details:{items:n.length,by_field:Object.fromEntries(Object.entries(r).sort(([o],[s])=>o.localeCompare(s))),rows:n.slice(0,i),truncated:n.length>i},warning:`validate_metadata_deferred_fields:${n.length}`}}ui();k();x();Z();ui();function hr(){let e=di();for(let t of ee()?.relationship_kinds??[])for(let n of t.definitions)e.register(n);return e}function cf(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function af(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function Q4(e,t){let n=new Set,r=[];for(let i of[...e].sort()){if(n.has(i))continue;n.add(i);let o=[{nodeId:i,children:[...t.get(i)??[]].sort(),nextChild:0}];for(;o.length>0;){let s=o.at(-1),a=s.children[s.nextChild];a===void 0?(r.push(s.nodeId),o.pop()):(s.nextChild+=1,n.has(a)||(n.add(a),o.push({nodeId:a,children:[...t.get(a)??[]].sort(),nextChild:0})))}}return r}function e5(e,t){let n=[...e].sort(),r=Q4(n,t),i=new Set,o=t5(n,t),s=[];for(let a of r.reverse()){if(i.has(a))continue;let c=n5(a,o,i);(c.length>1||t.get(c[0])?.has(c[0]))&&s.push(c)}return s.sort((a,c)=>a.join("\0").localeCompare(c.join("\0")))}function t5(e,t){let n=new Map(e.map(r=>[r,new Set]));for(let[r,i]of t)for(let o of i)n.get(o)?.add(r);return n}function n5(e,t,n){let r=[],i=[e];for(n.add(e);i.length>0;){let o=i.pop();r.push(o);for(let s of[...t.get(o)].sort())n.has(s)||(n.add(s),i.push(s))}return r.sort()}function r5(e){let t=new Map;for(let n of e){let r=cf(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function i5(e,t,n){let r=cf(t.parent);if(!(!r||!n.has(r)))return{parent_id:r,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function o5(e,t,n,r){let i=cf(t?.id),o=r.resolve(t?.kind);if(!i||!n.has(i)||!o?.hierarchy)return;let s=o.hierarchyDirection==="source_parent";return{parent_id:s?e:i,child_id:s?i:e,source:"dependency",kind:o.kind,holder_id:e,target_id:i,child_cardinality:s?o.incoming:o.outgoing}}function s5(e,t){let n=new Map;for(let[r,i]of e){let o=i5(r,i,e);o&&n.set(af(o),o);for(let s of i.dependencies??[]){let a=o5(r,s,e,t);a&&n.set(af(a),a)}}return[...n.values()].sort((r,i)=>af(r).localeCompare(af(i)))}function a5(e,t,n){let r=new Set(e.filter(i=>i.child_cardinality==="one").map(i=>i.child_id));return[...t].filter(([i,o])=>o.length>1&&r.has(i)).map(([i,o])=>({child_id:i,parent_ids:[...o],legacy_terminal:n.has(i)&&o.every(s=>n.has(s))})).sort((i,o)=>i.child_id.localeCompare(o.child_id))}function c5(e,t,n){let r=new Map;for(let o of t){if(o.source!=="dependency")continue;let s=r.get(o.child_id)??new Set;s.add(o.parent_id),r.set(o.child_id,s)}let i=[];for(let[o,s]of e){let a=cf(s.parent);if(!a||!e.has(a))continue;let c=[...r.get(o)??[]].filter(l=>l!==a).sort();c.length!==0&&i.push({child_id:o,scalar_parent_id:a,dependency_parent_ids:c,legacy_terminal:n.has(o)&&n.has(a)&&c.every(l=>n.has(l))})}return i.sort((o,s)=>o.child_id.localeCompare(s.child_id))}function vc(e,t=r=>r==="closed"||r==="canceled",n=hr()){let r=r5(e),i=s5(r,n),o=l5(i),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=e5([...r.keys()],new Map([...o.children_by_parent].map(([c,l])=>[c,new Set(l)]))).map(c=>({item_ids:c,legacy_terminal:c.every(l=>s.has(l))}));return{relations:i,cycles:a,cardinality_violations:a5(i,o.parents_by_child,s),divergences:c5(r,i,s)}}function l5(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.child_id)??new Set;i.add(r.parent_id),t.set(r.child_id,i);let o=n.get(r.parent_id)??new Set;o.add(r.child_id),n.set(r.parent_id,o)}return{parents_by_child:new Map([...t].map(([r,i])=>[r,[...i].sort()])),children_by_parent:new Map([...n].map(([r,i])=>[r,[...i].sort()]))}}function LN(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function d5(e,t,n=!0){let r=LN(e);return n&&(Kr(t)||r!==void 0&&Gi(r))}function MN(e,t=n=>n==="closed"||n==="canceled"){let n=e.filter(c=>typeof c?.id=="string"&&c.id.trim().length>0),r=new Set(n.map(c=>c.id.trim().toLowerCase())),i=new Map,o=(c,l,d,u,f)=>{let p=LN(l);if(!p||r.has(p.toLowerCase())||d5(p,void 0,f))return;let m={holder_id:c.id.trim(),target_id:p,kind:d,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:p.toLowerCase()==="no-active-blocker"};i.set(`${m.holder_id}::${m.target_id}::${m.kind}::${m.source}`,m)};for(let c of n){o(c,c.parent,"parent","parent",!1),o(c,c.blocked_by,"blocked_by","blocked_by",!0);for(let l of c.dependencies??[]){if(typeof l!="object"||l===null)continue;let d=l;Kr(d.source_kind)||o(c,d.id,typeof d.kind=="string"?d.kind:"related","dependency",!0)}}let s=[...i.values()].sort((c,l)=>c.holder_id.localeCompare(l.holder_id)||c.target_id.localeCompare(l.target_id)||c.kind.localeCompare(l.kind)||c.source.localeCompare(l.source)),a=s.filter(c=>c.legacy_terminal);return{active:s.filter(c=>!c.legacy_terminal),legacy_terminal:a,no_active_blocker_sentinels:s.filter(c=>c.no_active_blocker_sentinel)}}at();function lf(e,t,n=25){let r=e.definitions.filter(s=>s.roles.length===0).map(s=>s.id).sort((s,a)=>s.localeCompare(a)),i=new Set(r),o=t.filter(s=>{let a=mo(s.status,e);return a!==void 0&&i.has(a)}).map(s=>s.id).sort((s,a)=>s.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:o.length,affected_item_ids:o.slice(0,n),affected_item_ids_truncated:o.length>n}}function df(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}var zN=25,f5=ot.join("runtime","telemetry","events.jsonl"),p5=ot.join("runtime","telemetry","state.json"),m5=2500,_5=500,HN=QC-3,h5=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function qN(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("extension_disabled_pm_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("in_progress_unowned:")||e.startsWith("in_progress_idle:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function BN(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function bc(e){return e.trim().toLowerCase()}function DN(e,t){let n=bc(e),r=bc(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function GN(e){try{return(await gr.stat(e)).isDirectory()}catch{return!1}}async function g5(e){let t=(await gr.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>gr.readdir(ot.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>Zn.some(o=>i.name.endsWith(o))).map(i=>ot.parse(i.name).name)))}async function y5(e,t,n,r){let i=await lt({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:i,overThreshold:!1,classification:"live"};let s;try{s=await gr.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(o){let l=s.split(/\r?\n/).map(d=>d.trim()).filter(Boolean).at(-1);try{a=JSON.parse(l??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?s.split(/\r?\n/).filter(l=>l.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function w5(e,t,n){let r=ot.join(e,"history");if(!await GN(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await gr.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,f)=>u.localeCompare(f)),s=t.enabled?t.max_entries:null,a=[],c=[],l=[],d=[];for(let u of i){let f=ot.join(r,u),p=u.slice(0,-6),m=await y5(f,p,t,n);a.push(...m.warnings),m.classification==="tombstone"&&l.push(p),m.classification==="orphaned"&&d.push(p),m.overThreshold&&c.push(p)}return{count:i.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...d.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:s,tombstones:l,orphaned:d}}function nw(e,t){return ot.relative(e,t).replaceAll("\\","/")}async function v5(e,t){let n=[...new Set(Object.values(t))].sort((i,o)=>i.localeCompare(o)),r=[];for(let i of n){let o=ot.join(e,i),s=[];try{s=await gr.readdir(o)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&D(a))continue;continue}for(let a of s)Zn.some(c=>a.toLowerCase().endsWith(c))&&r.push(ot.join(o,a))}return r.sort((i,o)=>nw(e,i).localeCompare(nw(e,o))),r}function b5(e){return!(typeof e=="object"&&e!==null&&"code"in e&&D(e))}function E5(e){let t=sf(e,!1);return t===void 0?{}:{curation:{deferred_fields:t.details}}}async function k5(e,t,n){let r=await v5(e,t),i=[],o=[],s=[],a=[],c=dn(ee());for(let l of r){let d=nw(e,l),u;try{u=await gr.readFile(l,"utf8")}catch{i.push(d);continue}let f=_t(u);if(f){o.push({path:d,...f});continue}try{let p=Et(u,{format:Ao(l),schema:n,extensionFieldNames:c});a.push({ref:d,version:Yn(p.metadata)})}catch{s.push(d)}}return{paths:r,unreadable:i,conflictMarkers:o,parseFailures:s,formatVersions:a}}async function x5(e){let t=ot.join(e,"history"),n=[],r=[],i=[],o=[],s=[],a=[];try{a=(await gr.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,l)=>c.localeCompare(l))}catch(c){b5(c)&&n.push("history")}for(let c of a){let l=c.slice(0,-6),d;try{d=await gr.readFile(ot.join(t,c),"utf8")}catch{n.push(l);continue}let u=_t(d);if(u){r.push({id:l,...u});continue}d.split(/\r?\n/).forEach((f,p)=>{if(f.trim())try{let m=JSON.parse(f);o.push(...rf(m,l).map(g=>({itemId:l,line:p+1,...g}))),s.push(...SN(m,l,p+1))}catch{i.push({id:l,line:p+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:o,mergeReceiptDispositions:s}}function S5(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function A5(e,t,n,r,i,o){let s=await k5(e,t,n),a=await x5(e),c=wl(s.formatVersions,4,1),l=Ot(n),d=vc(o,L=>vl(L,l),hr()),u=await ef(e),f=await Mt(e),p=await yN(e,f),m=await wN(e,f,r,i),g=f===null?null:await Da(f),y=await hn(f??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),v=new Set(y.durable_receipt_ids),E=AN(a.mergeReceiptReferences,v,a.mergeReceiptDispositions),T=E.missing,R=y.receipts.filter(L=>L.state==="pending"),{pendingDecisions:C,lossless:F}=tu(R),O=g?.status==="missing"&&g.missing_keys.length===5&&g.drifted_keys.length===0,U=[...s.unreadable.map(L=>`integrity_item_unreadable:${L}`),...s.conflictMarkers.map(L=>`integrity_item_conflict_marker:${L.path}:L${L.line}`),...s.parseFailures.map(L=>`integrity_item_parse_failed:${L}`),...a.unreadable.map(L=>`integrity_history_unreadable:${L}`),...a.conflictMarkers.map(L=>`integrity_history_conflict_marker:${L.id}:L${L.line}`),...a.invalidJson.map(L=>`integrity_history_invalid_json:${L.id}:L${L.line}`),...c.outdated.map(L=>`integrity_item_outdated_format_version:${L}`),...c.ahead.map(L=>`integrity_item_ahead_format_version:${L}`),...S5(d),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...g!==null&&g.status!=="ok"?[`merge_driver_configuration_${O?"missing":"drift"}:${g.missing_keys.length+g.drifted_keys.length}`]:[],...m.warnings,...p.warnings,...C.length>0?[`merge_decisions_unreviewed:${C.length}`]:[],...F.length>0?[`merge_receipts_pending:${F.length}`]:[],...vN({invalidEvidenceCount:y.invalid_evidence_count,missingHistoryReferenceCount:T.length})],Y=[...new Set(U)].sort((L,I)=>L.localeCompare(I)),W=Y.filter(L=>!L.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:W.length===0?"ok":"warn",ok:W.length===0,details:{checked_item_files:s.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:s.unreadable.length,item_conflict_markers:s.conflictMarkers.length,item_parse_failures:s.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:d.cycles.length,hierarchy_cardinality_violations:d.cardinality_violations.length,hierarchy_parent_divergences:d.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:g===null||g.status==="ok"?0:g.missing_keys.length+g.drifted_keys.length,merge_fence:m.count,ignored_merge_artifacts:p.rules.length,pending_merge_decisions:C.length,lossless_merge_receipts:F.length,invalid_merge_receipt_evidence:y.invalid_evidence_count,missing_merge_receipt_history_references:T.length,accepted_legacy_merge_receipt_references:E.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:E.acceptedDispositionCount},item_unreadable:s.unreadable,item_conflict_markers:s.conflictMarkers,item_parse_failures:s.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,...E5(o),hierarchy_integrity:{...d,relations:Hn(d.relations,8)},history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:g===null?null:{...g,required:i},merge_fence:m.audit,ignored_merge_artifacts:p.rules,pending_merge_decision_items:[...new Set(C.map(L=>L.item_id))].sort((L,I)=>L.localeCompare(I)),lossless_merge_receipt_items:[...new Set(F.map(L=>L.item_id))].sort((L,I)=>L.localeCompare(I)),invalid_merge_receipt_evidence_details:y.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:y.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:T.slice(0,100),missing_merge_receipt_history_reference_details_truncated:T.length>100}},warnings:Y,gitWorkspaceRoot:f,pendingMergeReceipts:R}}function T5(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function O5(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:T5(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function C5(e,t){let n=Ie(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function R5(e){let n=Ie(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function I5(e){return Ie(e.reason)??Ie(e.error)??Ie(e.message)}function Qy(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function N5(e){let t=[],n=[],r=[];e.forEach((o,s)=>{let a=C5(o.definition,s),c=R5(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:a,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:a,status:c,reason:I5(o.definition)});return}n.push({layer:o.layer,name:o.name,id:a,status:c})}),t.sort(Qy),n.sort(Qy),r.sort(Qy);let i=[...r.map(o=>`extension_migration_failed:${o.layer}:${o.name}:${o.id}`),...n.map(o=>`extension_migration_pending:${o.layer}:${o.name}:${o.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function P5(e,t,n,r,i,o,s,a,c){let l=[...new Set(e)].sort((y,v)=>y.localeCompare(v)),d=[...new Set(l.map(y=>BN(y)))].sort((y,v)=>y.localeCompare(v)),u=l.filter(y=>y.startsWith("extension_capability_unknown:")).length,f=c.length>0,p=f?"partial":"full",m=l.map(Wu).filter(y=>y!==void 0),g=cN(l,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return g&&m.push(g),t>0&&m.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&m.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&m.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&m.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&m.push(`Unknown extension capabilities detected. Allowed capabilities: ${Ut.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),l.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&m.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),l.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&m.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),f?m.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):s.length>0&&m.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),m.length===0&&m.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:l.length===0?"ok":"warn",warning_count:l.length,warning_codes:d,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:o,unmanaged_loaded_extension_count:s.length,unmanaged_loaded_extensions:s,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:p,update_health_partial:f,unknown_capability_count:u,top_warnings:l.slice(0,8),remediation:m}}async function L5(e,t,n){let r=await fN(qt(e)),i=await aa({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),o=i.loaded.map(O=>O5(O)),s=await uI(i.loaded,qt(e)),a=await ca({...i,loaded:i.loaded}),[c,l]=await Promise.all([wc(i.roots.project),wc(i.roots.global)]);await dN(e,a.registrations.migrations);let d=N5(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:d.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:l.path,count:l.state.entries.length,entries:l.state.entries}}},f=new Set(c.state.entries.map(O=>bc(O.name))),p=new Set(l.state.entries.map(O=>bc(O.name))),m=[...new Map(i.loaded.filter(O=>!(O.layer==="project"?f:p).has(bc(O.name))).map(O=>[`${O.layer}:${O.name}`,{layer:O.layer,name:O.name,directory:O.directory}])).values()].sort((O,U)=>{let Y=`${O.layer}:${O.name}`,W=`${U.layer}:${U.name}`;return Y.localeCompare(W)}),g=m.map(O=>`${O.layer}:${O.name}`).sort((O,U)=>O.localeCompare(U)),y=m.filter(O=>DN(O.name,O.directory)).map(O=>`${O.layer}:${O.name}`).sort((O,U)=>O.localeCompare(U)),v=m.filter(O=>!DN(O.name,O.directory)).map(O=>`${O.layer}:${O.name}`).sort((O,U)=>O.localeCompare(U)),E=v.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${v.length}`]:[],T=[...r.warnings,...i.warnings,...u.warnings,...d.warnings,...c.warnings,...l.warnings,...E,...s.warnings],R=Gy(T),C=Wy(),F=P5(T,i.failed.length,a.failed.length,d.summary,c.warnings.length+l.warnings.length,c.state.entries.length+l.state.entries.length,g,y,v);return{check:{name:"extensions",status:T.length===0?"ok":"warn",ok:T.length===0,details:{...i,loaded:o,warnings:T,activation:u,author_manifest:r,triage:F,...d.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:C,capability_guidance:R,host_version_census:s}},warnings:T}}function FN(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=BR(e,zN);return{values:n.values,truncated:n.truncated,total:e.length}}function ew(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function M5(){let e=dc();return e.source_context_source==="env_override"?e.source_context:null}function $5(e){let t=0,n=0,r=0,i=0,o=0;for(let s of e.split(`
165
165
  `)){let a=s.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let l=Math.max(0,Math.trunc(c.attempts));t+=1,o=Math.max(o,l),l>=HN&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:o}}function D5(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function jN(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function F5(e,t){let n=Xg(e.telemetry.endpoint).trim();return!t||!e.telemetry.enabled||n.length===0||ms().telemetry_disabled?void 0:{attempted:!0,...await W5(n)}}function j5(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,o=n.last_failed_flush_at,s=o&&(!i||o>i),a=!i,c=t.validEntries>=_5;return(s||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function U5(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function z5(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>ZC?[`telemetry_schema_version_behind:${t}`]:[]}function H5(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function q5(){return{...ms(),pm_no_telemetry:ew("PM_NO_TELEMETRY"),telemetry_otel_disabled:ew("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:ew("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:M5()}}function B5(e,t){return e.telemetry.enabled&&t.validEntries>0}function G5(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}function UN(e){try{return decodeURIComponent(e)}catch{return e}}async function W5(e){let t=e,n={};try{let r=new URL(e);r.pathname="/healthz",r.search="",r.hash="",(r.username.length>0||r.password.length>0)&&(n.authorization=`Basic ${Buffer.from(`${UN(r.username)}:${UN(r.password)}`).toString("base64")}`,r.username="",r.password=""),t=r.toString()}catch{}try{let r=await fetch(t,{method:"GET",headers:n,signal:AbortSignal.timeout(m5)});return{probe_url:Vi(t),ok:r.ok,status:r.status,max_schema_version:(()=>{for(let i of h5){let o=r.headers.get(i)?.trim();if(o&&o.length>0)return o}})()}}catch(r){return{probe_url:Vi(t),ok:!1,error:r instanceof Error?Yg(r.message.replaceAll(t,Vi(t))):"probe_failed"}}}async function V5(e,t){let n=jN(await de(e)),r=e===t?n:jN(await de(t));return{runtimeState:n.runtimeState,spanState:r.runtimeState,stateParseFailed:n.stateParseFailed||r.stateParseFailed}}async function K5(e){let t=Ir(process.cwd()),n=await te(t),r=ot.join(ot.dirname(ot.join(t,f5)),zu("events.jsonl")),i=ot.join(t,p5),o=ot.join(ot.dirname(i),zu("state.json")),s=await de(r),a=s!==null,c=s?Buffer.byteLength(s,"utf8"):0,l=s?$5(s):D5(),{runtimeState:d,spanState:u,stateParseFailed:f}=await V5(o,i),p=Xg(n.telemetry.endpoint).trim(),m=Vi(p),g=await F5(n,e.checkTelemetry),y=[];f&&y.push("telemetry_state_invalid_json"),y.push(...j5(n,l,d),...U5(g),...z5(g),...H5(n,u));let v=B5(n,l),E=typeof u.pending_otel_spans=="number"?u.pending_otel_spans:0;return{check:{name:"telemetry",status:y.length===0?"ok":"warn",ok:y.length===0,details:{enabled:n.telemetry.enabled,capture_level:n.telemetry.capture_level,endpoint:m,global_pm_root:t,queue_path:r,queue_exists:a,queue_entries:l.validEntries,queue_draining:G5(v,y),queue_invalid_rows:l.invalidRows,queue_rows_total:l.totalRows,queue_size_bytes:c,queue_high_retry_entries:l.highRetryEntries,queue_high_retry_threshold:HN,queue_max_attempts:l.maxAttempts,runtime_state_path:o,last_attempted_flush_at:d.last_attempted_flush_at??null,last_successful_flush_at:d.last_successful_flush_at??null,last_failed_flush_at:d.last_failed_flush_at??null,last_failed_flush_error:d.last_failed_flush_error??null,pending_otel_spans:E,last_otel_attempt_at:u.last_otel_attempt_at??null,last_otel_success_at:u.last_otel_success_at??null,last_otel_failure_at:u.last_otel_failure_at??null,last_otel_failure_error:u.last_otel_failure_error??null,endpoint_probe:g??{attempted:!1},env_overrides:q5()}},warnings:y}}async function J5(e){let t;try{t=await sI(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,...t.owner_dead_lock_samples?{owner_dead_lock_samples:t.owner_dead_lock_samples,recovery_command:"pm gc --scope locks"}:{},unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function Y5(e){let t="metadata",n=e.items,r=await Ki(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,E)=>v.localeCompare(E)),o=[],s=[];if(i.length>0){n=await zi(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Ki(e.pmRoot,n),o=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((E,T)=>E.localeCompare(T));let v=new Set(o);s=i.filter(E=>!v.has(E))}let{missingStreams:a,unreadableStreams:c,hashMismatches:l,chainMismatches:d,versionSkews:u,driftedItems:f,workspaceStateMismatches:p,workspaceStateMissing:m,workspaceStateUnreadable:g}=r,y=[...a.map(v=>`history_drift_missing_stream:${v}`),...c.map(v=>`history_drift_unreadable_stream:${v}`),...l.map(v=>`history_drift_hash_mismatch:${v}`),...d.map(v=>`history_drift_chain_mismatch:${v}`),...u.map(v=>`history_drift_version_skew:${v}`),...p.map(v=>`history_drift_workspace_state_mismatch:${v}`),...m.map(v=>`history_drift_workspace_state_missing:${v}`),...g.map(v=>`history_drift_workspace_state_unreadable:${v}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:o,resolved_false_positive_items:s,authoritative_item_source:i.length>0},drifted_items:f,counts:{drifted:f.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:l.length,chain_mismatches:d.length,version_skews:u.length,workspace_state_mismatches:p.length,workspace_state_missing:m.length,workspace_state_unreadable:g.length},missing_streams:a,unreadable_streams:c,hash_mismatches:l,chain_mismatches:d,version_skews:u,workspace_state_mismatches:p,workspace_state_missing:m,workspace_state_unreadable:g}},warnings:y}}function X5(e,t){let n=ds(e),r=nc(n.settings),i=ic(n.settings,t),o=r.active?ps(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(r.active&&i.active)}}function Z5(){return{refreshed:[],skipped:[],warnings:[]}}async function Q5(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?Z5():MC(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function e8(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&oc(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function t8(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function n8(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function r8(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:Ig(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:Ig(r,e.vector_store?.adapter??null)}}function i8(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function o8(e,t,n){return e.enabled&&n.length>0&&t}async function s8(e,t,n,r,i){let o=X5(t,e),s=await cc(e),a=o.semanticRuntimeAvailable?yy(n,s.entries):[],c=await Q5({pmRoot:e,snapshot:o,refreshPolicy:r,staleBefore:a}),l=await cc(e),d=o.semanticRuntimeAvailable?yy(n,l.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,f=e8({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:s,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),p=t8({ledgerBefore:s,ledgerAfter:l,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:f,staleAfter:d}),m=FN(a,i),g=FN(d,i),y=o8(r,o.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:p.length===0?"ok":"warn",ok:p.length===0,details:{semantic_runtime_available:o.semanticRuntimeAvailable,compatibility_mode_auto_defaults:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:o.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:o.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:i8(r),...r8(t,o),embedding_identity_changed:f,embedding_identity_before:s.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(s.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:zN,stale_items_before_total:m.total,stale_items_before:m.values,stale_items_before_truncated:m.truncated,refresh_attempted:y,refresh_skipped_reason:n8(r,o.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(l.entries).length,stale_items_after_total:g.total,stale_items_after:g.values,stale_items_after_truncated:g.truncated}},warnings:p}}function a8(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function c8(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new _("--check-only cannot be combined with --refresh-vectors",h.USAGE);if(n&&e.noRefresh===!0)throw new _("--no-refresh cannot be combined with --refresh-vectors",h.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var l8=new Set(["extensions","locks","search"]);function d8(e){let t=new Set(Lf.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(bt));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of l8)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,o)=>i.localeCompare(o)),optionalDirs:[...n].sort((i,o)=>i.localeCompare(o)),optionalDirSet:n}}async function u8(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:o}=d8(t),s=[],a=[],c=[];for(let l of[...r,...i]){let d=ot.join(e,l);c.push(...await lt({path:d,scope:"project"})),!await GN(d)&&(o.has(l)?a.push(l):s.push(l))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:s,missingOptionalDirs:a,missingDirs:n?[...s,...a]:[...s],hookWarnings:c}}function f8(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=e.summary===!0||t,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function p8(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Va(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):zi(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function tw(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function m8(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function _8(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function h8(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var WN=e=>e.unknown_event_count??0,VN=e=>e.actionable_unknown_event_count??WN(e);function g8(e,t,n,r,i,o,s){let a=WN(r),c=VN(r),l=a>0,d=c>0,u=i.count>0||s!==void 0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...l?{author_attribution:r}:{},...i.count>0?{stale_in_progress:i}:{},...s===void 0?{}:{in_progress_work:s},...o.outcomes.length>0?{provenance_resolver_outcomes:o.outcomes}:{},...o.invalid_values.length>0?{provenance_invalid_values:o.invalid_values}:{},provenance_sample:o.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function y8(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function w8(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function v8(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function b8(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function E8(e){let t=new Map;for(let[i,o]of Object.entries(e.remediationSources))for(let s of o)t.has(s)||t.set(s,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let o=t.get(i)??"integrity",s=wy(i)?.code??BN(i),a=n.get(o)?.details,c=typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{},l=Wu(i)??(s==="agent_guidance_outdated"?"pm init --agent-guidance add":s==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":c[s]),d=qN(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:s,check:o,severity:d,...typeof l=="string"?{remediation:l}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function k8(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1&&PN(e.remediationMap),e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function x8(e){for(let t of e.checks){let n=vy(e.remediationSources[t.name]);k8({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount});for(let[r,i]of Object.entries(t.name==="storage"?e.storageRemediation:{}))Object.hasOwn(n,r)&&(n[r]=i);Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function S8(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(s=>typeof s=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(s=>Array.isArray(s)?s:[])),i=new Map;for(let s of e.pendingMergeReceipts){let a=i.get(s.item_id)??[];a.push(s),i.set(s.item_id,a)}let o=[];for(let s of n){if(r.has(s))continue;let a=i.get(s);if(!(!a||a.length===0))try{await vn(s,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),o.push(s)}catch{}}return[...new Set(o)].sort((s,a)=>s.localeCompare(a))}function A8(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function rw(e,t={}){let n=X(process.cwd(),e.path);await yt(n);let r=Se(n),{settings:i,warnings:o}=await Gr(n),s=[...new Set(o)],a=we(i,ee()),c=t.strictDirectories===!0,l=t.strictExit===!0||t.failOnWarn===!0,d=t.requireMergeDrivers===!0||l,u=c8(t),f=await u8(n,a,c),p=a8(i),m=await K5({checkTelemetry:t.checkTelemetry===!0}),g=await L5(n,i,!!e.noExtensions),y=f8(t),v=[],E=await p8({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:y,itemReadWarnings:v}),T=E,R=lf(Ot(i.schema),E),F=[...(await nI({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(mt=>mt.startsWith("agent_guidance_")),...p,...df(R)],O=y.skipDrift?{warnings:[]}:await gu({pmRoot:n,settings:i,itemIds:E.map(mt=>mt.id),commandLabel:"health"}),U=await w5(n,i.history.compact_policy,await g5(n)),Y=await Xu(n,20,t.verboseAuthorEvents===!0),W=VN(Y),L=W>0?[`history_unknown_author_events:${W}`]:[],I=Ot(i.schema),ce=await YC(n,E,{in_progress_status:I.in_progress_status,status_registry:I,threshold_hours:i.mutation_guard.stale_in_progress_hours}),vt=y8(ce.stale),ae=_N(ce,{in_progress:I.in_progress_status,open:I.open_status},xd(e)),he=[...vt.warnings,...ae.warnings],wr=await NR(n),Gn=wr.warnings,vr=await J5(n),En=y.skipIntegrity&&!d?{...tw("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await A5(n,a.type_to_folder,i.schema,i,d,E),jt=y.skipDrift?tw("history_drift"):await Y5({pmRoot:n,items:T,settings:i,typeRegistry:a,itemReadWarnings:v}),Qr=[...new Set(v)],Tc=await S8({gitWorkspaceRoot:En.gitWorkspaceRoot,pendingMergeReceipts:En.pendingMergeReceipts,historyDriftCheck:jt,global:e});A8(jt,Tc),NN(jt,await IN(jt,e,n));let to=y.skipVectors?tw("vectorization"):await s8(n,i,T,u,t.verboseStaleItems===!0),no=[m8(r,i,s),_8(f,c),h8(F,R),m.check,g.check,g8(E,i,U,Y,vt.scan,wr,ae.details),vr.check,En.check,jt.check,to.check],xf=w8({directoryState:f,normalizedSettingsReadWarnings:s,settingWarnings:F,normalizedItemReadWarnings:Qr,telemetryCheck:m,extensionCheck:g,historyPolicyWarnings:O.warnings,historySummary:U,authorAttributionWarnings:L,staleInProgressWarnings:he,provenanceWarnings:Gn,locksCheck:vr,integrityCheck:En,historyDriftCheck:jt,vectorizationCheck:to}),Lw=b8({directoryState:f,normalizedSettingsReadWarnings:s,settingWarnings:F,normalizedItemReadWarnings:Qr,telemetryCheck:m,extensionCheck:g,historyPolicyWarnings:O.warnings,historySummary:U,authorAttributionWarnings:L,staleInProgressWarnings:he,provenanceWarnings:Gn,locksCheck:vr,integrityCheck:En,historyDriftCheck:jt,vectorizationCheck:to});x8({checks:no,remediationSources:Lw,historyDriftedCount:v8(jt),overThresholdCount:U.over_threshold.length,storageRemediation:ae.remediation});let Sf=xf.filter(mt=>!qN(mt,d)),Af=E8({warnings:xf,checks:no,remediationSources:Lw,requireMergeDrivers:d}),gP=new Set(Af.filter(mt=>mt.severity==="gate_failing").map(mt=>mt.check)),yP=new Set(Af.map(mt=>mt.check));for(let mt of no)mt.ok=!gP.has(mt.name),yP.has(mt.name)&&(mt.status="warn");let wP={ok:Sf.length===0,verdict:{authority:"ok",...l?{strict_exit:!0}:{},...d?{require_merge_drivers:!0}:{},exit_code:l&&Sf.length>0?h.GENERIC_FAILURE:0},checks:no,warnings:xf,findings:Af,failed_because:Sf,generated_at:z()};return VR(wP,t,y.summaryMode)}yn();tt();at();We();k();x();J();q();me();function KN(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!nN(e,t).ok)return{reason:"unverified_history"};let r=Gt(),i={reason:"no_proven_transition"};for(let[o,s]of e.entries()){let a=n.has(String(r.metadata.status));r=ss(r,s.patch,o+1,s.op),n.has(String(r.metadata.status))?a||(i=["create","close","cancel","update","update_audit"].includes(s.op)&&xr(s.ts)?{timestamp:s.ts,source_index:o+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function JN(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function YN(e,t,n,r,i){let o=JN(n),s=t.filter(l=>o.has(l.status)&&!l.closed_at),a=[],c=[];for(let l of r?s:[]){let d;try{let u=await dt(Ae(e,l.id),l.id),{body:f,...p}=l;d=KN(u,{metadata:p,body:f},o)}catch{c.push({id:l.id,reason:"unreadable_history"});continue}if("reason"in d){c.push({id:l.id,reason:d.reason});continue}a.push({item_id:l.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:d.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:s.length,missing_closed_at_item_ids:s.slice(0,i).map(l=>l.id),missing_closed_at_item_ids_truncated:s.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:a.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...s.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:a,warnings:s.length>0?[`validate_metadata_missing_closed_at:${s.length}`]:[]}}async function XN(e,t){let n=X(process.cwd(),t.path),r=await te(n),i=Ot(r.schema);await Hi({pmRoot:n,settings:r,id:e.item_id,op:"update",author:Ge(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(o){if(o.metadata.closed_at)return{changedFields:[]};let s=await dt(Ae(n,o.metadata.id),o.metadata.id),a=JN(i),c=KN(s,o,a);if(!("timestamp"in c)||c.timestamp!==e.value)throw new _("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",h.GENERIC_FAILURE);return o.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}at();P();q();ru();import{constants as ZN}from"node:fs";import{open as T8}from"node:fs/promises";import QN from"node:path";async function Ec(e){try{let t=await T8(e,ZN.O_RDONLY|ZN.O_NONBLOCK);try{return(await t.stat()).isFile()?JSON.parse(await t.readFile("utf8")):void 0}finally{await t.close()}}catch{return}}function O8(e){let t=Ca(e);return t.success?t.data.schema:void 0}async function C8(e,t){let n=st(e,t?.files?.fields,Ye.fields);return Zf(await Ec(n))??[]}function uf(e,t,n,r){return t.flatMap((i,o)=>{let s=r(i,o);if(s.dropped===void 0&&s.ignored.length===0)return[];let a=i?.[n];return[{source:e,index:o,[n]:typeof a=="string"?a:null,...s.dropped===void 0?{}:{dropped:s.dropped},...s.ignored.length===0?{}:{ignored:s.ignored}}]})}function e0(e,t){return uf(e,t,"key",n=>Jf(n).loss)}async function iw(e,t){let n=O8(await Ec(Se(e)));return{inline:n,configured:n?.files===void 0?t:n}}function ff(e,t){return QN.relative(e,t).split(QN.sep).join("/")}async function t0(e,t,n){let{inline:r,configured:i}=await iw(e,t),o=st(e,i.files?.fields,Ye.fields),s=[...e0("settings.json",r?.fields??[]),...e0(ff(e,o),await C8(e,i))];if(s.length===0)return{details:{},warnings:[]};let a=s.filter(c=>c.dropped!==void 0).length;return{details:{schema_field_definition_loss_count:s.length,schema_field_definition_losses:s.slice(0,n),schema_field_definition_losses_truncated:s.length>n,schema_field_definition_loss_fix_hint:"A dropped definition registers no option and a field read in part ignores the listed members. Re-register a file-backed field with valid values: pm schema add-field <key> --cli-flag <flag> --alias <alias> --commands <commands>. add-field replaces the type, commands, description, flag, aliases and requirement settings it is given but keeps value_schema, metadata_key, front_matter_key and repeatable, so edit or remove those members in the fields file. Edit or remove an entry stored inline in settings.json there."},warnings:[...a>0?[`validate_schema_field_definition_dropped:${a}`]:[],...s.length>a?[`validate_schema_field_definition_partial:${s.length-a}`]:[]]}}at();ol();function n0(e,t,n){if(t.length===0)return{details:{},warnings:[]};let r=t.filter(i=>i.dropped!==void 0).length;return{details:{[`schema_${e}_definition_loss_count`]:t.length,[`schema_${e}_definition_losses`]:t.slice(0,n),[`schema_${e}_definition_losses_truncated`]:t.length>n},warnings:[...r>0?[`validate_schema_${e}_definition_dropped:${r}`]:[],...t.length>r?[`validate_schema_${e}_definition_partial:${t.length-r}`]:[]]}}async function r0(e,t,n){let{configured:r}=await iw(e,t),i=st(e,r.files?.statuses,Ye.statuses),o=st(e,r.files?.types,Ye.types),s=n0("status",uf(ff(e,i),Xf(await Ec(i))??[],"id",(l,d)=>Vf(l,d).loss),n),a=n0("type",uf(ff(e,o),Yf(await Ec(o))??[],"name",l=>po(l,"schema_file").loss),n),c=[...s.warnings,...a.warnings];return{details:{...s.details,...a.details,...c.length===0?{}:{schema_definition_loss_fix_hint:"A dropped status or type is not registered, and a definition read in part ignores the listed members. Edit or remove the listed entries in the named schema file: give every status an id and every type a name, use strings for names, descriptions, aliases and folders, and agent, human or gate for execution_role."}},warnings:c}}import Nw from"node:fs/promises";import{realpathSync as w3}from"node:fs";import{execFile as v3}from"node:child_process";import Ft from"node:path";import{promisify as b3}from"node:util";Z();Mr();P();Xn();De();at();k();x();xe();J();ii();q();me();k();x();Ch();var R8=["metadata","resolution"],ow=["metadata","resolution","estimates","timestamps","lifecycle"],I8="completed";function sw(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function i0(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function o0(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=i0(n.close_reason)??I8;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${sw(r)}`,gate:"resolution"})}return t}function s0(e){let t=[];for(let n of e){let r=i0(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${sw(r)}`,gate:"metadata"})}return t}function a0(e,t){return e.map(n=>{let r=YS(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function c0(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 l0(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${sw(n.path)}`})}return t}function d0(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new _(`--fix-scope values must not be empty. Supported values: ${ow.join(", ")}.`,h.USAGE);return new Set(R8)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(ow.includes(i)){n.add(i);continue}throw new _(`Unknown --fix-scope value "${r}". Supported values: ${ow.join(", ")}.`,h.USAGE)}return n}function u0(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function kc(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}var N8=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function P8(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=N8.exec(n);if(!r)return null;let i=r[1],o=i.toUpperCase(),s=i.slice(0,i.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(f=>f.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),l=t.evidenceText?.toUpperCase()??"",d=l.includes(`ISSUE CODE: ${o}`)||l.includes(`ISSUE CODE \`${o}\``)||l.includes(`\`${o}\``)||l.includes(`[${o}]`);return s===s.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(s.toUpperCase())||d?o:null}function f0(e){return typeof e=="string"&&e.trim().length>0}function L8(e){let t=new Set(e.map(a=>a.id.toLowerCase())),n=new Map,r=new Map;for(let a of e){let c=a.id.toLowerCase(),l=new Set([...a.parent===null?[]:[a.parent.toLowerCase()],...a.derivations].filter(d=>d!==c&&t.has(d)));n.set(c,l);for(let d of l){let u=r.get(d)??[];u.push(c),r.set(d,u)}}let o=[...[...n].filter(([,a])=>a.size===0).map(([a])=>a)],s=new Set;for(let a=0;a<o.length;a+=1)for(let c of r.get(o[a])??[]){let l=n.get(c);l.delete(o[a]),l.size===0&&(s.add(c),o.push(c))}return e.filter(a=>!s.has(a.id.toLowerCase()))}function p0(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||f0(i.duplicate_of))continue;let o=P8(i.title,{...t,evidenceText:i.body});if(o===null)continue;let s=n.get(o);s||(s=[],n.set(o,s)),s.some(a=>a.id===i.id)||s.push({id:i.id,title:i.title,parent:f0(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(a=>["discovered_from","supersedes","incident_from"].includes(a.kind)).map(a=>a.id.trim().toLowerCase()).filter(a=>a!==i.id.toLowerCase())})}let r=[];for(let[i,o]of n){if(o.length<2)continue;let s=L8(o);if(s.length<2)continue;let a=[...s].sort((c,l)=>c.id.localeCompare(l.id));r.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return r.sort((i,o)=>i.code.localeCompare(o.code))}function m0(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,o)=>i.localeCompare(o))){let i=t.get(r),o={};for(let s of[...i.keys()].sort((a,c)=>a.localeCompare(c)))o[s]=i.get(s);n[r]=o}return n}function _0(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function h0(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let o of t){let s=_0(o);if(s.length===0)continue;let a=i.get(s);a?a.push(o):i.set(s,[o])}return e.map(o=>{if(o.includes(",")||o.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:o,classification:"malformed",candidates:[],candidates_truncated:!1};let s=(i.get(_0(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,r),candidates_truncated:s.length>r}})}function g0(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}var M8=/^[a-z][a-z0-9+.-]+:\/\//i;function xc(e){return M8.test(e.trim())}kd();Mn();Xn();function $8(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function y0(e){return`${e.item_id} ${e.link_kind}`}function w0(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=$8(i.classification,r.classification),i.owners.set(y0(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[y0(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.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 v0(e,t,n,r,i=40){let o=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,s=new Map(t.map(l=>[l.path,l])),a={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=w0(e,n).map(l=>{let d=[],u=[];for(let p of l.items){let m=Sn(p.status,r)??p.status;r.terminal_statuses.has(m)?(u.push(p),m===r.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):d.push(p)}a.missing_linked_links_count+=l.items.length,a.active_missing_linked_links_count+=d.length,a.legacy_terminal_missing_linked_links_count+=u.length,d.length>0&&(a.active_missing_linked_paths_count+=1);let f=s.get(l.path);return{...l,candidates:f?.candidates??[],candidates_truncated:f?.candidates_truncated??!1,link_count:l.items.length,active_link_count:d.length,items:[...d,...u].slice(0,o),items_truncated:l.items.length>o}});return c.sort((l,d)=>+(d.active_link_count>0)-+(l.active_link_count>0)||l.path.localeCompare(d.path)),a.missing_linked_path_rows_count=c.length,a.missing_linked_path_rows=c.slice(0,o),a.missing_linked_path_rows_truncated=c.length>o,a}P();ln();oi();q();import bs from"node:fs/promises";import Es from"node:path";async function D8(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let o;try{o=await bs.readdir(Es.join(e,i))}catch{return}for(let s of o)for(let a of Zn)if(s.toLowerCase().endsWith(a)){r.push({relativePath:`${i}/${s}`,id:s.slice(0,-a.length)});break}})),r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath))}function F8(e,t){let{id:n,relativePath:r,liveItemIds:i,out:o}=e,s=_t(t);if(s){o.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=j8(e,t);a!==null&&(a.op==="delete"&&i.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 j8(e,t){let{id:n,relativePath:r,out:i}=e,o=null,s=!1,a=t.split(/\r?\n/).map((c,l)=>({content:c.trim(),number:l+1})).filter(c=>c.content.length>0);for(let c of a){try{let l=JSON.parse(c.content);if(typeof l!="object"||l===null||Array.isArray(l))throw new TypeError("history entry must be an object");o=l}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(o.op==="create"){if(s)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;s=!0}}return o}function aw(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 U8(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await bs.readdir(Es.join(e,"history"))}catch{return n}for(let i of r.sort((o,s)=>o.localeCompare(s))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await bs.readFile(Es.join(e,"history",i),"utf8")}catch(s){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:aw("history stream",s)});continue}F8({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},o)}return n}function b0(e){let t=_t(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 z8(e){let t=[],n=0,r=null;try{r=await de(Se(e))}catch(o){n+=1,t.push({path:"settings.json",detail:aw("configuration file",o)})}if(r!==null){n+=1;let o=b0(r);o!==null&&t.push({path:"settings.json",detail:o})}let i;try{i=await bs.readdir(Es.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of i.sort((s,a)=>s.localeCompare(a))){if(!o.endsWith(".json"))continue;n+=1;let s;try{s=await bs.readFile(Es.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:aw("configuration file",c)});continue}let a=b0(s);a!==null&&t.push({path:`schema/${o}`,detail:a})}return{scanned:n,unparseable:t}}async function E0(e,t,n,r={}){let i=await D8(e,n),o=new Set(i.map(u=>u.id)),s=new Map;for(let u of i){let f=s.get(u.id);f===void 0?s.set(u.id,[u.relativePath]):f.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,f])=>({id:u,paths:[...f].sort((p,m)=>p.localeCompare(m))})).sort((u,f)=>u.id.localeCompare(f.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let f=Es.join(e,u.relativePath);return Et(await bs.readFile(f,"utf8"),{format:f.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await U8(e,o),d=await z8(e);return{item_files_on_disk:i.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}}ui();yn();import u9 from"node:fs/promises";import Jt from"node:path";k();x();import{readdir as S0,realpath as A0,stat as T0}from"node:fs/promises";import At from"node:path";var H8=4096,q8=32,B8=1e3,G8=5e4,W8={nodes:1e4,edges:4e4,stateIds:2e6},Zi=47,ks=class extends Error{},V8=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function O0(){return new _("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",h.USAGE)}function K8(e,t){let n=t+1;for((e[n]==="!"||e[n]==="^")&&(n+=1),e[n]==="]"&&(n+=1);n<e.length;){let r=e[n];if(r==="\\")n+=2;else if(r==="["&&e[n+1]===":"){let i=e.indexOf(":",n+2);i===-1||e[i+1]!=="]"?n+=1:n=i+2}else{if(r==="]")return n+1;n+=1}}return-1}function J8(e,t,n){let r=e[t];if(r==="{")return{index:t,kind:"{"};if(r!=="(")return;let i=e[t-1];return i!==void 0&&"@?*+!".includes(i)&&!C0(e,t-1)?{index:t-1,kind:"("}:n.some(o=>o.kind==="(")?{index:t,kind:"plain"}:void 0}function Y8(e,t,n,r,i){let o=e[t],s=n.at(-1);if(o===")"&&s?.kind==="plain"){n.pop(),i.set(s.index,t);return}let a=o==="}"?"{":o===")"?"(":void 0;if(!(a===void 0||s?.kind!==a)&&(n.pop(),r.set(s.index,t),e[s.index]==="!"))throw O0()}function X8(e){let t=new Map,n=new Map,r=new Map,i=[],o=0;for(;o<e.length;){if(e[o]==="\\"){o+=2;continue}let s=e[o]==="["?K8(e,o):-1;if(s!==-1){n.set(o,s),o=s;continue}let a=J8(e,o,i);if(a!==void 0?i.push(a):Y8(e,o,i,t,r),i.length>q8)throw new ks;o+=1}return{closers:t,brackets:n,groups:r}}function C0(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r-=1)n+=1;return n%2===1}function Xi(e){return Array.from(e,t=>({kind:"char",value:t.codePointAt(0)}))}function Z8(e){let t=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(e),n=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(e);if(t===null&&n===null)return;let[r,i]=t!==null?[Number(t[1]),Number(t[2])]:[n[1].codePointAt(0),n[2].codePointAt(0)];if(Math.abs(i-r)+1>B8)throw new ks;let o=r<=i?1:-1,s=[];for(let a=r;a!==i+o;a+=o)s.push(t!==null?String(a):String.fromCodePoint(a));return s}function Q8(e,t){if(e[t]!=="["||e[t+1]!==":")return;let n=e.indexOf(":",t+2);if(!(n===-1||e[n+1]!=="]"))return{ranges:V8.get(e.slice(t+2,n).join(""))??[],next:n+2}}function k0(e,t,n){let r=e[t]==="\\"&&t+1<n;return{codePoint:e[r?t+1:t].codePointAt(0),next:t+(r?2:1)}}function e9(e,t,n){let r=[];for(let i=t;i<n;i+=1)e[i]==="\\"&&i+1<n&&(i+=1),r.push(e[i].codePointAt(0));return r}function t9(e,t,n){let r=t+1,i=e[r]==="!"||e[r]==="^";i&&(r+=1);let o=[],s=n-1;for(;r<s;){let a=Q8(e,r);if(a!==void 0){o.push(...a.ranges),r=a.next;continue}let c=k0(e,r,s);if(r=c.next,e[r]!=="-"||r+1>=s){o.push([c.codePoint,c.codePoint]);continue}let l=k0(e,r+1,s);r=l.next,c.codePoint<=l.codePoint&&o.push([c.codePoint,l.codePoint])}return{kind:"class",negated:i,ranges:o,literal:e9(e,t,n)}}var cw=class{chars;closers;brackets;groups;constructor(t,n){this.chars=t,this.closers=n.closers,this.brackets=n.brackets,this.groups=n.groups}alternatives(t,n,r){let i=[],o=t;for(;;){let{nodes:s,stop:a}=this.sequence(o,n,r);if(i.push(s),a>=n)return i;o=a+1}}sequence(t,n,r){let i=[],o=t;for(;o<n;){if(this.chars[o]===r)return{nodes:i,stop:o};let s=this.token(o,n);i.push(...s.nodes),o=s.next}return{nodes:i,stop:n}}token(t,n){let r=this.chars[t];if(r==="\\")return{nodes:Xi(t+1<n?this.chars[t+1]:"\\"),next:t+2};let i=this.closers.get(t);if(i!==void 0)return{nodes:r==="{"?this.brace(t,i):this.extglob(r,t,i),next:i+1};let o=this.groups.get(t);if(o!==void 0)return{nodes:[...Xi("("),...this.sequence(t+1,o,void 0).nodes,...Xi(")")],next:o+1};let s=this.brackets.get(t);return s!==void 0?{nodes:[t9(this.chars,t,s)],next:s}:r==="*"?this.stars(t,n):{nodes:r==="?"?[{kind:"any"}]:Xi(r),next:t+1}}extglob(t,n,r){let i=this.alternatives(n+2,r,"|");return[t==="@"?{kind:"alt",options:i}:{kind:"repeat",optional:t!=="+",many:t!=="?",options:i}]}brace(t,n){let r=this.alternatives(t+1,n,",");if(r.length>1)return[{kind:"alt",options:r}];let i=Z8(this.chars.slice(t+1,n).join(""));return i!==void 0?[{kind:"alt",options:i.map(Xi)}]:[...Xi("{"),...r[0],...Xi("}")]}stars(t,n){let r=1;for(;this.chars[t+r]==="*"&&t+r<n&&!this.closers.has(t+r);)r+=1;if(r!==2)return{nodes:[{kind:"star"}],next:t+r};let i=t+r<n&&this.chars[t+r]==="/";return{nodes:[{kind:"globstar",slash:i}],next:t+r+(i?1:0)}}},lw=["segment","inside"],pf={kind:"any"};function dw(e){return lw.flatMap(t=>e[t]===void 0?[]:[e[t]])}var uw=class{states=[];add(){if(this.states.length>=G8)throw new ks;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(t,n,r=!0){this.states[t].epsilon.push(n),r&&this.states[t].syntactic.push(n)}consume(t,n,r){let i=this.add();for(let o of dw(t))this.states[o].edges.push({test:n,to:i});return{[r]:i}}join(t){let n={};for(let r of lw){let i=t.flatMap(o=>o[r]===void 0?[]:[o[r]]);if(i.length===1&&(n[r]=i[0]),i.length>1){let o=this.add();for(let s of i)this.epsilon(s,o);n[r]=o}}return n}feed(t,n){for(let r of lw)t[r]!==void 0&&this.epsilon(t[r],n[r])}build(t,n){let r=n;for(let i of t)r=this.node(i,r);return r}alternation(t,n){return this.join(t.map(r=>this.build(r,n)))}star(t){let n=this.add();for(let r of dw(t))this.epsilon(r,n,!1);return this.states[n].edges.push({test:pf,to:n}),{inside:n}}segments(t){let n=this.add();this.epsilon(t,n,!1);let r=this.add();return this.states[n].edges.push({test:pf,to:r}),this.states[r].edges.push({test:pf,to:r},{test:{kind:"char",value:Zi},to:n}),n}globstar(t,n){if(n){let i=[];return t.segment!==void 0&&i.push({segment:this.segments(t.segment)}),t.inside!==void 0&&i.push(this.consume(this.star({inside:t.inside}),{kind:"char",value:Zi},"segment")),this.join(i)}let r=this.star(t);return t.segment!==void 0&&this.globstars.push({continuation:r.inside,entry:t.segment}),r}globstars=[];syntacticClosure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let i of this.states[r.pop()].syntactic)n.has(i)||(n.add(i),r.push(i));return n}resolveGlobstars(t){for(let{continuation:n,entry:r}of this.globstars){let i=this.syntacticClosure([n]);if(i.has(t)){let a=this.add();this.epsilon(r,a,!1),this.states[a].edges.push({test:{kind:"all"},to:a}),this.epsilon(a,t,!1)}let o=new Set;for(let a of i)for(let{test:c,to:l}of this.states[a].edges)R0(c,Zi)&&o.add(l);if(o.size===0)continue;let s=this.segments(r);for(let a of o)this.epsilon(s,a,!1)}}repeat(t,n){if(!t.many)return this.join([n,this.alternation(t.options,n)]);let r={segment:this.add(),inside:this.add()};return this.feed(t.optional?n:this.alternation(t.options,n),r),this.feed(this.alternation(t.options,r),r),r}node(t,n){switch(t.kind){case"char":return this.consume(n,{kind:"char",value:t.value},t.value===Zi?"segment":"inside");case"any":return this.consume(n,pf,"inside");case"star":return this.star(n);case"globstar":return this.globstar(n,t.slash);case"class":return this.join([this.consume(n,{kind:"class",negated:t.negated,ranges:t.ranges},"inside"),this.build(t.literal.map(r=>({kind:"char",value:r})),n)]);case"alt":return this.alternation(t.options,n);case"repeat":return this.repeat(t,n)}}};function R0(e,t){switch(e.kind){case"char":return e.value===t;case"any":return t!==Zi;case"all":return!0;case"class":return t!==Zi&&e.ranges.some(([n,r])=>t>=n&&t<=r)!==e.negated}}var fw=class{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(t,n,r,i){this.nfa=t,this.acceptState=r,this.limits=i,this.start=this.node(this.closure([n]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let i of this.nfa.states[r.pop()].epsilon)n.has(i)||(n.add(i),r.push(i));return[...n].sort((i,o)=>i-o)}node(t){let n=t.join(","),r=this.nodes.get(n);if(r!==void 0)return r;(this.nodes.size>=this.limits.nodes||this.stateIds+t.length>this.limits.stateIds)&&this.reset();let i={id:this.nextId,generation:this.generation,states:t,accepting:t.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(n,i),this.stateIds+=t.length,i}step(t,n){let r=`${t.id}:${n}`,i=t.generation===this.generation?this.edges.get(r):void 0;if(i!==void 0)return i;let o=[];for(let a of t.states)for(let{test:c,to:l}of this.nfa.states[a].edges)R0(c,n)&&o.push(l);let s=this.node(this.closure(o));return this.edges.size>=this.limits.edges&&this.reset(),t.generation===this.generation&&this.edges.set(r,s),s}advance(t,n){let r=t;for(let i of n){if(r.states.length===0)return r;r=this.step(r,i.codePointAt(0))}return r}};function n9(e,t=W8){let n=Array.from(e),r=new cw(n,X8(n)).sequence(0,n.length,void 0).nodes,i=new uw,o=i.add(),s=i.add();for(let a of dw(i.build(r,{segment:o})))i.epsilon(a,s);return i.resolveGlobstars(s),new fw(i,o,s,t)}function r9(e){return!/[*?[\]{}()!@+\\]/u.test(e)}function x0(e){return e.isFile()?"file":e.isDirectory()?"directory":"other"}async function i9(e,t,n){if(!n.isSymbolicLink())return{kind:x0(n),real:At.join(t,n.name)};try{let r=await A0(At.join(e,n.name));return{kind:x0(await T0(r)),real:r}}catch{return}}async function I0(e,t,n,r,i,o,s){let a;try{a=await S0(t,{withFileTypes:!0})}catch{return}for(let c of a){let l=e.advance(i,c.name);if(l.states.length===0)continue;let d=await i9(t,n,c);if(d===void 0)continue;let u=At.posix.join(r,c.name);if(d.kind==="file"&&l.accepting&&s.push(u),d.kind!=="directory")continue;let f=e.step(l,Zi);f.states.length===0||o.has(d.real)||(o.add(d.real),await I0(e,At.join(t,c.name),d.real,u,f,o,s),o.delete(d.real))}}function o9(e){let t=At.posix.normalize(e);return/^\/\/[^/]/u.test(e)?`/${t}`:t}function s9(e){let t=e;for(;t.length>1&&t.endsWith("/")&&!C0(t,t.length-1);)t=t.slice(0,-1);return t}async function N0(e,t){return(await S0(e).catch(()=>[])).includes(t)}async function P0(e,t){let n=e,r=0;for(;t[r]==="..";)n=At.dirname(n),r+=1;for(;r<t.length;r+=1){if(!await N0(n,t[r]))return!1;n=At.join(n,t[r])}return!0}function L0(e,t=process.platform){return e.startsWith("/")||t==="win32"&&/^[A-Za-z]:\//u.test(e)}async function a9(e,t){let n=At.resolve(t,e),r=await T0(n).catch(()=>{});if(r===void 0||!r.isFile())return[];let i=L0(e);return(i?await N0(At.dirname(n),At.basename(n)):await P0(t,e.split("/")))?[i?n.replaceAll("\\","/"):At.posix.normalize(e)]:[]}function c9(e,t){let n=e.split("/"),r=0;for(;r<n.length&&r9(n[r]);)r+=1;if(r===n.length)return;let i=r===0?"":`${n.slice(0,r).join("/")}/`,o=At.resolve(t,i),s=n.slice(r).join("/");if(L0(e))return{root:o,base:o.replaceAll("\\","/"),rest:s,prefix:[]};let a=At.posix.normalize(i===""?".":i).replace(/\/$/u,"");return{root:o,base:a==="."?"":a,rest:s,prefix:n.slice(0,r)}}function l9(e){try{return n9(e)}catch(t){if(t instanceof ks)return;throw t}}async function M0(e,t){if(e.startsWith("!"))throw O0();if(Array.from(e).length>H8)return[];let n=s9(o9(e)),r=c9(n,t);if(r===void 0)return a9(n,t);let i=l9(r.rest);if(i===void 0||!await P0(t,r.prefix))return[];let o=await A0(r.root).catch(()=>{});if(o===void 0)return[];let s=[];return await I0(i,r.root,o,"",i.start,new Set([o]),s),s.map(a=>d9(r.base,a))}function d9(e,t){return e.startsWith("//")?`/${At.posix.join(e.slice(1),t)}`:At.posix.join(e,t)}P();Z();De();k();x();ye();q();me();Yt();We();or();Rr();var pw=["refuse","replace","append"],_w="; ";function f9(e,t){if(e===void 0)return"refuse";let n=e.trim().toLowerCase();if(!pw.some(r=>r===n))throw new _(`--note-conflict must be one of ${pw.join(", ")}; got "${e}"`,h.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:e,required:`Pass --note-conflict ${pw.join("|")}.`});if(!t)throw new _("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",h.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return n}function p9(e,t,n){if(t===void 0||t===e)return{note:e,outcome:"unchanged",conflict:!1};if(e===void 0)return{note:t,outcome:"note_added",conflict:!1};if(n==="replace")return{note:t,outcome:"note_replaced",conflict:!1};if(n==="append"){let r=_w;return`${r}${e}${r}`.includes(`${r}${t}${r}`)?{note:e,outcome:"unchanged",conflict:!1}:{note:`${e}${_w}${t}`,outcome:"note_appended",conflict:!1}}return{note:e,outcome:"unchanged",conflict:!0}}function m9(e){let t=e.conflicts[0],n=e.conflicts.length>1?` and ${e.conflicts.length-1} more`:"",r=e.retryArgs("append"),i=e.retryArgs("replace"),o=t.source==="stored"?`${e.itemId} already links ${e.noun} ${t.path} with the note "${t.existing_note}"${n}; the add was refused so that note is kept`:`The add names ${e.noun} ${t.path} on ${e.itemId} with two notes, "${t.existing_note}" and then "${t.requested_note}"${n}; the add was refused because they disagree`;return new _(o,h.CONFLICT,{code:"linked_artifact_note_conflict",item_id:e.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...r===void 0||i===void 0?{}:{nextSteps:[e.render(r),e.render(i)],recovery:{suggested_retry:e.render(r),suggested_retry_args:r}},details:{conflicts:e.conflicts.map(s=>({...s}))}})}var hw=["path","scope","note"],_9=["pattern","glob","path","scope","note"],h9=["path"],g9=["from","to"],y9=new Set(["note","scope"]);function $0(e){return JSON.parse(JSON.stringify(e))}function w9(e,t){let n=e.map($0);return t.filter(r=>{let i=$0(r),o=n.findIndex(s=>Ke(s,i));return o>=0&&n.splice(o,1),o<0})}function D0(e){let t=e.fullHistory?[...e.stored]:[...e.written],n=t.length<e.stored.length;return{entries:t,total_count:e.stored.length,returned_count:t.length,has_more:n,mutation_receipt:{changed_count:e.written.length,removed_count:e.removedCount,full_history_included:!n,...e.linkOutcomes&&e.linkOutcomes.length>0?{link_outcomes:[...e.linkOutcomes]}:{}},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function F0(e){let t=e??"project";if(!Ff.includes(t))throw new _(`Invalid scope "${e}". Valid scopes: ${Ff.join(", ")} (default: project).`,h.USAGE);return t}function gw(e){if(e.startsWith("```")||e.includes(`
166
166
  `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||eh(e)}function v9(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function b9(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!gw(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let o=e.slice(t+2,-1).trim();if(o.length>0&&v9(o))return{path:o,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function vw(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let o=b9(r);if(o!==void 0)return[o]}rS(r,"--add",`${t} path`,gw(r));let i=gw(r)?Pi(n,"--add"):{path:r};if(Yo(i,"--add",hw),!i.path)throw new _(`--add requires path=<value> or a bare ${t} path`,h.USAGE);return[{path:i.path,scope:F0(i.scope),note:i.note?.trim()||void 0}]}):[]}function E9(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 r=Pi(n,"--add-glob");Yo(r,"--add-glob",_9);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new _("--add-glob key/value form requires pattern=<glob>",h.USAGE);return{pattern:i,scope:F0(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function k9(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 r=Pi(n,"--remove"),i=Object.keys(r).filter(o=>y9.has(o.toLowerCase()));if(i.length>0)throw new _(`--remove identifies a linked artifact by path only and does not accept ${i.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(Yo(r,"--remove",h9),!r.path)throw new _("--remove key/value form requires path=<value>",h.USAGE);return r.path}return n}):[]}function x9(e){return e?e.map(t=>{let n=Pi(t,"--migrate");Yo(n,"--migrate",g9);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new _("--migrate requires from=<value> and to=<value>",h.USAGE);return{from:r,to:i}}):[]}function xs(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function S9(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(o=>Yr(xs(o.path,n)))),i=[...new Set(t.map(o=>Yr(xs(o,n))).filter(o=>r.has(o)))].sort((o,s)=>o.localeCompare(s));if(i.length!==0)throw new _(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,h.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function _f(e){return e.split(Jt.sep).join("/")}function yw(e,t,n=process.cwd()){let r=e.trim();if(xc(r))return r;if(Jt.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return _f(r.replaceAll("\\",Jt.sep));let i=Jt.relative(t,n);return i.startsWith(`..${Jt.sep}`)||i===".."||Jt.isAbsolute(i)?_f(Jt.normalize(r)):_f(Jt.relative(t,Jt.resolve(n,r)))}async function A9(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){if(Jt.resolve(n,i.pattern)===Jt.resolve(n))continue;let o=await M0(i.pattern,n),s=[...new Set(o.map(a=>yw(a,t,n)))].sort((a,c)=>a.localeCompare(c));for(let a of s)r.push({path:a,scope:i.scope,note:i.note})}return r}function T9(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 r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function ww(e){return`${e.path}::${e.scope}`}function j0(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function U0(e){return[...new Map(e.map(t=>[ww(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function O9(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],i=[],o=[],s=[];for(let a of n){if(xc(a)){s.push(a.trim());continue}let c=Jt.isAbsolute(a)?a:Jt.resolve(t,a);try{(await u9.stat(c)).isFile()?r.push(a):o.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&ke(l)){i.push(a);continue}o.push(a)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:o,remote_references:s}}function C9(e,t,n,r){let i=0;for(let s=0;s<e.length;s+=1){let a=xs(e[s].path,r);a!==e[s].path&&(i+=1);let c=Yr(a);c!==e[s].path&&(e[s]={...e[s],path:c})}return{adds:t.map(s=>{let a=xs(s.path,r);return a!==s.path&&(i+=1),{...s,path:Yr(a)}}),removes:n.map(s=>Yr(xs(s,r))),count:i}}function Yr(e){return e.replaceAll("\\","/")}function mw(e){return`${e.scope}\0${Yr(e.path)}`}function R9(e,t,n){let r=new Map(e.map(s=>[mw(s),s.note])),i=new Map(t.map(s=>[mw(s),s.note])),o=new Map;for(let s of n){let a=mw(s);o.has(a)||o.set(a,{path:Yr(s.path),scope:s.scope,outcome:I9(r.has(a),r.get(a),i.get(a))})}return[...o.values()]}function I9(e,t,n){return e?n===t?"unchanged":t===void 0?"note_added":n?.startsWith(`${t}${_w}`)?"note_appended":"note_replaced":"added"}function N9(e,t,n){let r=e.merged.findIndex(s=>s.path===t.path&&s.scope===t.scope),i=e.merged[r];if(i===void 0){e.merged.push(t),t.note!==void 0&&e.notedHere.add(t);return}let o=p9(i.note,t.note,n);if(o.conflict)e.conflicts.push({path:t.path,scope:t.scope,existing_note:i.note,requested_note:t.note,source:e.notedHere.has(i)?"this_write":"stored"});else if(o.note!==i.note){let s={...i,note:o.note};e.merged[r]=s,e.notedHere.add(s)}}function P9(e,t,n,r,i){let o=U0(e),s={merged:[...o],notedHere:new Set,conflicts:[]};for(let l of t)N9(s,l,i);let{merged:a}=s,c=R9(o,a,t);if(n.length>0)for(let l=a.length-1;l>=0;l-=1)n.includes(a[l].path)&&a.splice(l,1);return{entries:r?a:j0(a),outcomes:c,conflicts:s.conflicts}}async function z0(e){let t=e.mutation?.entries??e.artifacts,n=e.options.validatePaths?e.artifacts:t,{counts:r,receipts:i}=j9(e.mutation);return{id:e.id,artifacts:t,changed:e.changed,count:t.length,...r,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed&&n.length>0?await O9(n.map(o=>o.path),e.workspaceRoot):void 0,...i}}function L9(e,t,n){let r=new Map;for(let o of t){let s=ww(o);r.set(s,(r.get(s)??0)+1)}let i=0;for(let o of e){let s=ww({...o,path:Yr(xs(o.path,n))}),a=r.get(s)??0;a>0?r.set(s,a-1):i+=1}return i}function M9(e,t){let n=/[\n\r]|^\s*[-*+`]/u.test(e)?[]:eS(e),r=n.findIndex(d=>d.key?.toLowerCase()==="note");if(r<0)return;let i=n.slice(0,r).map(d=>d.raw.trim()),o=new Set(n.slice(0,r).map(d=>d.key?.toLowerCase())),s=[n[r].value],a;for(let d of n.slice(r+1)){let u=d.key?.toLowerCase();if((u==="path"||u==="scope")&&!o.has(u)){i.push(d.raw.trim()),o.add(u);continue}a??=d.key===void 0?void 0:{segment:d.text.trim(),key:d.key},s.push(d.text)}if(a===void 0)return;let c=s.join(",").trim(),l=[...i,`note=${JSON.stringify(c)}`].join(",");try{vw([l],t)}catch{return}return{entry:l,note:c,...a}}function $9(e,t){return e.findIndex(n=>{try{return vw([n],t),!1}catch{return!0}})+1}function mf(e,t,n){return(t??[]).flatMap(r=>[e,n!==void 0&&r.trim()==="-"?`${n}=-`:r])}function H0(e){let{options:t}=e,n=e.noteConflict??t.noteConflict;return[...xd(e.global),...e.guards.map(r=>`--expect-hash=${r}`),e.config.metadataKey,e.id,...mf("--add",e.entries.map((r,i)=>i===e.position-1?e.rewritten:r),"path"),...mf("--add-glob",e.resolved.addGlob,"pattern"),...mf("--remove",e.resolved.remove,"path"),...mf("--migrate",e.resolved.migrate),...t.note===void 0?[]:["--note",t.note],...n===void 0?[]:["--note-conflict",n],...e.config.supportsAppendStable&&t.appendStable===!0?["--append-stable"]:[],...t.validatePaths===!0?["--validate-paths"]:[],...t.fullHistory===!0?["--full-history"]:[],...t.author?["--author",t.author]:[],...t.message?["--message",t.message]:[],...t.force===!0?["--force"]:[]]}function D9(e){return hw.some(t=>t===e.toLowerCase())?`If "${e}" was meant as a key, give it once per entry.`:`If "${e}" was meant as a key, it is not one of: ${hw.join(", ")}.`}function F9(e){try{return vw(e.entries,e.config.bareNoun)}catch(t){let n=e.entries,r=t,i=$9(n,e.config.bareNoun),o=M9(n[i-1],e.config.bareNoun);if(o===void 0)throw t;let s=Sl(e.pmRoot),a=s===void 0?void 0:H0({...e,entries:n,position:i,rewritten:o.entry,guards:s});throw new _(`--add read the note segment "${o.segment}" as a new key "${o.key}", so the ${e.config.bareNoun} link was refused (${r.message})`,h.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:n[i-1],required:`Retry with the note quoted so its commas stay prose (${a===void 0?`as ${o.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${D9(o.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...a===void 0?{}:{nextSteps:[re(a)]},details:{entry_index:i,misread_segment:o.segment,misread_key:o.key,note:o.note,rewritten_entry:o.entry,cause:r.context.code??"invalid_argument_value"},...a===void 0?{}:{recovery:{suggested_retry:re(a),suggested_retry_args:a}}})}}function j9(e){return e===void 0?{counts:{},receipts:{}}:{counts:{total_count:e.total_count,returned_count:e.returned_count,has_more:e.has_more},receipts:{mutation_receipt:e.mutation_receipt,omission_receipt:e.omission_receipt}}}async function U9(e){let{settings:t,config:n}=e,r=await Ce(e.pmRoot,e.id,t.id_prefix,t.item_format,e.typeToFolder);if(!r)throw new _(`Item ${e.id} not found`,h.NOT_FOUND);let o=(await Ue(r,{schema:t.schema})).document.metadata[n.metadataKey]??[],s=e.writeRequested?D0({collectionKey:n.metadataKey,stored:o,written:[],removedCount:0,fullHistory:e.options.fullHistory===!0}):void 0;return z0({id:r.id,artifacts:o,changed:!1,options:e.options,workspaceRoot:e.workspaceRoot,mutation:s})}async function hf(e,t,n,r){let{metadataKey:i}=r,o=Ea(),s=X(process.cwd(),n.path),a=qt(s),c=process.cwd();await yt(s);let l=await te(s),d=we(l,ee()),u=await o.resolveList(t.add,"--add"),f=await o.resolveList(t.addGlob,"--add-glob"),p=await o.resolveList(t.remove,"--remove"),m=await o.resolveList(t.migrate,"--migrate"),g=F9({id:e,pmRoot:s,entries:u,resolved:{addGlob:f,remove:p,migrate:m},options:t,global:n,config:r}).map(he=>({...he,path:yw(he.path,a,c)})),y=E9(f),v=await A9(y,a,c),E=g.length>0||y.length>0,T=T9([...g,...v],t.note,E),R=f9(t.noteConflict,E),C=k9(p).map(he=>yw(he,a,c)),F=x9(m);if(S9(T,C,F),!(T.length>0||C.length>0||F.length>0))return U9({id:e,pmRoot:s,settings:l,typeToFolder:d.type_to_folder,options:t,workspaceRoot:a,config:r,writeRequested:y.length>0});let U=Ge(t.author,l.author_default),Y=[],W=0,L=[],I=await Hi({pmRoot:s,settings:l,id:e,op:r.op,author:U,message:t.message,force:t.force,skipNoop:!0,mutate(he){let wr=he.metadata,Gn=wr[i]??[],vr=[...Gn],En=C9(vr,T,C,F),jt=P9(vr,En.adds,En.removes,r.supportsAppendStable&&t.appendStable===!0,R);if(jt.conflicts.length>0){let to=Sl(s);throw m9({itemId:he.metadata.id,noun:r.bareNoun,conflicts:jt.conflicts,retryArgs:no=>to===void 0?void 0:H0({id:he.metadata.id,entries:u??[],position:0,rewritten:"",resolved:{addGlob:f,remove:p,migrate:m},options:t,global:n,config:r,guards:to,noteConflict:no}),render:re})}let Qr=jt.entries;L=jt.outcomes,Qr.length>0?wr[i]=Qr:delete wr[i];let Tc=!Ke(Gn,Qr);return Y=Gn,W=L9(Gn,Qr,F),{changedFields:Tc?[i]:[],warnings:Tc&&En.count>0?[`path_migrations_applied:${En.count}`]:[]}}}),ce=I.item[i]??[],vt=I.warnings.find(he=>he.startsWith("path_migrations_applied:")),ae=vt?Number(vt.slice(24)):0;return z0({id:I.item.id,artifacts:ce,changed:I.changedFields.includes(i),migrationsApplied:ae,options:t,workspaceRoot:a,mutation:D0({collectionKey:i,stored:ce,written:w9(Y,ce),removedCount:W,fullHistory:t.fullHistory===!0,linkOutcomes:L})})}function gf(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}async function q0(e,t,n){let r=await hf(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return gf(r,"docs")}yn();Z();De();k();x();q();me();We();An();async function B0(e,t,n){let r=await hf(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return gf(r,"files")}k();x();import{readFileSync as z9}from"node:fs";import yf from"node:path";var H9=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),V0=new Set(["--pm-path","--path","--author","--expect-hash"]),q9={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"])},B9=new Set(["-p","--package"]),G9=new Set(["-c","--call"]),W9=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),V9=new Set(["-C","--prefix","--userconfig","--cache"]);var K9=new Set(["exec","x"]);function J9(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function Y9(e,t=process.cwd()){let n=X9(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...i]=n;if(G0(r)||W0(r,t))return i;if(r==="node"&&i[0]&&W0(i[0],t))return i.slice(1);let o=r==="npx"||r==="bunx"?bw(i):r==="pnpm"?e3(i):r==="npm"?t3(i):null;return o&&(G0(o.command)||Q9(o.command))?o.args:null}var K0=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let o=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of J9(o)){let c=Y9(a),l=c?n3(c):null,d=l&&H9.has(l.subcommand)?r3(l.remaining,q9[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&s.add(d)}return[...s].sort((a,c)=>a.localeCompare(c))};function X9(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 G0(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function Z9(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function Q9(e){let t=Z9(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function W0(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=yf.resolve(t,e);try{return JSON.parse(z9(yf.join(yf.dirname(yf.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function bw(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let o=i[1];return o?{command:o,args:e.slice(t+1)}:null}if(G9.has(r)){t+=1;break}t+=B9.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function J0(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function e3(e){let t=J0(e,W9);return t?.subcommand!=="dlx"?null:bw(t.args)}function t3(e){let t=J0(e,V9);return!t||!K9.has(t.subcommand)?null:bw(t.args)}function n3(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(V0.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function r3(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(V0.has(r)||t.has(r))&&(n+=1)}}var Vje=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]);P();ye();J();q();import{execFile as i3}from"node:child_process";import{readFile as o3}from"node:fs/promises";import s3 from"node:path";import{promisify as a3}from"node:util";var c3=a3(i3),Ew=1,l3="linked-test-trust.json";function d3(e){return s3.join(Il(e),l3)}function Y0(){return{version:Ew,acknowledged:{}}}async function u3(e){try{let t=JSON.parse(await o3(d3(e),"utf8"));return t.version!==Ew||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Y0():{version:Ew,acknowledged:t.acknowledged}}catch{return Y0()}}async function X0(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await c3("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function Z0(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function f3(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&cn(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Sc(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function p3(e){return Je(N({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}function m3(e,t,n){let r=p3(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let o=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!f3(e.provenance)?o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Sc(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...Sc(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...Sc(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Sc(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...Sc(i,t)}}async function Q0(e,t,n){let r=await u3(e);return t.map(i=>m3(i,n,r))}async function eP(e){return e.includeBody?zi(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Wa(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}Z();De();Qe();me();Lt();k();x();var _3=5;async function h3(e,t){let n=t.hashMismatches.filter(o=>o!==je);if(n.length===0)return;let r=await te(e),i=we(r,ee());for(let o of n){let s=await Te(e,o,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let a=await Ce(e,o,r.id_prefix,r.item_format,i.type_to_folder);if(a===null)throw new _(`Item ${o} not found`,h.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await Ue(a,{schema:r.schema});if(c.metadata.id!==o)throw new _(`Item identity changed while validating ${o}`,h.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let l=await TR(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(f=>f!==o),...l[u].filter(f=>f===o)].sort((f,p)=>f.localeCompare(p));let d=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==o),...(l.identityDiscontinuities??[]).filter(u=>u.item_id===o)];d.length>0?t.identityDiscontinuities=d:delete t.identityDiscontinuities}finally{await s()}}}async function tP(e,t,n){let r=await Ki(e,t);await h3(e,r);let o=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,l])=>l>0).map(([l,d])=>`${l}:${d}`),s=n?Number.POSITIVE_INFINITY:_3,a=r.driftedItems.slice(0,s),c=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:c.length>0?"error":o.length===0?"ok":"warn",ok:c.length===0&&o.length===0,details:{identity_discontinuities:c.slice(0,s),identity_discontinuities_count:c.length,identity_discontinuities_truncated:c.length>s,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,s)}},warnings:o}}function nP(e){let t=0,n=new Map,r=new Map,i=[],o=new Set,s=[],a=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),o.add(d);for(let f of e.get(d)??[])n.has(f)?o.has(f)&&r.set(d,Math.min(r.get(d),n.get(f))):(a(f),r.set(d,Math.min(r.get(d),r.get(f))));if(r.get(d)!==n.get(d))return;let u=[];for(;i.length>0;){let f=i.pop();if(o.delete(f),u.push(f),f===d)break}u.sort((f,p)=>f.localeCompare(p)),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(",")))}at();function kw(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],o=new Set([n]),s=a=>{for(let c of(t.get(a)??[]).filter(l=>r.has(l))){if(c===n&&i.length>1)return i.push(n),!0;if(!o.has(c)){if(o.add(c),i.push(c),s(c))return!0;i.pop(),o.delete(c)}}return!1};return s(n)?[...i]:[...e,n]}function g3(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function y3(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let o=r.resolve(i.kind);if(!o?.hierarchy)continue;let s=n.get(i.id.toLowerCase());s&&(o.hierarchyDirection==="source_parent"?t.get(s).push(e.id):t.get(e.id).push(s))}}function rP(e,t=hr()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((o,s)=>o.id.localeCompare(s.id))){let o=r.get(i.id),s=g3(i.parent,n);s&&o.push(s),y3(i,r,n,t)}for(let[i,o]of r)r.set(i,[...new Set(o)].sort());return r}function iP(e,t,n=hr()){let r=vc(e,s=>t?Qf(s,t):s==="closed"||s==="canceled",n),i=rP(e,n),o=r.cycles.map(s=>s.item_ids);return{cycle_count:o.length,active_cycle_count:r.cycles.filter(s=>!s.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(s=>s.legacy_terminal).length,cycle_item_ids:[...new Set(o.flat())].sort(),cycle_sample_paths:o.map(s=>kw(s,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(s=>!s.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(s=>s.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(s=>`${s.child_id}:${s.parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(s=>!s.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(s=>s.legacy_terminal).length,parent_divergence_rows:r.divergences.map(s=>`${s.child_id}:scalar=${s.scalar_parent_id}:dependencies=${s.dependency_parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`)}}xe();function Xr(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function xw(e){return Xr(e).replace(/\/+$/,"")}function qn(e){let t=Ie(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Sw(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}var E3=["src","tests","docs"],k3=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],x3=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),S3=["resolution","expected_result","actual_result"],A3=["default","tracked-all","tracked-all-strict"],oP=["core","strict","custom"],bf=["off","warn","error"],Ow=["author","acceptance_criteria","estimated_minutes","close_reason"],lP=[...Ow,"reviewer","risk","confidence","sprint","release"],Cw=Array.from(new Set(lP)),T3={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"},O3={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"},C3={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"},R3={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"},I3={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"},N3=32*1024*1024,P3=1e4,Rw=40,bn=5,L3=4096,M3=255,$3=b3(v3);function dP(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?dP(r):r);return t}function D3(e){return{...e,checks:e.checks.map(t=>({...t,details:dP(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 kf(e,t){return Sn(e,t)??e}function Ac(e,t){return t.terminal_statuses.has(kf(e,t))}function Zr(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function wf(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function F3(e){let t=Zr($f),n={blocked_reason:Zr(ei.blocked_reason),resolution:Zr(ei.resolution),actual_result:Zr(ei.actual_result)},r=Zr(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:Zr(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Zr(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Zr(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:wf(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:wf(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:wf(i.resolution,n.resolution)?"default":"settings",actual_result:wf(i.actual_result,n.actual_result)?"default":"settings"}}}function j3(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(oP.includes(t))return t;throw new _(`Unknown --metadata-profile value "${e}". Supported values: ${oP.join(", ")}.`,h.USAGE)}function U3(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(bf.includes(t))return t;throw new _(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${bf.join(", ")}.`,h.USAGE)}function z3(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(bf.includes(t))return t;throw new _(`Unknown --parent-cycle-severity value "${e}". Supported values: ${bf.join(", ")}.`,h.USAGE)}function H3(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>T3[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function q3(e,t,n){let r=H3(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Ow],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...lP],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Ow],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var B3=new Set(["acceptance_criteria","estimated_minutes"]);function G3(e,t,n,r){return!r&&B3.has(t)&&Ac(e.status,n)?!1:t==="author"?!Ie(e.author):t==="acceptance_criteria"?!Ie(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?kf(e.status,n)===n.close_status&&!Ie(e.close_reason):t==="reviewer"?!Ie(e.reviewer):t==="risk"?!Ie(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!Ie(e.confidence):t==="sprint"?!Ie(e.sprint):!Ie(e.release)}function W3(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: ${A3.join(", ")}.`,h.USAGE)}function V3(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Ft.resolve(t);let n=Ft.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Ft.dirname(Ft.dirname(n));let i=Ft.resolve(process.cwd()),o=sP(n),s=sP(i),a=Ft.relative(o,s);return a.length===0||!a.startsWith("..")&&!Ft.isAbsolute(a)?n:i}function sP(e){try{return w3.native(e)}catch{return Ft.resolve(e)}}function K3(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function uP(e,t,n){let r=t.length>0?Ft.join(e,t):e,i;try{i=await Nw.readdir(r,{withFileTypes:!0})}catch(o){if(D(o))return;throw o}for(let o of i){if(o.name.startsWith("."))continue;let s=t.length>0?Ft.join(t,o.name):o.name;if(o.isDirectory()){if(x3.has(o.name))continue;await uP(e,s,n);continue}o.isFile()&&n.push(Xr(s))}}async function aP(e){let t=[];for(let n of E3)await uP(e,n,t);for(let n of k3){let r=Ft.join(e,n);try{(await Nw.stat(r)).isFile()&&t.push(Xr(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function J3(e){try{let{stdout:t}=await $3("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:N3,windowsHide:!0,timeout:P3}),n=t.split("\0").map(r=>Xr(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function Y3(e,t){let n=new Set,r=xw(so);r.length>0&&n.add(r);let i=xw(Ft.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((o,s)=>o.localeCompare(s))}function cP(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function X3(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await J3(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await aP(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await aP(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function Pe(e,t=bn){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Qi(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Pe(e,Rw);return{values:n.values,truncated:n.truncated,total:e.length}}var Z3={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},Q3={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function eZ(e){let t=e.missing_fields.map(n=>`${Z3[n]} "${Q3[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function tZ(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(s=>typeof s=="string"):aI(t);if(i.length===0)return;let o=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...o?{fix_hints_truncated:!0}:{}}}function nZ(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),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("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var rZ="validate_metadata_duplicate_issue_codes";function iZ(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:bn,r=e.slice(0,n);return{rows:r.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:r.length<e.length,warnings:[`${rZ}:${e.length}`]}}function oZ(e,t,n){let r=Object.fromEntries(Cw.map(i=>[i,[]]));for(let i of e)for(let o of Cw)G3(i,o,t,n)&&r[o].push(i.id);return r}function sZ(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let o=t[i];o.length>0&&r.push(`${O3[i]}:${o.length}`)}return r.push(...n),r}function aZ(e,t){let n={};for(let r of e.required_fields){let i=t[r],o=i?i.length:0,s=C3[r];n[s]=o}return n}function cZ(e,t,n){let r=[];for(let i of e.required_fields){let o=t[i];if(o)for(let s of o){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:i})}}return r}function lZ(e,t,n,r){for(let i of t.required_fields){let o=n[i];if(!o||o.length===0)continue;let s=R3[i],a=I3[i];if(!s||!a)continue;let c=Pe(o,r?o.length:bn);e[s]=c.values,e[a]=c.truncated}}function dZ(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:Ie(n.get(i)?.resolution)})):[]}function uZ(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:Ie(n.get(i)?.type)})):[]}function fZ(e,t,n,r,i){let o=new Map(e.map(E=>[E.id,E])),s=t.profile==="strict",a=oZ(e,n,s),c=p0(e,{configuredPrefixes:i}),l=iZ(c,r),d=sZ(t,a,l.warnings),u=aZ(t,a),f=cZ(t,a,o),p=m0(f),m={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:[...Cw],counts:u,missing_by_type:p,duplicate_issue_codes_count:c.length,duplicate_issue_codes:l.rows,duplicate_issue_codes_truncated:l.truncated};t.configured_custom_fields.length>0&&(m.configured_custom_required_fields=[...t.configured_custom_fields]);let g=sf(e,r);g!==void 0&&(m.deferred_fields=g.details,d.push(g.warning)),lZ(m,t,a,r);let y=dZ(t,a,o),v=uZ(t,a,o);return{check:{name:"metadata",status:d.length===0?"ok":"warn",ok:d.length===0,details:m},warnings:d,closeReasonBackfillRows:y,estimateBackfillRows:v}}function pZ(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(f=>r.has(kf(f.status,t))),o=[],s=[];for(let f of i){let p=S3.filter(m=>!Ie(f[m]));p.length!==0&&(o.push({id:f.id,missing_fields:p}),s.push({id:f.id,missing_fields:p,close_reason:Ie(f.close_reason)}))}let a=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:bn,l=Pe(o.map(f=>`${f.id}:${f.missing_fields.join(",")}`),c),d=o.map(f=>eZ(f)),u=Pe(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:i.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 mZ(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _Z(e,t="pm",n=di()){let r=new Set(e.map(o=>o.id)),i=[...e].sort((o,s)=>o.id.localeCompare(s.id));return new Map(i.map(o=>{let s=new Set,a=qn(o.blocked_by);a&&r.has(a)&&s.add(a),(o.dependencies??[]).filter(l=>{let d=qn(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>qn(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=qn(o.definition_of_ready);return gZ(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[o.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function hZ(e,t,n){let r=MN(e,n?d=>Ac(d,n):void 0),i=r.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),o=r.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),s=t?Number.POSITIVE_INFINITY:bn,a=Pe(i,s),c=Pe(o,s),l=Pe(r.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),s);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+o.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:o.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function gZ(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${mZ(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,o)=>i.localeCompare(o))}function yZ(e,t="pm"){let n=_Z(e,t),r=nP(n),i=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),o=r.map(s=>kw(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:o}}function wZ(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 Ef(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function vZ(e,t){let n=Ef(e).split("/").filter(Boolean),r=Ef(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function bZ(e,t){let n=Ef(t),r=Ef(e),i=t.endsWith("/")?t:`${t}/`,o=e.startsWith(i),s=n.length>0&&n===r,a=vZ(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 EZ(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function kZ(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(o=>(r==="docs"?o.docs??[]:o.files??[]).map(s=>({item:o,link:s}))).forEach(({item:o,link:s})=>{if(s.scope!=="project")return;let a=Xr(s.path);if(a.length===0||a===e)return;let c=bZ(e,a);c!==null&&EZ(i,o,c.score)&&(i={item:o,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function xZ(e,t){return e.map(n=>{let r=wZ(n),i=r==="docs_unowned"?"docs":"files",o=kZ(n,r,t),s=o?.id??"<id>";return{path:n,classification:r,owner_candidate:o,remediation_hint:`pm ${i} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function SZ(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function AZ(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=qn(e[n]);return i?r.some(o=>i.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function TZ(e,t,n,r,i){let o=qn(t.parent),s=o?n.get(r.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!Ac(s.status,i)}}function OZ(e,t,n,r){let i=qn(e.blocked_by),o=qn(e.blocked_reason),s=o?.toLowerCase(),a=kf(e.status,n),c=[];return t.has(a)?(!i&&!o&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(l=>s.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function CZ(e,t,n,r){let i=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=>!Ac(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=AZ(c,r);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=qn(c.parent),u=d?i.get(o.get(d.toLowerCase())??d):void 0;if(u&&Ac(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(TZ(c,u,i,o,n))),t){let f=OZ(c,s,n,r);f.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(f)].sort((p,m)=>p.localeCompare(m))})}}return a}function RZ(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 vf(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Aw(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function IZ(e,t,n,r,i){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=vf("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),a=vf("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=vf("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),l=vf("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),d=Aw("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=Aw("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),f=Aw("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...o,...s?[s]:[],...a?[a]:[],...c?[c]:[],...l?[l]:[],...d?[d]:[],...u?[u]:[],...f?[f]:[]]}function NZ(e){let t=Xr(e);return t.length>L3||t.split(/[\\/]/).some(n=>n.length>M3)}async function PZ(e,t){let n=Ft.isAbsolute(t)?t:Ft.resolve(e,t);if(NZ(n))return!1;try{let r=await Nw.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return K3(r,["ENOENT","ENOTDIR"])}}async function LZ(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(o=>({item:i,artifact:o,link_kind:"files"})),...(i.docs??[]).map(o=>({item:i,artifact:o,link_kind:"docs"}))]);for(let{item:i,artifact:o,link_kind:s}of r){if(o.scope!=="project")continue;if(xc(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let a=Xr(o.path);a.length!==0&&(n.linkedProjectPaths.add(a),await PZ(t,o.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:s})))}return n}function MZ(e,t,n,r,i,o){let s=r==="tracked-all-strict",a=s&&!i,c=i||s,l=c?[]:Y3(t,n),d=l.length===0?[]:e.candidateFiles.filter(p=>cP(p,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(p=>!cP(p,l)),f={};if(d.length>0){let p=Qi(d,o);f.pm_internals={count:d.length,paths:p.values,paths_truncated:p.truncated,paths_total:p.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:f}}function $Z(e,t,n,r,i,o,s,a="pm"){let c=CZ(e,t,i,o);RZ(c);let l=yZ(c.activeItems,a),d=iP(e,i),u=lf(i,e,s?Number.POSITIVE_INFINITY:bn),f=[...IZ(c,t,n,r,{dependencyCycles:l.cycle_count,activeHierarchyCycles:d.active_cycle_count,activeHierarchyCardinality:d.active_cardinality_violation_count,activeHierarchyDivergence:d.active_parent_divergence_count,legacyHierarchyCycles:d.legacy_cycle_count,legacyHierarchyCardinality:d.legacy_cardinality_violation_count,legacyHierarchyDivergence:d.legacy_parent_divergence_count}),...df(u)],p=s?Number.POSITIVE_INFINITY:bn,m=Pe(c.closureLikeRows.map(U=>`${U.id}:${U.fields.join(",")}`),p),g=Pe(c.terminalParentRows.map(U=>`${U.id}:${U.parent_id}:${U.parent_status}`),p),y=Pe(c.staleBlockerRows.map(U=>`${U.id}:${U.status}:${U.reasons.join(",")}`),p),v=Pe(l.cycle_item_ids,p),E=Pe(l.cycle_sample_paths,p),T=Pe(d.cycle_item_ids,p),R=Pe(d.cycle_sample_paths,p),C=Pe(d.cardinality_violation_rows,p),F=Pe(d.parent_divergence_rows,p),O=l.cycle_count>0&&n==="error"||(d.active_cycle_count>0||d.active_cardinality_violation_count>0||d.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:O?"error":f.length===0?"ok":"warn",ok:!O&&f.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:m.values,active_closure_like_metadata_rows_truncated:m.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:g.values,active_terminal_parent_rows_truncated:g.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:v.values,dependency_cycle_item_ids_truncated:v.truncated,dependency_cycle_sample_paths:E.values,dependency_cycle_sample_paths_truncated:E.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,active_parent_cycle_count:d.active_cycle_count,legacy_parent_cycle_count:d.legacy_cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:T.values,parent_cycle_item_ids_truncated:T.truncated,parent_cycle_sample_paths:R.values,parent_cycle_sample_paths_truncated:R.truncated,hierarchy_cardinality_violation_count:d.cardinality_violation_count,active_hierarchy_cardinality_violation_count:d.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:d.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:C.values,hierarchy_cardinality_violation_rows_truncated:C.truncated,hierarchy_parent_divergence_count:d.parent_divergence_count,active_hierarchy_parent_divergence_count:d.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:d.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:F.values,hierarchy_parent_divergence_rows_truncated:F.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:f,terminalParentFixRows:c.terminalParentFixRows}}async function DZ(e,t,n,r,i,o,s=Ot(Le.schema)){let a=await LZ(e,t),c=new Map(e.map(I=>[I.id,I])),l=[...new Set(a.missingLinkedPaths)].sort((I,ce)=>I.localeCompare(ce)),d=await X3(t,r),u=MZ(d,n,t,r,i,o),f=u.candidateFiles.filter(I=>!a.linkedProjectPaths.has(I)),p=xZ(f,e),m=h0(l,u.candidateFiles),g=new Map(m.map(I=>[I.path,I.classification])),y=m.filter(I=>I.classification==="moved").length,v=a.staleLinkRows.map(I=>({...I,classification:g.get(I.path)??"deleted"})).sort((I,ce)=>I.item_id.localeCompare(ce.item_id)||I.path.localeCompare(ce.path)||I.link_kind.localeCompare(ce.link_kind)),E=[];u.strictModeForcesPmInternals&&E.push("validate_files_tracked_all_strict_forces_pm_internals"),f.length>0&&E.push(`validate_files_orphaned_paths:${f.length}`);let T=[...a.remoteLinkedPaths].sort((I,ce)=>I.localeCompare(ce)),R=Qi(T,o),C=Qi(l,o),F=Qi(f,o),O=Qi(p.map(I=>`${I.path}:${I.classification}:owner_candidate=${I.owner_candidate?.id??"unowned"}`),o),U=o?p:Qi(SZ(p),!1).values,Y=Qi(g0(m),o),L=v0(v,m,I=>c.get(I),s,o?1/0:Rw);return L.active_missing_linked_paths_count>0&&E.push(`validate_files_missing_linked_paths:${L.active_missing_linked_paths_count}`),{check:{name:"files",status:E.length===0?"ok":"warn",ok:E.length===0,details:{workspace_root:t,scan_mode_requested:d.requestedMode,scan_mode_applied:d.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.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:Rw,candidate_scan_source:d.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:T.length,remote_linked_paths_total:R.total,remote_linked_paths:R.values,remote_linked_paths_truncated:R.truncated,candidate_total_raw:d.candidateTotal,candidate_scanned_raw:d.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:l.length,missing_linked_paths_total:C.total,missing_linked_paths:C.values,missing_linked_paths_truncated:C.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:m.filter(I=>I.classification==="deleted").length,missing_linked_paths_malformed_count:m.filter(I=>I.classification==="malformed").length,missing_linked_path_classifications:Y.values,missing_linked_path_classifications_truncated:Y.truncated,...L,orphaned_paths_count:f.length,orphaned_paths_total:F.total,orphaned_paths:F.values,orphaned_paths_truncated:F.truncated,orphaned_path_classifications:O.values,orphaned_path_classifications_truncated:O.truncated,orphaned_path_rows_count:p.length,orphaned_path_rows:U}},warnings:E,staleLinkPruneRows:v}}function FZ(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},o)=>{let s=t[o];if(s.trusted)return;let a=Sw(i.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function jZ(e,t,n,r){let i=new Set(e.map(C=>C.id.toLowerCase())),o=0,s=0,a=new Set,c=[],l=e.flatMap(C=>(C.tests??[]).map(F=>({item:C,linkedTest:F}))),d=await X0(Z0()),u=await Q0(r,l.map(({linkedTest:C})=>C),d),f=FZ(l,u);for(let{item:C,linkedTest:F}of l){if(typeof F.command!="string"||F.command.trim().length===0)continue;o+=1;let O=K0(F.command,t);if(O.length!==0){s+=O.length;for(let U of O)a.add(U),i.has(U.toLowerCase())||c.push(`${C.id}:${U}:${Sw(F.command)}`)}}let p=[...new Set(c)].sort((C,F)=>C.localeCompare(F)),m=[...new Set(p.map(C=>C.split(":")[1]??""))].filter(C=>C.length>0).sort((C,F)=>C.localeCompare(F)),g=[];p.length>0&&g.push(`validate_command_references_stale_pm_ids:${p.length}`),f.length>0&&g.push(`validate_linked_test_trust_unacknowledged:${f.length}`);let y=n?Number.POSITIVE_INFINITY:bn,v=Pe(p,y),E=Pe(m,y),T=Pe([...a].sort((C,F)=>C.localeCompare(F)),y),R=Pe(f,y);return{check:{name:"command_references",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_items:e.length,linked_commands_scanned:o,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:T.values,unique_referenced_pm_ids_truncated:T.truncated,linked_test_trust_current_source_ref:d??null,untrusted_linked_tests_count:f.length,untrusted_linked_tests:R.values,untrusted_linked_tests_truncated:R.truncated,stale_pm_id_references_count:p.length,stale_pm_ids_count:m.length,stale_pm_ids:E.values,stale_pm_ids_truncated:E.truncated,stale_pm_id_reference_rows:v.values,stale_pm_id_reference_rows_truncated:v.truncated}},warnings:g}}function UZ(e,t){let n=wl(e.map(c=>({ref:c.id,version:Yn(c)})),4,1),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:bn,o=Pe(n.outdated,i),s=Pe(n.ahead,i),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:4,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:r}}var Iw="pm validate auto-fix";async function zZ(e,t,n){switch(e.kind){case"set_closed_at":await XN(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Iw};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new _("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",h.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Tw(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function HZ(e,t,n){let r=[],i=[],o=new Map;for(let s of e.filter(a=>Tw(a)===null))try{await zZ(s,t,n),r.push(s)}catch(a){i.push({fix:s,error:a})}for(let s of e.filter(a=>Tw(a)!==null)){let a=Tw(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 B0(a.item_id,{remove:c,message:Iw},t):await q0(a.item_id,{remove:c,message:Iw},t),r.push(...s)}catch(l){i.push(...s.map(d=>({fix:d,error:l})))}}return iR(i.map(s=>s.error)),{applied:r,failed:i}}function qZ(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function BZ(e,t,n,r){let i=await E0(e,new Set(t.map(y=>y.id)),n,{schema:r.schema,extensionFieldNames:dn(ee())}),o=[];i.unreadable_item_files.length>0&&o.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&o.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&o.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&o.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&o.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&o.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let s=o.length,a=await ef(e);a.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Mt(e),l=await $a(e,is(r),{gitWorkspaceRoot:c});l.status==="drift"&&o.push(`validate_merge_fence_drift:${l.missing_patterns.length+l.stale_patterns.length}`);let d=c===null?null:await Da(c);d!==null&&d.status!=="ok"&&o.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=await hn(c??e,{includeLossless:!0,pmRoot:e}),f=u.receipts,{pendingDecisions:p,lossless:m}=tu(f);p.length>0&&o.push(`validate_merge_decisions_unreviewed:${p.length}`),qZ(o,u.invalid_evidence_count);let g=s>0?"error":o.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:g,ok:g==="ok",details:{...i,merge_fence:l,merge_driver_configuration:d,pending_merge_decision_count:p.length,pending_merge_decision_items:[...new Set(p.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),lossless_merge_receipt_count:m.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(m.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),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}}async function GZ(e,t,n,r){let i=[XI(n,r),await t0(t,n,r),await r0(t,n,r)];for(let o of i)Object.assign(e.check.details,o.details),e.warnings.push(...o.warnings)}function Bn(e,t,n){n&&tZ(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function WZ(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let i=await QI(e.pmRoot,e.items,r?1/0:bn,e.sourceIncomplete);Bn(t,i,n)}if(e.requestedChecks.has("metadata")){let i=fZ(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let o=r?1/0:bn,s=await YN(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,o);t.closureTimestampFixes=s.fixes,Object.assign(i.check.details,s.details),i.warnings.push(...s.warnings),await GZ(i,e.pmRoot,e.settings.schema,o),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",Bn(t,i,n)}if(e.requestedChecks.has("resolution")){let i=pZ(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,Bn(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=$Z(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,Bn(t,i,n),Bn(t,hZ(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await DZ(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,Bn(t,i,n)}return e.requestedChecks.has("command_references")&&Bn(t,await jZ(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&Bn(t,await tP(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&Bn(t,UZ(e.items,r),n),e.requestedChecks.has("storage_integrity")&&Bn(t,await BZ(e.pmRoot,e.items,we(e.settings,ee()).type_to_folder,e.settings),n),t}function VZ(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...s0(t.closeReasonBackfillRows)),r.push(...o0(t.resolutionBackfillRows)),r.push(...a0(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...c0(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...l0(t.staleLinkPruneRows)),r}async function KZ(e,t,n,r,i,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=VZ(e,t,n),{applicable:a,gated:c}=u0(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let f=await HZ(a,i,o);d.push(...f.applied.map(kc)),u.push(...f.failed.map(({fix:p,error:m})=>({...kc(p),error:m instanceof Error?m.message:String(m)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((f,p)=>f.localeCompare(p)),planned_count:s.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(kc),applied_fixes:d,gated_fixes:c.map(f=>({...kc(f),gate_hint:`Withheld: re-run with --fix-scope ${f.gate} to apply.`})),failed_fixes:u}}async function fP(e,t,n={}){Kk(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new _("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",h.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new _("--fix-scope requires --auto-fix.",h.USAGE);let i=d0(e.fixScope),o=X(process.cwd(),t.path);await yt(o);let s=await te(o),a=Ot(s.schema),c=we(s,ee()),l=nZ(e),d=[],u=await eP({includeBody:["history_drift","metadata","completeness"].some(W=>l.has(W)),pmRoot:o,settings:s,typeToFolder:c.type_to_folder,warnings:d}),f=d.length>0;if(l.has("history_drift")){let W=await Xu(o);W.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${W.actionable_unknown_event_count}`)}let p=typeof e.metadataProfile=="string"?"option":"settings",m=j3(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),g=q3(m,p,s.validation.metadata_required_fields),y=F3(s),v=U3(e.dependencyCycleSeverity),E=z3(e.parentCycleSeverity),T=W3(e.scanMode),R=V3(o),C=await WZ({requestedChecks:l,options:e,global:t,pmRoot:o,workspaceRoot:R,settings:s,items:u,statusRegistry:a,metadataPolicy:g,lifecyclePatternPolicy:y,dependencyCycleSeverity:v,parentCycleSeverity:E,fileScanMode:T,initialWarnings:[...new Set(d)],sourceIncomplete:f}),F=r?await KZ(e,C,s,i,t,n):void 0,O=[...new Set(C.warnings)].sort((W,L)=>W.localeCompare(L)),Y={ok:!C.checks.some(W=>W.status==="error"),has_warnings:O.length>0,checks:C.checks,warnings:O,...F!==void 0?{fixes:F}:{},generated_at:z(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?Y:{...D3(Y),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}Mn();var sQ=4;function hP(e){let t=e.checks.find(a=>a.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,i=t?.details.missing_merge_receipt_history_reference_details,o=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,s=Array.isArray(i)?i.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:o,coordinates:s}}async function aQ(e,t){let n=[];for(let r of t){let i;try{i=await iQ(oQ.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let o=i.split(/\r?\n/)[r.history_line-1];if(o===void 0||o.trim().length===0)continue;let s;try{s=JSON.parse(o)}catch{continue}let a=rf(s,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!Xy(a)||a.eventTimestamp===void 0||He(a.eventTimestamp,Yy)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function cQ(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;let t=new Map;for(let n of e.candidates){let r=t.get(n.item_id)??[];r.push(n),t.set(n.item_id,r)}for(let[n,r]of t)await vn(n,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:r.map(i=>({receipt_id:i.receipt_id,original_history_line:i.history_line,original_event_ts:i.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function lQ(e){try{return{status:"fulfilled",value:await vn(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function dQ(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let i=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:i,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[i]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function uQ(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>Oa(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}function fQ(e,t){if(!(e===0||t))return'If receipt proof is unavailable or competing values were discarded, first review receipts.summaries and repair.streams and re-apply intended values. Only with explicit authority to accept that review, run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>". This appends an audit event; it does not restore missing evidence or discarded values.'}async function pQ(e,t){if(e.force===!0)throw new _("Automatic staging cannot accept forced reconciliation.",h.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let n={...e,stage:!1},{stageLosslessMergeReconciliation:r,resolveMergeSettlementGlobal:i}=await Promise.resolve().then(()=>(_P(),mP)),o=await i(t),s=await Pw({...n,dryRun:!0},o);return r({preview:s,dryRun:e.dryRun===!0,global:o,apply:()=>Pw({...n,dryRun:!1},o)})}async function Pw(e,t){return e.stage===!0?pQ(e,t):mQ(e,t)}async function mQ(e,t){let n=e.dryRun===!0,r=X(process.cwd(),t.path),i=await rw(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),o=hP(i),s=await aQ(r,o.coordinates),a=await Mt(r),c=a??r,l=await hn(c,{includeLossless:!0,pmRoot:r});if(l.invalid_evidence_count>0)throw new _(`Merge reconciliation refused ${l.invalid_evidence_count} invalid receipt evidence file(s).`,h.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});eu(l.receipts.map(ae=>ae.id),l,n);let d=await cQ({candidates:s,options:e,global:t}),u=l.receipts,f=await HR({cwd:a,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),p=new Set(f),m=new Map;for(let ae of u.filter(he=>!p.has(he.id))){let he=m.get(ae.item_id)??[];he.push(ae),m.set(ae.item_id,he)}let g=Object.fromEntries([...m].map(([ae,he])=>[ae,{merge:{receipts:he.map(on)}}])),y=Object.fromEntries([...m].map(([ae,he])=>[ae,{gitWorkspaceRoot:a,receipts:he}])),v=await zR({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:g,...u.length>0?{mergeReceiptProofById:y}:{}},t),E=new Set(v.streams.map(ae=>ae.id)),T=[...m.keys()].filter(ae=>!E.has(ae)),R=await _s(T,sQ,ae=>lQ({id:ae,dryRun:n,options:e,global:t,auditContext:g[ae],mergeReceiptProof:y[ae]}));dQ({receiptOnlyIds:T,results:R,repair:v});let C=await uQ({dryRun:n,pendingReceipts:u,repair:v,receiptWorkspaceRoot:c}),F=await fP({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),O=d===0?i:await rw(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),U=hP(O),Y=F.checks.every(ae=>ae.status==="ok"),W=n?u.length===0:C+f.length===u.length,L=[v.totals.failed===0,Y,W,U.count===0,!U.truncated].every(Boolean),I=o.truncated||U.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,ce=fQ(u.length,L),vt=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",I,ce,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:L?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.",I,ce,...s.length>0&&d===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(ae=>ae!==void 0);return{ok:L,dry_run:n,repair:v,receipts:{pending_before:u.length,reconciled:C,abandoned:f.length,summaries:u.map(on),unstaged_durable_receipt_ids:l.unstaged_durable_receipt_ids,missing_history_references_before:o.count,legacy_disposition_eligible:s.length,legacy_disposition_recorded:d,missing_history_references_after:U.count},validation:F,guidance:vt,generated_at:F.generated_at}}Mn();export{_S as ITEM_LATEST_TIMESTAMP_FIELDS,lS as ITEM_SCALAR_MISSING_VALUE,ph as ITEM_UNION_COLLECTION_FIELDS,Mh as MERGE_DRIVER_ARTIFACT_VALUES,AA as PM_GITATTRIBUTES_END,Ma as PM_GITATTRIBUTES_START,Wh as PM_GITATTRIBUTES_V2_END,rs as PM_GITATTRIBUTES_V2_START,$a as auditMergeAttributeFence,Da as auditMergeDriverConfiguration,_u as buildMergeAttributePatterns,fe as encodeItemScalarDecisionValue,Mt as findGitWorkspaceRoot,_n as hashItemScalarDecisionValue,hn as inspectMergeReceiptEvidence,HG as installMergeFence,Mi as isItemScalarMissingValue,zS as listMergeReceipts,Oa as markMergeReceiptReconciled,uh as mergeHistoryStreams,_h as mergeItemDocuments,hh as mergeJsonDocuments,fh as mergeRelationshipEventStreams,PA as refreshMergeAttributeFenceIfInstalled,OA as resolveMergeInstallContext,is as resolveProjectMergeTypeFolders,cG as runMergeDriver,UG as runMergeInstall,qq as runMergeReceiptEvidenceReport,Hq as runMergeReceiptReport,Pw as runMergeReconcile,on as summarizeMergeReceipt};
167
167
  //# sourceMappingURL=sdk-merge.js.map