@unbrained/pm-cli 2026.11.13 → 2026.11.15

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 (289) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +1 -1
  3. package/dist/cli/extension-command-help.js +2 -2
  4. package/dist/cli/register-mutation.js +2 -2
  5. package/dist/cli/register-operations.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/chunk-6UTBX62V.js +2 -0
  8. package/dist/cli-bundle/chunks/{chunk-GWVP23RZ.js → chunk-7AODVNHX.js} +2 -2
  9. package/dist/cli-bundle/chunks/chunk-ASGAELBQ.js +9 -0
  10. package/dist/cli-bundle/chunks/{chunk-PUU5DXSV.js → chunk-DBUBX4DL.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-5LG5YZYF.js → chunk-E4B2HWH7.js} +13 -13
  12. package/dist/cli-bundle/chunks/chunk-E74OMFBZ.js +6 -0
  13. package/dist/cli-bundle/chunks/chunk-FSE624WQ.js +2 -0
  14. package/dist/cli-bundle/chunks/chunk-FYOIH56R.js +20 -0
  15. package/dist/cli-bundle/chunks/chunk-GAFALSR2.js +8 -0
  16. package/dist/cli-bundle/chunks/{chunk-LKVFPQNY.js → chunk-GCSKHCYK.js} +2 -2
  17. package/dist/cli-bundle/chunks/chunk-HMVZSXB4.js +8 -0
  18. package/dist/cli-bundle/chunks/chunk-IXV5UM4U.js +31 -0
  19. package/dist/cli-bundle/chunks/chunk-J6L3Q5J4.js +3 -0
  20. package/dist/cli-bundle/chunks/chunk-KLWGIEDC.js +114 -0
  21. package/dist/cli-bundle/chunks/chunk-KSLPRST2.js +10 -0
  22. package/dist/cli-bundle/chunks/chunk-LC6DL446.js +3 -0
  23. package/dist/cli-bundle/chunks/{chunk-UFZQPKQS.js → chunk-NAX554KY.js} +35 -35
  24. package/dist/cli-bundle/chunks/chunk-PMIGRSNZ.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-Q6GBRK27.js +3 -0
  26. package/dist/cli-bundle/chunks/chunk-QZNDEZYI.js +2 -0
  27. package/dist/cli-bundle/chunks/chunk-S5UXBECQ.js +2 -0
  28. package/dist/cli-bundle/chunks/{chunk-UJMQP2HP.js → chunk-TESRFVGF.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-GXGMMIZN.js → chunk-VWKLTHYQ.js} +80 -70
  30. package/dist/cli-bundle/chunks/chunk-YJNY5MKP.js +2 -0
  31. package/dist/cli-bundle/chunks/chunk-YLPZE2TK.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-RSAN2YUU.js → chunk-ZVDXGAYV.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-ZWUS65LN.js +2 -0
  34. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-I6RQGD6Y.js → indexed-receipt-blobs-42Y2CSEQ.js} +2 -2
  35. package/dist/cli-bundle/chunks/item-revision-JCEDTAVX.js +2 -0
  36. package/dist/cli-bundle/chunks/item-transaction-BSMGKZ4S.js +2 -0
  37. package/dist/cli-bundle/chunks/mutation-actor-IQHBRFAJ.js +2 -0
  38. package/dist/cli-bundle/chunks/mutation-admission-DF6BFGG6.js +2 -0
  39. package/dist/cli-bundle/chunks/{register-list-query-JNJY2D3N.js → register-list-query-DNKPQB76.js} +2 -2
  40. package/dist/cli-bundle/chunks/register-mutation-WVTDFLEF.js +20 -0
  41. package/dist/cli-bundle/chunks/register-operations-NR5MTT5T.js +2 -0
  42. package/dist/cli-bundle/chunks/register-setup-2RTG3LII.js +2 -0
  43. package/dist/cli-bundle/chunks/{settlement-hook-JHXLUBEN.js → settlement-hook-W5ULPKIE.js} +2 -2
  44. package/dist/cli-bundle/chunks/stage-YFNK7U26.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-Q3OA5OAK.js → chunk-2UQFFVQK.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/chunk-52H6AELE.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/{chunk-J3LQQP3N.js → chunk-63FM3TIG.js} +7 -7
  48. package/dist/cli-bundle/focused-chunks/{chunk-VGFKTSGY.js → chunk-7GCAZJT4.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-BSY6FZ3Y.js +2 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-CZZKAGHE.js +91 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-DRBXOAGY.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-DXMQ32EH.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-EALGFJRP.js +78 -0
  54. package/dist/cli-bundle/focused-chunks/chunk-FK2X6MJY.js +44 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-IDAYTYNN.js → chunk-JE3MFEQZ.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-JR75B6HU.js → chunk-JRRHN2PZ.js} +12 -12
  57. package/dist/cli-bundle/focused-chunks/chunk-JXA77YIV.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-LQZ5F6LE.js +3 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-LSWUTTE6.js +6 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-QXOFSZR6.js +3 -0
  61. package/dist/cli-bundle/focused-chunks/chunk-RMCODWHZ.js +65 -0
  62. package/dist/cli-bundle/focused-chunks/chunk-S6GTALM4.js +24 -0
  63. package/dist/cli-bundle/focused-chunks/chunk-UPUIDGNJ.js +2 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-TVJ2PHAK.js → chunk-W2KIQ7RF.js} +3 -3
  65. package/dist/cli-bundle/focused-chunks/chunk-WGYR3X6O.js +26 -0
  66. package/dist/cli-bundle/focused-chunks/chunk-WVYXR3YX.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-ZJF6ZA7B.js → chunk-XQZKGTZV.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{chunk-4LFE3FQL.js → chunk-YTNUUEY6.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/chunk-YZUBG4W2.js +6 -0
  70. package/dist/cli-bundle/focused-chunks/chunk-Z6HCQYSW.js +8 -0
  71. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-7XGVHYAO.js → indexed-receipt-blobs-LSBWMXKS.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/item-revision-YO7YGQYE.js +2 -0
  73. package/dist/cli-bundle/focused-chunks/item-transaction-7A3Q4CAJ.js +2 -0
  74. package/dist/cli-bundle/focused-chunks/mutation-actor-UQHBNHOF.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/mutation-admission-G565NLPE.js +2 -0
  76. package/dist/cli-bundle/focused-chunks/{settlement-hook-H56537UV.js → settlement-hook-UXN76GMA.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/stage-F3YJGNRK.js +2 -0
  78. package/dist/cli-bundle/main.js +7 -7
  79. package/dist/cli-bundle/sdk-authoring.js +1 -1
  80. package/dist/cli-bundle/sdk-contracts.js +3 -3
  81. package/dist/cli-bundle/sdk-core.js +1 -1
  82. package/dist/cli-bundle/sdk-governance.js +1 -1
  83. package/dist/cli-bundle/sdk-graph.js +1 -1
  84. package/dist/cli-bundle/sdk-merge.js +57 -57
  85. package/dist/cli-bundle/sdk-query.js +1 -1
  86. package/dist/cli-bundle/sdk-runtime.js +1 -1
  87. package/dist/cli-bundle/sdk-testing.js +1 -1
  88. package/dist/cli-bundle/sdk.js +11 -11
  89. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  90. package/dist/core/extensions/extension-types.d.ts +30 -0
  91. package/dist/core/extensions/extension-types.js +1 -1
  92. package/dist/core/extensions/index.d.ts +21 -1
  93. package/dist/core/extensions/index.js +1 -1
  94. package/dist/core/extensions/mutation-actor-snapshot.js +2 -0
  95. package/dist/core/extensions/mutation-actor.js +2 -0
  96. package/dist/core/item/deferred-fields.js +2 -0
  97. package/dist/core/item/item-format-version.d.ts +8 -6
  98. package/dist/core/item/item-format-version.js +1 -1
  99. package/dist/core/item/item-format.js +2 -2
  100. package/dist/core/lock/lock.js +3 -3
  101. package/dist/core/output/linked-test-projection.js +6 -0
  102. package/dist/core/output/output.d.ts +7 -0
  103. package/dist/core/output/output.js +9 -7
  104. package/dist/core/schema/runtime-field-values.d.ts +4 -0
  105. package/dist/core/schema/runtime-field-values.js +1 -1
  106. package/dist/core/session/session-state.js +1 -1
  107. package/dist/core/shared/item-metadata-contract.js +1 -1
  108. package/dist/core/shared/text-normalization.d.ts +24 -0
  109. package/dist/core/shared/text-normalization.js +1 -1
  110. package/dist/core/shared/url-credentials.js +1 -1
  111. package/dist/core/store/item-store.js +1 -1
  112. package/dist/core/test/run-selectors.d.ts +3 -1
  113. package/dist/core/test/run-selectors.js +1 -1
  114. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  115. package/dist/sdk/annotations.js +1 -1
  116. package/dist/sdk/authoring.d.ts +1 -1
  117. package/dist/sdk/authoring.js +1 -1
  118. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  119. package/dist/sdk/cli-contracts/completeness.js +1 -1
  120. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  121. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  122. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  123. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +1 -1
  124. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  125. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +1 -1
  126. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  127. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  128. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  129. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  130. package/dist/sdk/completion/bash.js +1 -1
  131. package/dist/sdk/completion/fish.js +6 -1
  132. package/dist/sdk/completion/zsh.js +6 -1
  133. package/dist/sdk/context-intent-contracts.js +1 -1
  134. package/dist/sdk/docs.d.ts +3 -1
  135. package/dist/sdk/docs.js +1 -1
  136. package/dist/sdk/environment/project-runtime-compatibility.d.ts +8 -1
  137. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  138. package/dist/sdk/extension/command-options.d.ts +23 -4
  139. package/dist/sdk/extension/command-options.js +1 -1
  140. package/dist/sdk/extension/native-command-options.js +2 -0
  141. package/dist/sdk/files.d.ts +3 -1
  142. package/dist/sdk/files.js +1 -1
  143. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  144. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  145. package/dist/sdk/governance/health.js +1 -1
  146. package/dist/sdk/governance/lifecycle-dependency-cycles.d.ts +12 -0
  147. package/dist/sdk/governance/lifecycle-dependency-cycles.js +2 -0
  148. package/dist/sdk/governance/validate-deferred-fields.js +2 -0
  149. package/dist/sdk/governance/validate.d.ts +2 -2
  150. package/dist/sdk/governance/validate.js +1 -1
  151. package/dist/sdk/guide-topics.js +1 -1
  152. package/dist/sdk/index.d.ts +1 -1
  153. package/dist/sdk/index.js +1 -1
  154. package/dist/sdk/item-transaction.d.ts +2 -2
  155. package/dist/sdk/item-transaction.js +1 -1
  156. package/dist/sdk/lifecycle/claim.d.ts +5 -1
  157. package/dist/sdk/lifecycle/claim.js +1 -1
  158. package/dist/sdk/lifecycle/close.js +1 -1
  159. package/dist/sdk/lifecycle/copy.js +1 -1
  160. package/dist/sdk/lifecycle/create-deferrals.js +2 -0
  161. package/dist/sdk/lifecycle/create.d.ts +6 -2
  162. package/dist/sdk/lifecycle/create.js +1 -1
  163. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  164. package/dist/sdk/lifecycle/plan.js +1 -1
  165. package/dist/sdk/lifecycle/restore.js +1 -1
  166. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +7 -1
  167. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  168. package/dist/sdk/linked-artifacts.d.ts +45 -3
  169. package/dist/sdk/linked-artifacts.js +2 -2
  170. package/dist/sdk/merge/three-way.d.ts +1 -1
  171. package/dist/sdk/merge/three-way.js +2 -2
  172. package/dist/sdk/output/table-rows.d.ts +28 -4
  173. package/dist/sdk/output/table-rows.js +1 -1
  174. package/dist/sdk/output.d.ts +1 -1
  175. package/dist/sdk/output.js +1 -1
  176. package/dist/sdk/package-import-adapters.d.ts +9 -1
  177. package/dist/sdk/package-import-adapters.js +1 -1
  178. package/dist/sdk/pagination.js +1 -1
  179. package/dist/sdk/public-surface.json +1 -1
  180. package/dist/sdk/query/complete-list.d.ts +14 -5
  181. package/dist/sdk/query/complete-list.js +1 -1
  182. package/dist/sdk/query/list.js +1 -1
  183. package/dist/sdk/query/projection-contracts.d.ts +6 -0
  184. package/dist/sdk/query/projection-contracts.js +1 -1
  185. package/dist/sdk/read-output/continuation.js +1 -1
  186. package/dist/sdk/read-output/extension.js +1 -1
  187. package/dist/sdk/read-output-budget.js +1 -1
  188. package/dist/sdk/runtime-input.d.ts +6 -2
  189. package/dist/sdk/runtime-input.js +1 -1
  190. package/dist/sdk/runtime-primitives.d.ts +1 -1
  191. package/dist/sdk/runtime-primitives.js +1 -1
  192. package/dist/sdk/runtime.d.ts +2 -2
  193. package/dist/sdk/runtime.js +1 -1
  194. package/dist/sdk/structured-mutations.js +1 -1
  195. package/dist/sdk/test/batch.d.ts +5 -2
  196. package/dist/sdk/test/batch.js +2 -2
  197. package/dist/sdk/test/command-args.js +1 -1
  198. package/dist/sdk/test/entry.js +2 -2
  199. package/dist/sdk/test/execution.d.ts +10 -7
  200. package/dist/sdk/test/execution.js +2 -2
  201. package/dist/sdk/test/parsers.js +1 -1
  202. package/dist/sdk/test/prerequisites.d.ts +1 -1
  203. package/dist/sdk/test/prerequisites.js +1 -1
  204. package/dist/sdk/test/run-phases.d.ts +44 -0
  205. package/dist/sdk/test/run-phases.js +2 -0
  206. package/dist/sdk/testing.d.ts +15 -2
  207. package/dist/sdk/testing.js +1 -1
  208. package/dist/types.d.ts +11 -1
  209. package/dist/types.js +1 -1
  210. package/docs/AGENT_OUTPUT_ENCODINGS.md +16 -4
  211. package/docs/COMMANDS.md +31 -4
  212. package/docs/EXTENSIONS.md +1 -1
  213. package/docs/LINKED_TEST_EDITS.md +2 -1
  214. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +6 -3
  215. package/docs/README.md +2 -2
  216. package/docs/READ_OUTPUT_CONTRACTS.md +23 -2
  217. package/docs/SDK.md +129 -6
  218. package/docs/TESTING.md +64 -1
  219. package/docs/WORKSPACE_CONCURRENCY.md +5 -1
  220. package/docs/generated/FLAG_LEXICON_BUDGETS.md +9 -9
  221. package/marketplace.json +1 -1
  222. package/package.json +6 -4
  223. package/packages/pm-beads/package.json +1 -1
  224. package/packages/pm-calendar/extensions/calendar/command-definitions.ts +2 -0
  225. package/packages/pm-calendar/package.json +1 -1
  226. package/packages/pm-command-kit/package.json +1 -1
  227. package/packages/pm-digital-twin/package.json +1 -1
  228. package/packages/pm-governance-audit/package.json +1 -1
  229. package/packages/pm-guide-shell/package.json +1 -1
  230. package/packages/pm-kanban/package.json +1 -1
  231. package/packages/pm-lifecycle-hooks/package.json +1 -1
  232. package/packages/pm-linked-test-adapters/package.json +1 -1
  233. package/packages/pm-search-advanced/package.json +1 -1
  234. package/packages/pm-templates/package.json +1 -1
  235. package/packages/pm-todos/extensions/todos/runtime.ts +3 -0
  236. package/packages/pm-todos/package.json +1 -1
  237. package/packages/pm-vcs/package.json +1 -1
  238. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  239. package/plugins/pm-claude/package.json +1 -1
  240. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  241. package/plugins/pm-codex/package.json +1 -1
  242. package/plugins/pm-codex/plugin.json +1 -1
  243. package/runtime-dependencies.json +1 -1
  244. package/CHANGELOG.md +0 -4793
  245. package/dist/cli-bundle/chunks/chunk-36E4L2R4.js +0 -2
  246. package/dist/cli-bundle/chunks/chunk-4WD4CHVH.js +0 -8
  247. package/dist/cli-bundle/chunks/chunk-6UXBWMEM.js +0 -2
  248. package/dist/cli-bundle/chunks/chunk-CO7RWLCM.js +0 -2
  249. package/dist/cli-bundle/chunks/chunk-COTC2QOR.js +0 -6
  250. package/dist/cli-bundle/chunks/chunk-FAYX6C7H.js +0 -2
  251. package/dist/cli-bundle/chunks/chunk-GIAJX2QJ.js +0 -9
  252. package/dist/cli-bundle/chunks/chunk-HQINCDF6.js +0 -116
  253. package/dist/cli-bundle/chunks/chunk-IYDIPXBO.js +0 -2
  254. package/dist/cli-bundle/chunks/chunk-L4F4ZHGR.js +0 -2
  255. package/dist/cli-bundle/chunks/chunk-O4ZLEN4T.js +0 -3
  256. package/dist/cli-bundle/chunks/chunk-O6PBQMD7.js +0 -2
  257. package/dist/cli-bundle/chunks/chunk-O6T24Z3M.js +0 -2
  258. package/dist/cli-bundle/chunks/chunk-OQCVU2SG.js +0 -8
  259. package/dist/cli-bundle/chunks/chunk-QSSENTXG.js +0 -20
  260. package/dist/cli-bundle/chunks/chunk-TCYIGAQG.js +0 -31
  261. package/dist/cli-bundle/chunks/chunk-URWNUZQZ.js +0 -3
  262. package/dist/cli-bundle/chunks/chunk-UYARS5XF.js +0 -3
  263. package/dist/cli-bundle/chunks/item-revision-G5OVYGZ5.js +0 -2
  264. package/dist/cli-bundle/chunks/item-transaction-I2X2P4TW.js +0 -2
  265. package/dist/cli-bundle/chunks/mutation-admission-SET4KY73.js +0 -2
  266. package/dist/cli-bundle/chunks/register-mutation-WTHZHPOP.js +0 -20
  267. package/dist/cli-bundle/chunks/register-operations-EZP3EG6A.js +0 -2
  268. package/dist/cli-bundle/chunks/register-setup-THFZP23A.js +0 -2
  269. package/dist/cli-bundle/chunks/stage-JXJILTYE.js +0 -2
  270. package/dist/cli-bundle/focused-chunks/chunk-2ZPGEGTB.js +0 -2
  271. package/dist/cli-bundle/focused-chunks/chunk-3MB47JLT.js +0 -2
  272. package/dist/cli-bundle/focused-chunks/chunk-5KTOMFLR.js +0 -44
  273. package/dist/cli-bundle/focused-chunks/chunk-5NTLNE54.js +0 -26
  274. package/dist/cli-bundle/focused-chunks/chunk-ADBFVDTG.js +0 -8
  275. package/dist/cli-bundle/focused-chunks/chunk-CSKDIMQP.js +0 -2
  276. package/dist/cli-bundle/focused-chunks/chunk-FNIX62V6.js +0 -3
  277. package/dist/cli-bundle/focused-chunks/chunk-G6ERMFJ5.js +0 -3
  278. package/dist/cli-bundle/focused-chunks/chunk-IYV3IPRF.js +0 -65
  279. package/dist/cli-bundle/focused-chunks/chunk-QGQJBQCH.js +0 -2
  280. package/dist/cli-bundle/focused-chunks/chunk-RIMNSVFA.js +0 -26
  281. package/dist/cli-bundle/focused-chunks/chunk-VGJDKDKA.js +0 -2
  282. package/dist/cli-bundle/focused-chunks/chunk-VGUQ4V47.js +0 -82
  283. package/dist/cli-bundle/focused-chunks/chunk-VTOTZ5UC.js +0 -91
  284. package/dist/cli-bundle/focused-chunks/chunk-WFVZ7GGR.js +0 -2
  285. package/dist/cli-bundle/focused-chunks/chunk-ZOGEQFGH.js +0 -2
  286. package/dist/cli-bundle/focused-chunks/item-revision-IF7E7BVY.js +0 -2
  287. package/dist/cli-bundle/focused-chunks/item-transaction-5TFWIOXI.js +0 -2
  288. package/dist/cli-bundle/focused-chunks/mutation-admission-KELM46JF.js +0 -2
  289. package/dist/cli-bundle/focused-chunks/stage-UAKMQTCI.js +0 -2
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3ff209da-9855-53ee-8ae4-8c6ec7d5f964")}catch{}})();import{throwFirstItemRevisionConflict}from"../lifecycle/item-revision.js";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{applyClosureTimestampFix,scanClosureTimestamps}from"./closure-timestamps.js";import{readWorkflowCompletenessCheck}from"./workflow-completeness.js";import fs from"node:fs/promises";import{realpathSync}from"node:fs";import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{buildRemediationCommands}from"../../core/diagnostics/remediation.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{collectRegisteredItemFieldNames}from"../../core/extensions/item-fields.js";import{isFileMissingError}from"../../core/fs/fs-utils.js";import{normalizeStatusInput}from"../../core/item/status.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{resolveRuntimeStatusRegistry}from"../../core/schema/runtime-schema.js";import{DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS,DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS,EXIT_CODE,PM_DIRNAME,SETTINGS_DEFAULTS}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{toNonEmptyStringOrUndefined}from"../../core/shared/primitives.js";import{nowIso}from"../../core/shared/time.js";import{CURRENT_ITEM_FORMAT_VERSION,BASELINE_ITEM_FORMAT_VERSION,effectiveItemFormatVersion,scanItemFormatVersions}from"../../core/item/item-format-version.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{partitionFixesByGrant,planCloseReasonBackfillFixes,planEstimateBackfillFixes,planResolutionBackfillFixes,planStaleLinkPruneFixes,planTerminalParentFixes,resolveGrantedFixScopes,toFixOutputRow}from"../../core/validate/fix-planning.js";import{findDuplicateIssueCodes}from"../../core/governance/issue-codes.js";import{buildMissingByTypeCounts}from"../../core/validate/missing-by-type.js";import{classifyStaleLinkedPaths,summarizeStaleLinkedPathClassifications}from"../../core/validate/stale-file-classification.js";import{isRemoteLinkedArtifactReference}from"../../core/validate/linked-artifact-reference.js";import{assertProjectionModeChoice}from"../output-projection.js";import{collectDanglingDependencyReferences}from"../graph/assembly.js";import{auditMergeAttributeFence,auditMergeDriverConfiguration,findGitWorkspaceRoot,resolveProjectMergeTypeFolders}from"../merge/install.js";import{inspectMergeReceiptEvidence,partitionMergeReceipts}from"../merge/receipts.js";import{buildLinkedFileRepairReport}from"./linked-file-report.js";import{scanStorageIntegrity}from"./storage-integrity.js";import{scanTrackedRuntimeCache}from"./tracked-runtime-cache.js";import{scanHistoryAuthorAttribution}from"../author-attribution.js";import{createRelationshipKindRegistry}from"../relationships.js";import{runDocs}from"../docs.js";import{runFiles}from"../files.js";import{extractReferencedPmItemIdsFromCommand}from"../test/linked-command-detection.js";import{resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrustBatch}from"../test/trust.js";import{readValidateItems}from"./validate-item-reader.js";import{buildValidateHistoryDriftCheck}from"./validate-history-drift.js";import{buildLifecycleParentGraph,detectLifecycleParentCycles,resolveLifecycleDependencyCycleSamplePath}from"./hierarchy-validation.js";import{buildStatusRoleWarnings,inspectStatusRoleAssignments}from"./status-role-diagnostics.js";import{summarizeCommandPreview,normalizeRelativeDirectoryPath,normalizeRelativePath,toMeaningfulString}from"./validate-normalization.js";const FILE_SCAN_DIRECTORIES=["src","tests","docs"],FILE_SCAN_ROOT_FILES=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],DIRECTORY_IGNORE_SET=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),RESOLUTION_FIELD_KEYS=["resolution","expected_result","actual_result"],VALIDATE_FILE_SCAN_MODES=["default","tracked-all","tracked-all-strict"],VALIDATE_METADATA_PROFILE_VALUES=["core","strict","custom"],VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES=["off","warn","error"],CORE_METADATA_REQUIRED_FIELDS=["author","acceptance_criteria","estimated_minutes","close_reason"],STRICT_METADATA_REQUIRED_FIELDS=[...CORE_METADATA_REQUIRED_FIELDS,"reviewer","risk","confidence","sprint","release"],SUPPORTED_METADATA_REQUIRED_FIELDS=Array.from(new Set(STRICT_METADATA_REQUIRED_FIELDS)),METADATA_REQUIRED_FIELD_ALIASES={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"},METADATA_WARNING_TOKEN_BY_FIELD={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"},METADATA_COUNT_KEY_BY_FIELD={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"},METADATA_ITEM_IDS_KEY_BY_FIELD={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"},METADATA_TRUNCATED_KEY_BY_FIELD={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"},GIT_LS_FILES_MAX_BUFFER=32*1024*1024,GIT_LS_FILES_TIMEOUT_MS=1e4,FILE_LIST_SUMMARY_LIMIT=40,DIAGNOSTIC_LIST_SUMMARY_LIMIT=5,LINKED_ARTIFACT_MAX_PATH_LENGTH=4096,LINKED_ARTIFACT_MAX_SEGMENT_LENGTH=255,execFileAsync=promisify(execFile);function projectValidateCountsRecord(record){const projected={};for(const[key,value]of Object.entries(record))Array.isArray(value)||value===!1&&key.endsWith("_truncated")||(projected[key]=typeof value=="object"&&value!==null?projectValidateCountsRecord(value):value);return projected}function projectValidateCounts(result){return{...result,checks:result.checks.map(check=>({...check,details:projectValidateCountsRecord(check.details)})),...result.fixes?{fixes:{mode:result.fixes.mode,auto_fix:result.fixes.auto_fix,prune_missing:result.fixes.prune_missing,planned_count:result.fixes.planned_count,applied_count:result.fixes.applied_count,gated_count:result.fixes.gated_count,failed_count:result.fixes.failed_count}}:{}}}function normalizeStatusForRegistry(status,statusRegistry){return normalizeStatusInput(status,statusRegistry)??status}function isTerminalStatus(status,statusRegistry){return statusRegistry.terminal_statuses.has(normalizeStatusForRegistry(status,statusRegistry))}function normalizeLifecyclePatternList(values){return[...new Set((values??[]).map(value=>value.trim().toLowerCase()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right))}function areSortedStringListsEqual(left,right){return left.length!==right.length?!1:left.every((value,index)=>value===right[index])}function resolveLifecyclePatternPolicy(settings){const defaultStalePatterns=normalizeLifecyclePatternList(DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS),defaultClosureLikePatterns={blocked_reason:normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.blocked_reason),resolution:normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.resolution),actual_result:normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.actual_result)},staleBlockerReasonPatterns=normalizeLifecyclePatternList(settings.validation.lifecycle_stale_blocker_reason_patterns),closureLikePatterns={blocked_reason:normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_resolution_patterns),actual_result:normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:staleBlockerReasonPatterns,stale_blocker_reason_pattern_source:areSortedStringListsEqual(staleBlockerReasonPatterns,defaultStalePatterns)?"default":"settings",closure_like_metadata_field_patterns:closureLikePatterns,closure_like_metadata_field_pattern_sources:{blocked_reason:areSortedStringListsEqual(closureLikePatterns.blocked_reason,defaultClosureLikePatterns.blocked_reason)?"default":"settings",resolution:areSortedStringListsEqual(closureLikePatterns.resolution,defaultClosureLikePatterns.resolution)?"default":"settings",actual_result:areSortedStringListsEqual(closureLikePatterns.actual_result,defaultClosureLikePatterns.actual_result)?"default":"settings"}}}function resolveValidateMetadataProfile(value){const normalized=value?.trim().toLowerCase();if(!normalized||normalized.length===0)return"core";if(VALIDATE_METADATA_PROFILE_VALUES.includes(normalized))return normalized;throw new PmCliError(`Unknown --metadata-profile value "${value}". Supported values: ${VALIDATE_METADATA_PROFILE_VALUES.join(", ")}.`,EXIT_CODE.USAGE)}function resolveDependencyCycleSeverity(value){const normalized=value?.trim().toLowerCase();if(!normalized||normalized.length===0)return"warn";if(VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES.includes(normalized))return normalized;throw new PmCliError(`Unknown --dependency-cycle-severity value "${value}". Supported values: ${VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES.join(", ")}.`,EXIT_CODE.USAGE)}function resolveParentCycleSeverity(value){const normalized=value?.trim().toLowerCase();if(!normalized||normalized.length===0)return"warn";if(VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES.includes(normalized))return normalized;throw new PmCliError(`Unknown --parent-cycle-severity value "${value}". Supported values: ${VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES.join(", ")}.`,EXIT_CODE.USAGE)}function normalizeMetadataRequiredFieldsFromSettings(values){return[...new Set((values??[]).map(value=>value.trim().toLowerCase().replaceAll("-","_")))].map(value=>METADATA_REQUIRED_FIELD_ALIASES[value]).filter(value=>value!==void 0).sort((left,right)=>left.localeCompare(right))}function resolveValidateMetadataPolicy(profile,profileSource,configuredCustomFields){const normalizedCustomFields=normalizeMetadataRequiredFieldsFromSettings(configuredCustomFields);return profile==="core"?{profile,profile_source:profileSource,required_fields:[...CORE_METADATA_REQUIRED_FIELDS],configured_custom_fields:normalizedCustomFields,fallback_to_core:!1,warnings:[]}:profile==="strict"?{profile,profile_source:profileSource,required_fields:[...STRICT_METADATA_REQUIRED_FIELDS],configured_custom_fields:normalizedCustomFields,fallback_to_core:!1,warnings:[]}:normalizedCustomFields.length>0?{profile,profile_source:profileSource,required_fields:normalizedCustomFields,configured_custom_fields:normalizedCustomFields,fallback_to_core:!1,warnings:[]}:{profile,profile_source:profileSource,required_fields:[...CORE_METADATA_REQUIRED_FIELDS],configured_custom_fields:normalizedCustomFields,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}const TERMINAL_EXEMPT_PLANNING_FIELDS=new Set(["acceptance_criteria","estimated_minutes"]);function isMetadataFieldMissing(item,field,statusRegistry,enforcePlanningFieldsOnTerminal){return!enforcePlanningFieldsOnTerminal&&TERMINAL_EXEMPT_PLANNING_FIELDS.has(field)&&isTerminalStatus(item.status,statusRegistry)?!1:field==="author"?!toNonEmptyStringOrUndefined(item.author):field==="acceptance_criteria"?!toNonEmptyStringOrUndefined(item.acceptance_criteria):field==="estimated_minutes"?!Number.isFinite(item.estimated_minutes):field==="close_reason"?normalizeStatusForRegistry(item.status,statusRegistry)===statusRegistry.close_status&&!toNonEmptyStringOrUndefined(item.close_reason):field==="reviewer"?!toNonEmptyStringOrUndefined(item.reviewer):field==="risk"?!toNonEmptyStringOrUndefined(item.risk):field==="confidence"?typeof item.confidence=="number"?!Number.isFinite(item.confidence):!toNonEmptyStringOrUndefined(item.confidence):field==="sprint"?!toNonEmptyStringOrUndefined(item.sprint):!toNonEmptyStringOrUndefined(item.release)}function resolveFileScanMode(scanMode){if(scanMode===void 0)return"default";const normalized=scanMode.trim().toLowerCase();if(normalized.length===0||normalized==="default")return"default";if(normalized==="tracked-all"||normalized==="tracked_all")return"tracked-all";if(normalized==="tracked-all-strict"||normalized==="tracked_all_strict")return"tracked-all-strict";throw new PmCliError(`Unknown --scan-mode value "${scanMode}". Supported values: ${VALIDATE_FILE_SCAN_MODES.join(", ")}.`,EXIT_CODE.USAGE)}function resolveWorkspaceRoot(pmRoot){const sourceWorkspaceRoot=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(sourceWorkspaceRoot)return path.resolve(sourceWorkspaceRoot);const resolvedPmRoot=path.resolve(pmRoot);if(resolvedPmRoot.replaceAll("\\","/").endsWith("/.agents/pm"))return path.dirname(path.dirname(resolvedPmRoot));const resolvedCwd=path.resolve(process.cwd()),canonicalPmRoot=realpathForWorkspaceRoot(resolvedPmRoot),canonicalCwd=realpathForWorkspaceRoot(resolvedCwd),relativeFromPmRoot=path.relative(canonicalPmRoot,canonicalCwd);return relativeFromPmRoot.length===0||!relativeFromPmRoot.startsWith("..")&&!path.isAbsolute(relativeFromPmRoot)?resolvedPmRoot:resolvedCwd}function realpathForWorkspaceRoot(inputPath){try{return realpathSync.native(inputPath)}catch{return path.resolve(inputPath)}}function hasFilesystemErrorCode(error,acceptedCodes){return typeof error=="object"&&error!==null&&"code"in error&&typeof error.code=="string"&&acceptedCodes.includes(error.code)}async function listFilesRecursive(basePath,relativePath,output){const targetDirectory=relativePath.length>0?path.join(basePath,relativePath):basePath;let entries;try{entries=await fs.readdir(targetDirectory,{withFileTypes:!0})}catch(error){if(isFileMissingError(error))return;throw error}for(const entry of entries){if(entry.name.startsWith("."))continue;const childRelative=relativePath.length>0?path.join(relativePath,entry.name):entry.name;if(entry.isDirectory()){if(DIRECTORY_IGNORE_SET.has(entry.name))continue;await listFilesRecursive(basePath,childRelative,output);continue}entry.isFile()&&output.push(normalizeRelativePath(childRelative))}}async function collectDefaultProjectFileCandidates(workspaceRoot){const discovered=[];for(const directory of FILE_SCAN_DIRECTORIES)await listFilesRecursive(workspaceRoot,directory,discovered);for(const candidate of FILE_SCAN_ROOT_FILES){const absolute=path.join(workspaceRoot,candidate);try{(await fs.stat(absolute)).isFile()&&discovered.push(normalizeRelativePath(candidate))}catch{}}return[...new Set(discovered)].sort((left,right)=>left.localeCompare(right))}async function collectTrackedGitFileCandidates(workspaceRoot){try{const{stdout}=await execFileAsync("git",["ls-files","-z"],{cwd:workspaceRoot,encoding:"utf8",maxBuffer:GIT_LS_FILES_MAX_BUFFER,windowsHide:!0,timeout:GIT_LS_FILES_TIMEOUT_MS}),discovered=stdout.split("\0").map(value=>normalizeRelativePath(value)).filter(value=>value.length>0);return[...new Set(discovered)].sort((left,right)=>left.localeCompare(right))}catch{return null}}function resolvePmInternalCandidatePrefixes(pmRoot,workspaceRoot){const prefixes=new Set,configuredDefault=normalizeRelativeDirectoryPath(PM_DIRNAME);configuredDefault.length>0&&prefixes.add(configuredDefault);const relativePmRoot=normalizeRelativeDirectoryPath(path.relative(workspaceRoot,pmRoot));return relativePmRoot.length>0&&!relativePmRoot.startsWith("..")&&prefixes.add(relativePmRoot),[...prefixes].sort((left,right)=>left.localeCompare(right))}function hasPathPrefix(candidate,prefixes){for(const prefix of prefixes)if(candidate===prefix||candidate.startsWith(`${prefix}/`))return!0;return!1}async function collectProjectFileCandidates(workspaceRoot,scanMode){if(scanMode==="tracked-all"||scanMode==="tracked-all-strict"){const trackedCandidates=await collectTrackedGitFileCandidates(workspaceRoot);if(trackedCandidates)return{requestedMode:scanMode,appliedMode:scanMode,source:"tracked-git",candidateFiles:trackedCandidates,candidateTotal:trackedCandidates.length,candidateScanned:trackedCandidates.length};const fallbackCandidates=await collectDefaultProjectFileCandidates(workspaceRoot);return{requestedMode:scanMode,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:fallbackCandidates,candidateTotal:fallbackCandidates.length,candidateScanned:fallbackCandidates.length}}const defaultCandidates=await collectDefaultProjectFileCandidates(workspaceRoot);return{requestedMode:scanMode,appliedMode:"default",source:"default-curated",candidateFiles:defaultCandidates,candidateTotal:defaultCandidates.length,candidateScanned:defaultCandidates.length}}function summarizeList(values,limit=DIAGNOSTIC_LIST_SUMMARY_LIMIT){return values.length<=limit?{values,truncated:!1}:{values:values.slice(0,limit),truncated:!0}}function summarizeFileList(values,verboseFileLists){if(verboseFileLists)return{values,truncated:!1,total:values.length};const summary=summarizeList(values,FILE_LIST_SUMMARY_LIMIT);return{values:summary.values,truncated:summary.truncated,total:values.length}}const RESOLUTION_REMEDIATION_FLAG_BY_FIELD={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},RESOLUTION_REMEDIATION_PLACEHOLDER_BY_FIELD={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function buildResolutionRemediationCommand(row){const fieldArguments=row.missing_fields.map(field=>`${RESOLUTION_REMEDIATION_FLAG_BY_FIELD[field]} "${RESOLUTION_REMEDIATION_PLACEHOLDER_BY_FIELD[field]}"`).join(" ");return`pm update ${row.id} ${fieldArguments} --message "Backfill resolution metadata"`}function attachValidateFixHints(check,checkWarnings){const existingResolutionHints=check.details?.missing_resolution_remediation_hints,aliasedResolution=Array.isArray(existingResolutionHints)&&existingResolutionHints.length>0,fixHints=aliasedResolution?existingResolutionHints.filter(hint=>typeof hint=="string"):buildRemediationCommands(checkWarnings);if(fixHints.length===0)return;const truncated=aliasedResolution&&check.details?.missing_resolution_remediation_hints_truncated===!0;check.details={...check.details,fix_hints:fixHints,...truncated?{fix_hints_truncated:!0}:{}}}function resolveRequestedChecks(options){const requested=new Set;return options.checkCompleteness&&requested.add("completeness"),options.checkMetadata&&requested.add("metadata"),options.checkResolution&&requested.add("resolution"),(options.checkLifecycle||options.checkStaleBlockers)&&requested.add("lifecycle"),options.checkFiles&&requested.add("files"),options.checkHistoryDrift&&requested.add("history_drift"),options.checkCommandReferences&&requested.add("command_references"),options.checkStorageIntegrity&&requested.add("storage_integrity"),requested.size===0?(options.autoFix&&(requested.add("metadata"),requested.add("resolution"),requested.add("lifecycle")),options.pruneMissing&&requested.add("files"),requested.size===0&&(requested.add("metadata"),requested.add("resolution"),requested.add("lifecycle"),requested.add("files"),requested.add("command_references"),requested.add("history_drift"),requested.add("format_version"),requested.add("completeness"),requested.add("storage_integrity")),requested):(options.pruneMissing&&requested.add("files"),requested)}const DUPLICATE_ISSUE_CODE_WARNING_TOKEN="validate_metadata_duplicate_issue_codes";function summarizeDuplicateIssueCodes(duplicates,verboseDiagnostics){if(duplicates.length===0)return{rows:[],truncated:!1,warnings:[]};const limit=verboseDiagnostics?duplicates.length:DIAGNOSTIC_LIST_SUMMARY_LIMIT,shown=duplicates.slice(0,limit);return{rows:shown.map(duplicate=>({code:duplicate.code,count:duplicate.count,ids:duplicate.ids,titles:duplicate.titles,remediation_hint:`Items ${duplicate.ids.join(", ")} share issue code "${duplicate.code}"; rename or merge so each logical code maps to one item.`})),truncated:shown.length<duplicates.length,warnings:[`${DUPLICATE_ISSUE_CODE_WARNING_TOKEN}:${duplicates.length}`]}}function collectMissingMetadataByField(items,statusRegistry,enforcePlanningFieldsOnTerminal){const missingByField=Object.fromEntries(SUPPORTED_METADATA_REQUIRED_FIELDS.map(field=>[field,[]]));for(const item of items)for(const field of SUPPORTED_METADATA_REQUIRED_FIELDS)isMetadataFieldMissing(item,field,statusRegistry,enforcePlanningFieldsOnTerminal)&&missingByField[field].push(item.id);return missingByField}function buildMetadataWarningTokens(metadataPolicy,missingByField,duplicateWarnings){const warningTokens=[...metadataPolicy.warnings];for(const field of metadataPolicy.required_fields){const missingItems=missingByField[field];missingItems.length>0&&warningTokens.push(`${METADATA_WARNING_TOKEN_BY_FIELD[field]}:${missingItems.length}`)}return warningTokens.push(...duplicateWarnings),warningTokens}function buildMetadataCounts(metadataPolicy,missingByField){const counts={};for(const field of metadataPolicy.required_fields){const missing=missingByField[field],value=missing?missing.length:0,countKey=METADATA_COUNT_KEY_BY_FIELD[field];counts[countKey]=value}return counts}function buildMissingFieldOccurrences(metadataPolicy,missingByField,itemsById){const occurrences=[];for(const field of metadataPolicy.required_fields){const missing=missingByField[field];if(missing)for(const itemId of missing){const itemType=itemsById.get(itemId)?.type,normalizedItemType=typeof itemType=="string"&&itemType.length>0?itemType:"Unknown";occurrences.push({item_type:normalizedItemType,field})}}return occurrences}function attachMissingMetadataItemIds(details,metadataPolicy,missingByField,verboseDiagnostics){for(const field of metadataPolicy.required_fields){const missing=missingByField[field];if(!missing||missing.length===0)continue;const idsKey=METADATA_ITEM_IDS_KEY_BY_FIELD[field],truncatedKey=METADATA_TRUNCATED_KEY_BY_FIELD[field];if(!idsKey||!truncatedKey)continue;const summarized=summarizeList(missing,verboseDiagnostics?missing.length:DIAGNOSTIC_LIST_SUMMARY_LIMIT);details[idsKey]=summarized.values,details[truncatedKey]=summarized.truncated}}function buildCloseReasonBackfillRows(metadataPolicy,missingByField,itemsById){if(!metadataPolicy.required_fields.includes("close_reason"))return[];const missing=missingByField.close_reason;return missing?missing.map(itemId=>({id:itemId,resolution:toNonEmptyStringOrUndefined(itemsById.get(itemId)?.resolution)})):[]}function buildEstimateBackfillRows(metadataPolicy,missingByField,itemsById){if(!metadataPolicy.required_fields.includes("estimated_minutes"))return[];const missing=missingByField.estimated_minutes;return missing?missing.map(itemId=>({id:itemId,type:toNonEmptyStringOrUndefined(itemsById.get(itemId)?.type)})):[]}function buildMetadataCheck(items,metadataPolicy,statusRegistry,verboseDiagnostics,configuredIssueCodePrefixes){const itemsById=new Map(items.map(item=>[item.id,item])),enforcePlanningFieldsOnTerminal=metadataPolicy.profile==="strict",missingByField=collectMissingMetadataByField(items,statusRegistry,enforcePlanningFieldsOnTerminal),duplicateIssueCodes=findDuplicateIssueCodes(items,{configuredPrefixes:configuredIssueCodePrefixes}),duplicateIssueCodeSummary=summarizeDuplicateIssueCodes(duplicateIssueCodes,verboseDiagnostics),warningTokens=buildMetadataWarningTokens(metadataPolicy,missingByField,duplicateIssueCodeSummary.warnings),counts=buildMetadataCounts(metadataPolicy,missingByField),missingFieldOccurrences=buildMissingFieldOccurrences(metadataPolicy,missingByField,itemsById),missingByType=buildMissingByTypeCounts(missingFieldOccurrences),details={checked_items:items.length,metadata_profile:metadataPolicy.profile,metadata_profile_source:metadataPolicy.profile_source,metadata_profile_fallback_to_core:metadataPolicy.fallback_to_core,required_fields:[...metadataPolicy.required_fields],supported_required_fields:[...SUPPORTED_METADATA_REQUIRED_FIELDS],counts,missing_by_type:missingByType,duplicate_issue_codes_count:duplicateIssueCodes.length,duplicate_issue_codes:duplicateIssueCodeSummary.rows,duplicate_issue_codes_truncated:duplicateIssueCodeSummary.truncated};metadataPolicy.configured_custom_fields.length>0&&(details.configured_custom_required_fields=[...metadataPolicy.configured_custom_fields]),attachMissingMetadataItemIds(details,metadataPolicy,missingByField,verboseDiagnostics);const closeReasonBackfillRows=buildCloseReasonBackfillRows(metadataPolicy,missingByField,itemsById),estimateBackfillRows=buildEstimateBackfillRows(metadataPolicy,missingByField,itemsById);return{check:{name:"metadata",status:warningTokens.length===0?"ok":"warn",ok:warningTokens.length===0,details},warnings:warningTokens,closeReasonBackfillRows,estimateBackfillRows}}function buildResolutionCheck(items,statusRegistry,verboseDiagnostics){const terminalDoneStatuses=new Set(statusRegistry.terminal_done_statuses);terminalDoneStatuses.add(statusRegistry.close_status);const closedItems=items.filter(item=>terminalDoneStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),missingResolutionRows=[],resolutionBackfillRows=[];for(const item of closedItems){const missingFields=RESOLUTION_FIELD_KEYS.filter(field=>!toNonEmptyStringOrUndefined(item[field]));missingFields.length!==0&&(missingResolutionRows.push({id:item.id,missing_fields:missingFields}),resolutionBackfillRows.push({id:item.id,missing_fields:missingFields,close_reason:toNonEmptyStringOrUndefined(item.close_reason)}))}const warnings=missingResolutionRows.length>0?[`validate_resolution_missing_fields:${missingResolutionRows.length}`]:[],diagnosticLimit=verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT,summarizedRows=summarizeList(missingResolutionRows.map(row=>`${row.id}:${row.missing_fields.join(",")}`),diagnosticLimit),remediationHints=missingResolutionRows.map(row=>buildResolutionRemediationCommand(row)),summarizedHints=summarizeList(remediationHints,diagnosticLimit);return{check:{name:"resolution",status:warnings.length===0?"ok":"warn",ok:warnings.length===0,details:{checked_closed_items:closedItems.length,missing_resolution_items:missingResolutionRows.length,missing_resolution_rows:summarizedRows.values,missing_resolution_rows_truncated:summarizedRows.truncated,missing_resolution_remediation_hints:summarizedHints.values,missing_resolution_remediation_hints_truncated:summarizedHints.truncated}},warnings,resolutionBackfillRows}}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildLifecycleDependencyGraph(activeItems,idPrefix="pm",relationshipRegistry=createRelationshipKindRegistry()){const activeItemIds=new Set(activeItems.map(item=>item.id)),sortedItems=[...activeItems].sort((left,right)=>left.id.localeCompare(right.id));return new Map(sortedItems.map(item=>{const edges=new Set,blockedBy=toMeaningfulString(item.blocked_by);blockedBy&&activeItemIds.has(blockedBy)&&edges.add(blockedBy),(item.dependencies??[]).filter(dependency=>{const dependencyKind=toMeaningfulString(dependency.kind);return dependencyKind!==void 0&&relationshipRegistry.resolve(dependencyKind)?.ordering===!0}).map(dependency=>toMeaningfulString(dependency.id)).filter(dependencyId=>dependencyId!==void 0&&activeItemIds.has(dependencyId)).forEach(dependencyId=>edges.add(dependencyId));const definitionOfReady=toMeaningfulString(item.definition_of_ready);return extractItemIds(definitionOfReady??"",idPrefix).filter(referencedId=>activeItemIds.has(referencedId)).forEach(referencedId=>edges.add(referencedId)),[item.id,[...edges].sort((left,right)=>left.localeCompare(right))]}))}function buildDependencyReferencesCheck(items,verboseDiagnostics,statusRegistry){const classified=collectDanglingDependencyReferences(items,statusRegistry?status=>isTerminalStatus(status,statusRegistry):void 0),activeRows=classified.active.map(row=>`${row.holder_id}:${row.target_id}:${row.kind}`),legacyRows=classified.legacy_terminal.map(row=>`${row.holder_id}:${row.target_id}:${row.kind}:${row.holder_status}`),diagnosticLimit=verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT,summarizedRows=summarizeList(activeRows,diagnosticLimit),summarizedLegacyRows=summarizeList(legacyRows,diagnosticLimit),hints=summarizeList(classified.active.map(row=>row.source==="parent"?`pm update ${row.holder_id} --unset parent`:row.source==="blocked_by"?`pm update ${row.holder_id} --unset blocked_by`:`pm update ${row.holder_id} --replace-deps '<correct dependency edges>'`),diagnosticLimit);return{check:{name:"dependency_references",status:activeRows.length===0?"ok":"warn",ok:activeRows.length===0,details:{checked_items:items.length,dangling_reference_count:activeRows.length+legacyRows.length,active_dangling_reference_count:activeRows.length,dangling_reference_rows:summarizedRows.values,dangling_reference_rows_truncated:summarizedRows.truncated,legacy_terminal_dangling_reference_count:legacyRows.length,legacy_closed_dangling_reference_count:classified.legacy_terminal.filter(row=>row.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:summarizedLegacyRows.values,legacy_terminal_dangling_reference_rows_truncated:summarizedLegacyRows.truncated,no_active_blocker_sentinel_count:classified.no_active_blocker_sentinels.length,remediation_hints:hints.values,remediation_hints_truncated:hints.truncated}},warnings:activeRows.length>0?[`validate_dangling_dependency_references:${activeRows.length}`]:[]}}function extractItemIds(value,idPrefix="pm"){const normalizedPrefix=(idPrefix.trim().toLowerCase()||"pm").replace(/-+$/g,""),pattern=new RegExp(`(?:^|[^a-z0-9-])(${escapeRegExp(normalizedPrefix)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...value.matchAll(pattern)].map(match=>match[1].toLowerCase()))].sort((left,right)=>left.localeCompare(right))}function findLifecycleDependencyCycleComponents(graph){let nextIndex=0;const indexById=new Map,lowLinkById=new Map,stack=[],inStack=new Set,components=[],visit=id=>{indexById.set(id,nextIndex),lowLinkById.set(id,nextIndex),nextIndex+=1,stack.push(id),inStack.add(id);for(const dependencyId of graph.get(id)??[])indexById.has(dependencyId)?inStack.has(dependencyId)&&lowLinkById.set(id,Math.min(lowLinkById.get(id),indexById.get(dependencyId))):(visit(dependencyId),lowLinkById.set(id,Math.min(lowLinkById.get(id),lowLinkById.get(dependencyId))));if(lowLinkById.get(id)!==indexById.get(id))return;const component=[];for(;stack.length>0;){const member=stack.pop();if(inStack.delete(member),component.push(member),member===id)break}component.sort((left,right)=>left.localeCompare(right)),components.push(component)},sortedNodeIds=[...graph.keys()].sort((left,right)=>left.localeCompare(right));for(const id of sortedNodeIds)indexById.has(id)||visit(id);return components.filter(component=>{if(component.length>1)return!0;const selfId=component[0];return(graph.get(selfId)??[]).includes(selfId)}).sort((left,right)=>left[0].localeCompare(right[0])||left.length-right.length||left.join(",").localeCompare(right.join(",")))}function detectLifecycleDependencyCycles(activeItems,idPrefix="pm"){const graph=buildLifecycleDependencyGraph(activeItems,idPrefix),cycleComponents=findLifecycleDependencyCycleComponents(graph),cycleItemIds=[...new Set(cycleComponents.flat())].sort((left,right)=>left.localeCompare(right)),cycleSamplePaths=cycleComponents.map(component=>resolveLifecycleDependencyCycleSamplePath(component,graph).join("->"));return{cycle_count:cycleComponents.length,cycle_item_ids:cycleItemIds,cycle_sample_paths:cycleSamplePaths}}function classifyOrphanedPath(pathValue){return pathValue.startsWith("docs/")?"docs_unowned":pathValue.startsWith("tests/")?"tests_unowned":pathValue.startsWith("src/")?"source_unowned":pathValue.endsWith(".md")?"docs_unowned":"unlinked_existing"}function directoryOf(relativePath){const slash=relativePath.lastIndexOf("/");return slash===-1?"":relativePath.slice(0,slash)}function sharedDirectoryPrefixLength(left,right){const leftParts=directoryOf(left).split("/").filter(Boolean),rightParts=directoryOf(right).split("/").filter(Boolean);let count=0;for(;count<leftParts.length&&count<rightParts.length&&leftParts[count]===rightParts[count];)count+=1;return count}function scoreOrphanOwnerCandidate(pathValue,linkedPath){const linkedDir=directoryOf(linkedPath),orphanDir=directoryOf(pathValue),directoryPrefix=linkedPath.endsWith("/")?linkedPath:`${linkedPath}/`,isDirectoryPrefix=pathValue.startsWith(directoryPrefix),sameDirectory=linkedDir.length>0&&linkedDir===orphanDir,sharedPrefixLength=sharedDirectoryPrefixLength(pathValue,linkedPath);return!isDirectoryPrefix&&!sameDirectory&&sharedPrefixLength===0?null:isDirectoryPrefix?{score:linkedPath.length+1e3,confidence:"path_prefix"}:sameDirectory?{score:sharedPrefixLength+500,confidence:"same_directory"}:{score:sharedPrefixLength,confidence:"shared_directory"}}function shouldReplaceOrphanOwnerCandidate(best,item,score){return best===void 0||score>best.score||score===best.score&&item.id.localeCompare(best.item.id)<0}function findOrphanOwnerCandidate(pathValue,classification,items){const linkKind=classification==="docs_unowned"?"docs":"files";let best;return items.flatMap(item=>(linkKind==="docs"?item.docs??[]:item.files??[]).map(link=>({item,link}))).forEach(({item,link})=>{if(link.scope!=="project")return;const linkedPath=normalizeRelativePath(link.path);if(linkedPath.length===0||linkedPath===pathValue)return;const scored=scoreOrphanOwnerCandidate(pathValue,linkedPath);scored!==null&&shouldReplaceOrphanOwnerCandidate(best,item,scored.score)&&(best={item,score:scored.score,confidence:scored.confidence})}),best?{id:best.item.id,type:best.item.type,title:best.item.title,status:best.item.status,confidence:best.confidence}:null}function buildOrphanedPathRows(orphanedFiles,items){return orphanedFiles.map(pathValue=>{const classification=classifyOrphanedPath(pathValue),linkCommand=classification==="docs_unowned"?"docs":"files",ownerCandidate=findOrphanOwnerCandidate(pathValue,classification,items),target=ownerCandidate?.id??"<id>";return{path:pathValue,classification,owner_candidate:ownerCandidate,remediation_hint:`pm ${linkCommand} ${target} --add path=${pathValue},scope=project,note="<why this artifact belongs to the item>"`}})}function summarizeOrphanedPathRows(rows){return rows.map(row=>`${row.path}:${row.classification} owner_candidate=${row.owner_candidate?.id??"unowned"} hint=${JSON.stringify(row.remediation_hint)}`)}function closureLikeFieldsForItem(item,lifecyclePatternPolicy){return Object.entries(lifecyclePatternPolicy.closure_like_metadata_field_patterns).filter(([field,patterns])=>{const value=toMeaningfulString(item[field]);return value?patterns.some(pattern=>value.toLowerCase().includes(pattern)):!1}).map(([field])=>field).sort((left,right)=>left.localeCompare(right))}function buildTerminalParentFixRow(item,parent,itemsById,canonicalIdByLowercase,statusRegistry){const grandparentId=toMeaningfulString(parent.parent),grandparent=grandparentId?itemsById.get(canonicalIdByLowercase.get(grandparentId.toLowerCase())??grandparentId):void 0;return{id:item.id,parent_id:parent.id,grandparent_id:grandparent?.id,grandparent_active:grandparent!==void 0&&!isTerminalStatus(grandparent.status,statusRegistry)}}function staleBlockerReasonsForItem(item,blockedStatuses,statusRegistry,lifecyclePatternPolicy){const blockedBy=toMeaningfulString(item.blocked_by),blockedReason=toMeaningfulString(item.blocked_reason),blockedReasonNormalized=blockedReason?.toLowerCase(),normalizedStatus=normalizeStatusForRegistry(item.status,statusRegistry),reasons=[];return blockedStatuses.has(normalizedStatus)?(!blockedBy&&!blockedReason&&reasons.push("blocked_status_missing_blocker_context"),blockedReasonNormalized?.includes("no active blocker")&&reasons.push("blocked_status_reason_reports_no_active_blocker"),blockedReasonNormalized&&lifecyclePatternPolicy.stale_blocker_reason_patterns.some(pattern=>blockedReasonNormalized.includes(pattern))&&reasons.push("blocked_status_reason_matches_stale_pattern"),reasons):(blockedBy&&reasons.push("non_blocked_status_has_blocked_by"),blockedReason&&reasons.push("non_blocked_status_has_blocked_reason"),reasons)}function collectLifecycleScanRows(items,includeStaleBlockers,statusRegistry,lifecyclePatternPolicy){const itemsById=new Map(items.map(item=>[item.id,item])),canonicalIdByLowercase=new Map(items.map(item=>[item.id.toLowerCase(),item.id])),blockedStatuses=statusRegistry.blocked_statuses.size>0?statusRegistry.blocked_statuses:new Set(["blocked"]),rows={activeItems:items.filter(item=>!isTerminalStatus(item.status,statusRegistry)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(const item of rows.activeItems){const closureLikeFields=closureLikeFieldsForItem(item,lifecyclePatternPolicy);closureLikeFields.length>0&&rows.closureLikeRows.push({id:item.id,fields:closureLikeFields});const parentId=toMeaningfulString(item.parent),parent=parentId?itemsById.get(canonicalIdByLowercase.get(parentId.toLowerCase())??parentId):void 0;if(parent&&isTerminalStatus(parent.status,statusRegistry)&&(rows.terminalParentRows.push({id:item.id,parent_id:parent.id,parent_status:parent.status}),rows.terminalParentFixRows.push(buildTerminalParentFixRow(item,parent,itemsById,canonicalIdByLowercase,statusRegistry))),includeStaleBlockers){const reasons=staleBlockerReasonsForItem(item,blockedStatuses,statusRegistry,lifecyclePatternPolicy);reasons.length>0&&rows.staleBlockerRows.push({id:item.id,status:item.status,reasons:[...new Set(reasons)].sort((left,right)=>left.localeCompare(right))})}}return rows}function sortLifecycleScanRows(rows){rows.closureLikeRows.sort((left,right)=>left.id.localeCompare(right.id)),rows.terminalParentRows.sort((left,right)=>left.id.localeCompare(right.id)||left.parent_id.localeCompare(right.parent_id)),rows.terminalParentFixRows.sort((left,right)=>left.id.localeCompare(right.id)||left.parent_id.localeCompare(right.parent_id)),rows.staleBlockerRows.sort((left,right)=>left.id.localeCompare(right.id))}function lifecycleCycleWarningToken(prefix,severity,count){return count<=0||severity==="off"?null:`${severity==="error"?`${prefix}_error`:prefix}:${count}`}function lifecycleAdvisoryWarningToken(prefix,severity,count){return count>0&&severity!=="off"?`${prefix}:${count}`:null}function buildLifecycleWarnings(rows,includeStaleBlockers,dependencyCycleSeverity,parentCycleSeverity,counts){const warnings=[];rows.closureLikeRows.length>0&&warnings.push(`validate_lifecycle_active_closure_like_metadata:${rows.closureLikeRows.length}`),rows.terminalParentRows.length>0&&warnings.push(`validate_lifecycle_active_terminal_parent:${rows.terminalParentRows.length}`),includeStaleBlockers&&rows.staleBlockerRows.length>0&&warnings.push(`validate_lifecycle_stale_blockers:${rows.staleBlockerRows.length}`);const dependencyWarning=lifecycleCycleWarningToken("validate_lifecycle_dependency_cycles",dependencyCycleSeverity,counts.dependencyCycles),parentWarning=lifecycleCycleWarningToken("validate_hierarchy_parent_cycle",parentCycleSeverity,counts.activeHierarchyCycles),cardinalityWarning=lifecycleCycleWarningToken("validate_hierarchy_cardinality_violation",parentCycleSeverity,counts.activeHierarchyCardinality),divergenceWarning=lifecycleCycleWarningToken("validate_hierarchy_parent_divergence",parentCycleSeverity,counts.activeHierarchyDivergence),legacyCycleWarning=lifecycleAdvisoryWarningToken("validate_legacy_hierarchy_parent_cycle",parentCycleSeverity,counts.legacyHierarchyCycles),legacyCardinalityWarning=lifecycleAdvisoryWarningToken("validate_legacy_hierarchy_cardinality_violation",parentCycleSeverity,counts.legacyHierarchyCardinality),legacyDivergenceWarning=lifecycleAdvisoryWarningToken("validate_legacy_hierarchy_parent_divergence",parentCycleSeverity,counts.legacyHierarchyDivergence);return[...warnings,...dependencyWarning?[dependencyWarning]:[],...parentWarning?[parentWarning]:[],...cardinalityWarning?[cardinalityWarning]:[],...divergenceWarning?[divergenceWarning]:[],...legacyCycleWarning?[legacyCycleWarning]:[],...legacyCardinalityWarning?[legacyCardinalityWarning]:[],...legacyDivergenceWarning?[legacyDivergenceWarning]:[]]}function linkedArtifactPathExceedsFilesystemLimits(artifactPath){const normalized=normalizeRelativePath(artifactPath);return normalized.length>LINKED_ARTIFACT_MAX_PATH_LENGTH||normalized.split(/[\\/]/).some(segment=>segment.length>LINKED_ARTIFACT_MAX_SEGMENT_LENGTH)}async function linkedArtifactIsMissing(workspaceRoot,artifactPath){const absolutePath=path.isAbsolute(artifactPath)?artifactPath:path.resolve(workspaceRoot,artifactPath);if(linkedArtifactPathExceedsFilesystemLimits(absolutePath))return!1;try{const stats=await fs.stat(absolutePath);return!stats.isFile()&&!stats.isDirectory()}catch(error){return hasFilesystemErrorCode(error,["ENOENT","ENOTDIR"])}}async function collectLinkedPathScanState(items,workspaceRoot){const state={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},linkedArtifacts=items.flatMap(item=>[...(item.files??[]).map(artifact=>({item,artifact,link_kind:"files"})),...(item.docs??[]).map(artifact=>({item,artifact,link_kind:"docs"}))]);for(const{item,artifact,link_kind}of linkedArtifacts){if(artifact.scope!=="project")continue;if(isRemoteLinkedArtifactReference(artifact.path)){state.remoteLinkedPaths.add(artifact.path.trim());continue}const normalizedPath=normalizeRelativePath(artifact.path);normalizedPath.length!==0&&(state.linkedProjectPaths.add(normalizedPath),await linkedArtifactIsMissing(workspaceRoot,artifact.path)&&(state.missingLinkedPaths.push(normalizedPath),state.staleLinkRows.push({item_id:item.id,path:normalizedPath,link_kind})))}return state}function partitionFileCandidates(fileCandidates,pmRoot,workspaceRoot,fileScanMode,includePmInternals,verboseFileLists){const strictTrackedAllMode=fileScanMode==="tracked-all-strict",strictModeForcesPmInternals=strictTrackedAllMode&&!includePmInternals,includePmInternalsEffective=includePmInternals||strictTrackedAllMode,pmInternalCandidatePrefixes=includePmInternalsEffective?[]:resolvePmInternalCandidatePrefixes(pmRoot,workspaceRoot),excludedPmInternalPaths=pmInternalCandidatePrefixes.length===0?[]:fileCandidates.candidateFiles.filter(candidate=>hasPathPrefix(candidate,pmInternalCandidatePrefixes)),candidateFiles=pmInternalCandidatePrefixes.length===0?fileCandidates.candidateFiles:fileCandidates.candidateFiles.filter(candidate=>!hasPathPrefix(candidate,pmInternalCandidatePrefixes)),excludedByReason={};if(excludedPmInternalPaths.length>0){const summarizedPmInternalPaths=summarizeFileList(excludedPmInternalPaths,verboseFileLists);excludedByReason.pm_internals={count:excludedPmInternalPaths.length,paths:summarizedPmInternalPaths.values,paths_truncated:summarizedPmInternalPaths.truncated,paths_total:summarizedPmInternalPaths.total}}return{strictTrackedAllMode,strictModeForcesPmInternals,includePmInternalsEffective,pmInternalCandidatePrefixes,excludedPmInternalPaths,candidateFiles,excludedByReason}}function buildLifecycleCheck(items,includeStaleBlockers,dependencyCycleSeverity,parentCycleSeverity,statusRegistry,lifecyclePatternPolicy,verboseDiagnostics,idPrefix="pm"){const rows=collectLifecycleScanRows(items,includeStaleBlockers,statusRegistry,lifecyclePatternPolicy);sortLifecycleScanRows(rows);const dependencyCycleDiagnostics=detectLifecycleDependencyCycles(rows.activeItems,idPrefix),parentCycleDiagnostics=detectLifecycleParentCycles(items,statusRegistry),statusRoleDiagnostics=inspectStatusRoleAssignments(statusRegistry,items,verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT),warnings=[...buildLifecycleWarnings(rows,includeStaleBlockers,dependencyCycleSeverity,parentCycleSeverity,{dependencyCycles:dependencyCycleDiagnostics.cycle_count,activeHierarchyCycles:parentCycleDiagnostics.active_cycle_count,activeHierarchyCardinality:parentCycleDiagnostics.active_cardinality_violation_count,activeHierarchyDivergence:parentCycleDiagnostics.active_parent_divergence_count,legacyHierarchyCycles:parentCycleDiagnostics.legacy_cycle_count,legacyHierarchyCardinality:parentCycleDiagnostics.legacy_cardinality_violation_count,legacyHierarchyDivergence:parentCycleDiagnostics.legacy_parent_divergence_count}),...buildStatusRoleWarnings(statusRoleDiagnostics)],diagnosticLimit=verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT,summarizedClosureLikeRows=summarizeList(rows.closureLikeRows.map(row=>`${row.id}:${row.fields.join(",")}`),diagnosticLimit),summarizedTerminalParentRows=summarizeList(rows.terminalParentRows.map(row=>`${row.id}:${row.parent_id}:${row.parent_status}`),diagnosticLimit),summarizedStaleBlockerRows=summarizeList(rows.staleBlockerRows.map(row=>`${row.id}:${row.status}:${row.reasons.join(",")}`),diagnosticLimit),summarizedDependencyCycleItemIds=summarizeList(dependencyCycleDiagnostics.cycle_item_ids,diagnosticLimit),summarizedDependencyCycleSamplePaths=summarizeList(dependencyCycleDiagnostics.cycle_sample_paths,diagnosticLimit),summarizedParentCycleItemIds=summarizeList(parentCycleDiagnostics.cycle_item_ids,diagnosticLimit),summarizedParentCycleSamplePaths=summarizeList(parentCycleDiagnostics.cycle_sample_paths,diagnosticLimit),summarizedHierarchyCardinalityRows=summarizeList(parentCycleDiagnostics.cardinality_violation_rows,diagnosticLimit),summarizedHierarchyDivergenceRows=summarizeList(parentCycleDiagnostics.parent_divergence_rows,diagnosticLimit),hasErrorSeverityCycle=dependencyCycleDiagnostics.cycle_count>0&&dependencyCycleSeverity==="error"||(parentCycleDiagnostics.active_cycle_count>0||parentCycleDiagnostics.active_cardinality_violation_count>0||parentCycleDiagnostics.active_parent_divergence_count>0)&&parentCycleSeverity==="error";return{check:{name:"lifecycle",status:hasErrorSeverityCycle?"error":warnings.length===0?"ok":"warn",ok:!hasErrorSeverityCycle&&warnings.length===0,details:{checked_active_items:rows.activeItems.length,lifecycle_status_roles:statusRoleDiagnostics,active_closure_like_metadata_items:rows.closureLikeRows.length,active_closure_like_metadata_rows:summarizedClosureLikeRows.values,active_closure_like_metadata_rows_truncated:summarizedClosureLikeRows.truncated,active_terminal_parent_items:rows.terminalParentRows.length,active_terminal_parent_rows:summarizedTerminalParentRows.values,active_terminal_parent_rows_truncated:summarizedTerminalParentRows.truncated,stale_blocker_checks_enabled:includeStaleBlockers,stale_blocker_items:rows.staleBlockerRows.length,stale_blocker_rows:summarizedStaleBlockerRows.values,stale_blocker_rows_truncated:summarizedStaleBlockerRows.truncated,dependency_cycle_severity_policy:dependencyCycleSeverity,dependency_cycle_count:dependencyCycleDiagnostics.cycle_count,dependency_cycle_item_count:dependencyCycleDiagnostics.cycle_item_ids.length,dependency_cycle_item_ids:summarizedDependencyCycleItemIds.values,dependency_cycle_item_ids_truncated:summarizedDependencyCycleItemIds.truncated,dependency_cycle_sample_paths:summarizedDependencyCycleSamplePaths.values,dependency_cycle_sample_paths_truncated:summarizedDependencyCycleSamplePaths.truncated,parent_cycle_severity_policy:parentCycleSeverity,parent_cycle_count:parentCycleDiagnostics.cycle_count,active_parent_cycle_count:parentCycleDiagnostics.active_cycle_count,legacy_parent_cycle_count:parentCycleDiagnostics.legacy_cycle_count,parent_cycle_item_count:parentCycleDiagnostics.cycle_item_ids.length,parent_cycle_item_ids:summarizedParentCycleItemIds.values,parent_cycle_item_ids_truncated:summarizedParentCycleItemIds.truncated,parent_cycle_sample_paths:summarizedParentCycleSamplePaths.values,parent_cycle_sample_paths_truncated:summarizedParentCycleSamplePaths.truncated,hierarchy_cardinality_violation_count:parentCycleDiagnostics.cardinality_violation_count,active_hierarchy_cardinality_violation_count:parentCycleDiagnostics.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:parentCycleDiagnostics.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:summarizedHierarchyCardinalityRows.values,hierarchy_cardinality_violation_rows_truncated:summarizedHierarchyCardinalityRows.truncated,hierarchy_parent_divergence_count:parentCycleDiagnostics.parent_divergence_count,active_hierarchy_parent_divergence_count:parentCycleDiagnostics.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:parentCycleDiagnostics.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:summarizedHierarchyDivergenceRows.values,hierarchy_parent_divergence_rows_truncated:summarizedHierarchyDivergenceRows.truncated,stale_blocker_reason_patterns:[...lifecyclePatternPolicy.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:lifecyclePatternPolicy.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...lifecyclePatternPolicy.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...lifecyclePatternPolicy.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...lifecyclePatternPolicy.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.actual_result}},warnings,terminalParentFixRows:rows.terminalParentFixRows}}async function buildFilesCheck(items,workspaceRoot,pmRoot,fileScanMode,includePmInternals,verboseFileLists,statusRegistry=resolveRuntimeStatusRegistry(SETTINGS_DEFAULTS.schema)){const linkedPathState=await collectLinkedPathScanState(items,workspaceRoot),itemsById=new Map(items.map(item=>[item.id,item])),uniqueMissingLinkedPaths=[...new Set(linkedPathState.missingLinkedPaths)].sort((left,right)=>left.localeCompare(right)),fileCandidates=await collectProjectFileCandidates(workspaceRoot,fileScanMode),partition=partitionFileCandidates(fileCandidates,pmRoot,workspaceRoot,fileScanMode,includePmInternals,verboseFileLists),orphanedFiles=partition.candidateFiles.filter(candidate=>!linkedPathState.linkedProjectPaths.has(candidate)),orphanedPathRows=buildOrphanedPathRows(orphanedFiles,items),classifiedStalePaths=classifyStaleLinkedPaths(uniqueMissingLinkedPaths,partition.candidateFiles),classificationByPath=new Map(classifiedStalePaths.map(entry=>[entry.path,entry.classification])),movedStalePathCount=classifiedStalePaths.filter(entry=>entry.classification==="moved").length,staleLinkPruneRows=linkedPathState.staleLinkRows.map(row=>({...row,classification:classificationByPath.get(row.path)??"deleted"})).sort((left,right)=>left.item_id.localeCompare(right.item_id)||left.path.localeCompare(right.path)||left.link_kind.localeCompare(right.link_kind)),warnings=[];partition.strictModeForcesPmInternals&&warnings.push("validate_files_tracked_all_strict_forces_pm_internals"),orphanedFiles.length>0&&warnings.push(`validate_files_orphaned_paths:${orphanedFiles.length}`);const uniqueRemoteLinkedPaths=[...linkedPathState.remoteLinkedPaths].sort((left,right)=>left.localeCompare(right)),summarizedRemote=summarizeFileList(uniqueRemoteLinkedPaths,verboseFileLists),summarizedMissing=summarizeFileList(uniqueMissingLinkedPaths,verboseFileLists),summarizedOrphaned=summarizeFileList(orphanedFiles,verboseFileLists),summarizedOrphanedClassifications=summarizeFileList(orphanedPathRows.map(row=>`${row.path}:${row.classification}:owner_candidate=${row.owner_candidate?.id??"unowned"}`),verboseFileLists),orphanedPathRowDetail=verboseFileLists?orphanedPathRows:summarizeFileList(summarizeOrphanedPathRows(orphanedPathRows),!1).values,summarizedClassifications=summarizeFileList(summarizeStaleLinkedPathClassifications(classifiedStalePaths),verboseFileLists),repairReport=buildLinkedFileRepairReport(staleLinkPruneRows,classifiedStalePaths,id=>itemsById.get(id),statusRegistry,verboseFileLists?1/0:FILE_LIST_SUMMARY_LIMIT);return repairReport.active_missing_linked_paths_count>0&&warnings.push(`validate_files_missing_linked_paths:${repairReport.active_missing_linked_paths_count}`),{check:{name:"files",status:warnings.length===0?"ok":"warn",ok:warnings.length===0,details:{workspace_root:workspaceRoot,scan_mode_requested:fileCandidates.requestedMode,scan_mode_applied:fileCandidates.appliedMode,strict_tracked_all_mode:partition.strictTrackedAllMode,strict_mode_forces_pm_internals:partition.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:partition.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:verboseFileLists?"full":"summary",file_list_summary_limit:FILE_LIST_SUMMARY_LIMIT,candidate_scan_source:fileCandidates.source,include_pm_internals:partition.includePmInternalsEffective,include_pm_internals_requested:includePmInternals,pm_internal_candidate_prefixes:partition.pmInternalCandidatePrefixes,pm_internal_excluded_count:partition.excludedPmInternalPaths.length,excluded_total:partition.excludedPmInternalPaths.length,excluded_by_reason:partition.excludedByReason,linked_project_paths:linkedPathState.linkedProjectPaths.size,remote_linked_paths_count:uniqueRemoteLinkedPaths.length,remote_linked_paths_total:summarizedRemote.total,remote_linked_paths:summarizedRemote.values,remote_linked_paths_truncated:summarizedRemote.truncated,candidate_total_raw:fileCandidates.candidateTotal,candidate_scanned_raw:fileCandidates.candidateScanned,candidate_total:partition.candidateFiles.length,candidate_scanned:partition.candidateFiles.length,scanned_candidate_files:partition.candidateFiles.length,missing_linked_paths_count:uniqueMissingLinkedPaths.length,missing_linked_paths_total:summarizedMissing.total,missing_linked_paths:summarizedMissing.values,missing_linked_paths_truncated:summarizedMissing.truncated,missing_linked_paths_moved_count:movedStalePathCount,missing_linked_paths_deleted_count:classifiedStalePaths.filter(entry=>entry.classification==="deleted").length,missing_linked_paths_malformed_count:classifiedStalePaths.filter(entry=>entry.classification==="malformed").length,missing_linked_path_classifications:summarizedClassifications.values,missing_linked_path_classifications_truncated:summarizedClassifications.truncated,...repairReport,orphaned_paths_count:orphanedFiles.length,orphaned_paths_total:summarizedOrphaned.total,orphaned_paths:summarizedOrphaned.values,orphaned_paths_truncated:summarizedOrphaned.truncated,orphaned_path_classifications:summarizedOrphanedClassifications.values,orphaned_path_classifications_truncated:summarizedOrphanedClassifications.truncated,orphaned_path_rows_count:orphanedPathRows.length,orphaned_path_rows:orphanedPathRowDetail}},warnings,staleLinkPruneRows}}function buildUntrustedLinkedTestRows(linkedTests,trustDecisions){const rows=[];return linkedTests.forEach(({item,linkedTest},index)=>{const trust=trustDecisions[index];if(trust.trusted)return;const command=summarizeCommandPreview(linkedTest.command??"");rows.push(`${item.id}:${trust.source_ref??"unknown"}->${trust.current_source_ref??"unknown"}:${command}`)}),rows}async function buildCommandReferencesCheck(items,idPrefix,verboseDiagnostics,pmRoot){const knownIds=new Set(items.map(item=>item.id.toLowerCase()));let linkedCommandsScanned=0,referencedPmIdCount=0;const referencedPmIds=new Set,staleReferenceRows=[],linkedTests=items.flatMap(item=>(item.tests??[]).map(linkedTest=>({item,linkedTest}))),currentSourceRef=await resolveLinkedTestSourceRef(resolveLinkedTestSourceWorkspaceRoot()),trustDecisions=await resolveLinkedTestTrustBatch(pmRoot,linkedTests.map(({linkedTest})=>linkedTest),currentSourceRef),untrustedRows=buildUntrustedLinkedTestRows(linkedTests,trustDecisions);for(const{item,linkedTest}of linkedTests){if(typeof linkedTest.command!="string"||linkedTest.command.trim().length===0)continue;linkedCommandsScanned+=1;const referencedIds=extractReferencedPmItemIdsFromCommand(linkedTest.command,idPrefix);if(referencedIds.length!==0){referencedPmIdCount+=referencedIds.length;for(const referencedId of referencedIds)referencedPmIds.add(referencedId),knownIds.has(referencedId.toLowerCase())||staleReferenceRows.push(`${item.id}:${referencedId}:${summarizeCommandPreview(linkedTest.command)}`)}}const uniqueStaleReferenceRows=[...new Set(staleReferenceRows)].sort((left,right)=>left.localeCompare(right)),stalePmIds=[...new Set(uniqueStaleReferenceRows.map(row=>row.split(":")[1]??""))].filter(value=>value.length>0).sort((left,right)=>left.localeCompare(right)),warnings=[];uniqueStaleReferenceRows.length>0&&warnings.push(`validate_command_references_stale_pm_ids:${uniqueStaleReferenceRows.length}`),untrustedRows.length>0&&warnings.push(`validate_linked_test_trust_unacknowledged:${untrustedRows.length}`);const diagnosticLimit=verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT,summarizedRows=summarizeList(uniqueStaleReferenceRows,diagnosticLimit),summarizedStalePmIds=summarizeList(stalePmIds,diagnosticLimit),summarizedReferencedPmIds=summarizeList([...referencedPmIds].sort((left,right)=>left.localeCompare(right)),diagnosticLimit),summarizedUntrustedRows=summarizeList(untrustedRows,diagnosticLimit);return{check:{name:"command_references",status:warnings.length===0?"ok":"warn",ok:warnings.length===0,details:{checked_items:items.length,linked_commands_scanned:linkedCommandsScanned,referenced_pm_ids_count:referencedPmIdCount,unique_referenced_pm_ids_count:referencedPmIds.size,unique_referenced_pm_ids:summarizedReferencedPmIds.values,unique_referenced_pm_ids_truncated:summarizedReferencedPmIds.truncated,linked_test_trust_current_source_ref:currentSourceRef??null,untrusted_linked_tests_count:untrustedRows.length,untrusted_linked_tests:summarizedUntrustedRows.values,untrusted_linked_tests_truncated:summarizedUntrustedRows.truncated,stale_pm_id_references_count:uniqueStaleReferenceRows.length,stale_pm_ids_count:stalePmIds.length,stale_pm_ids:summarizedStalePmIds.values,stale_pm_ids_truncated:summarizedStalePmIds.truncated,stale_pm_id_reference_rows:summarizedRows.values,stale_pm_id_reference_rows_truncated:summarizedRows.truncated}},warnings}}function buildFormatVersionCheck(items,verboseDiagnostics){const scan=scanItemFormatVersions(items.map(item=>({ref:item.id,version:effectiveItemFormatVersion(item)})),CURRENT_ITEM_FORMAT_VERSION,BASELINE_ITEM_FORMAT_VERSION),warnings=[];scan.outdated.length>0&&warnings.push(`validate_format_version_outdated_items:${scan.outdated.length}`),scan.ahead.length>0&&warnings.push(`validate_format_version_ahead_items:${scan.ahead.length}`);const diagnosticLimit=verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT,summarizedOutdated=summarizeList(scan.outdated,diagnosticLimit),summarizedAhead=summarizeList(scan.ahead,diagnosticLimit),status=scan.ahead.length>0?"error":scan.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status,ok:status==="ok",details:{checked_items:items.length,current_format_version:CURRENT_ITEM_FORMAT_VERSION,outdated_items_count:scan.outdated.length,outdated_items:summarizedOutdated.values,outdated_items_truncated:summarizedOutdated.truncated,ahead_items_count:scan.ahead.length,ahead_items:summarizedAhead.values,ahead_items_truncated:summarizedAhead.truncated}},warnings}}const VALIDATE_AUTO_FIX_MESSAGE="pm validate auto-fix";async function applyValidateFix(fix,global2,services){switch(fix.kind){case"set_closed_at":await applyClosureTimestampFix(fix,global2);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{const updateOptions={message:VALIDATE_AUTO_FIX_MESSAGE};if(fix.kind==="set_resolution"?updateOptions.resolution=fix.value:fix.kind==="set_close_reason"?updateOptions.closeReason=fix.value:fix.kind==="set_estimate"?updateOptions.estimatedMinutes=fix.value:fix.kind==="reparent"?updateOptions.parent=fix.parent_id:updateOptions.unset=["parent"],!services.runUpdate)throw new PmCliError("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",EXIT_CODE.USAGE);await services.runUpdate(fix.item_id,updateOptions,global2);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${fix.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${fix.kind}`)}}function pruneBatchKey(fix){return fix.kind!=="prune_file_link"&&fix.kind!=="prune_doc_link"?null:`${fix.kind}:${fix.item_id}`}async function applyValidateFixes(applicable,global2,services){const applied=[],failed=[],pruneBatches=new Map;for(const fix of applicable.filter(candidate=>pruneBatchKey(candidate)===null))try{await applyValidateFix(fix,global2,services),applied.push(fix)}catch(error){failed.push({fix,error})}for(const fix of applicable.filter(candidate=>pruneBatchKey(candidate)!==null)){const batchKey=pruneBatchKey(fix),existing=pruneBatches.get(batchKey);existing?existing.push(fix):pruneBatches.set(batchKey,[fix])}for(const batch of pruneBatches.values()){const first=batch[0];if(!first)continue;const remove=batch.map(fix=>fix.path).filter(value=>typeof value=="string"&&value.length>0);try{first.kind==="prune_file_link"?await runFiles(first.item_id,{remove,message:VALIDATE_AUTO_FIX_MESSAGE},global2):await runDocs(first.item_id,{remove,message:VALIDATE_AUTO_FIX_MESSAGE},global2),applied.push(...batch)}catch(error){failed.push(...batch.map(fix=>({fix,error})))}}return throwFirstItemRevisionConflict(failed.map(entry=>entry.error)),{applied,failed}}const _testOnlyValidateCommand={applyValidateFix,applyValidateFixes,attachValidateFixHints,buildCommandReferencesCheck,buildDependencyReferencesCheck,buildCloseReasonBackfillRows,buildFilesCheck,buildLifecycleCheck,buildLifecycleDependencyGraph,buildLifecycleParentGraph,buildEstimateBackfillRows,buildMetadataCounts,buildMissingFieldOccurrences,buildOrphanedPathRows,classifyOrphanedPath,collectDefaultProjectFileCandidates,collectTrackedGitFileCandidates,detectLifecycleDependencyCycles,detectLifecycleParentCycles,escapeRegExp,extractItemIds,findLifecycleDependencyCycleComponents,isMetadataFieldMissing,linkedArtifactPathExceedsFilesystemLimits,listFilesRecursive,resolveDependencyCycleSeverity,resolveParentCycleSeverity,resolveFileScanMode,resolveLifecycleDependencyCycleSamplePath,resolveRequestedChecks,resolveValidateMetadataProfile,resolveWorkspaceRoot,sharedDirectoryPrefixLength,summarizeOrphanedPathRows,summarizeDuplicateIssueCodes,toMeaningfulString};function appendInvalidMergeReceiptEvidenceWarning(warnings,invalidEvidenceCount){invalidEvidenceCount>0&&warnings.push(`merge_receipt_evidence_invalid:${invalidEvidenceCount}`)}async function buildStorageIntegrityCheck(pmRoot,items,typeToFolder,settings){const scan=await scanStorageIntegrity(pmRoot,new Set(items.map(item=>item.id)),typeToFolder,{schema:settings.schema,extensionFieldNames:collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}),warnings=[];scan.unreadable_item_files.length>0&&warnings.push(`validate_storage_unreadable_items:${scan.unreadable_item_files.length}`),scan.duplicate_item_ids.length>0&&warnings.push(`validate_storage_duplicate_item_ids:${scan.duplicate_item_ids.length}`),scan.history_conflict_marker_streams.length>0&&warnings.push(`validate_storage_history_conflict_markers:${scan.history_conflict_marker_streams.length}`),scan.history_unparseable_streams.length>0&&warnings.push(`validate_storage_unparseable_history:${scan.history_unparseable_streams.length}`),scan.resurrected_items.length>0&&warnings.push(`validate_storage_resurrected_items:${scan.resurrected_items.length}`),scan.unparseable_config_files.length>0&&warnings.push(`validate_storage_unparseable_config:${scan.unparseable_config_files.length}`);const errorCount=warnings.length,trackedRuntimeCache=await scanTrackedRuntimeCache(pmRoot);trackedRuntimeCache.tracked_path_count>0&&warnings.push(`validate_storage_tracked_runtime_cache_files:${trackedRuntimeCache.tracked_path_count}`);const fenceAudit=await auditMergeAttributeFence(pmRoot,resolveProjectMergeTypeFolders(settings));fenceAudit.status==="drift"&&warnings.push(`validate_merge_fence_drift:${fenceAudit.missing_patterns.length+fenceAudit.stale_patterns.length}`);const gitWorkspaceRoot=await findGitWorkspaceRoot(pmRoot),mergeDriverAudit=gitWorkspaceRoot===null?null:await auditMergeDriverConfiguration(gitWorkspaceRoot);mergeDriverAudit!==null&&mergeDriverAudit.status!=="ok"&&warnings.push(`validate_merge_driver_configuration:${mergeDriverAudit.missing_keys.length+mergeDriverAudit.drifted_keys.length}`);const mergeReceiptEvidence=await inspectMergeReceiptEvidence(gitWorkspaceRoot??pmRoot,{includeLossless:!0,pmRoot}),pendingMergeReceipts=mergeReceiptEvidence.receipts,{pendingDecisions:pendingMergeDecisions,lossless:losslessMergeReceipts}=partitionMergeReceipts(pendingMergeReceipts);pendingMergeDecisions.length>0&&warnings.push(`validate_merge_decisions_unreviewed:${pendingMergeDecisions.length}`),appendInvalidMergeReceiptEvidenceWarning(warnings,mergeReceiptEvidence.invalid_evidence_count);const status=errorCount>0?"error":warnings.length>0?"warn":"ok";return{check:{name:"storage_integrity",status,ok:status==="ok",details:{...scan,merge_fence:fenceAudit,merge_driver_configuration:mergeDriverAudit,pending_merge_decision_count:pendingMergeDecisions.length,pending_merge_decision_items:[...new Set(pendingMergeDecisions.map(receipt=>receipt.item_id))].sort((left,right)=>left.localeCompare(right)),lossless_merge_receipt_count:losslessMergeReceipts.length,invalid_merge_receipt_evidence_count:mergeReceiptEvidence.invalid_evidence_count,invalid_merge_receipt_evidence_details:mergeReceiptEvidence.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:mergeReceiptEvidence.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(losslessMergeReceipts.map(receipt=>receipt.item_id))].sort((left,right)=>left.localeCompare(right)),tracked_runtime_cache:{tracker_relative_root:trackedRuntimeCache.tracker_relative_root,tracked_paths:trackedRuntimeCache.tracked_paths,tracked_path_count:trackedRuntimeCache.tracked_path_count,remediation_command:trackedRuntimeCache.remediation_command}}},warnings}}function recordValidateCheck(state,built,fixHintsEnabled){fixHintsEnabled&&attachValidateFixHints(built.check,built.warnings),state.checks.push(built.check),state.warnings.push(...built.warnings)}async function executeRequestedValidateChecks(params){const state={closureTimestampFixes:[],checks:[],warnings:[...params.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},fixHintsEnabled=params.options.fixHints===!0,fullDiagnostics=params.options.verboseDiagnostics===!0||params.options.allAffectedIds===!0||params.global.json===!0;if(params.requestedChecks.has("completeness")){const built=await readWorkflowCompletenessCheck(params.pmRoot,params.items,fullDiagnostics?1/0:DIAGNOSTIC_LIST_SUMMARY_LIMIT,params.sourceIncomplete);recordValidateCheck(state,built,fixHintsEnabled)}if(params.requestedChecks.has("metadata")){const built=buildMetadataCheck(params.items,params.metadataPolicy,params.statusRegistry,fullDiagnostics,[params.settings.id_prefix]);state.closeReasonBackfillRows=built.closeReasonBackfillRows,state.estimateBackfillRows=built.estimateBackfillRows;const timestamps=await scanClosureTimestamps(params.pmRoot,params.items,params.statusRegistry,params.options.autoFix===!0||fixHintsEnabled,fullDiagnostics?1/0:DIAGNOSTIC_LIST_SUMMARY_LIMIT);state.closureTimestampFixes=timestamps.fixes,Object.assign(built.check.details,timestamps.details),built.warnings.push(...timestamps.warnings),built.check.ok=built.warnings.length===0,built.check.status=built.check.ok?"ok":"warn",recordValidateCheck(state,built,fixHintsEnabled)}if(params.requestedChecks.has("resolution")){const built=buildResolutionCheck(params.items,params.statusRegistry,fullDiagnostics);state.resolutionBackfillRows=built.resolutionBackfillRows,recordValidateCheck(state,built,fixHintsEnabled)}if(params.requestedChecks.has("lifecycle")){const built=buildLifecycleCheck(params.items,!!params.options.checkStaleBlockers,params.dependencyCycleSeverity,params.parentCycleSeverity,params.statusRegistry,params.lifecyclePatternPolicy,fullDiagnostics,params.settings.id_prefix);state.terminalParentFixRows=built.terminalParentFixRows,recordValidateCheck(state,built,fixHintsEnabled),recordValidateCheck(state,buildDependencyReferencesCheck(params.items,fullDiagnostics,params.statusRegistry),fixHintsEnabled)}if(params.requestedChecks.has("files")){const built=await buildFilesCheck(params.items,params.workspaceRoot,params.pmRoot,params.fileScanMode,!!params.options.includePmInternals,!!params.options.verboseFileLists,params.statusRegistry);state.staleLinkPruneRows=built.staleLinkPruneRows,recordValidateCheck(state,built,fixHintsEnabled)}return params.requestedChecks.has("command_references")&&recordValidateCheck(state,await buildCommandReferencesCheck(params.items,params.settings.id_prefix,fullDiagnostics,params.pmRoot),fixHintsEnabled),params.requestedChecks.has("history_drift")&&recordValidateCheck(state,await buildValidateHistoryDriftCheck(params.pmRoot,params.items,fullDiagnostics),fixHintsEnabled),params.requestedChecks.has("format_version")&&recordValidateCheck(state,buildFormatVersionCheck(params.items,fullDiagnostics),fixHintsEnabled),params.requestedChecks.has("storage_integrity")&&recordValidateCheck(state,await buildStorageIntegrityCheck(params.pmRoot,params.items,resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,params.settings),fixHintsEnabled),state}function planValidateFixes(options,state,settings){const planned=[];return options.autoFix===!0&&(planned.push(...state.closureTimestampFixes),planned.push(...planCloseReasonBackfillFixes(state.closeReasonBackfillRows)),planned.push(...planResolutionBackfillFixes(state.resolutionBackfillRows)),planned.push(...planEstimateBackfillFixes(state.estimateBackfillRows,settings.validation.estimate_defaults_by_type)),planned.push(...planTerminalParentFixes(state.terminalParentFixRows))),options.pruneMissing===!0&&planned.push(...planStaleLinkPruneFixes(state.staleLinkPruneRows)),planned}async function buildValidateFixesSummary(options,state,settings,grantedFixScopes,global2,services){if(options.autoFix!==!0&&options.pruneMissing!==!0)return;const planned=planValidateFixes(options,state,settings),{applicable,gated}=partitionFixesByGrant(planned,grantedFixScopes),dryRun=options.dryRun===!0,appliedFixRows=[],failedFixRows=[];if(!dryRun){const applied=await applyValidateFixes(applicable,global2,services);appliedFixRows.push(...applied.applied.map(toFixOutputRow)),failedFixRows.push(...applied.failed.map(({fix,error})=>({...toFixOutputRow(fix),error:error instanceof Error?error.message:String(error)})))}return{mode:dryRun?"dry_run":"apply",auto_fix:options.autoFix===!0,prune_missing:options.pruneMissing===!0,granted_fix_scopes:[...grantedFixScopes].sort((left,right)=>left.localeCompare(right)),planned_count:planned.length,applied_count:appliedFixRows.length,gated_count:gated.length,failed_count:failedFixRows.length,planned_fixes:planned.map(toFixOutputRow),applied_fixes:appliedFixRows,gated_fixes:gated.map(fix=>({...toFixOutputRow(fix),gate_hint:`Withheld: re-run with --fix-scope ${fix.gate} to apply.`})),failed_fixes:failedFixRows}}async function runValidate(options,global2,services={}){assertProjectionModeChoice(options.counts===!0,options.full===!0,"--counts");const fixesRequested=options.autoFix===!0||options.pruneMissing===!0;if(options.dryRun===!0&&!fixesRequested)throw new PmCliError("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",EXIT_CODE.USAGE);if(options.fixScope!==void 0&&options.fixScope.length>0&&options.autoFix!==!0)throw new PmCliError("--fix-scope requires --auto-fix.",EXIT_CODE.USAGE);const grantedFixScopes=resolveGrantedFixScopes(options.fixScope),pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),requestedChecks=resolveRequestedChecks(options),itemReadWarnings=[],items=await readValidateItems({includeBody:["history_drift","metadata","completeness"].some(check=>requestedChecks.has(check)),pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,warnings:itemReadWarnings}),sourceIncomplete=itemReadWarnings.length>0;if(requestedChecks.has("history_drift")){const authorAttribution=await scanHistoryAuthorAttribution(pmRoot);authorAttribution.actionable_unknown_event_count>0&&itemReadWarnings.push(`validate_history_unknown_author_events:${authorAttribution.actionable_unknown_event_count}`)}const metadataProfileSource=typeof options.metadataProfile=="string"?"option":"settings",metadataProfile=resolveValidateMetadataProfile(typeof options.metadataProfile=="string"?options.metadataProfile:settings.validation.metadata_profile),metadataPolicy=resolveValidateMetadataPolicy(metadataProfile,metadataProfileSource,settings.validation.metadata_required_fields),lifecyclePatternPolicy=resolveLifecyclePatternPolicy(settings),dependencyCycleSeverity=resolveDependencyCycleSeverity(options.dependencyCycleSeverity),parentCycleSeverity=resolveParentCycleSeverity(options.parentCycleSeverity),fileScanMode=resolveFileScanMode(options.scanMode),workspaceRoot=resolveWorkspaceRoot(pmRoot),state=await executeRequestedValidateChecks({requestedChecks,options,global:global2,pmRoot,workspaceRoot,settings,items,statusRegistry,metadataPolicy,lifecyclePatternPolicy,dependencyCycleSeverity,parentCycleSeverity,fileScanMode,initialWarnings:[...new Set(itemReadWarnings)],sourceIncomplete}),fixes=fixesRequested?await buildValidateFixesSummary(options,state,settings,grantedFixScopes,global2,services):void 0,normalizedWarnings=[...new Set(state.warnings)].sort((left,right)=>left.localeCompare(right)),result={ok:!state.checks.some(check=>check.status==="error"),has_warnings:normalizedWarnings.length>0,checks:state.checks,warnings:normalizedWarnings,...fixes!==void 0?{fixes}:{},generated_at:nowIso(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return options.counts!==!0?result:{...projectValidateCounts(result),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{_testOnlyValidateCommand,projectValidateCounts,runValidate};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e046350f-afca-59d1-83c0-5df1e837d59d")}catch{}})();import{throwFirstItemRevisionConflict}from"../lifecycle/item-revision.js";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{applyClosureTimestampFix,scanClosureTimestamps}from"./closure-timestamps.js";import{readWorkflowCompletenessCheck}from"./workflow-completeness.js";import fs from"node:fs/promises";import{realpathSync}from"node:fs";import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{buildRemediationCommands}from"../../core/diagnostics/remediation.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{collectRegisteredItemFieldNames}from"../../core/extensions/item-fields.js";import{isFileMissingError}from"../../core/fs/fs-utils.js";import{normalizeStatusInput}from"../../core/item/status.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{resolveRuntimeStatusRegistry}from"../../core/schema/runtime-schema.js";import{DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS,DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS,EXIT_CODE,PM_DIRNAME,SETTINGS_DEFAULTS}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{toNonEmptyStringOrUndefined}from"../../core/shared/primitives.js";import{nowIso}from"../../core/shared/time.js";import{CURRENT_ITEM_FORMAT_VERSION,BASELINE_ITEM_FORMAT_VERSION,effectiveItemFormatVersion,scanItemFormatVersions}from"../../core/item/item-format-version.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{partitionFixesByGrant,planCloseReasonBackfillFixes,planEstimateBackfillFixes,planResolutionBackfillFixes,planStaleLinkPruneFixes,planTerminalParentFixes,resolveGrantedFixScopes,toFixOutputRow}from"../../core/validate/fix-planning.js";import{findDuplicateIssueCodes}from"../../core/governance/issue-codes.js";import{buildMissingByTypeCounts}from"../../core/validate/missing-by-type.js";import{classifyStaleLinkedPaths,summarizeStaleLinkedPathClassifications}from"../../core/validate/stale-file-classification.js";import{isRemoteLinkedArtifactReference}from"../../core/validate/linked-artifact-reference.js";import{assertProjectionModeChoice}from"../output-projection.js";import{collectDanglingDependencyReferences}from"../graph/assembly.js";import{auditMergeAttributeFence,auditMergeDriverConfiguration,findGitWorkspaceRoot,resolveProjectMergeTypeFolders}from"../merge/install.js";import{inspectMergeReceiptEvidence,partitionMergeReceipts}from"../merge/receipts.js";import{buildLinkedFileRepairReport}from"./linked-file-report.js";import{scanStorageIntegrity}from"./storage-integrity.js";import{scanTrackedRuntimeCache}from"./tracked-runtime-cache.js";import{scanHistoryAuthorAttribution}from"../author-attribution.js";import{createRelationshipKindRegistry}from"../relationships.js";import{runDocs}from"../docs.js";import{runFiles}from"../files.js";import{extractReferencedPmItemIdsFromCommand}from"../test/linked-command-detection.js";import{resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrustBatch}from"../test/trust.js";import{readValidateItems}from"./validate-item-reader.js";import{buildValidateHistoryDriftCheck}from"./validate-history-drift.js";import{findLifecycleDependencyCycleComponents}from"./lifecycle-dependency-cycles.js";import{summarizeDeferredFieldCuration}from"./validate-deferred-fields.js";import{buildLifecycleParentGraph,detectLifecycleParentCycles,resolveLifecycleDependencyCycleSamplePath}from"./hierarchy-validation.js";import{buildStatusRoleWarnings,inspectStatusRoleAssignments}from"./status-role-diagnostics.js";import{summarizeCommandPreview,normalizeRelativeDirectoryPath,normalizeRelativePath,toMeaningfulString}from"./validate-normalization.js";const FILE_SCAN_DIRECTORIES=["src","tests","docs"],FILE_SCAN_ROOT_FILES=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],DIRECTORY_IGNORE_SET=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),RESOLUTION_FIELD_KEYS=["resolution","expected_result","actual_result"],VALIDATE_FILE_SCAN_MODES=["default","tracked-all","tracked-all-strict"],VALIDATE_METADATA_PROFILE_VALUES=["core","strict","custom"],VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES=["off","warn","error"],CORE_METADATA_REQUIRED_FIELDS=["author","acceptance_criteria","estimated_minutes","close_reason"],STRICT_METADATA_REQUIRED_FIELDS=[...CORE_METADATA_REQUIRED_FIELDS,"reviewer","risk","confidence","sprint","release"],SUPPORTED_METADATA_REQUIRED_FIELDS=Array.from(new Set(STRICT_METADATA_REQUIRED_FIELDS)),METADATA_REQUIRED_FIELD_ALIASES={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"},METADATA_WARNING_TOKEN_BY_FIELD={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"},METADATA_COUNT_KEY_BY_FIELD={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"},METADATA_ITEM_IDS_KEY_BY_FIELD={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"},METADATA_TRUNCATED_KEY_BY_FIELD={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"},GIT_LS_FILES_MAX_BUFFER=32*1024*1024,GIT_LS_FILES_TIMEOUT_MS=1e4,FILE_LIST_SUMMARY_LIMIT=40,DIAGNOSTIC_LIST_SUMMARY_LIMIT=5,LINKED_ARTIFACT_MAX_PATH_LENGTH=4096,LINKED_ARTIFACT_MAX_SEGMENT_LENGTH=255,execFileAsync=promisify(execFile);function projectValidateCountsRecord(record){const projected={};for(const[key,value]of Object.entries(record))Array.isArray(value)||value===!1&&key.endsWith("_truncated")||(projected[key]=typeof value=="object"&&value!==null?projectValidateCountsRecord(value):value);return projected}function projectValidateCounts(result){return{...result,checks:result.checks.map(check=>({...check,details:projectValidateCountsRecord(check.details)})),...result.fixes?{fixes:{mode:result.fixes.mode,auto_fix:result.fixes.auto_fix,prune_missing:result.fixes.prune_missing,planned_count:result.fixes.planned_count,applied_count:result.fixes.applied_count,gated_count:result.fixes.gated_count,failed_count:result.fixes.failed_count}}:{}}}function normalizeStatusForRegistry(status,statusRegistry){return normalizeStatusInput(status,statusRegistry)??status}function isTerminalStatus(status,statusRegistry){return statusRegistry.terminal_statuses.has(normalizeStatusForRegistry(status,statusRegistry))}function normalizeLifecyclePatternList(values){return[...new Set((values??[]).map(value=>value.trim().toLowerCase()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right))}function areSortedStringListsEqual(left,right){return left.length!==right.length?!1:left.every((value,index)=>value===right[index])}function resolveLifecyclePatternPolicy(settings){const defaultStalePatterns=normalizeLifecyclePatternList(DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS),defaultClosureLikePatterns={blocked_reason:normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.blocked_reason),resolution:normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.resolution),actual_result:normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.actual_result)},staleBlockerReasonPatterns=normalizeLifecyclePatternList(settings.validation.lifecycle_stale_blocker_reason_patterns),closureLikePatterns={blocked_reason:normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_resolution_patterns),actual_result:normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:staleBlockerReasonPatterns,stale_blocker_reason_pattern_source:areSortedStringListsEqual(staleBlockerReasonPatterns,defaultStalePatterns)?"default":"settings",closure_like_metadata_field_patterns:closureLikePatterns,closure_like_metadata_field_pattern_sources:{blocked_reason:areSortedStringListsEqual(closureLikePatterns.blocked_reason,defaultClosureLikePatterns.blocked_reason)?"default":"settings",resolution:areSortedStringListsEqual(closureLikePatterns.resolution,defaultClosureLikePatterns.resolution)?"default":"settings",actual_result:areSortedStringListsEqual(closureLikePatterns.actual_result,defaultClosureLikePatterns.actual_result)?"default":"settings"}}}function resolveValidateMetadataProfile(value){const normalized=value?.trim().toLowerCase();if(!normalized||normalized.length===0)return"core";if(VALIDATE_METADATA_PROFILE_VALUES.includes(normalized))return normalized;throw new PmCliError(`Unknown --metadata-profile value "${value}". Supported values: ${VALIDATE_METADATA_PROFILE_VALUES.join(", ")}.`,EXIT_CODE.USAGE)}function resolveDependencyCycleSeverity(value){const normalized=value?.trim().toLowerCase();if(!normalized||normalized.length===0)return"warn";if(VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES.includes(normalized))return normalized;throw new PmCliError(`Unknown --dependency-cycle-severity value "${value}". Supported values: ${VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES.join(", ")}.`,EXIT_CODE.USAGE)}function resolveParentCycleSeverity(value){const normalized=value?.trim().toLowerCase();if(!normalized||normalized.length===0)return"warn";if(VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES.includes(normalized))return normalized;throw new PmCliError(`Unknown --parent-cycle-severity value "${value}". Supported values: ${VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES.join(", ")}.`,EXIT_CODE.USAGE)}function normalizeMetadataRequiredFieldsFromSettings(values){return[...new Set((values??[]).map(value=>value.trim().toLowerCase().replaceAll("-","_")))].map(value=>METADATA_REQUIRED_FIELD_ALIASES[value]).filter(value=>value!==void 0).sort((left,right)=>left.localeCompare(right))}function resolveValidateMetadataPolicy(profile,profileSource,configuredCustomFields){const normalizedCustomFields=normalizeMetadataRequiredFieldsFromSettings(configuredCustomFields);return profile==="core"?{profile,profile_source:profileSource,required_fields:[...CORE_METADATA_REQUIRED_FIELDS],configured_custom_fields:normalizedCustomFields,fallback_to_core:!1,warnings:[]}:profile==="strict"?{profile,profile_source:profileSource,required_fields:[...STRICT_METADATA_REQUIRED_FIELDS],configured_custom_fields:normalizedCustomFields,fallback_to_core:!1,warnings:[]}:normalizedCustomFields.length>0?{profile,profile_source:profileSource,required_fields:normalizedCustomFields,configured_custom_fields:normalizedCustomFields,fallback_to_core:!1,warnings:[]}:{profile,profile_source:profileSource,required_fields:[...CORE_METADATA_REQUIRED_FIELDS],configured_custom_fields:normalizedCustomFields,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}const TERMINAL_EXEMPT_PLANNING_FIELDS=new Set(["acceptance_criteria","estimated_minutes"]);function isMetadataFieldMissing(item,field,statusRegistry,enforcePlanningFieldsOnTerminal){return!enforcePlanningFieldsOnTerminal&&TERMINAL_EXEMPT_PLANNING_FIELDS.has(field)&&isTerminalStatus(item.status,statusRegistry)?!1:field==="author"?!toNonEmptyStringOrUndefined(item.author):field==="acceptance_criteria"?!toNonEmptyStringOrUndefined(item.acceptance_criteria):field==="estimated_minutes"?!Number.isFinite(item.estimated_minutes):field==="close_reason"?normalizeStatusForRegistry(item.status,statusRegistry)===statusRegistry.close_status&&!toNonEmptyStringOrUndefined(item.close_reason):field==="reviewer"?!toNonEmptyStringOrUndefined(item.reviewer):field==="risk"?!toNonEmptyStringOrUndefined(item.risk):field==="confidence"?typeof item.confidence=="number"?!Number.isFinite(item.confidence):!toNonEmptyStringOrUndefined(item.confidence):field==="sprint"?!toNonEmptyStringOrUndefined(item.sprint):!toNonEmptyStringOrUndefined(item.release)}function resolveFileScanMode(scanMode){if(scanMode===void 0)return"default";const normalized=scanMode.trim().toLowerCase();if(normalized.length===0||normalized==="default")return"default";if(normalized==="tracked-all"||normalized==="tracked_all")return"tracked-all";if(normalized==="tracked-all-strict"||normalized==="tracked_all_strict")return"tracked-all-strict";throw new PmCliError(`Unknown --scan-mode value "${scanMode}". Supported values: ${VALIDATE_FILE_SCAN_MODES.join(", ")}.`,EXIT_CODE.USAGE)}function resolveWorkspaceRoot(pmRoot){const sourceWorkspaceRoot=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(sourceWorkspaceRoot)return path.resolve(sourceWorkspaceRoot);const resolvedPmRoot=path.resolve(pmRoot);if(resolvedPmRoot.replaceAll("\\","/").endsWith("/.agents/pm"))return path.dirname(path.dirname(resolvedPmRoot));const resolvedCwd=path.resolve(process.cwd()),canonicalPmRoot=realpathForWorkspaceRoot(resolvedPmRoot),canonicalCwd=realpathForWorkspaceRoot(resolvedCwd),relativeFromPmRoot=path.relative(canonicalPmRoot,canonicalCwd);return relativeFromPmRoot.length===0||!relativeFromPmRoot.startsWith("..")&&!path.isAbsolute(relativeFromPmRoot)?resolvedPmRoot:resolvedCwd}function realpathForWorkspaceRoot(inputPath){try{return realpathSync.native(inputPath)}catch{return path.resolve(inputPath)}}function hasFilesystemErrorCode(error,acceptedCodes){return typeof error=="object"&&error!==null&&"code"in error&&typeof error.code=="string"&&acceptedCodes.includes(error.code)}async function listFilesRecursive(basePath,relativePath,output){const targetDirectory=relativePath.length>0?path.join(basePath,relativePath):basePath;let entries;try{entries=await fs.readdir(targetDirectory,{withFileTypes:!0})}catch(error){if(isFileMissingError(error))return;throw error}for(const entry of entries){if(entry.name.startsWith("."))continue;const childRelative=relativePath.length>0?path.join(relativePath,entry.name):entry.name;if(entry.isDirectory()){if(DIRECTORY_IGNORE_SET.has(entry.name))continue;await listFilesRecursive(basePath,childRelative,output);continue}entry.isFile()&&output.push(normalizeRelativePath(childRelative))}}async function collectDefaultProjectFileCandidates(workspaceRoot){const discovered=[];for(const directory of FILE_SCAN_DIRECTORIES)await listFilesRecursive(workspaceRoot,directory,discovered);for(const candidate of FILE_SCAN_ROOT_FILES){const absolute=path.join(workspaceRoot,candidate);try{(await fs.stat(absolute)).isFile()&&discovered.push(normalizeRelativePath(candidate))}catch{}}return[...new Set(discovered)].sort((left,right)=>left.localeCompare(right))}async function collectTrackedGitFileCandidates(workspaceRoot){try{const{stdout}=await execFileAsync("git",["ls-files","-z"],{cwd:workspaceRoot,encoding:"utf8",maxBuffer:GIT_LS_FILES_MAX_BUFFER,windowsHide:!0,timeout:GIT_LS_FILES_TIMEOUT_MS}),discovered=stdout.split("\0").map(value=>normalizeRelativePath(value)).filter(value=>value.length>0);return[...new Set(discovered)].sort((left,right)=>left.localeCompare(right))}catch{return null}}function resolvePmInternalCandidatePrefixes(pmRoot,workspaceRoot){const prefixes=new Set,configuredDefault=normalizeRelativeDirectoryPath(PM_DIRNAME);configuredDefault.length>0&&prefixes.add(configuredDefault);const relativePmRoot=normalizeRelativeDirectoryPath(path.relative(workspaceRoot,pmRoot));return relativePmRoot.length>0&&!relativePmRoot.startsWith("..")&&prefixes.add(relativePmRoot),[...prefixes].sort((left,right)=>left.localeCompare(right))}function hasPathPrefix(candidate,prefixes){for(const prefix of prefixes)if(candidate===prefix||candidate.startsWith(`${prefix}/`))return!0;return!1}async function collectProjectFileCandidates(workspaceRoot,scanMode){if(scanMode==="tracked-all"||scanMode==="tracked-all-strict"){const trackedCandidates=await collectTrackedGitFileCandidates(workspaceRoot);if(trackedCandidates)return{requestedMode:scanMode,appliedMode:scanMode,source:"tracked-git",candidateFiles:trackedCandidates,candidateTotal:trackedCandidates.length,candidateScanned:trackedCandidates.length};const fallbackCandidates=await collectDefaultProjectFileCandidates(workspaceRoot);return{requestedMode:scanMode,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:fallbackCandidates,candidateTotal:fallbackCandidates.length,candidateScanned:fallbackCandidates.length}}const defaultCandidates=await collectDefaultProjectFileCandidates(workspaceRoot);return{requestedMode:scanMode,appliedMode:"default",source:"default-curated",candidateFiles:defaultCandidates,candidateTotal:defaultCandidates.length,candidateScanned:defaultCandidates.length}}function summarizeList(values,limit=DIAGNOSTIC_LIST_SUMMARY_LIMIT){return values.length<=limit?{values,truncated:!1}:{values:values.slice(0,limit),truncated:!0}}function summarizeFileList(values,verboseFileLists){if(verboseFileLists)return{values,truncated:!1,total:values.length};const summary=summarizeList(values,FILE_LIST_SUMMARY_LIMIT);return{values:summary.values,truncated:summary.truncated,total:values.length}}const RESOLUTION_REMEDIATION_FLAG_BY_FIELD={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},RESOLUTION_REMEDIATION_PLACEHOLDER_BY_FIELD={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function buildResolutionRemediationCommand(row){const fieldArguments=row.missing_fields.map(field=>`${RESOLUTION_REMEDIATION_FLAG_BY_FIELD[field]} "${RESOLUTION_REMEDIATION_PLACEHOLDER_BY_FIELD[field]}"`).join(" ");return`pm update ${row.id} ${fieldArguments} --message "Backfill resolution metadata"`}function attachValidateFixHints(check,checkWarnings){const existingResolutionHints=check.details?.missing_resolution_remediation_hints,aliasedResolution=Array.isArray(existingResolutionHints)&&existingResolutionHints.length>0,fixHints=aliasedResolution?existingResolutionHints.filter(hint=>typeof hint=="string"):buildRemediationCommands(checkWarnings);if(fixHints.length===0)return;const truncated=aliasedResolution&&check.details?.missing_resolution_remediation_hints_truncated===!0;check.details={...check.details,fix_hints:fixHints,...truncated?{fix_hints_truncated:!0}:{}}}function resolveRequestedChecks(options){const requested=new Set;return options.checkCompleteness&&requested.add("completeness"),options.checkMetadata&&requested.add("metadata"),options.checkResolution&&requested.add("resolution"),(options.checkLifecycle||options.checkStaleBlockers)&&requested.add("lifecycle"),options.checkFiles&&requested.add("files"),options.checkHistoryDrift&&requested.add("history_drift"),options.checkCommandReferences&&requested.add("command_references"),options.checkStorageIntegrity&&requested.add("storage_integrity"),requested.size===0?(options.autoFix&&(requested.add("metadata"),requested.add("resolution"),requested.add("lifecycle")),options.pruneMissing&&requested.add("files"),requested.size===0&&(requested.add("metadata"),requested.add("resolution"),requested.add("lifecycle"),requested.add("files"),requested.add("command_references"),requested.add("history_drift"),requested.add("format_version"),requested.add("completeness"),requested.add("storage_integrity")),requested):(options.pruneMissing&&requested.add("files"),requested)}const DUPLICATE_ISSUE_CODE_WARNING_TOKEN="validate_metadata_duplicate_issue_codes";function summarizeDuplicateIssueCodes(duplicates,verboseDiagnostics){if(duplicates.length===0)return{rows:[],truncated:!1,warnings:[]};const limit=verboseDiagnostics?duplicates.length:DIAGNOSTIC_LIST_SUMMARY_LIMIT,shown=duplicates.slice(0,limit);return{rows:shown.map(duplicate=>({code:duplicate.code,count:duplicate.count,ids:duplicate.ids,titles:duplicate.titles,remediation_hint:`Items ${duplicate.ids.join(", ")} share issue code "${duplicate.code}"; rename or merge so each logical code maps to one item.`})),truncated:shown.length<duplicates.length,warnings:[`${DUPLICATE_ISSUE_CODE_WARNING_TOKEN}:${duplicates.length}`]}}function collectMissingMetadataByField(items,statusRegistry,enforcePlanningFieldsOnTerminal){const missingByField=Object.fromEntries(SUPPORTED_METADATA_REQUIRED_FIELDS.map(field=>[field,[]]));for(const item of items)for(const field of SUPPORTED_METADATA_REQUIRED_FIELDS)isMetadataFieldMissing(item,field,statusRegistry,enforcePlanningFieldsOnTerminal)&&missingByField[field].push(item.id);return missingByField}function buildMetadataWarningTokens(metadataPolicy,missingByField,duplicateWarnings){const warningTokens=[...metadataPolicy.warnings];for(const field of metadataPolicy.required_fields){const missingItems=missingByField[field];missingItems.length>0&&warningTokens.push(`${METADATA_WARNING_TOKEN_BY_FIELD[field]}:${missingItems.length}`)}return warningTokens.push(...duplicateWarnings),warningTokens}function buildMetadataCounts(metadataPolicy,missingByField){const counts={};for(const field of metadataPolicy.required_fields){const missing=missingByField[field],value=missing?missing.length:0,countKey=METADATA_COUNT_KEY_BY_FIELD[field];counts[countKey]=value}return counts}function buildMissingFieldOccurrences(metadataPolicy,missingByField,itemsById){const occurrences=[];for(const field of metadataPolicy.required_fields){const missing=missingByField[field];if(missing)for(const itemId of missing){const itemType=itemsById.get(itemId)?.type,normalizedItemType=typeof itemType=="string"&&itemType.length>0?itemType:"Unknown";occurrences.push({item_type:normalizedItemType,field})}}return occurrences}function attachMissingMetadataItemIds(details,metadataPolicy,missingByField,verboseDiagnostics){for(const field of metadataPolicy.required_fields){const missing=missingByField[field];if(!missing||missing.length===0)continue;const idsKey=METADATA_ITEM_IDS_KEY_BY_FIELD[field],truncatedKey=METADATA_TRUNCATED_KEY_BY_FIELD[field];if(!idsKey||!truncatedKey)continue;const summarized=summarizeList(missing,verboseDiagnostics?missing.length:DIAGNOSTIC_LIST_SUMMARY_LIMIT);details[idsKey]=summarized.values,details[truncatedKey]=summarized.truncated}}function buildCloseReasonBackfillRows(metadataPolicy,missingByField,itemsById){if(!metadataPolicy.required_fields.includes("close_reason"))return[];const missing=missingByField.close_reason;return missing?missing.map(itemId=>({id:itemId,resolution:toNonEmptyStringOrUndefined(itemsById.get(itemId)?.resolution)})):[]}function buildEstimateBackfillRows(metadataPolicy,missingByField,itemsById){if(!metadataPolicy.required_fields.includes("estimated_minutes"))return[];const missing=missingByField.estimated_minutes;return missing?missing.map(itemId=>({id:itemId,type:toNonEmptyStringOrUndefined(itemsById.get(itemId)?.type)})):[]}function buildMetadataCheck(items,metadataPolicy,statusRegistry,verboseDiagnostics,configuredIssueCodePrefixes){const itemsById=new Map(items.map(item=>[item.id,item])),enforcePlanningFieldsOnTerminal=metadataPolicy.profile==="strict",missingByField=collectMissingMetadataByField(items,statusRegistry,enforcePlanningFieldsOnTerminal),duplicateIssueCodes=findDuplicateIssueCodes(items,{configuredPrefixes:configuredIssueCodePrefixes}),duplicateIssueCodeSummary=summarizeDuplicateIssueCodes(duplicateIssueCodes,verboseDiagnostics),warningTokens=buildMetadataWarningTokens(metadataPolicy,missingByField,duplicateIssueCodeSummary.warnings),counts=buildMetadataCounts(metadataPolicy,missingByField),missingFieldOccurrences=buildMissingFieldOccurrences(metadataPolicy,missingByField,itemsById),missingByType=buildMissingByTypeCounts(missingFieldOccurrences),details={checked_items:items.length,metadata_profile:metadataPolicy.profile,metadata_profile_source:metadataPolicy.profile_source,metadata_profile_fallback_to_core:metadataPolicy.fallback_to_core,required_fields:[...metadataPolicy.required_fields],supported_required_fields:[...SUPPORTED_METADATA_REQUIRED_FIELDS],counts,missing_by_type:missingByType,duplicate_issue_codes_count:duplicateIssueCodes.length,duplicate_issue_codes:duplicateIssueCodeSummary.rows,duplicate_issue_codes_truncated:duplicateIssueCodeSummary.truncated};metadataPolicy.configured_custom_fields.length>0&&(details.configured_custom_required_fields=[...metadataPolicy.configured_custom_fields]);const deferredCuration=summarizeDeferredFieldCuration(items,verboseDiagnostics);deferredCuration!==void 0&&(details.deferred_fields=deferredCuration.details,warningTokens.push(deferredCuration.warning)),attachMissingMetadataItemIds(details,metadataPolicy,missingByField,verboseDiagnostics);const closeReasonBackfillRows=buildCloseReasonBackfillRows(metadataPolicy,missingByField,itemsById),estimateBackfillRows=buildEstimateBackfillRows(metadataPolicy,missingByField,itemsById);return{check:{name:"metadata",status:warningTokens.length===0?"ok":"warn",ok:warningTokens.length===0,details},warnings:warningTokens,closeReasonBackfillRows,estimateBackfillRows}}function buildResolutionCheck(items,statusRegistry,verboseDiagnostics){const terminalDoneStatuses=new Set(statusRegistry.terminal_done_statuses);terminalDoneStatuses.add(statusRegistry.close_status);const closedItems=items.filter(item=>terminalDoneStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),missingResolutionRows=[],resolutionBackfillRows=[];for(const item of closedItems){const missingFields=RESOLUTION_FIELD_KEYS.filter(field=>!toNonEmptyStringOrUndefined(item[field]));missingFields.length!==0&&(missingResolutionRows.push({id:item.id,missing_fields:missingFields}),resolutionBackfillRows.push({id:item.id,missing_fields:missingFields,close_reason:toNonEmptyStringOrUndefined(item.close_reason)}))}const warnings=missingResolutionRows.length>0?[`validate_resolution_missing_fields:${missingResolutionRows.length}`]:[],diagnosticLimit=verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT,summarizedRows=summarizeList(missingResolutionRows.map(row=>`${row.id}:${row.missing_fields.join(",")}`),diagnosticLimit),remediationHints=missingResolutionRows.map(row=>buildResolutionRemediationCommand(row)),summarizedHints=summarizeList(remediationHints,diagnosticLimit);return{check:{name:"resolution",status:warnings.length===0?"ok":"warn",ok:warnings.length===0,details:{checked_closed_items:closedItems.length,missing_resolution_items:missingResolutionRows.length,missing_resolution_rows:summarizedRows.values,missing_resolution_rows_truncated:summarizedRows.truncated,missing_resolution_remediation_hints:summarizedHints.values,missing_resolution_remediation_hints_truncated:summarizedHints.truncated}},warnings,resolutionBackfillRows}}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildLifecycleDependencyGraph(activeItems,idPrefix="pm",relationshipRegistry=createRelationshipKindRegistry()){const activeItemIds=new Set(activeItems.map(item=>item.id)),sortedItems=[...activeItems].sort((left,right)=>left.id.localeCompare(right.id));return new Map(sortedItems.map(item=>{const edges=new Set,blockedBy=toMeaningfulString(item.blocked_by);blockedBy&&activeItemIds.has(blockedBy)&&edges.add(blockedBy),(item.dependencies??[]).filter(dependency=>{const dependencyKind=toMeaningfulString(dependency.kind);return dependencyKind!==void 0&&relationshipRegistry.resolve(dependencyKind)?.ordering===!0}).map(dependency=>toMeaningfulString(dependency.id)).filter(dependencyId=>dependencyId!==void 0&&activeItemIds.has(dependencyId)).forEach(dependencyId=>edges.add(dependencyId));const definitionOfReady=toMeaningfulString(item.definition_of_ready);return extractItemIds(definitionOfReady??"",idPrefix).filter(referencedId=>activeItemIds.has(referencedId)).forEach(referencedId=>edges.add(referencedId)),[item.id,[...edges].sort((left,right)=>left.localeCompare(right))]}))}function buildDependencyReferencesCheck(items,verboseDiagnostics,statusRegistry){const classified=collectDanglingDependencyReferences(items,statusRegistry?status=>isTerminalStatus(status,statusRegistry):void 0),activeRows=classified.active.map(row=>`${row.holder_id}:${row.target_id}:${row.kind}`),legacyRows=classified.legacy_terminal.map(row=>`${row.holder_id}:${row.target_id}:${row.kind}:${row.holder_status}`),diagnosticLimit=verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT,summarizedRows=summarizeList(activeRows,diagnosticLimit),summarizedLegacyRows=summarizeList(legacyRows,diagnosticLimit),hints=summarizeList(classified.active.map(row=>row.source==="parent"?`pm update ${row.holder_id} --unset parent`:row.source==="blocked_by"?`pm update ${row.holder_id} --unset blocked_by`:`pm update ${row.holder_id} --replace-deps '<correct dependency edges>'`),diagnosticLimit);return{check:{name:"dependency_references",status:activeRows.length===0?"ok":"warn",ok:activeRows.length===0,details:{checked_items:items.length,dangling_reference_count:activeRows.length+legacyRows.length,active_dangling_reference_count:activeRows.length,dangling_reference_rows:summarizedRows.values,dangling_reference_rows_truncated:summarizedRows.truncated,legacy_terminal_dangling_reference_count:legacyRows.length,legacy_closed_dangling_reference_count:classified.legacy_terminal.filter(row=>row.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:summarizedLegacyRows.values,legacy_terminal_dangling_reference_rows_truncated:summarizedLegacyRows.truncated,no_active_blocker_sentinel_count:classified.no_active_blocker_sentinels.length,remediation_hints:hints.values,remediation_hints_truncated:hints.truncated}},warnings:activeRows.length>0?[`validate_dangling_dependency_references:${activeRows.length}`]:[]}}function extractItemIds(value,idPrefix="pm"){const normalizedPrefix=(idPrefix.trim().toLowerCase()||"pm").replace(/-+$/g,""),pattern=new RegExp(`(?:^|[^a-z0-9-])(${escapeRegExp(normalizedPrefix)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...value.matchAll(pattern)].map(match=>match[1].toLowerCase()))].sort((left,right)=>left.localeCompare(right))}function detectLifecycleDependencyCycles(activeItems,idPrefix="pm"){const graph=buildLifecycleDependencyGraph(activeItems,idPrefix),cycleComponents=findLifecycleDependencyCycleComponents(graph),cycleItemIds=[...new Set(cycleComponents.flat())].sort((left,right)=>left.localeCompare(right)),cycleSamplePaths=cycleComponents.map(component=>resolveLifecycleDependencyCycleSamplePath(component,graph).join("->"));return{cycle_count:cycleComponents.length,cycle_item_ids:cycleItemIds,cycle_sample_paths:cycleSamplePaths}}function classifyOrphanedPath(pathValue){return pathValue.startsWith("docs/")?"docs_unowned":pathValue.startsWith("tests/")?"tests_unowned":pathValue.startsWith("src/")?"source_unowned":pathValue.endsWith(".md")?"docs_unowned":"unlinked_existing"}function directoryOf(relativePath){const slash=relativePath.lastIndexOf("/");return slash===-1?"":relativePath.slice(0,slash)}function sharedDirectoryPrefixLength(left,right){const leftParts=directoryOf(left).split("/").filter(Boolean),rightParts=directoryOf(right).split("/").filter(Boolean);let count=0;for(;count<leftParts.length&&count<rightParts.length&&leftParts[count]===rightParts[count];)count+=1;return count}function scoreOrphanOwnerCandidate(pathValue,linkedPath){const linkedDir=directoryOf(linkedPath),orphanDir=directoryOf(pathValue),directoryPrefix=linkedPath.endsWith("/")?linkedPath:`${linkedPath}/`,isDirectoryPrefix=pathValue.startsWith(directoryPrefix),sameDirectory=linkedDir.length>0&&linkedDir===orphanDir,sharedPrefixLength=sharedDirectoryPrefixLength(pathValue,linkedPath);return!isDirectoryPrefix&&!sameDirectory&&sharedPrefixLength===0?null:isDirectoryPrefix?{score:linkedPath.length+1e3,confidence:"path_prefix"}:sameDirectory?{score:sharedPrefixLength+500,confidence:"same_directory"}:{score:sharedPrefixLength,confidence:"shared_directory"}}function shouldReplaceOrphanOwnerCandidate(best,item,score){return best===void 0||score>best.score||score===best.score&&item.id.localeCompare(best.item.id)<0}function findOrphanOwnerCandidate(pathValue,classification,items){const linkKind=classification==="docs_unowned"?"docs":"files";let best;return items.flatMap(item=>(linkKind==="docs"?item.docs??[]:item.files??[]).map(link=>({item,link}))).forEach(({item,link})=>{if(link.scope!=="project")return;const linkedPath=normalizeRelativePath(link.path);if(linkedPath.length===0||linkedPath===pathValue)return;const scored=scoreOrphanOwnerCandidate(pathValue,linkedPath);scored!==null&&shouldReplaceOrphanOwnerCandidate(best,item,scored.score)&&(best={item,score:scored.score,confidence:scored.confidence})}),best?{id:best.item.id,type:best.item.type,title:best.item.title,status:best.item.status,confidence:best.confidence}:null}function buildOrphanedPathRows(orphanedFiles,items){return orphanedFiles.map(pathValue=>{const classification=classifyOrphanedPath(pathValue),linkCommand=classification==="docs_unowned"?"docs":"files",ownerCandidate=findOrphanOwnerCandidate(pathValue,classification,items),target=ownerCandidate?.id??"<id>";return{path:pathValue,classification,owner_candidate:ownerCandidate,remediation_hint:`pm ${linkCommand} ${target} --add path=${pathValue},scope=project,note="<why this artifact belongs to the item>"`}})}function summarizeOrphanedPathRows(rows){return rows.map(row=>`${row.path}:${row.classification} owner_candidate=${row.owner_candidate?.id??"unowned"} hint=${JSON.stringify(row.remediation_hint)}`)}function closureLikeFieldsForItem(item,lifecyclePatternPolicy){return Object.entries(lifecyclePatternPolicy.closure_like_metadata_field_patterns).filter(([field,patterns])=>{const value=toMeaningfulString(item[field]);return value?patterns.some(pattern=>value.toLowerCase().includes(pattern)):!1}).map(([field])=>field).sort((left,right)=>left.localeCompare(right))}function buildTerminalParentFixRow(item,parent,itemsById,canonicalIdByLowercase,statusRegistry){const grandparentId=toMeaningfulString(parent.parent),grandparent=grandparentId?itemsById.get(canonicalIdByLowercase.get(grandparentId.toLowerCase())??grandparentId):void 0;return{id:item.id,parent_id:parent.id,grandparent_id:grandparent?.id,grandparent_active:grandparent!==void 0&&!isTerminalStatus(grandparent.status,statusRegistry)}}function staleBlockerReasonsForItem(item,blockedStatuses,statusRegistry,lifecyclePatternPolicy){const blockedBy=toMeaningfulString(item.blocked_by),blockedReason=toMeaningfulString(item.blocked_reason),blockedReasonNormalized=blockedReason?.toLowerCase(),normalizedStatus=normalizeStatusForRegistry(item.status,statusRegistry),reasons=[];return blockedStatuses.has(normalizedStatus)?(!blockedBy&&!blockedReason&&reasons.push("blocked_status_missing_blocker_context"),blockedReasonNormalized?.includes("no active blocker")&&reasons.push("blocked_status_reason_reports_no_active_blocker"),blockedReasonNormalized&&lifecyclePatternPolicy.stale_blocker_reason_patterns.some(pattern=>blockedReasonNormalized.includes(pattern))&&reasons.push("blocked_status_reason_matches_stale_pattern"),reasons):(blockedBy&&reasons.push("non_blocked_status_has_blocked_by"),blockedReason&&reasons.push("non_blocked_status_has_blocked_reason"),reasons)}function collectLifecycleScanRows(items,includeStaleBlockers,statusRegistry,lifecyclePatternPolicy){const itemsById=new Map(items.map(item=>[item.id,item])),canonicalIdByLowercase=new Map(items.map(item=>[item.id.toLowerCase(),item.id])),blockedStatuses=statusRegistry.blocked_statuses.size>0?statusRegistry.blocked_statuses:new Set(["blocked"]),rows={activeItems:items.filter(item=>!isTerminalStatus(item.status,statusRegistry)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(const item of rows.activeItems){const closureLikeFields=closureLikeFieldsForItem(item,lifecyclePatternPolicy);closureLikeFields.length>0&&rows.closureLikeRows.push({id:item.id,fields:closureLikeFields});const parentId=toMeaningfulString(item.parent),parent=parentId?itemsById.get(canonicalIdByLowercase.get(parentId.toLowerCase())??parentId):void 0;if(parent&&isTerminalStatus(parent.status,statusRegistry)&&(rows.terminalParentRows.push({id:item.id,parent_id:parent.id,parent_status:parent.status}),rows.terminalParentFixRows.push(buildTerminalParentFixRow(item,parent,itemsById,canonicalIdByLowercase,statusRegistry))),includeStaleBlockers){const reasons=staleBlockerReasonsForItem(item,blockedStatuses,statusRegistry,lifecyclePatternPolicy);reasons.length>0&&rows.staleBlockerRows.push({id:item.id,status:item.status,reasons:[...new Set(reasons)].sort((left,right)=>left.localeCompare(right))})}}return rows}function sortLifecycleScanRows(rows){rows.closureLikeRows.sort((left,right)=>left.id.localeCompare(right.id)),rows.terminalParentRows.sort((left,right)=>left.id.localeCompare(right.id)||left.parent_id.localeCompare(right.parent_id)),rows.terminalParentFixRows.sort((left,right)=>left.id.localeCompare(right.id)||left.parent_id.localeCompare(right.parent_id)),rows.staleBlockerRows.sort((left,right)=>left.id.localeCompare(right.id))}function lifecycleCycleWarningToken(prefix,severity,count){return count<=0||severity==="off"?null:`${severity==="error"?`${prefix}_error`:prefix}:${count}`}function lifecycleAdvisoryWarningToken(prefix,severity,count){return count>0&&severity!=="off"?`${prefix}:${count}`:null}function buildLifecycleWarnings(rows,includeStaleBlockers,dependencyCycleSeverity,parentCycleSeverity,counts){const warnings=[];rows.closureLikeRows.length>0&&warnings.push(`validate_lifecycle_active_closure_like_metadata:${rows.closureLikeRows.length}`),rows.terminalParentRows.length>0&&warnings.push(`validate_lifecycle_active_terminal_parent:${rows.terminalParentRows.length}`),includeStaleBlockers&&rows.staleBlockerRows.length>0&&warnings.push(`validate_lifecycle_stale_blockers:${rows.staleBlockerRows.length}`);const dependencyWarning=lifecycleCycleWarningToken("validate_lifecycle_dependency_cycles",dependencyCycleSeverity,counts.dependencyCycles),parentWarning=lifecycleCycleWarningToken("validate_hierarchy_parent_cycle",parentCycleSeverity,counts.activeHierarchyCycles),cardinalityWarning=lifecycleCycleWarningToken("validate_hierarchy_cardinality_violation",parentCycleSeverity,counts.activeHierarchyCardinality),divergenceWarning=lifecycleCycleWarningToken("validate_hierarchy_parent_divergence",parentCycleSeverity,counts.activeHierarchyDivergence),legacyCycleWarning=lifecycleAdvisoryWarningToken("validate_legacy_hierarchy_parent_cycle",parentCycleSeverity,counts.legacyHierarchyCycles),legacyCardinalityWarning=lifecycleAdvisoryWarningToken("validate_legacy_hierarchy_cardinality_violation",parentCycleSeverity,counts.legacyHierarchyCardinality),legacyDivergenceWarning=lifecycleAdvisoryWarningToken("validate_legacy_hierarchy_parent_divergence",parentCycleSeverity,counts.legacyHierarchyDivergence);return[...warnings,...dependencyWarning?[dependencyWarning]:[],...parentWarning?[parentWarning]:[],...cardinalityWarning?[cardinalityWarning]:[],...divergenceWarning?[divergenceWarning]:[],...legacyCycleWarning?[legacyCycleWarning]:[],...legacyCardinalityWarning?[legacyCardinalityWarning]:[],...legacyDivergenceWarning?[legacyDivergenceWarning]:[]]}function linkedArtifactPathExceedsFilesystemLimits(artifactPath){const normalized=normalizeRelativePath(artifactPath);return normalized.length>LINKED_ARTIFACT_MAX_PATH_LENGTH||normalized.split(/[\\/]/).some(segment=>segment.length>LINKED_ARTIFACT_MAX_SEGMENT_LENGTH)}async function linkedArtifactIsMissing(workspaceRoot,artifactPath){const absolutePath=path.isAbsolute(artifactPath)?artifactPath:path.resolve(workspaceRoot,artifactPath);if(linkedArtifactPathExceedsFilesystemLimits(absolutePath))return!1;try{const stats=await fs.stat(absolutePath);return!stats.isFile()&&!stats.isDirectory()}catch(error){return hasFilesystemErrorCode(error,["ENOENT","ENOTDIR"])}}async function collectLinkedPathScanState(items,workspaceRoot){const state={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},linkedArtifacts=items.flatMap(item=>[...(item.files??[]).map(artifact=>({item,artifact,link_kind:"files"})),...(item.docs??[]).map(artifact=>({item,artifact,link_kind:"docs"}))]);for(const{item,artifact,link_kind}of linkedArtifacts){if(artifact.scope!=="project")continue;if(isRemoteLinkedArtifactReference(artifact.path)){state.remoteLinkedPaths.add(artifact.path.trim());continue}const normalizedPath=normalizeRelativePath(artifact.path);normalizedPath.length!==0&&(state.linkedProjectPaths.add(normalizedPath),await linkedArtifactIsMissing(workspaceRoot,artifact.path)&&(state.missingLinkedPaths.push(normalizedPath),state.staleLinkRows.push({item_id:item.id,path:normalizedPath,link_kind})))}return state}function partitionFileCandidates(fileCandidates,pmRoot,workspaceRoot,fileScanMode,includePmInternals,verboseFileLists){const strictTrackedAllMode=fileScanMode==="tracked-all-strict",strictModeForcesPmInternals=strictTrackedAllMode&&!includePmInternals,includePmInternalsEffective=includePmInternals||strictTrackedAllMode,pmInternalCandidatePrefixes=includePmInternalsEffective?[]:resolvePmInternalCandidatePrefixes(pmRoot,workspaceRoot),excludedPmInternalPaths=pmInternalCandidatePrefixes.length===0?[]:fileCandidates.candidateFiles.filter(candidate=>hasPathPrefix(candidate,pmInternalCandidatePrefixes)),candidateFiles=pmInternalCandidatePrefixes.length===0?fileCandidates.candidateFiles:fileCandidates.candidateFiles.filter(candidate=>!hasPathPrefix(candidate,pmInternalCandidatePrefixes)),excludedByReason={};if(excludedPmInternalPaths.length>0){const summarizedPmInternalPaths=summarizeFileList(excludedPmInternalPaths,verboseFileLists);excludedByReason.pm_internals={count:excludedPmInternalPaths.length,paths:summarizedPmInternalPaths.values,paths_truncated:summarizedPmInternalPaths.truncated,paths_total:summarizedPmInternalPaths.total}}return{strictTrackedAllMode,strictModeForcesPmInternals,includePmInternalsEffective,pmInternalCandidatePrefixes,excludedPmInternalPaths,candidateFiles,excludedByReason}}function buildLifecycleCheck(items,includeStaleBlockers,dependencyCycleSeverity,parentCycleSeverity,statusRegistry,lifecyclePatternPolicy,verboseDiagnostics,idPrefix="pm"){const rows=collectLifecycleScanRows(items,includeStaleBlockers,statusRegistry,lifecyclePatternPolicy);sortLifecycleScanRows(rows);const dependencyCycleDiagnostics=detectLifecycleDependencyCycles(rows.activeItems,idPrefix),parentCycleDiagnostics=detectLifecycleParentCycles(items,statusRegistry),statusRoleDiagnostics=inspectStatusRoleAssignments(statusRegistry,items,verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT),warnings=[...buildLifecycleWarnings(rows,includeStaleBlockers,dependencyCycleSeverity,parentCycleSeverity,{dependencyCycles:dependencyCycleDiagnostics.cycle_count,activeHierarchyCycles:parentCycleDiagnostics.active_cycle_count,activeHierarchyCardinality:parentCycleDiagnostics.active_cardinality_violation_count,activeHierarchyDivergence:parentCycleDiagnostics.active_parent_divergence_count,legacyHierarchyCycles:parentCycleDiagnostics.legacy_cycle_count,legacyHierarchyCardinality:parentCycleDiagnostics.legacy_cardinality_violation_count,legacyHierarchyDivergence:parentCycleDiagnostics.legacy_parent_divergence_count}),...buildStatusRoleWarnings(statusRoleDiagnostics)],diagnosticLimit=verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT,summarizedClosureLikeRows=summarizeList(rows.closureLikeRows.map(row=>`${row.id}:${row.fields.join(",")}`),diagnosticLimit),summarizedTerminalParentRows=summarizeList(rows.terminalParentRows.map(row=>`${row.id}:${row.parent_id}:${row.parent_status}`),diagnosticLimit),summarizedStaleBlockerRows=summarizeList(rows.staleBlockerRows.map(row=>`${row.id}:${row.status}:${row.reasons.join(",")}`),diagnosticLimit),summarizedDependencyCycleItemIds=summarizeList(dependencyCycleDiagnostics.cycle_item_ids,diagnosticLimit),summarizedDependencyCycleSamplePaths=summarizeList(dependencyCycleDiagnostics.cycle_sample_paths,diagnosticLimit),summarizedParentCycleItemIds=summarizeList(parentCycleDiagnostics.cycle_item_ids,diagnosticLimit),summarizedParentCycleSamplePaths=summarizeList(parentCycleDiagnostics.cycle_sample_paths,diagnosticLimit),summarizedHierarchyCardinalityRows=summarizeList(parentCycleDiagnostics.cardinality_violation_rows,diagnosticLimit),summarizedHierarchyDivergenceRows=summarizeList(parentCycleDiagnostics.parent_divergence_rows,diagnosticLimit),hasErrorSeverityCycle=dependencyCycleDiagnostics.cycle_count>0&&dependencyCycleSeverity==="error"||(parentCycleDiagnostics.active_cycle_count>0||parentCycleDiagnostics.active_cardinality_violation_count>0||parentCycleDiagnostics.active_parent_divergence_count>0)&&parentCycleSeverity==="error";return{check:{name:"lifecycle",status:hasErrorSeverityCycle?"error":warnings.length===0?"ok":"warn",ok:!hasErrorSeverityCycle&&warnings.length===0,details:{checked_active_items:rows.activeItems.length,lifecycle_status_roles:statusRoleDiagnostics,active_closure_like_metadata_items:rows.closureLikeRows.length,active_closure_like_metadata_rows:summarizedClosureLikeRows.values,active_closure_like_metadata_rows_truncated:summarizedClosureLikeRows.truncated,active_terminal_parent_items:rows.terminalParentRows.length,active_terminal_parent_rows:summarizedTerminalParentRows.values,active_terminal_parent_rows_truncated:summarizedTerminalParentRows.truncated,stale_blocker_checks_enabled:includeStaleBlockers,stale_blocker_items:rows.staleBlockerRows.length,stale_blocker_rows:summarizedStaleBlockerRows.values,stale_blocker_rows_truncated:summarizedStaleBlockerRows.truncated,dependency_cycle_severity_policy:dependencyCycleSeverity,dependency_cycle_count:dependencyCycleDiagnostics.cycle_count,dependency_cycle_item_count:dependencyCycleDiagnostics.cycle_item_ids.length,dependency_cycle_item_ids:summarizedDependencyCycleItemIds.values,dependency_cycle_item_ids_truncated:summarizedDependencyCycleItemIds.truncated,dependency_cycle_sample_paths:summarizedDependencyCycleSamplePaths.values,dependency_cycle_sample_paths_truncated:summarizedDependencyCycleSamplePaths.truncated,parent_cycle_severity_policy:parentCycleSeverity,parent_cycle_count:parentCycleDiagnostics.cycle_count,active_parent_cycle_count:parentCycleDiagnostics.active_cycle_count,legacy_parent_cycle_count:parentCycleDiagnostics.legacy_cycle_count,parent_cycle_item_count:parentCycleDiagnostics.cycle_item_ids.length,parent_cycle_item_ids:summarizedParentCycleItemIds.values,parent_cycle_item_ids_truncated:summarizedParentCycleItemIds.truncated,parent_cycle_sample_paths:summarizedParentCycleSamplePaths.values,parent_cycle_sample_paths_truncated:summarizedParentCycleSamplePaths.truncated,hierarchy_cardinality_violation_count:parentCycleDiagnostics.cardinality_violation_count,active_hierarchy_cardinality_violation_count:parentCycleDiagnostics.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:parentCycleDiagnostics.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:summarizedHierarchyCardinalityRows.values,hierarchy_cardinality_violation_rows_truncated:summarizedHierarchyCardinalityRows.truncated,hierarchy_parent_divergence_count:parentCycleDiagnostics.parent_divergence_count,active_hierarchy_parent_divergence_count:parentCycleDiagnostics.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:parentCycleDiagnostics.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:summarizedHierarchyDivergenceRows.values,hierarchy_parent_divergence_rows_truncated:summarizedHierarchyDivergenceRows.truncated,stale_blocker_reason_patterns:[...lifecyclePatternPolicy.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:lifecyclePatternPolicy.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...lifecyclePatternPolicy.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...lifecyclePatternPolicy.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...lifecyclePatternPolicy.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.actual_result}},warnings,terminalParentFixRows:rows.terminalParentFixRows}}async function buildFilesCheck(items,workspaceRoot,pmRoot,fileScanMode,includePmInternals,verboseFileLists,statusRegistry=resolveRuntimeStatusRegistry(SETTINGS_DEFAULTS.schema)){const linkedPathState=await collectLinkedPathScanState(items,workspaceRoot),itemsById=new Map(items.map(item=>[item.id,item])),uniqueMissingLinkedPaths=[...new Set(linkedPathState.missingLinkedPaths)].sort((left,right)=>left.localeCompare(right)),fileCandidates=await collectProjectFileCandidates(workspaceRoot,fileScanMode),partition=partitionFileCandidates(fileCandidates,pmRoot,workspaceRoot,fileScanMode,includePmInternals,verboseFileLists),orphanedFiles=partition.candidateFiles.filter(candidate=>!linkedPathState.linkedProjectPaths.has(candidate)),orphanedPathRows=buildOrphanedPathRows(orphanedFiles,items),classifiedStalePaths=classifyStaleLinkedPaths(uniqueMissingLinkedPaths,partition.candidateFiles),classificationByPath=new Map(classifiedStalePaths.map(entry=>[entry.path,entry.classification])),movedStalePathCount=classifiedStalePaths.filter(entry=>entry.classification==="moved").length,staleLinkPruneRows=linkedPathState.staleLinkRows.map(row=>({...row,classification:classificationByPath.get(row.path)??"deleted"})).sort((left,right)=>left.item_id.localeCompare(right.item_id)||left.path.localeCompare(right.path)||left.link_kind.localeCompare(right.link_kind)),warnings=[];partition.strictModeForcesPmInternals&&warnings.push("validate_files_tracked_all_strict_forces_pm_internals"),orphanedFiles.length>0&&warnings.push(`validate_files_orphaned_paths:${orphanedFiles.length}`);const uniqueRemoteLinkedPaths=[...linkedPathState.remoteLinkedPaths].sort((left,right)=>left.localeCompare(right)),summarizedRemote=summarizeFileList(uniqueRemoteLinkedPaths,verboseFileLists),summarizedMissing=summarizeFileList(uniqueMissingLinkedPaths,verboseFileLists),summarizedOrphaned=summarizeFileList(orphanedFiles,verboseFileLists),summarizedOrphanedClassifications=summarizeFileList(orphanedPathRows.map(row=>`${row.path}:${row.classification}:owner_candidate=${row.owner_candidate?.id??"unowned"}`),verboseFileLists),orphanedPathRowDetail=verboseFileLists?orphanedPathRows:summarizeFileList(summarizeOrphanedPathRows(orphanedPathRows),!1).values,summarizedClassifications=summarizeFileList(summarizeStaleLinkedPathClassifications(classifiedStalePaths),verboseFileLists),repairReport=buildLinkedFileRepairReport(staleLinkPruneRows,classifiedStalePaths,id=>itemsById.get(id),statusRegistry,verboseFileLists?1/0:FILE_LIST_SUMMARY_LIMIT);return repairReport.active_missing_linked_paths_count>0&&warnings.push(`validate_files_missing_linked_paths:${repairReport.active_missing_linked_paths_count}`),{check:{name:"files",status:warnings.length===0?"ok":"warn",ok:warnings.length===0,details:{workspace_root:workspaceRoot,scan_mode_requested:fileCandidates.requestedMode,scan_mode_applied:fileCandidates.appliedMode,strict_tracked_all_mode:partition.strictTrackedAllMode,strict_mode_forces_pm_internals:partition.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:partition.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:verboseFileLists?"full":"summary",file_list_summary_limit:FILE_LIST_SUMMARY_LIMIT,candidate_scan_source:fileCandidates.source,include_pm_internals:partition.includePmInternalsEffective,include_pm_internals_requested:includePmInternals,pm_internal_candidate_prefixes:partition.pmInternalCandidatePrefixes,pm_internal_excluded_count:partition.excludedPmInternalPaths.length,excluded_total:partition.excludedPmInternalPaths.length,excluded_by_reason:partition.excludedByReason,linked_project_paths:linkedPathState.linkedProjectPaths.size,remote_linked_paths_count:uniqueRemoteLinkedPaths.length,remote_linked_paths_total:summarizedRemote.total,remote_linked_paths:summarizedRemote.values,remote_linked_paths_truncated:summarizedRemote.truncated,candidate_total_raw:fileCandidates.candidateTotal,candidate_scanned_raw:fileCandidates.candidateScanned,candidate_total:partition.candidateFiles.length,candidate_scanned:partition.candidateFiles.length,scanned_candidate_files:partition.candidateFiles.length,missing_linked_paths_count:uniqueMissingLinkedPaths.length,missing_linked_paths_total:summarizedMissing.total,missing_linked_paths:summarizedMissing.values,missing_linked_paths_truncated:summarizedMissing.truncated,missing_linked_paths_moved_count:movedStalePathCount,missing_linked_paths_deleted_count:classifiedStalePaths.filter(entry=>entry.classification==="deleted").length,missing_linked_paths_malformed_count:classifiedStalePaths.filter(entry=>entry.classification==="malformed").length,missing_linked_path_classifications:summarizedClassifications.values,missing_linked_path_classifications_truncated:summarizedClassifications.truncated,...repairReport,orphaned_paths_count:orphanedFiles.length,orphaned_paths_total:summarizedOrphaned.total,orphaned_paths:summarizedOrphaned.values,orphaned_paths_truncated:summarizedOrphaned.truncated,orphaned_path_classifications:summarizedOrphanedClassifications.values,orphaned_path_classifications_truncated:summarizedOrphanedClassifications.truncated,orphaned_path_rows_count:orphanedPathRows.length,orphaned_path_rows:orphanedPathRowDetail}},warnings,staleLinkPruneRows}}function buildUntrustedLinkedTestRows(linkedTests,trustDecisions){const rows=[];return linkedTests.forEach(({item,linkedTest},index)=>{const trust=trustDecisions[index];if(trust.trusted)return;const command=summarizeCommandPreview(linkedTest.command??"");rows.push(`${item.id}:${trust.source_ref??"unknown"}->${trust.current_source_ref??"unknown"}:${command}`)}),rows}async function buildCommandReferencesCheck(items,idPrefix,verboseDiagnostics,pmRoot){const knownIds=new Set(items.map(item=>item.id.toLowerCase()));let linkedCommandsScanned=0,referencedPmIdCount=0;const referencedPmIds=new Set,staleReferenceRows=[],linkedTests=items.flatMap(item=>(item.tests??[]).map(linkedTest=>({item,linkedTest}))),currentSourceRef=await resolveLinkedTestSourceRef(resolveLinkedTestSourceWorkspaceRoot()),trustDecisions=await resolveLinkedTestTrustBatch(pmRoot,linkedTests.map(({linkedTest})=>linkedTest),currentSourceRef),untrustedRows=buildUntrustedLinkedTestRows(linkedTests,trustDecisions);for(const{item,linkedTest}of linkedTests){if(typeof linkedTest.command!="string"||linkedTest.command.trim().length===0)continue;linkedCommandsScanned+=1;const referencedIds=extractReferencedPmItemIdsFromCommand(linkedTest.command,idPrefix);if(referencedIds.length!==0){referencedPmIdCount+=referencedIds.length;for(const referencedId of referencedIds)referencedPmIds.add(referencedId),knownIds.has(referencedId.toLowerCase())||staleReferenceRows.push(`${item.id}:${referencedId}:${summarizeCommandPreview(linkedTest.command)}`)}}const uniqueStaleReferenceRows=[...new Set(staleReferenceRows)].sort((left,right)=>left.localeCompare(right)),stalePmIds=[...new Set(uniqueStaleReferenceRows.map(row=>row.split(":")[1]??""))].filter(value=>value.length>0).sort((left,right)=>left.localeCompare(right)),warnings=[];uniqueStaleReferenceRows.length>0&&warnings.push(`validate_command_references_stale_pm_ids:${uniqueStaleReferenceRows.length}`),untrustedRows.length>0&&warnings.push(`validate_linked_test_trust_unacknowledged:${untrustedRows.length}`);const diagnosticLimit=verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT,summarizedRows=summarizeList(uniqueStaleReferenceRows,diagnosticLimit),summarizedStalePmIds=summarizeList(stalePmIds,diagnosticLimit),summarizedReferencedPmIds=summarizeList([...referencedPmIds].sort((left,right)=>left.localeCompare(right)),diagnosticLimit),summarizedUntrustedRows=summarizeList(untrustedRows,diagnosticLimit);return{check:{name:"command_references",status:warnings.length===0?"ok":"warn",ok:warnings.length===0,details:{checked_items:items.length,linked_commands_scanned:linkedCommandsScanned,referenced_pm_ids_count:referencedPmIdCount,unique_referenced_pm_ids_count:referencedPmIds.size,unique_referenced_pm_ids:summarizedReferencedPmIds.values,unique_referenced_pm_ids_truncated:summarizedReferencedPmIds.truncated,linked_test_trust_current_source_ref:currentSourceRef??null,untrusted_linked_tests_count:untrustedRows.length,untrusted_linked_tests:summarizedUntrustedRows.values,untrusted_linked_tests_truncated:summarizedUntrustedRows.truncated,stale_pm_id_references_count:uniqueStaleReferenceRows.length,stale_pm_ids_count:stalePmIds.length,stale_pm_ids:summarizedStalePmIds.values,stale_pm_ids_truncated:summarizedStalePmIds.truncated,stale_pm_id_reference_rows:summarizedRows.values,stale_pm_id_reference_rows_truncated:summarizedRows.truncated}},warnings}}function buildFormatVersionCheck(items,verboseDiagnostics){const scan=scanItemFormatVersions(items.map(item=>({ref:item.id,version:effectiveItemFormatVersion(item)})),CURRENT_ITEM_FORMAT_VERSION,BASELINE_ITEM_FORMAT_VERSION),warnings=[];scan.outdated.length>0&&warnings.push(`validate_format_version_outdated_items:${scan.outdated.length}`),scan.ahead.length>0&&warnings.push(`validate_format_version_ahead_items:${scan.ahead.length}`);const diagnosticLimit=verboseDiagnostics?Number.POSITIVE_INFINITY:DIAGNOSTIC_LIST_SUMMARY_LIMIT,summarizedOutdated=summarizeList(scan.outdated,diagnosticLimit),summarizedAhead=summarizeList(scan.ahead,diagnosticLimit),status=scan.ahead.length>0?"error":scan.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status,ok:status==="ok",details:{checked_items:items.length,current_format_version:CURRENT_ITEM_FORMAT_VERSION,outdated_items_count:scan.outdated.length,outdated_items:summarizedOutdated.values,outdated_items_truncated:summarizedOutdated.truncated,ahead_items_count:scan.ahead.length,ahead_items:summarizedAhead.values,ahead_items_truncated:summarizedAhead.truncated}},warnings}}const VALIDATE_AUTO_FIX_MESSAGE="pm validate auto-fix";async function applyValidateFix(fix,global2,services){switch(fix.kind){case"set_closed_at":await applyClosureTimestampFix(fix,global2);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{const updateOptions={message:VALIDATE_AUTO_FIX_MESSAGE};if(fix.kind==="set_resolution"?updateOptions.resolution=fix.value:fix.kind==="set_close_reason"?updateOptions.closeReason=fix.value:fix.kind==="set_estimate"?updateOptions.estimatedMinutes=fix.value:fix.kind==="reparent"?updateOptions.parent=fix.parent_id:updateOptions.unset=["parent"],!services.runUpdate)throw new PmCliError("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",EXIT_CODE.USAGE);await services.runUpdate(fix.item_id,updateOptions,global2);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${fix.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${fix.kind}`)}}function pruneBatchKey(fix){return fix.kind!=="prune_file_link"&&fix.kind!=="prune_doc_link"?null:`${fix.kind}:${fix.item_id}`}async function applyValidateFixes(applicable,global2,services){const applied=[],failed=[],pruneBatches=new Map;for(const fix of applicable.filter(candidate=>pruneBatchKey(candidate)===null))try{await applyValidateFix(fix,global2,services),applied.push(fix)}catch(error){failed.push({fix,error})}for(const fix of applicable.filter(candidate=>pruneBatchKey(candidate)!==null)){const batchKey=pruneBatchKey(fix),existing=pruneBatches.get(batchKey);existing?existing.push(fix):pruneBatches.set(batchKey,[fix])}for(const batch of pruneBatches.values()){const first=batch[0];if(!first)continue;const remove=batch.map(fix=>fix.path).filter(value=>typeof value=="string"&&value.length>0);try{first.kind==="prune_file_link"?await runFiles(first.item_id,{remove,message:VALIDATE_AUTO_FIX_MESSAGE},global2):await runDocs(first.item_id,{remove,message:VALIDATE_AUTO_FIX_MESSAGE},global2),applied.push(...batch)}catch(error){failed.push(...batch.map(fix=>({fix,error})))}}return throwFirstItemRevisionConflict(failed.map(entry=>entry.error)),{applied,failed}}const _testOnlyValidateCommand={applyValidateFix,applyValidateFixes,attachValidateFixHints,buildCommandReferencesCheck,buildDependencyReferencesCheck,buildCloseReasonBackfillRows,buildFilesCheck,buildLifecycleCheck,buildLifecycleDependencyGraph,buildLifecycleParentGraph,buildEstimateBackfillRows,buildMetadataCounts,buildMissingFieldOccurrences,buildOrphanedPathRows,classifyOrphanedPath,collectDefaultProjectFileCandidates,collectTrackedGitFileCandidates,detectLifecycleDependencyCycles,detectLifecycleParentCycles,escapeRegExp,extractItemIds,findLifecycleDependencyCycleComponents,isMetadataFieldMissing,linkedArtifactPathExceedsFilesystemLimits,listFilesRecursive,resolveDependencyCycleSeverity,resolveParentCycleSeverity,resolveFileScanMode,resolveLifecycleDependencyCycleSamplePath,resolveRequestedChecks,resolveValidateMetadataProfile,resolveWorkspaceRoot,sharedDirectoryPrefixLength,summarizeOrphanedPathRows,summarizeDuplicateIssueCodes,toMeaningfulString};function appendInvalidMergeReceiptEvidenceWarning(warnings,invalidEvidenceCount){invalidEvidenceCount>0&&warnings.push(`merge_receipt_evidence_invalid:${invalidEvidenceCount}`)}async function buildStorageIntegrityCheck(pmRoot,items,typeToFolder,settings){const scan=await scanStorageIntegrity(pmRoot,new Set(items.map(item=>item.id)),typeToFolder,{schema:settings.schema,extensionFieldNames:collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}),warnings=[];scan.unreadable_item_files.length>0&&warnings.push(`validate_storage_unreadable_items:${scan.unreadable_item_files.length}`),scan.duplicate_item_ids.length>0&&warnings.push(`validate_storage_duplicate_item_ids:${scan.duplicate_item_ids.length}`),scan.history_conflict_marker_streams.length>0&&warnings.push(`validate_storage_history_conflict_markers:${scan.history_conflict_marker_streams.length}`),scan.history_unparseable_streams.length>0&&warnings.push(`validate_storage_unparseable_history:${scan.history_unparseable_streams.length}`),scan.resurrected_items.length>0&&warnings.push(`validate_storage_resurrected_items:${scan.resurrected_items.length}`),scan.unparseable_config_files.length>0&&warnings.push(`validate_storage_unparseable_config:${scan.unparseable_config_files.length}`);const errorCount=warnings.length,trackedRuntimeCache=await scanTrackedRuntimeCache(pmRoot);trackedRuntimeCache.tracked_path_count>0&&warnings.push(`validate_storage_tracked_runtime_cache_files:${trackedRuntimeCache.tracked_path_count}`);const fenceAudit=await auditMergeAttributeFence(pmRoot,resolveProjectMergeTypeFolders(settings));fenceAudit.status==="drift"&&warnings.push(`validate_merge_fence_drift:${fenceAudit.missing_patterns.length+fenceAudit.stale_patterns.length}`);const gitWorkspaceRoot=await findGitWorkspaceRoot(pmRoot),mergeDriverAudit=gitWorkspaceRoot===null?null:await auditMergeDriverConfiguration(gitWorkspaceRoot);mergeDriverAudit!==null&&mergeDriverAudit.status!=="ok"&&warnings.push(`validate_merge_driver_configuration:${mergeDriverAudit.missing_keys.length+mergeDriverAudit.drifted_keys.length}`);const mergeReceiptEvidence=await inspectMergeReceiptEvidence(gitWorkspaceRoot??pmRoot,{includeLossless:!0,pmRoot}),pendingMergeReceipts=mergeReceiptEvidence.receipts,{pendingDecisions:pendingMergeDecisions,lossless:losslessMergeReceipts}=partitionMergeReceipts(pendingMergeReceipts);pendingMergeDecisions.length>0&&warnings.push(`validate_merge_decisions_unreviewed:${pendingMergeDecisions.length}`),appendInvalidMergeReceiptEvidenceWarning(warnings,mergeReceiptEvidence.invalid_evidence_count);const status=errorCount>0?"error":warnings.length>0?"warn":"ok";return{check:{name:"storage_integrity",status,ok:status==="ok",details:{...scan,merge_fence:fenceAudit,merge_driver_configuration:mergeDriverAudit,pending_merge_decision_count:pendingMergeDecisions.length,pending_merge_decision_items:[...new Set(pendingMergeDecisions.map(receipt=>receipt.item_id))].sort((left,right)=>left.localeCompare(right)),lossless_merge_receipt_count:losslessMergeReceipts.length,invalid_merge_receipt_evidence_count:mergeReceiptEvidence.invalid_evidence_count,invalid_merge_receipt_evidence_details:mergeReceiptEvidence.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:mergeReceiptEvidence.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(losslessMergeReceipts.map(receipt=>receipt.item_id))].sort((left,right)=>left.localeCompare(right)),tracked_runtime_cache:{tracker_relative_root:trackedRuntimeCache.tracker_relative_root,tracked_paths:trackedRuntimeCache.tracked_paths,tracked_path_count:trackedRuntimeCache.tracked_path_count,remediation_command:trackedRuntimeCache.remediation_command}}},warnings}}function recordValidateCheck(state,built,fixHintsEnabled){fixHintsEnabled&&attachValidateFixHints(built.check,built.warnings),state.checks.push(built.check),state.warnings.push(...built.warnings)}async function executeRequestedValidateChecks(params){const state={closureTimestampFixes:[],checks:[],warnings:[...params.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},fixHintsEnabled=params.options.fixHints===!0,fullDiagnostics=params.options.verboseDiagnostics===!0||params.options.allAffectedIds===!0||params.global.json===!0;if(params.requestedChecks.has("completeness")){const built=await readWorkflowCompletenessCheck(params.pmRoot,params.items,fullDiagnostics?1/0:DIAGNOSTIC_LIST_SUMMARY_LIMIT,params.sourceIncomplete);recordValidateCheck(state,built,fixHintsEnabled)}if(params.requestedChecks.has("metadata")){const built=buildMetadataCheck(params.items,params.metadataPolicy,params.statusRegistry,fullDiagnostics,[params.settings.id_prefix]);state.closeReasonBackfillRows=built.closeReasonBackfillRows,state.estimateBackfillRows=built.estimateBackfillRows;const timestamps=await scanClosureTimestamps(params.pmRoot,params.items,params.statusRegistry,params.options.autoFix===!0||fixHintsEnabled,fullDiagnostics?1/0:DIAGNOSTIC_LIST_SUMMARY_LIMIT);state.closureTimestampFixes=timestamps.fixes,Object.assign(built.check.details,timestamps.details),built.warnings.push(...timestamps.warnings),built.check.ok=built.warnings.length===0,built.check.status=built.check.ok?"ok":"warn",recordValidateCheck(state,built,fixHintsEnabled)}if(params.requestedChecks.has("resolution")){const built=buildResolutionCheck(params.items,params.statusRegistry,fullDiagnostics);state.resolutionBackfillRows=built.resolutionBackfillRows,recordValidateCheck(state,built,fixHintsEnabled)}if(params.requestedChecks.has("lifecycle")){const built=buildLifecycleCheck(params.items,!!params.options.checkStaleBlockers,params.dependencyCycleSeverity,params.parentCycleSeverity,params.statusRegistry,params.lifecyclePatternPolicy,fullDiagnostics,params.settings.id_prefix);state.terminalParentFixRows=built.terminalParentFixRows,recordValidateCheck(state,built,fixHintsEnabled),recordValidateCheck(state,buildDependencyReferencesCheck(params.items,fullDiagnostics,params.statusRegistry),fixHintsEnabled)}if(params.requestedChecks.has("files")){const built=await buildFilesCheck(params.items,params.workspaceRoot,params.pmRoot,params.fileScanMode,!!params.options.includePmInternals,!!params.options.verboseFileLists,params.statusRegistry);state.staleLinkPruneRows=built.staleLinkPruneRows,recordValidateCheck(state,built,fixHintsEnabled)}return params.requestedChecks.has("command_references")&&recordValidateCheck(state,await buildCommandReferencesCheck(params.items,params.settings.id_prefix,fullDiagnostics,params.pmRoot),fixHintsEnabled),params.requestedChecks.has("history_drift")&&recordValidateCheck(state,await buildValidateHistoryDriftCheck(params.pmRoot,params.items,fullDiagnostics),fixHintsEnabled),params.requestedChecks.has("format_version")&&recordValidateCheck(state,buildFormatVersionCheck(params.items,fullDiagnostics),fixHintsEnabled),params.requestedChecks.has("storage_integrity")&&recordValidateCheck(state,await buildStorageIntegrityCheck(params.pmRoot,params.items,resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,params.settings),fixHintsEnabled),state}function planValidateFixes(options,state,settings){const planned=[];return options.autoFix===!0&&(planned.push(...state.closureTimestampFixes),planned.push(...planCloseReasonBackfillFixes(state.closeReasonBackfillRows)),planned.push(...planResolutionBackfillFixes(state.resolutionBackfillRows)),planned.push(...planEstimateBackfillFixes(state.estimateBackfillRows,settings.validation.estimate_defaults_by_type)),planned.push(...planTerminalParentFixes(state.terminalParentFixRows))),options.pruneMissing===!0&&planned.push(...planStaleLinkPruneFixes(state.staleLinkPruneRows)),planned}async function buildValidateFixesSummary(options,state,settings,grantedFixScopes,global2,services){if(options.autoFix!==!0&&options.pruneMissing!==!0)return;const planned=planValidateFixes(options,state,settings),{applicable,gated}=partitionFixesByGrant(planned,grantedFixScopes),dryRun=options.dryRun===!0,appliedFixRows=[],failedFixRows=[];if(!dryRun){const applied=await applyValidateFixes(applicable,global2,services);appliedFixRows.push(...applied.applied.map(toFixOutputRow)),failedFixRows.push(...applied.failed.map(({fix,error})=>({...toFixOutputRow(fix),error:error instanceof Error?error.message:String(error)})))}return{mode:dryRun?"dry_run":"apply",auto_fix:options.autoFix===!0,prune_missing:options.pruneMissing===!0,granted_fix_scopes:[...grantedFixScopes].sort((left,right)=>left.localeCompare(right)),planned_count:planned.length,applied_count:appliedFixRows.length,gated_count:gated.length,failed_count:failedFixRows.length,planned_fixes:planned.map(toFixOutputRow),applied_fixes:appliedFixRows,gated_fixes:gated.map(fix=>({...toFixOutputRow(fix),gate_hint:`Withheld: re-run with --fix-scope ${fix.gate} to apply.`})),failed_fixes:failedFixRows}}async function runValidate(options,global2,services={}){assertProjectionModeChoice(options.counts===!0,options.full===!0,"--counts");const fixesRequested=options.autoFix===!0||options.pruneMissing===!0;if(options.dryRun===!0&&!fixesRequested)throw new PmCliError("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",EXIT_CODE.USAGE);if(options.fixScope!==void 0&&options.fixScope.length>0&&options.autoFix!==!0)throw new PmCliError("--fix-scope requires --auto-fix.",EXIT_CODE.USAGE);const grantedFixScopes=resolveGrantedFixScopes(options.fixScope),pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),requestedChecks=resolveRequestedChecks(options),itemReadWarnings=[],items=await readValidateItems({includeBody:["history_drift","metadata","completeness"].some(check=>requestedChecks.has(check)),pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,warnings:itemReadWarnings}),sourceIncomplete=itemReadWarnings.length>0;if(requestedChecks.has("history_drift")){const authorAttribution=await scanHistoryAuthorAttribution(pmRoot);authorAttribution.actionable_unknown_event_count>0&&itemReadWarnings.push(`validate_history_unknown_author_events:${authorAttribution.actionable_unknown_event_count}`)}const metadataProfileSource=typeof options.metadataProfile=="string"?"option":"settings",metadataProfile=resolveValidateMetadataProfile(typeof options.metadataProfile=="string"?options.metadataProfile:settings.validation.metadata_profile),metadataPolicy=resolveValidateMetadataPolicy(metadataProfile,metadataProfileSource,settings.validation.metadata_required_fields),lifecyclePatternPolicy=resolveLifecyclePatternPolicy(settings),dependencyCycleSeverity=resolveDependencyCycleSeverity(options.dependencyCycleSeverity),parentCycleSeverity=resolveParentCycleSeverity(options.parentCycleSeverity),fileScanMode=resolveFileScanMode(options.scanMode),workspaceRoot=resolveWorkspaceRoot(pmRoot),state=await executeRequestedValidateChecks({requestedChecks,options,global:global2,pmRoot,workspaceRoot,settings,items,statusRegistry,metadataPolicy,lifecyclePatternPolicy,dependencyCycleSeverity,parentCycleSeverity,fileScanMode,initialWarnings:[...new Set(itemReadWarnings)],sourceIncomplete}),fixes=fixesRequested?await buildValidateFixesSummary(options,state,settings,grantedFixScopes,global2,services):void 0,normalizedWarnings=[...new Set(state.warnings)].sort((left,right)=>left.localeCompare(right)),result={ok:!state.checks.some(check=>check.status==="error"),has_warnings:normalizedWarnings.length>0,checks:state.checks,warnings:normalizedWarnings,...fixes!==void 0?{fixes}:{},generated_at:nowIso(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return options.counts!==!0?result:{...projectValidateCounts(result),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{_testOnlyValidateCommand,projectValidateCounts,runValidate};
2
2
  //# sourceMappingURL=validate.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bcc7d1aa-b02e-567e-8fda-981a79780d98")}catch{}})();import{listPmCommandCapabilityGroups}from"./agent-capability-contracts.js";function normalizeTopicToken(value){return value.trim().toLowerCase().replaceAll("_","-")}const GUIDE_TOPICS=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:listPmCommandCapabilityGroups().flatMap(({commands})=>commands.map(command=>`pm ${command}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks (repository checkout only; excluded from the npm package).",optional:!0},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering (repository checkout only; not in the npm package).",optional:!0}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],TOPIC_BY_TOKEN=new Map;for(const topic of GUIDE_TOPICS){TOPIC_BY_TOKEN.set(topic.id,topic);for(const alias of topic.aliases)TOPIC_BY_TOKEN.set(alias,topic)}function listGuideTopics(){return GUIDE_TOPICS.map(topic=>({...topic,aliases:[...topic.aliases],commands:[...topic.commands],workflows:topic.workflows.map(workflow=>({...workflow,commands:[...workflow.commands]})),docs:topic.docs.map(doc=>({...doc})),related:[...topic.related]}))}function listGuideTopicIds(){return GUIDE_TOPICS.map(topic=>topic.id)}function resolveGuideTopic(rawTopic){if(!rawTopic)return null;const normalized=normalizeTopicToken(rawTopic);return normalized?TOPIC_BY_TOKEN.get(normalized)??null:null}export{listGuideTopicIds,listGuideTopics,resolveGuideTopic};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="59f6a03b-a7d4-5f20-a1c7-40ab140a8355")}catch{}})();import{listPmCommandCapabilityGroups}from"./agent-capability-contracts.js";function normalizeTopicToken(value){return value.trim().toLowerCase().replaceAll("_","-")}const GUIDE_TOPICS=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:listPmCommandCapabilityGroups().flatMap(({commands})=>commands.map(command=>`pm ${command}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks (repository checkout only; excluded from the npm package).",optional:!0},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes (repository checkout only; excluded from the npm package).",optional:!0},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering (repository checkout only; not in the npm package).",optional:!0}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],TOPIC_BY_TOKEN=new Map;for(const topic of GUIDE_TOPICS){TOPIC_BY_TOKEN.set(topic.id,topic);for(const alias of topic.aliases)TOPIC_BY_TOKEN.set(alias,topic)}function listGuideTopics(){return GUIDE_TOPICS.map(topic=>({...topic,aliases:[...topic.aliases],commands:[...topic.commands],workflows:topic.workflows.map(workflow=>({...workflow,commands:[...workflow.commands]})),docs:topic.docs.map(doc=>({...doc})),related:[...topic.related]}))}function listGuideTopicIds(){return GUIDE_TOPICS.map(topic=>topic.id)}function resolveGuideTopic(rawTopic){if(!rawTopic)return null;const normalized=normalizeTopicToken(rawTopic);return normalized?TOPIC_BY_TOKEN.get(normalized)??null:null}export{listGuideTopicIds,listGuideTopics,resolveGuideTopic};
2
2
  //# sourceMappingURL=guide-topics.js.map