@unbrained/pm-cli 2026.5.30 → 2026.5.31

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 (228) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/cli/commands/calendar.js +81 -9
  3. package/dist/cli/commands/calendar.js.map +1 -1
  4. package/dist/cli/commands/create.js +34 -4
  5. package/dist/cli/commands/create.js.map +1 -1
  6. package/dist/cli/commands/extension/install-sources.d.ts +2 -0
  7. package/dist/cli/commands/extension/install-sources.js +11 -4
  8. package/dist/cli/commands/extension/install-sources.js.map +1 -1
  9. package/dist/cli/commands/reindex.js +3 -3
  10. package/dist/cli/commands/reindex.js.map +1 -1
  11. package/dist/cli/commands/search.d.ts +17 -0
  12. package/dist/cli/commands/search.js +40 -10
  13. package/dist/cli/commands/search.js.map +1 -1
  14. package/dist/cli/register-list-query.js +9 -11
  15. package/dist/cli/register-list-query.js.map +1 -1
  16. package/dist/cli/register-mutation.js +20 -22
  17. package/dist/cli/register-mutation.js.map +1 -1
  18. package/dist/cli/register-operations.js +32 -25
  19. package/dist/cli/register-operations.js.map +1 -1
  20. package/dist/cli/register-setup.js +6 -8
  21. package/dist/cli/register-setup.js.map +1 -1
  22. package/dist/cli/registration-helpers.js +6 -3
  23. package/dist/cli/registration-helpers.js.map +1 -1
  24. package/dist/cli/search-refresh.d.ts +2 -0
  25. package/dist/cli/search-refresh.js +13 -0
  26. package/dist/cli/search-refresh.js.map +1 -0
  27. package/dist/cli-bundle/chunks/activity-OWYSUZOY.js +17 -0
  28. package/dist/cli-bundle/chunks/activity-OWYSUZOY.js.map +7 -0
  29. package/dist/cli-bundle/chunks/aggregate-ADUOSFRO.js +209 -0
  30. package/dist/cli-bundle/chunks/aggregate-ADUOSFRO.js.map +7 -0
  31. package/dist/cli-bundle/chunks/append-JD2DETU7.js +73 -0
  32. package/dist/cli-bundle/chunks/append-JD2DETU7.js.map +7 -0
  33. package/dist/cli-bundle/chunks/chunk-3HUE7XOF.js +27 -0
  34. package/dist/cli-bundle/chunks/chunk-3HUE7XOF.js.map +7 -0
  35. package/dist/cli-bundle/chunks/chunk-3M73P3G6.js +1636 -0
  36. package/dist/cli-bundle/chunks/chunk-3M73P3G6.js.map +7 -0
  37. package/dist/cli-bundle/chunks/chunk-4AEZR5EJ.js +189 -0
  38. package/dist/cli-bundle/chunks/chunk-4AEZR5EJ.js.map +7 -0
  39. package/dist/cli-bundle/chunks/chunk-5HSEP75M.js +330 -0
  40. package/dist/cli-bundle/chunks/chunk-5HSEP75M.js.map +7 -0
  41. package/dist/cli-bundle/chunks/chunk-6HT2F4TK.js +1770 -0
  42. package/dist/cli-bundle/chunks/chunk-6HT2F4TK.js.map +7 -0
  43. package/dist/cli-bundle/chunks/chunk-6YCV7WSL.js +552 -0
  44. package/dist/cli-bundle/chunks/chunk-6YCV7WSL.js.map +7 -0
  45. package/dist/cli-bundle/chunks/chunk-7Y53ZJIQ.js +202 -0
  46. package/dist/cli-bundle/chunks/chunk-7Y53ZJIQ.js.map +7 -0
  47. package/dist/cli-bundle/chunks/chunk-A7E7PUVX.js +157 -0
  48. package/dist/cli-bundle/chunks/chunk-A7E7PUVX.js.map +7 -0
  49. package/dist/cli-bundle/chunks/chunk-AKOOMO3T.js +90 -0
  50. package/dist/cli-bundle/chunks/chunk-AKOOMO3T.js.map +7 -0
  51. package/dist/cli-bundle/chunks/chunk-BUPWJ3IJ.js +950 -0
  52. package/dist/cli-bundle/chunks/chunk-BUPWJ3IJ.js.map +7 -0
  53. package/dist/cli-bundle/chunks/chunk-CEFIVZPG.js +79 -0
  54. package/dist/cli-bundle/chunks/chunk-CEFIVZPG.js.map +7 -0
  55. package/dist/cli-bundle/chunks/chunk-D7AOMPRH.js +349 -0
  56. package/dist/cli-bundle/chunks/chunk-D7AOMPRH.js.map +7 -0
  57. package/dist/cli-bundle/chunks/chunk-EAOG77HM.js +56 -0
  58. package/dist/cli-bundle/chunks/chunk-EAOG77HM.js.map +7 -0
  59. package/dist/cli-bundle/chunks/chunk-EGUGFSNX.js +47 -0
  60. package/dist/cli-bundle/chunks/chunk-EGUGFSNX.js.map +7 -0
  61. package/dist/cli-bundle/chunks/chunk-FM26RGSU.js +56 -0
  62. package/dist/cli-bundle/chunks/chunk-FM26RGSU.js.map +7 -0
  63. package/dist/cli-bundle/chunks/chunk-FQE6XZDB.js +435 -0
  64. package/dist/cli-bundle/chunks/chunk-FQE6XZDB.js.map +7 -0
  65. package/dist/cli-bundle/chunks/chunk-G57E5D7T.js +185 -0
  66. package/dist/cli-bundle/chunks/chunk-G57E5D7T.js.map +7 -0
  67. package/dist/cli-bundle/chunks/chunk-GN7IJPCD.js +3621 -0
  68. package/dist/cli-bundle/chunks/chunk-GN7IJPCD.js.map +7 -0
  69. package/dist/cli-bundle/chunks/chunk-JFWUHHS2.js +233 -0
  70. package/dist/cli-bundle/chunks/chunk-JFWUHHS2.js.map +7 -0
  71. package/dist/cli-bundle/chunks/chunk-JTWRXG4B.js +1861 -0
  72. package/dist/cli-bundle/chunks/chunk-JTWRXG4B.js.map +7 -0
  73. package/dist/cli-bundle/chunks/chunk-JULRTHJQ.js +648 -0
  74. package/dist/cli-bundle/chunks/chunk-JULRTHJQ.js.map +7 -0
  75. package/dist/cli-bundle/chunks/{chunk-PB2YU2E3.js → chunk-KBQY3YG5.js} +28 -70
  76. package/dist/cli-bundle/chunks/chunk-KBQY3YG5.js.map +7 -0
  77. package/dist/cli-bundle/chunks/chunk-L2FXEKDB.js +185 -0
  78. package/dist/cli-bundle/chunks/chunk-L2FXEKDB.js.map +7 -0
  79. package/dist/cli-bundle/chunks/chunk-LRBOHPUE.js +189 -0
  80. package/dist/cli-bundle/chunks/chunk-LRBOHPUE.js.map +7 -0
  81. package/dist/cli-bundle/chunks/chunk-LSXGH6NE.js +5153 -0
  82. package/dist/cli-bundle/chunks/chunk-LSXGH6NE.js.map +7 -0
  83. package/dist/cli-bundle/chunks/chunk-MD7K4JYF.js +1345 -0
  84. package/dist/cli-bundle/chunks/chunk-MD7K4JYF.js.map +7 -0
  85. package/dist/cli-bundle/chunks/chunk-NGN7UV5K.js +341 -0
  86. package/dist/cli-bundle/chunks/chunk-NGN7UV5K.js.map +7 -0
  87. package/dist/cli-bundle/chunks/chunk-O7IWB35H.js +18 -0
  88. package/dist/cli-bundle/chunks/chunk-O7IWB35H.js.map +7 -0
  89. package/dist/cli-bundle/chunks/chunk-OGZEG5TT.js +2929 -0
  90. package/dist/cli-bundle/chunks/chunk-OGZEG5TT.js.map +7 -0
  91. package/dist/cli-bundle/chunks/{chunk-RJONRNXN.js → chunk-P53TN6IA.js} +22 -30
  92. package/dist/cli-bundle/chunks/chunk-P53TN6IA.js.map +7 -0
  93. package/dist/cli-bundle/chunks/chunk-PVNQLCIS.js +176 -0
  94. package/dist/cli-bundle/chunks/chunk-PVNQLCIS.js.map +7 -0
  95. package/dist/cli-bundle/chunks/chunk-PXUAZUUY.js +1680 -0
  96. package/dist/cli-bundle/chunks/chunk-PXUAZUUY.js.map +7 -0
  97. package/dist/cli-bundle/chunks/chunk-QAJBIGRA.js +20 -0
  98. package/dist/cli-bundle/chunks/chunk-QAJBIGRA.js.map +7 -0
  99. package/dist/cli-bundle/chunks/chunk-SEXQN4KL.js +60 -0
  100. package/dist/cli-bundle/chunks/chunk-SEXQN4KL.js.map +7 -0
  101. package/dist/cli-bundle/chunks/chunk-U7FMKRXH.js +362 -0
  102. package/dist/cli-bundle/chunks/chunk-U7FMKRXH.js.map +7 -0
  103. package/dist/cli-bundle/chunks/chunk-VGICHR7D.js +141 -0
  104. package/dist/cli-bundle/chunks/chunk-VGICHR7D.js.map +7 -0
  105. package/dist/cli-bundle/chunks/chunk-WDPXDQFG.js +632 -0
  106. package/dist/cli-bundle/chunks/chunk-WDPXDQFG.js.map +7 -0
  107. package/dist/cli-bundle/chunks/chunk-WJ2NAC37.js +252 -0
  108. package/dist/cli-bundle/chunks/chunk-WJ2NAC37.js.map +7 -0
  109. package/dist/cli-bundle/chunks/claim-EE4TKKCV.js +133 -0
  110. package/dist/cli-bundle/chunks/claim-EE4TKKCV.js.map +7 -0
  111. package/dist/cli-bundle/chunks/close-XY4CSAYF.js +14 -0
  112. package/dist/cli-bundle/chunks/close-XY4CSAYF.js.map +7 -0
  113. package/dist/cli-bundle/chunks/comments-AAKJQ6LW.js +104 -0
  114. package/dist/cli-bundle/chunks/comments-AAKJQ6LW.js.map +7 -0
  115. package/dist/cli-bundle/chunks/config-V3FZOKLI.js +1577 -0
  116. package/dist/cli-bundle/chunks/config-V3FZOKLI.js.map +7 -0
  117. package/dist/cli-bundle/chunks/context-RZ5QPNJB.js +1458 -0
  118. package/dist/cli-bundle/chunks/context-RZ5QPNJB.js.map +7 -0
  119. package/dist/cli-bundle/chunks/contracts-YLMH33VU.js +1245 -0
  120. package/dist/cli-bundle/chunks/contracts-YLMH33VU.js.map +7 -0
  121. package/dist/cli-bundle/chunks/create-PZVHRIZQ.js +28 -0
  122. package/dist/cli-bundle/chunks/create-PZVHRIZQ.js.map +7 -0
  123. package/dist/cli-bundle/chunks/delete-RHCTEORS.js +59 -0
  124. package/dist/cli-bundle/chunks/delete-RHCTEORS.js.map +7 -0
  125. package/dist/cli-bundle/chunks/deps-MZYCMLAO.js +229 -0
  126. package/dist/cli-bundle/chunks/deps-MZYCMLAO.js.map +7 -0
  127. package/dist/cli-bundle/chunks/docs-FXXUCZYU.js +35 -0
  128. package/dist/cli-bundle/chunks/docs-FXXUCZYU.js.map +7 -0
  129. package/dist/cli-bundle/chunks/extension-B4WL7BQU.js +25 -0
  130. package/dist/cli-bundle/chunks/extension-B4WL7BQU.js.map +7 -0
  131. package/dist/cli-bundle/chunks/files-WVOX67PE.js +286 -0
  132. package/dist/cli-bundle/chunks/files-WVOX67PE.js.map +7 -0
  133. package/dist/cli-bundle/chunks/gc-JWNF66EC.js +181 -0
  134. package/dist/cli-bundle/chunks/gc-JWNF66EC.js.map +7 -0
  135. package/dist/cli-bundle/chunks/get-LTK3HOCQ.js +198 -0
  136. package/dist/cli-bundle/chunks/get-LTK3HOCQ.js.map +7 -0
  137. package/dist/cli-bundle/chunks/health-TCWL55KM.js +1233 -0
  138. package/dist/cli-bundle/chunks/health-TCWL55KM.js.map +7 -0
  139. package/dist/cli-bundle/chunks/history-A2JUDXUE.js +21 -0
  140. package/dist/cli-bundle/chunks/history-A2JUDXUE.js.map +7 -0
  141. package/dist/cli-bundle/chunks/history-redact-ED6RFCPL.js +20 -0
  142. package/dist/cli-bundle/chunks/history-redact-ED6RFCPL.js.map +7 -0
  143. package/dist/cli-bundle/chunks/history-repair-ZWSTDRH2.js +198 -0
  144. package/dist/cli-bundle/chunks/history-repair-ZWSTDRH2.js.map +7 -0
  145. package/dist/cli-bundle/chunks/init-M2WUB4YH.js +16 -0
  146. package/dist/cli-bundle/chunks/init-M2WUB4YH.js.map +7 -0
  147. package/dist/cli-bundle/chunks/learnings-NXTWE3FR.js +48 -0
  148. package/dist/cli-bundle/chunks/learnings-NXTWE3FR.js.map +7 -0
  149. package/dist/cli-bundle/chunks/list-OGWQPC26.js +20 -0
  150. package/dist/cli-bundle/chunks/list-OGWQPC26.js.map +7 -0
  151. package/dist/cli-bundle/chunks/notes-DFS5ZGOO.js +48 -0
  152. package/dist/cli-bundle/chunks/notes-DFS5ZGOO.js.map +7 -0
  153. package/dist/cli-bundle/chunks/plan-67AB2PLM.js +1175 -0
  154. package/dist/cli-bundle/chunks/plan-67AB2PLM.js.map +7 -0
  155. package/dist/cli-bundle/chunks/{register-list-query-EIVQ5FMR.js → register-list-query-UP3VRUFS.js} +24 -15
  156. package/dist/cli-bundle/chunks/register-list-query-UP3VRUFS.js.map +7 -0
  157. package/dist/cli-bundle/chunks/{register-mutation-RSZNPSGI.js → register-mutation-YWSBF545.js} +38 -28
  158. package/dist/cli-bundle/chunks/register-mutation-YWSBF545.js.map +7 -0
  159. package/dist/cli-bundle/chunks/{register-operations-APUSYDMR.js → register-operations-3BDTGSDH.js} +49 -30
  160. package/dist/cli-bundle/chunks/register-operations-3BDTGSDH.js.map +7 -0
  161. package/dist/cli-bundle/chunks/{register-setup-OZOKSMPJ.js → register-setup-V56GDRUS.js} +21 -12
  162. package/dist/cli-bundle/chunks/register-setup-V56GDRUS.js.map +7 -0
  163. package/dist/cli-bundle/chunks/restore-MB2ISME7.js +18 -0
  164. package/dist/cli-bundle/chunks/restore-MB2ISME7.js.map +7 -0
  165. package/dist/cli-bundle/chunks/schema-Q622KC46.js +119 -0
  166. package/dist/cli-bundle/chunks/schema-Q622KC46.js.map +7 -0
  167. package/dist/cli-bundle/chunks/search-HENBL456.js +1135 -0
  168. package/dist/cli-bundle/chunks/search-HENBL456.js.map +7 -0
  169. package/dist/cli-bundle/chunks/stats-N6H3YP2F.js +124 -0
  170. package/dist/cli-bundle/chunks/stats-N6H3YP2F.js.map +7 -0
  171. package/dist/cli-bundle/chunks/test-VNBDRJ4Z.js +32 -0
  172. package/dist/cli-bundle/chunks/test-VNBDRJ4Z.js.map +7 -0
  173. package/dist/cli-bundle/chunks/test-all-G2AZOHXI.js +332 -0
  174. package/dist/cli-bundle/chunks/test-all-G2AZOHXI.js.map +7 -0
  175. package/dist/cli-bundle/chunks/test-runs-GX5HTPSF.js +939 -0
  176. package/dist/cli-bundle/chunks/test-runs-GX5HTPSF.js.map +7 -0
  177. package/dist/cli-bundle/chunks/update-H6SCWNMA.js +22 -0
  178. package/dist/cli-bundle/chunks/update-H6SCWNMA.js.map +7 -0
  179. package/dist/cli-bundle/chunks/update-many-46HRSP2Q.js +676 -0
  180. package/dist/cli-bundle/chunks/update-many-46HRSP2Q.js.map +7 -0
  181. package/dist/cli-bundle/chunks/upgrade-H5HHM5UV.js +271 -0
  182. package/dist/cli-bundle/chunks/upgrade-H5HHM5UV.js.map +7 -0
  183. package/dist/cli-bundle/chunks/validate-TMCVKIGZ.js +1110 -0
  184. package/dist/cli-bundle/chunks/validate-TMCVKIGZ.js.map +7 -0
  185. package/dist/cli-bundle/main.js +146 -90
  186. package/dist/cli-bundle/main.js.map +4 -4
  187. package/dist/core/item/item-type-definition.js +6 -2
  188. package/dist/core/item/item-type-definition.js.map +1 -1
  189. package/dist/core/item/type-registry.d.ts +4 -0
  190. package/dist/core/item/type-registry.js +10 -2
  191. package/dist/core/item/type-registry.js.map +1 -1
  192. package/dist/core/search/background-refresh.d.ts +53 -0
  193. package/dist/core/search/background-refresh.js +286 -0
  194. package/dist/core/search/background-refresh.js.map +1 -0
  195. package/dist/core/search/cache.d.ts +20 -1
  196. package/dist/core/search/cache.js +33 -4
  197. package/dist/core/search/cache.js.map +1 -1
  198. package/dist/core/search/vector-stores.js +7 -3
  199. package/dist/core/search/vector-stores.js.map +1 -1
  200. package/dist/core/shared/constants.d.ts +2 -2
  201. package/dist/core/shared/constants.js +2 -3
  202. package/dist/core/shared/constants.js.map +1 -1
  203. package/dist/core/store/item-format-migration.js +25 -15
  204. package/dist/core/store/item-format-migration.js.map +1 -1
  205. package/dist/core/store/settings-validator.js +6 -2
  206. package/dist/core/store/settings-validator.js.map +1 -1
  207. package/dist/core/telemetry/runtime.d.ts +10 -0
  208. package/dist/core/telemetry/runtime.js +86 -2
  209. package/dist/core/telemetry/runtime.js.map +1 -1
  210. package/dist/sdk/cli-contracts/tool-parameter-tables.js +4 -4
  211. package/dist/sdk/cli-contracts/tool-parameter-tables.js.map +1 -1
  212. package/dist/sdk/cli-contracts.js +26 -5
  213. package/dist/sdk/cli-contracts.js.map +1 -1
  214. package/dist/types.d.ts +7 -1
  215. package/dist/types.js +2 -2
  216. package/dist/types.js.map +1 -1
  217. package/docs/RELEASING.md +1 -1
  218. package/package.json +1 -2
  219. package/dist/cli-bundle/chunks/chunk-PB2YU2E3.js.map +0 -7
  220. package/dist/cli-bundle/chunks/chunk-RJONRNXN.js.map +0 -7
  221. package/dist/cli-bundle/chunks/chunk-SW5BMMCU.js +0 -13864
  222. package/dist/cli-bundle/chunks/chunk-SW5BMMCU.js.map +0 -7
  223. package/dist/cli-bundle/chunks/commands-XJ4TJ5UN.js +0 -24225
  224. package/dist/cli-bundle/chunks/commands-XJ4TJ5UN.js.map +0 -7
  225. package/dist/cli-bundle/chunks/register-list-query-EIVQ5FMR.js.map +0 -7
  226. package/dist/cli-bundle/chunks/register-mutation-RSZNPSGI.js.map +0 -7
  227. package/dist/cli-bundle/chunks/register-operations-APUSYDMR.js.map +0 -7
  228. package/dist/cli-bundle/chunks/register-setup-OZOKSMPJ.js.map +0 -7
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../../../cli/commands/validate.ts"],
4
+ "sourcesContent": ["import fs from \"node:fs/promises\";\nimport { realpathSync } from \"node:fs\";\nimport type { Dirent } from \"node:fs\";\nimport { execFile } from \"node:child_process\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { getActiveExtensionRegistrations } from \"../../core/extensions/index.js\";\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport { scanHistoryDrift } from \"../../core/history/drift-scan.js\";\nimport { normalizeStatusInput } from \"../../core/item/status.js\";\nimport { resolveItemTypeRegistry } from \"../../core/item/type-registry.js\";\nimport { resolveRuntimeStatusRegistry, type RuntimeStatusRegistry } from \"../../core/schema/runtime-schema.js\";\nimport {\n DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS,\n DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS,\n EXIT_CODE,\n PM_DIRNAME,\n} from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { toNonEmptyStringOrUndefined } from \"../../core/shared/primitives.js\";\nimport { nowIso } from \"../../core/shared/time.js\";\nimport { listAllFrontMatterWithBody } from \"../../core/store/item-store.js\";\nimport { getSettingsPath, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport type { ValidateMetadataProfile, ValidateMetadataRequiredField } from \"../../types/index.js\";\nimport { extractReferencedPmItemIdsFromCommand } from \"./test.js\";\n\ntype ValidateCheckName = \"metadata\" | \"resolution\" | \"lifecycle\" | \"files\" | \"command_references\" | \"history_drift\";\ntype ValidateStatus = \"ok\" | \"warn\" | \"error\";\ntype ValidateDependencyCycleSeverity = \"off\" | \"warn\" | \"error\";\ntype ValidateFileScanMode = \"default\" | \"tracked-all\" | \"tracked-all-strict\";\ntype ItemWithBody = Awaited<ReturnType<typeof listAllFrontMatterWithBody>>[number];\ntype FileCandidateSource = \"default-curated\" | \"tracked-git\" | \"tracked-all-fallback-default\";\n\nconst FILE_SCAN_DIRECTORIES = [\"src\", \"tests\", \"docs\"] as const;\nconst FILE_SCAN_ROOT_FILES = [\n \"README.md\",\n \"PRD.md\",\n \"CHANGELOG.md\",\n \"AGENTS.md\",\n \"CONTRIBUTING.md\",\n \"SECURITY.md\",\n \"CODE_OF_CONDUCT.md\",\n \"LICENSE\",\n] as const;\nconst DIRECTORY_IGNORE_SET = new Set([\"node_modules\", \".git\", \".cursor\", \".agents\", \"dist\", \"coverage\"]);\nconst RESOLUTION_FIELD_KEYS = [\"resolution\", \"expected_result\", \"actual_result\"] as const;\ntype ResolutionFieldKey = (typeof RESOLUTION_FIELD_KEYS)[number];\nconst VALIDATE_FILE_SCAN_MODES = [\"default\", \"tracked-all\", \"tracked-all-strict\"] as const;\nconst VALIDATE_METADATA_PROFILE_VALUES = [\"core\", \"strict\", \"custom\"] as const;\nconst VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES = [\"off\", \"warn\", \"error\"] as const;\nconst LIFECYCLE_PATTERN_FIELD_KEYS = [\"blocked_reason\", \"resolution\", \"actual_result\"] as const;\ntype LifecyclePatternFieldKey = (typeof LIFECYCLE_PATTERN_FIELD_KEYS)[number];\nconst CORE_METADATA_REQUIRED_FIELDS = [\"author\", \"acceptance_criteria\", \"estimated_minutes\", \"close_reason\"] as const;\nconst STRICT_METADATA_REQUIRED_FIELDS = [\n ...CORE_METADATA_REQUIRED_FIELDS,\n \"reviewer\",\n \"risk\",\n \"confidence\",\n \"sprint\",\n \"release\",\n] as const;\nconst SUPPORTED_METADATA_REQUIRED_FIELDS = [\n ...new Set([...STRICT_METADATA_REQUIRED_FIELDS]),\n] as ValidateMetadataRequiredField[];\nconst METADATA_REQUIRED_FIELD_ALIASES: Record<string, ValidateMetadataRequiredField> = {\n author: \"author\",\n acceptance_criteria: \"acceptance_criteria\",\n \"acceptance-criteria\": \"acceptance_criteria\",\n estimated_minutes: \"estimated_minutes\",\n \"estimated-minutes\": \"estimated_minutes\",\n estimate: \"estimated_minutes\",\n close_reason: \"close_reason\",\n \"close-reason\": \"close_reason\",\n reviewer: \"reviewer\",\n risk: \"risk\",\n confidence: \"confidence\",\n sprint: \"sprint\",\n release: \"release\",\n};\nconst METADATA_WARNING_TOKEN_BY_FIELD: Record<ValidateMetadataRequiredField, string> = {\n author: \"validate_metadata_missing_author\",\n acceptance_criteria: \"validate_metadata_missing_acceptance_criteria\",\n estimated_minutes: \"validate_metadata_missing_estimate\",\n close_reason: \"validate_metadata_missing_close_reason\",\n reviewer: \"validate_metadata_missing_reviewer\",\n risk: \"validate_metadata_missing_risk\",\n confidence: \"validate_metadata_missing_confidence\",\n sprint: \"validate_metadata_missing_sprint\",\n release: \"validate_metadata_missing_release\",\n};\nconst METADATA_COUNT_KEY_BY_FIELD: Record<ValidateMetadataRequiredField, string> = {\n author: \"missing_author\",\n acceptance_criteria: \"missing_acceptance_criteria\",\n estimated_minutes: \"missing_estimated_minutes\",\n close_reason: \"closed_missing_close_reason\",\n reviewer: \"missing_reviewer\",\n risk: \"missing_risk\",\n confidence: \"missing_confidence\",\n sprint: \"missing_sprint\",\n release: \"missing_release\",\n};\nconst METADATA_ITEM_IDS_KEY_BY_FIELD: Record<ValidateMetadataRequiredField, string> = {\n author: \"missing_author_item_ids\",\n acceptance_criteria: \"missing_acceptance_criteria_item_ids\",\n estimated_minutes: \"missing_estimated_minutes_item_ids\",\n close_reason: \"closed_missing_close_reason_item_ids\",\n reviewer: \"missing_reviewer_item_ids\",\n risk: \"missing_risk_item_ids\",\n confidence: \"missing_confidence_item_ids\",\n sprint: \"missing_sprint_item_ids\",\n release: \"missing_release_item_ids\",\n};\nconst METADATA_TRUNCATED_KEY_BY_FIELD: Record<ValidateMetadataRequiredField, string> = {\n author: \"missing_author_truncated\",\n acceptance_criteria: \"missing_acceptance_criteria_truncated\",\n estimated_minutes: \"missing_estimated_minutes_truncated\",\n close_reason: \"closed_missing_close_reason_truncated\",\n reviewer: \"missing_reviewer_truncated\",\n risk: \"missing_risk_truncated\",\n confidence: \"missing_confidence_truncated\",\n sprint: \"missing_sprint_truncated\",\n release: \"missing_release_truncated\",\n};\nconst GIT_LS_FILES_MAX_BUFFER = 32 * 1024 * 1024;\nconst FILE_LIST_SUMMARY_LIMIT = 40;\nconst DIAGNOSTIC_LIST_SUMMARY_LIMIT = 40;\nconst execFileAsync = promisify(execFile);\n\nexport interface ValidateCommandOptions {\n checkMetadata?: boolean;\n checkResolution?: boolean;\n checkLifecycle?: boolean;\n checkStaleBlockers?: boolean;\n dependencyCycleSeverity?: string;\n checkFiles?: boolean;\n includePmInternals?: boolean;\n verboseFileLists?: boolean;\n verboseDiagnostics?: boolean;\n checkHistoryDrift?: boolean;\n checkCommandReferences?: boolean;\n scanMode?: string;\n metadataProfile?: string;\n}\n\nexport interface ValidateCheck {\n name: ValidateCheckName;\n status: ValidateStatus;\n details: Record<string, unknown>;\n}\n\nexport interface ValidateResult {\n ok: boolean;\n has_warnings: boolean;\n checks: ValidateCheck[];\n warnings: string[];\n generated_at: string;\n}\n\nfunction normalizeRelativePath(value: string): string {\n return value.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\/+/, \"\").replace(/^\\/+/, \"\");\n}\n\nfunction normalizeRelativeDirectoryPath(value: string): string {\n const normalized = normalizeRelativePath(value);\n return normalized.replace(/\\/+$/, \"\");\n}\n\n\n\nfunction toMeaningfulString(value: unknown): string | undefined {\n const normalized = toNonEmptyStringOrUndefined(value);\n if (!normalized) {\n return undefined;\n }\n const lowered = normalized.toLowerCase();\n if (lowered === \"none\" || lowered === \"null\" || lowered === \"n/a\" || lowered === \"na\") {\n return undefined;\n }\n return normalized;\n}\n\nfunction normalizeStatusForRegistry(status: string, statusRegistry: RuntimeStatusRegistry): string {\n return normalizeStatusInput(status, statusRegistry) ?? status;\n}\n\nfunction isTerminalStatus(status: string, statusRegistry: RuntimeStatusRegistry): boolean {\n return statusRegistry.terminal_statuses.has(normalizeStatusForRegistry(status, statusRegistry));\n}\n\ninterface ValidateMetadataPolicy {\n profile: ValidateMetadataProfile;\n profile_source: \"default\" | \"settings\" | \"option\";\n required_fields: ValidateMetadataRequiredField[];\n configured_custom_fields: ValidateMetadataRequiredField[];\n fallback_to_core: boolean;\n warnings: string[];\n}\n\ntype LifecyclePatternSource = \"default\" | \"settings\";\n\ninterface LifecyclePatternPolicy {\n stale_blocker_reason_patterns: string[];\n stale_blocker_reason_pattern_source: LifecyclePatternSource;\n closure_like_metadata_field_patterns: Record<LifecyclePatternFieldKey, string[]>;\n closure_like_metadata_field_pattern_sources: Record<LifecyclePatternFieldKey, LifecyclePatternSource>;\n}\n\ninterface LifecyclePatternSettingsSource {\n validation: {\n lifecycle_stale_blocker_reason_patterns: string[];\n lifecycle_closure_like_blocked_reason_patterns: string[];\n lifecycle_closure_like_resolution_patterns: string[];\n lifecycle_closure_like_actual_result_patterns: string[];\n };\n}\n\nfunction normalizeLifecyclePatternList(values: readonly string[] | undefined): string[] {\n return [...new Set((values ?? []).map((value) => value.trim().toLowerCase()).filter((value) => value.length > 0))].sort(\n (left, right) => left.localeCompare(right),\n );\n}\n\nfunction areSortedStringListsEqual(left: readonly string[], right: readonly string[]): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => value === right[index]);\n}\n\nfunction resolveLifecyclePatternPolicy(settings: LifecyclePatternSettingsSource): LifecyclePatternPolicy {\n const defaultStalePatterns = normalizeLifecyclePatternList(DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS);\n const defaultClosureLikePatterns = {\n blocked_reason: normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.blocked_reason),\n resolution: normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.resolution),\n actual_result: normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.actual_result),\n } satisfies Record<LifecyclePatternFieldKey, string[]>;\n const staleBlockerReasonPatterns = normalizeLifecyclePatternList(\n settings.validation.lifecycle_stale_blocker_reason_patterns,\n );\n const closureLikePatterns = {\n blocked_reason: normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_blocked_reason_patterns),\n resolution: normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_resolution_patterns),\n actual_result: normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_actual_result_patterns),\n } satisfies Record<LifecyclePatternFieldKey, string[]>;\n return {\n stale_blocker_reason_patterns: staleBlockerReasonPatterns,\n stale_blocker_reason_pattern_source: areSortedStringListsEqual(staleBlockerReasonPatterns, defaultStalePatterns)\n ? \"default\"\n : \"settings\",\n closure_like_metadata_field_patterns: closureLikePatterns,\n closure_like_metadata_field_pattern_sources: {\n blocked_reason: areSortedStringListsEqual(closureLikePatterns.blocked_reason, defaultClosureLikePatterns.blocked_reason)\n ? \"default\"\n : \"settings\",\n resolution: areSortedStringListsEqual(closureLikePatterns.resolution, defaultClosureLikePatterns.resolution)\n ? \"default\"\n : \"settings\",\n actual_result: areSortedStringListsEqual(closureLikePatterns.actual_result, defaultClosureLikePatterns.actual_result)\n ? \"default\"\n : \"settings\",\n },\n };\n}\n\nfunction resolveValidateMetadataProfile(value: string | undefined): ValidateMetadataProfile {\n const normalized = value?.trim().toLowerCase();\n if (!normalized || normalized.length === 0) {\n return \"core\";\n }\n if ((VALIDATE_METADATA_PROFILE_VALUES as readonly string[]).includes(normalized)) {\n return normalized as ValidateMetadataProfile;\n }\n throw new PmCliError(\n `Unknown --metadata-profile value \"${value}\". Supported values: ${VALIDATE_METADATA_PROFILE_VALUES.join(\", \")}.`,\n EXIT_CODE.USAGE,\n );\n}\n\nfunction resolveDependencyCycleSeverity(value: string | undefined): ValidateDependencyCycleSeverity {\n const normalized = value?.trim().toLowerCase();\n if (!normalized || normalized.length === 0) {\n return \"warn\";\n }\n if ((VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES as readonly string[]).includes(normalized)) {\n return normalized as ValidateDependencyCycleSeverity;\n }\n throw new PmCliError(\n `Unknown --dependency-cycle-severity value \"${value}\". Supported values: ${VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES.join(\", \")}.`,\n EXIT_CODE.USAGE,\n );\n}\n\nfunction normalizeMetadataRequiredFieldsFromSettings(\n values: readonly ValidateMetadataRequiredField[] | undefined,\n): ValidateMetadataRequiredField[] {\n const normalized = [...new Set((values ?? []).map((value) => value.trim().toLowerCase().replaceAll(\"-\", \"_\")))];\n return normalized\n .map((value) => METADATA_REQUIRED_FIELD_ALIASES[value])\n .filter((value): value is ValidateMetadataRequiredField => value !== undefined)\n .sort((left, right) => left.localeCompare(right));\n}\n\nfunction resolveValidateMetadataPolicy(\n profile: ValidateMetadataProfile,\n profileSource: \"default\" | \"settings\" | \"option\",\n configuredCustomFields: readonly ValidateMetadataRequiredField[],\n): ValidateMetadataPolicy {\n const normalizedCustomFields = normalizeMetadataRequiredFieldsFromSettings(configuredCustomFields);\n if (profile === \"core\") {\n return {\n profile,\n profile_source: profileSource,\n required_fields: [...CORE_METADATA_REQUIRED_FIELDS],\n configured_custom_fields: normalizedCustomFields,\n fallback_to_core: false,\n warnings: [],\n };\n }\n if (profile === \"strict\") {\n return {\n profile,\n profile_source: profileSource,\n required_fields: [...STRICT_METADATA_REQUIRED_FIELDS],\n configured_custom_fields: normalizedCustomFields,\n fallback_to_core: false,\n warnings: [],\n };\n }\n if (normalizedCustomFields.length > 0) {\n return {\n profile,\n profile_source: profileSource,\n required_fields: normalizedCustomFields,\n configured_custom_fields: normalizedCustomFields,\n fallback_to_core: false,\n warnings: [],\n };\n }\n return {\n profile,\n profile_source: profileSource,\n required_fields: [...CORE_METADATA_REQUIRED_FIELDS],\n configured_custom_fields: normalizedCustomFields,\n fallback_to_core: true,\n warnings: [\"validate_metadata_custom_profile_missing_required_fields:0\"],\n };\n}\n\nfunction isMetadataFieldMissing(\n item: ItemWithBody,\n field: ValidateMetadataRequiredField,\n statusRegistry: RuntimeStatusRegistry,\n): boolean {\n if (field === \"author\") {\n return !toNonEmptyStringOrUndefined(item.author);\n }\n if (field === \"acceptance_criteria\") {\n return !toNonEmptyStringOrUndefined(item.acceptance_criteria);\n }\n if (field === \"estimated_minutes\") {\n return !Number.isFinite(item.estimated_minutes);\n }\n if (field === \"close_reason\") {\n return normalizeStatusForRegistry(item.status, statusRegistry) === statusRegistry.close_status && !toNonEmptyStringOrUndefined(item.close_reason);\n }\n if (field === \"reviewer\") {\n return !toNonEmptyStringOrUndefined(item.reviewer);\n }\n if (field === \"risk\") {\n return !toNonEmptyStringOrUndefined(item.risk);\n }\n if (field === \"confidence\") {\n if (typeof item.confidence === \"number\") {\n return !Number.isFinite(item.confidence);\n }\n return !toNonEmptyStringOrUndefined(item.confidence);\n }\n if (field === \"sprint\") {\n return !toNonEmptyStringOrUndefined(item.sprint);\n }\n return !toNonEmptyStringOrUndefined(item.release);\n}\n\nfunction resolveFileScanMode(scanMode: string | undefined): ValidateFileScanMode {\n if (scanMode === undefined) {\n return \"default\";\n }\n const normalized = scanMode.trim().toLowerCase();\n if (normalized.length === 0) {\n return \"default\";\n }\n if (normalized === \"default\") {\n return \"default\";\n }\n if (normalized === \"tracked-all\" || normalized === \"tracked_all\") {\n return \"tracked-all\";\n }\n if (normalized === \"tracked-all-strict\" || normalized === \"tracked_all_strict\") {\n return \"tracked-all-strict\";\n }\n throw new PmCliError(\n `Unknown --scan-mode value \"${scanMode}\". Supported values: ${VALIDATE_FILE_SCAN_MODES.join(\", \")}.`,\n EXIT_CODE.USAGE,\n );\n}\n\nfunction resolveWorkspaceRoot(pmRoot: string): string {\n const resolvedPmRoot = path.resolve(pmRoot);\n const normalizedPmRoot = resolvedPmRoot.replaceAll(\"\\\\\", \"/\");\n if (normalizedPmRoot.endsWith(\"/.agents/pm\")) {\n return path.dirname(path.dirname(resolvedPmRoot));\n }\n const resolvedCwd = path.resolve(process.cwd());\n const canonicalPmRoot = realpathForWorkspaceRoot(resolvedPmRoot);\n const canonicalCwd = realpathForWorkspaceRoot(resolvedCwd);\n const relativeFromPmRoot = path.relative(canonicalPmRoot, canonicalCwd);\n const cwdInsidePmRoot =\n relativeFromPmRoot.length === 0 ||\n (!relativeFromPmRoot.startsWith(\"..\") && !path.isAbsolute(relativeFromPmRoot));\n if (cwdInsidePmRoot) {\n return resolvedPmRoot;\n }\n /* c8 ignore next 2 -- non-standard PM root layouts are integration-only edge cases. */\n return resolvedCwd;\n}\n\nfunction realpathForWorkspaceRoot(inputPath: string): string {\n try {\n return realpathSync.native(inputPath);\n } catch {\n return path.resolve(inputPath);\n }\n}\n\nasync function listFilesRecursive(basePath: string, relativePath: string, output: string[]): Promise<void> {\n const targetDirectory = relativePath.length > 0 ? path.join(basePath, relativePath) : basePath;\n let entries: Dirent[];\n try {\n entries = await fs.readdir(targetDirectory, { withFileTypes: true });\n } catch (error: unknown) {\n if (typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: string }).code === \"ENOENT\") {\n return;\n }\n throw error;\n }\n\n for (const entry of entries) {\n if (entry.name.startsWith(\".\")) {\n continue;\n }\n const childRelative = relativePath.length > 0 ? path.join(relativePath, entry.name) : entry.name;\n if (entry.isDirectory()) {\n if (DIRECTORY_IGNORE_SET.has(entry.name)) {\n continue;\n }\n await listFilesRecursive(basePath, childRelative, output);\n continue;\n }\n /* c8 ignore next 3 -- non-file dirent variants (symlink/socket) are filesystem-specific. */\n if (!entry.isFile()) {\n continue;\n }\n output.push(normalizeRelativePath(childRelative));\n }\n}\n\nasync function collectDefaultProjectFileCandidates(workspaceRoot: string): Promise<string[]> {\n const discovered: string[] = [];\n for (const directory of FILE_SCAN_DIRECTORIES) {\n await listFilesRecursive(workspaceRoot, directory, discovered);\n }\n for (const candidate of FILE_SCAN_ROOT_FILES) {\n const absolute = path.join(workspaceRoot, candidate);\n try {\n const stats = await fs.stat(absolute);\n /* c8 ignore start -- root-candidate presence depends on fixture workspace composition. */\n if (stats.isFile()) {\n discovered.push(normalizeRelativePath(candidate));\n }\n /* c8 ignore stop */\n } catch {\n // Ignore root-file candidates that are not present in this workspace.\n }\n }\n return [...new Set(discovered)].sort((left, right) => left.localeCompare(right));\n}\n\nasync function collectTrackedGitFileCandidates(workspaceRoot: string): Promise<string[] | null> {\n try {\n const { stdout } = await execFileAsync(\"git\", [\"ls-files\", \"-z\"], {\n cwd: workspaceRoot,\n encoding: \"utf8\",\n maxBuffer: GIT_LS_FILES_MAX_BUFFER,\n windowsHide: true,\n });\n const discovered = stdout\n .split(\"\\0\")\n .map((value) => normalizeRelativePath(value))\n .filter((value) => value.length > 0);\n return [...new Set(discovered)].sort((left, right) => left.localeCompare(right));\n } catch {\n /* c8 ignore start -- fallback path exercised only when git metadata is unavailable. */\n return null;\n /* c8 ignore stop */\n }\n}\n\ninterface FileCandidateCollection {\n requestedMode: ValidateFileScanMode;\n appliedMode: ValidateFileScanMode;\n source: FileCandidateSource;\n candidateFiles: string[];\n candidateTotal: number;\n candidateScanned: number;\n}\n\nfunction resolvePmInternalCandidatePrefixes(pmRoot: string, workspaceRoot: string): string[] {\n const prefixes = new Set<string>();\n const configuredDefault = normalizeRelativeDirectoryPath(PM_DIRNAME);\n if (configuredDefault.length > 0) {\n prefixes.add(configuredDefault);\n }\n const relativePmRoot = normalizeRelativeDirectoryPath(path.relative(workspaceRoot, pmRoot));\n if (relativePmRoot.length > 0 && !relativePmRoot.startsWith(\"..\")) {\n prefixes.add(relativePmRoot);\n }\n return [...prefixes].sort((left, right) => left.localeCompare(right));\n}\n\nfunction hasPathPrefix(candidate: string, prefixes: string[]): boolean {\n for (const prefix of prefixes) {\n if (candidate === prefix || candidate.startsWith(`${prefix}/`)) {\n return true;\n }\n }\n return false;\n}\n\nasync function collectProjectFileCandidates(\n workspaceRoot: string,\n scanMode: ValidateFileScanMode,\n): Promise<FileCandidateCollection> {\n if (scanMode === \"tracked-all\" || scanMode === \"tracked-all-strict\") {\n const trackedCandidates = await collectTrackedGitFileCandidates(workspaceRoot);\n if (trackedCandidates) {\n return {\n requestedMode: scanMode,\n appliedMode: scanMode,\n source: \"tracked-git\",\n candidateFiles: trackedCandidates,\n candidateTotal: trackedCandidates.length,\n candidateScanned: trackedCandidates.length,\n };\n }\n /* c8 ignore start -- deterministic fallback retained for non-git workspaces. */\n const fallbackCandidates = await collectDefaultProjectFileCandidates(workspaceRoot);\n return {\n requestedMode: scanMode,\n appliedMode: \"default\",\n source: \"tracked-all-fallback-default\",\n candidateFiles: fallbackCandidates,\n candidateTotal: fallbackCandidates.length,\n candidateScanned: fallbackCandidates.length,\n };\n /* c8 ignore stop */\n }\n\n const defaultCandidates = await collectDefaultProjectFileCandidates(workspaceRoot);\n return {\n requestedMode: scanMode,\n appliedMode: \"default\",\n source: \"default-curated\",\n candidateFiles: defaultCandidates,\n candidateTotal: defaultCandidates.length,\n candidateScanned: defaultCandidates.length,\n };\n}\n\nfunction summarizeList(values: string[], limit = DIAGNOSTIC_LIST_SUMMARY_LIMIT): { values: string[]; truncated: boolean } {\n /* c8 ignore start -- truncation behavior only surfaces with very large synthetic datasets. */\n if (values.length <= limit) {\n return { values, truncated: false };\n }\n return {\n values: values.slice(0, limit),\n truncated: true,\n };\n /* c8 ignore stop */\n}\n\nfunction summarizeFileList(\n values: string[],\n verboseFileLists: boolean,\n): {\n values: string[];\n truncated: boolean;\n total: number;\n} {\n if (verboseFileLists) {\n return {\n values,\n truncated: false,\n total: values.length,\n };\n }\n const summary = summarizeList(values, FILE_LIST_SUMMARY_LIMIT);\n return {\n values: summary.values,\n truncated: summary.truncated,\n total: values.length,\n };\n}\n\nconst RESOLUTION_REMEDIATION_FLAG_BY_FIELD: Record<ResolutionFieldKey, string> = {\n resolution: \"--resolution\",\n expected_result: \"--expected-result\",\n actual_result: \"--actual-result\",\n};\n\nconst RESOLUTION_REMEDIATION_PLACEHOLDER_BY_FIELD: Record<ResolutionFieldKey, string> = {\n resolution: \"Describe how this item was resolved\",\n expected_result: \"Describe the expected result\",\n actual_result: \"Describe the actual result\",\n};\n\nfunction buildResolutionRemediationCommand(row: { id: string; missing_fields: ResolutionFieldKey[] }): string {\n const fieldArguments = row.missing_fields\n .map((field) => `${RESOLUTION_REMEDIATION_FLAG_BY_FIELD[field]} \\\"${RESOLUTION_REMEDIATION_PLACEHOLDER_BY_FIELD[field]}\\\"`)\n .join(\" \");\n return `pm update ${row.id} ${fieldArguments} --message \\\"Backfill resolution metadata\\\"`;\n}\n\nfunction resolveRequestedChecks(options: ValidateCommandOptions): Set<ValidateCheckName> {\n const requested = new Set<ValidateCheckName>();\n if (options.checkMetadata) {\n requested.add(\"metadata\");\n }\n if (options.checkResolution) {\n requested.add(\"resolution\");\n }\n if (options.checkLifecycle || options.checkStaleBlockers) {\n requested.add(\"lifecycle\");\n }\n if (options.checkFiles) {\n requested.add(\"files\");\n }\n if (options.checkHistoryDrift) {\n requested.add(\"history_drift\");\n }\n if (options.checkCommandReferences) {\n requested.add(\"command_references\");\n }\n if (requested.size === 0) {\n requested.add(\"metadata\");\n requested.add(\"resolution\");\n requested.add(\"lifecycle\");\n requested.add(\"files\");\n requested.add(\"command_references\");\n requested.add(\"history_drift\");\n }\n return requested;\n}\n\nfunction buildMetadataCheck(\n items: ItemWithBody[],\n metadataPolicy: ValidateMetadataPolicy,\n statusRegistry: RuntimeStatusRegistry,\n verboseDiagnostics: boolean,\n): { check: ValidateCheck; warnings: string[] } {\n const missingByField = Object.fromEntries(\n SUPPORTED_METADATA_REQUIRED_FIELDS.map((field) => [field, [] as string[]]),\n ) as Record<ValidateMetadataRequiredField, string[]>;\n\n for (const item of items) {\n for (const field of SUPPORTED_METADATA_REQUIRED_FIELDS) {\n if (!isMetadataFieldMissing(item, field, statusRegistry)) {\n continue;\n }\n missingByField[field].push(item.id);\n }\n }\n\n const warningTokens = [...metadataPolicy.warnings];\n for (const field of metadataPolicy.required_fields) {\n const missingItems = missingByField[field];\n if (missingItems.length === 0) {\n continue;\n }\n warningTokens.push(`${METADATA_WARNING_TOKEN_BY_FIELD[field]}:${missingItems.length}`);\n }\n\n // Zero-suppress counts to reduce agent token cost (telemetry pm-tylj).\n // Only emit counts for the ACTIVE required fields of the resolved profile so a\n // looser profile (e.g. core) never reports missing reviewer/risk/sprint/etc.\n // Defensive guards (Gemini high #1, PR #78 follow-up): a future settings\n // shape could include an unsupported field in required_fields — fall back\n // to 0 instead of throwing TypeError, and skip writing when the count-key\n // mapping is undefined.\n const counts: Record<string, number> = {};\n for (const field of metadataPolicy.required_fields) {\n const value = missingByField[field]?.length ?? 0;\n const countKey = METADATA_COUNT_KEY_BY_FIELD[field];\n if (value > 0 && countKey) {\n counts[countKey] = value;\n }\n }\n const details: Record<string, unknown> = {\n checked_items: items.length,\n metadata_profile: metadataPolicy.profile,\n metadata_profile_source: metadataPolicy.profile_source,\n metadata_profile_fallback_to_core: metadataPolicy.fallback_to_core,\n required_fields: [...metadataPolicy.required_fields],\n supported_required_fields: [...SUPPORTED_METADATA_REQUIRED_FIELDS],\n counts,\n };\n if (metadataPolicy.configured_custom_fields.length > 0) {\n details.configured_custom_required_fields = [...metadataPolicy.configured_custom_fields];\n }\n\n // Only emit per-field item_ids/truncated keys for the ACTIVE required fields of\n // the resolved profile (and only when there are missing items). This stops a\n // looser profile (e.g. core) from emitting the identical full ID array for\n // reviewer/risk/confidence/sprint/release that it does not even require\n // (pm-edge #2 — ~150 redundant lines per validate run on minimal/core).\n // Defensive guard (Gemini high #2, PR #78 follow-up): same optional-chain\n // safety as the counts loop above — never throw if a future settings shape\n // includes an unsupported field.\n for (const field of metadataPolicy.required_fields) {\n const missing = missingByField[field];\n if (!missing || missing.length === 0) {\n continue;\n }\n const idsKey = METADATA_ITEM_IDS_KEY_BY_FIELD[field];\n const truncatedKey = METADATA_TRUNCATED_KEY_BY_FIELD[field];\n if (!idsKey || !truncatedKey) {\n continue;\n }\n const summarized = summarizeList(missing, verboseDiagnostics ? missing.length : DIAGNOSTIC_LIST_SUMMARY_LIMIT);\n details[idsKey] = summarized.values;\n details[truncatedKey] = summarized.truncated;\n }\n\n return {\n check: {\n name: \"metadata\",\n status: warningTokens.length === 0 ? \"ok\" : \"warn\",\n details,\n },\n warnings: warningTokens,\n };\n}\n\nfunction buildResolutionCheck(\n items: ItemWithBody[],\n statusRegistry: RuntimeStatusRegistry,\n verboseDiagnostics: boolean,\n): { check: ValidateCheck; warnings: string[] } {\n const terminalDoneStatuses = new Set<string>(statusRegistry.terminal_done_statuses);\n terminalDoneStatuses.add(statusRegistry.close_status);\n const closedItems = items.filter((item) => terminalDoneStatuses.has(normalizeStatusForRegistry(item.status, statusRegistry)));\n const missingResolutionRows: Array<{ id: string; missing_fields: ResolutionFieldKey[] }> = [];\n\n for (const item of closedItems) {\n const missingFields = RESOLUTION_FIELD_KEYS.filter((field) => !toNonEmptyStringOrUndefined(item[field]));\n if (missingFields.length === 0) {\n continue;\n }\n missingResolutionRows.push({\n id: item.id,\n missing_fields: missingFields,\n });\n }\n\n const warnings =\n missingResolutionRows.length > 0 ? [`validate_resolution_missing_fields:${missingResolutionRows.length}`] : [];\n const diagnosticLimit = verboseDiagnostics ? Number.POSITIVE_INFINITY : DIAGNOSTIC_LIST_SUMMARY_LIMIT;\n const summarizedRows = summarizeList(\n missingResolutionRows.map((row) => `${row.id}:${row.missing_fields.join(\",\")}`),\n diagnosticLimit,\n );\n const remediationHints = missingResolutionRows.map((row) => buildResolutionRemediationCommand(row));\n const summarizedHints = summarizeList(remediationHints, diagnosticLimit);\n return {\n check: {\n name: \"resolution\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n checked_closed_items: closedItems.length,\n missing_resolution_items: missingResolutionRows.length,\n missing_resolution_rows: summarizedRows.values,\n missing_resolution_rows_truncated: summarizedRows.truncated,\n missing_resolution_remediation_hints: summarizedHints.values,\n missing_resolution_remediation_hints_truncated: summarizedHints.truncated,\n },\n },\n warnings,\n };\n}\n\nfunction buildLifecycleDependencyGraph(activeItems: ItemWithBody[]): Map<string, string[]> {\n const activeItemIds = new Set(activeItems.map((item) => item.id));\n const graph = new Map<string, string[]>();\n const sortedItems = [...activeItems].sort((left, right) => left.id.localeCompare(right.id));\n for (const item of sortedItems) {\n const edges = new Set<string>();\n for (const dependency of item.dependencies ?? []) {\n const dependencyId = toMeaningfulString(dependency.id);\n if (!dependencyId || !activeItemIds.has(dependencyId)) {\n continue;\n }\n edges.add(dependencyId);\n }\n graph.set(item.id, [...edges].sort((left, right) => left.localeCompare(right)));\n }\n return graph;\n}\n\nfunction findLifecycleDependencyCycleComponents(graph: Map<string, string[]>): string[][] {\n let nextIndex = 0;\n const indexById = new Map<string, number>();\n const lowLinkById = new Map<string, number>();\n const stack: string[] = [];\n const inStack = new Set<string>();\n const components: string[][] = [];\n\n const visit = (id: string): void => {\n indexById.set(id, nextIndex);\n lowLinkById.set(id, nextIndex);\n nextIndex += 1;\n stack.push(id);\n inStack.add(id);\n\n for (const dependencyId of graph.get(id) ?? []) {\n if (!indexById.has(dependencyId)) {\n visit(dependencyId);\n lowLinkById.set(id, Math.min(lowLinkById.get(id)!, lowLinkById.get(dependencyId)!));\n } else if (inStack.has(dependencyId)) {\n lowLinkById.set(id, Math.min(lowLinkById.get(id)!, indexById.get(dependencyId)!));\n }\n }\n\n if (lowLinkById.get(id) !== indexById.get(id)) {\n return;\n }\n const component: string[] = [];\n while (stack.length > 0) {\n const member = stack.pop()!;\n inStack.delete(member);\n component.push(member);\n if (member === id) {\n break;\n }\n }\n component.sort((left, right) => left.localeCompare(right));\n components.push(component);\n };\n\n const sortedNodeIds = [...graph.keys()].sort((left, right) => left.localeCompare(right));\n for (const id of sortedNodeIds) {\n if (!indexById.has(id)) {\n visit(id);\n }\n }\n\n const cycleComponents = components.filter((component) => {\n if (component.length > 1) {\n return true;\n }\n const selfId = component[0];\n return (graph.get(selfId) ?? []).includes(selfId);\n });\n return cycleComponents.sort(\n (left, right) =>\n left[0].localeCompare(right[0]) ||\n left.length - right.length ||\n left.join(\",\").localeCompare(right.join(\",\")),\n );\n}\n\nfunction resolveLifecycleDependencyCycleSamplePath(component: string[], graph: Map<string, string[]>): string[] {\n const start = component[0];\n if (component.length === 1) {\n return [start, start];\n }\n const componentSet = new Set(component);\n const path: string[] = [start];\n const visited = new Set<string>([start]);\n\n const search = (current: string): boolean => {\n const neighbors = (graph.get(current) ?? []).filter((candidate) => componentSet.has(candidate));\n for (const next of neighbors) {\n if (next === start && path.length > 1) {\n path.push(start);\n return true;\n }\n if (visited.has(next)) {\n continue;\n }\n visited.add(next);\n path.push(next);\n if (search(next)) {\n return true;\n }\n path.pop();\n visited.delete(next);\n }\n return false;\n };\n\n if (search(start)) {\n return [...path];\n }\n return [...component, start];\n}\n\nfunction detectLifecycleDependencyCycles(activeItems: ItemWithBody[]): {\n cycle_count: number;\n cycle_item_ids: string[];\n cycle_sample_paths: string[];\n} {\n const graph = buildLifecycleDependencyGraph(activeItems);\n const cycleComponents = findLifecycleDependencyCycleComponents(graph);\n const cycleItemIds = [...new Set(cycleComponents.flat())].sort((left, right) => left.localeCompare(right));\n const cycleSamplePaths = cycleComponents.map((component) =>\n resolveLifecycleDependencyCycleSamplePath(component, graph).join(\"->\"),\n );\n return {\n cycle_count: cycleComponents.length,\n cycle_item_ids: cycleItemIds,\n cycle_sample_paths: cycleSamplePaths,\n };\n}\n\nfunction buildLifecycleCheck(\n items: ItemWithBody[],\n includeStaleBlockers: boolean,\n dependencyCycleSeverity: ValidateDependencyCycleSeverity,\n statusRegistry: RuntimeStatusRegistry,\n lifecyclePatternPolicy: LifecyclePatternPolicy,\n): { check: ValidateCheck; warnings: string[] } {\n const itemsById = new Map(items.map((item) => [item.id, item]));\n const blockedStatuses =\n statusRegistry.blocked_statuses.size > 0 ? statusRegistry.blocked_statuses : new Set<string>([\"blocked\"]);\n const activeItems = items.filter((item) => !isTerminalStatus(item.status, statusRegistry));\n const closureLikeRows: Array<{ id: string; fields: string[] }> = [];\n const terminalParentRows: Array<{ id: string; parent_id: string; parent_status: string }> = [];\n const staleBlockerRows: Array<{ id: string; status: string; reasons: string[] }> = [];\n\n for (const item of activeItems) {\n const closureLikeFields = Object.entries(lifecyclePatternPolicy.closure_like_metadata_field_patterns)\n .filter(([field, patterns]) => {\n const value = toMeaningfulString(item[field as keyof ItemWithBody]);\n if (!value) {\n return false;\n }\n const normalized = value.toLowerCase();\n return patterns.some((pattern) => normalized.includes(pattern));\n })\n .map(([field]) => field)\n .sort((left, right) => left.localeCompare(right));\n\n if (closureLikeFields.length > 0) {\n closureLikeRows.push({\n id: item.id,\n fields: closureLikeFields,\n });\n }\n\n const parentId = toMeaningfulString(item.parent);\n if (parentId) {\n const parent = itemsById.get(parentId);\n if (parent && isTerminalStatus(parent.status, statusRegistry)) {\n terminalParentRows.push({\n id: item.id,\n parent_id: parent.id,\n parent_status: parent.status,\n });\n }\n }\n\n if (includeStaleBlockers) {\n const blockedBy = toMeaningfulString(item.blocked_by);\n const blockedReason = toMeaningfulString(item.blocked_reason);\n const blockedReasonNormalized = blockedReason?.toLowerCase();\n const reasons: string[] = [];\n const normalizedStatus = normalizeStatusForRegistry(item.status, statusRegistry);\n\n if (!blockedStatuses.has(normalizedStatus)) {\n if (blockedBy) {\n reasons.push(\"non_blocked_status_has_blocked_by\");\n }\n if (blockedReason) {\n reasons.push(\"non_blocked_status_has_blocked_reason\");\n }\n } else {\n if (!blockedBy && !blockedReason) {\n reasons.push(\"blocked_status_missing_blocker_context\");\n }\n if (blockedReasonNormalized?.includes(\"no active blocker\")) {\n reasons.push(\"blocked_status_reason_reports_no_active_blocker\");\n }\n if (\n blockedReasonNormalized &&\n lifecyclePatternPolicy.stale_blocker_reason_patterns.some((pattern) => blockedReasonNormalized.includes(pattern))\n ) {\n reasons.push(\"blocked_status_reason_matches_stale_pattern\");\n }\n }\n\n if (reasons.length > 0) {\n staleBlockerRows.push({\n id: item.id,\n status: item.status,\n reasons: [...new Set(reasons)].sort((left, right) => left.localeCompare(right)),\n });\n }\n }\n }\n\n closureLikeRows.sort((left, right) => left.id.localeCompare(right.id));\n terminalParentRows.sort(\n (left, right) => left.id.localeCompare(right.id) || left.parent_id.localeCompare(right.parent_id),\n );\n staleBlockerRows.sort((left, right) => left.id.localeCompare(right.id));\n const dependencyCycleDiagnostics = detectLifecycleDependencyCycles(activeItems);\n\n const warnings: string[] = [];\n if (closureLikeRows.length > 0) {\n warnings.push(`validate_lifecycle_active_closure_like_metadata:${closureLikeRows.length}`);\n }\n if (terminalParentRows.length > 0) {\n warnings.push(`validate_lifecycle_active_terminal_parent:${terminalParentRows.length}`);\n }\n if (includeStaleBlockers && staleBlockerRows.length > 0) {\n warnings.push(`validate_lifecycle_stale_blockers:${staleBlockerRows.length}`);\n }\n if (dependencyCycleDiagnostics.cycle_count > 0 && dependencyCycleSeverity !== \"off\") {\n warnings.push(\n `${\n dependencyCycleSeverity === \"error\"\n ? \"validate_lifecycle_dependency_cycles_error\"\n : \"validate_lifecycle_dependency_cycles\"\n }:${dependencyCycleDiagnostics.cycle_count}`,\n );\n }\n\n const summarizedClosureLikeRows = summarizeList(\n closureLikeRows.map((row) => `${row.id}:${row.fields.join(\",\")}`),\n );\n const summarizedTerminalParentRows = summarizeList(\n terminalParentRows.map((row) => `${row.id}:${row.parent_id}:${row.parent_status}`),\n );\n const summarizedStaleBlockerRows = summarizeList(\n staleBlockerRows.map((row) => `${row.id}:${row.status}:${row.reasons.join(\",\")}`),\n );\n const summarizedDependencyCycleItemIds = summarizeList(dependencyCycleDiagnostics.cycle_item_ids);\n const summarizedDependencyCycleSamplePaths = summarizeList(dependencyCycleDiagnostics.cycle_sample_paths);\n\n return {\n check: {\n name: \"lifecycle\",\n status: dependencyCycleDiagnostics.cycle_count > 0 && dependencyCycleSeverity === \"error\"\n ? \"error\"\n : warnings.length === 0\n ? \"ok\"\n : \"warn\",\n details: {\n checked_active_items: activeItems.length,\n active_closure_like_metadata_items: closureLikeRows.length,\n active_closure_like_metadata_rows: summarizedClosureLikeRows.values,\n active_closure_like_metadata_rows_truncated: summarizedClosureLikeRows.truncated,\n active_terminal_parent_items: terminalParentRows.length,\n active_terminal_parent_rows: summarizedTerminalParentRows.values,\n active_terminal_parent_rows_truncated: summarizedTerminalParentRows.truncated,\n stale_blocker_checks_enabled: includeStaleBlockers,\n stale_blocker_items: staleBlockerRows.length,\n stale_blocker_rows: summarizedStaleBlockerRows.values,\n stale_blocker_rows_truncated: summarizedStaleBlockerRows.truncated,\n dependency_cycle_severity_policy: dependencyCycleSeverity,\n dependency_cycle_count: dependencyCycleDiagnostics.cycle_count,\n dependency_cycle_item_count: dependencyCycleDiagnostics.cycle_item_ids.length,\n dependency_cycle_item_ids: summarizedDependencyCycleItemIds.values,\n dependency_cycle_item_ids_truncated: summarizedDependencyCycleItemIds.truncated,\n dependency_cycle_sample_paths: summarizedDependencyCycleSamplePaths.values,\n dependency_cycle_sample_paths_truncated: summarizedDependencyCycleSamplePaths.truncated,\n stale_blocker_reason_patterns: [...lifecyclePatternPolicy.stale_blocker_reason_patterns],\n stale_blocker_reason_pattern_source: lifecyclePatternPolicy.stale_blocker_reason_pattern_source,\n closure_like_blocked_reason_patterns: [\n ...lifecyclePatternPolicy.closure_like_metadata_field_patterns.blocked_reason,\n ],\n closure_like_blocked_reason_pattern_source:\n lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.blocked_reason,\n closure_like_resolution_patterns: [...lifecyclePatternPolicy.closure_like_metadata_field_patterns.resolution],\n closure_like_resolution_pattern_source:\n lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.resolution,\n closure_like_actual_result_patterns: [...lifecyclePatternPolicy.closure_like_metadata_field_patterns.actual_result],\n closure_like_actual_result_pattern_source:\n lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.actual_result,\n },\n },\n warnings,\n };\n}\n\nasync function buildFilesCheck(\n items: ItemWithBody[],\n workspaceRoot: string,\n pmRoot: string,\n fileScanMode: ValidateFileScanMode,\n includePmInternals: boolean,\n verboseFileLists: boolean,\n): Promise<{ check: ValidateCheck; warnings: string[] }> {\n const linkedProjectPaths = new Set<string>();\n const missingLinkedPaths: string[] = [];\n\n for (const item of items) {\n const linkedArtifacts = [...(item.files ?? []), ...(item.docs ?? [])];\n for (const artifact of linkedArtifacts) {\n if (artifact.scope !== \"project\") {\n continue;\n }\n const normalizedPath = normalizeRelativePath(artifact.path);\n if (normalizedPath.length === 0) {\n continue;\n }\n linkedProjectPaths.add(normalizedPath);\n const absolutePath = path.isAbsolute(artifact.path) ? artifact.path : path.resolve(workspaceRoot, artifact.path);\n try {\n const stats = await fs.stat(absolutePath);\n if (!stats.isFile()) {\n missingLinkedPaths.push(normalizedPath);\n }\n } catch {\n missingLinkedPaths.push(normalizedPath);\n }\n }\n }\n\n const uniqueMissingLinkedPaths = [...new Set(missingLinkedPaths)].sort((left, right) => left.localeCompare(right));\n const fileCandidates = await collectProjectFileCandidates(workspaceRoot, fileScanMode);\n const strictTrackedAllMode = fileScanMode === \"tracked-all-strict\";\n const strictModeForcesPmInternals = strictTrackedAllMode && !includePmInternals;\n const includePmInternalsEffective = includePmInternals || strictTrackedAllMode;\n const pmInternalCandidatePrefixes = includePmInternalsEffective ? [] : resolvePmInternalCandidatePrefixes(pmRoot, workspaceRoot);\n const excludedPmInternalPaths =\n pmInternalCandidatePrefixes.length === 0\n ? []\n : fileCandidates.candidateFiles.filter((candidate) => hasPathPrefix(candidate, pmInternalCandidatePrefixes));\n const candidateFiles =\n pmInternalCandidatePrefixes.length === 0\n ? fileCandidates.candidateFiles\n : fileCandidates.candidateFiles.filter((candidate) => !hasPathPrefix(candidate, pmInternalCandidatePrefixes));\n const excludedPmInternalCount = excludedPmInternalPaths.length;\n const excludedByReason: Record<string, unknown> = {};\n if (excludedPmInternalCount > 0) {\n const summarizedPmInternalPaths = summarizeFileList(excludedPmInternalPaths, verboseFileLists);\n excludedByReason.pm_internals = {\n count: excludedPmInternalCount,\n paths: summarizedPmInternalPaths.values,\n paths_truncated: summarizedPmInternalPaths.truncated,\n paths_total: summarizedPmInternalPaths.total,\n };\n }\n const orphanedFiles = candidateFiles.filter((candidate) => !linkedProjectPaths.has(candidate));\n const warnings: string[] = [];\n if (strictModeForcesPmInternals) {\n warnings.push(\"validate_files_tracked_all_strict_forces_pm_internals\");\n }\n if (uniqueMissingLinkedPaths.length > 0) {\n warnings.push(`validate_files_missing_linked_paths:${uniqueMissingLinkedPaths.length}`);\n }\n if (orphanedFiles.length > 0) {\n warnings.push(`validate_files_orphaned_paths:${orphanedFiles.length}`);\n }\n const summarizedMissing = summarizeFileList(uniqueMissingLinkedPaths, verboseFileLists);\n const summarizedOrphaned = summarizeFileList(orphanedFiles, verboseFileLists);\n\n return {\n check: {\n name: \"files\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n workspace_root: workspaceRoot,\n scan_mode_requested: fileCandidates.requestedMode,\n scan_mode_applied: fileCandidates.appliedMode,\n strict_tracked_all_mode: strictTrackedAllMode,\n strict_mode_forces_pm_internals: strictModeForcesPmInternals,\n strict_mode_forces_pm_internals_notice: strictModeForcesPmInternals\n ? \"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.\"\n : null,\n file_list_detail_mode: verboseFileLists ? \"full\" : \"summary\",\n file_list_summary_limit: FILE_LIST_SUMMARY_LIMIT,\n candidate_scan_source: fileCandidates.source,\n include_pm_internals: includePmInternalsEffective,\n include_pm_internals_requested: includePmInternals,\n pm_internal_candidate_prefixes: pmInternalCandidatePrefixes,\n pm_internal_excluded_count: excludedPmInternalCount,\n excluded_total: excludedPmInternalCount,\n excluded_by_reason: excludedByReason,\n linked_project_paths: linkedProjectPaths.size,\n candidate_total_raw: fileCandidates.candidateTotal,\n candidate_scanned_raw: fileCandidates.candidateScanned,\n candidate_total: candidateFiles.length,\n candidate_scanned: candidateFiles.length,\n scanned_candidate_files: candidateFiles.length,\n missing_linked_paths_count: uniqueMissingLinkedPaths.length,\n missing_linked_paths_total: summarizedMissing.total,\n missing_linked_paths: summarizedMissing.values,\n missing_linked_paths_truncated: summarizedMissing.truncated,\n orphaned_paths_count: orphanedFiles.length,\n orphaned_paths_total: summarizedOrphaned.total,\n orphaned_paths: summarizedOrphaned.values,\n orphaned_paths_truncated: summarizedOrphaned.truncated,\n },\n },\n warnings,\n };\n}\n\nasync function buildHistoryDriftCheck(pmRoot: string, items: ItemWithBody[]): Promise<{ check: ValidateCheck; warnings: string[] }> {\n const { missingStreams, unreadableStreams, hashMismatches, chainMismatches, driftedItems } = await scanHistoryDrift(\n pmRoot,\n items,\n );\n const warnings: string[] = [];\n if (missingStreams.length > 0) {\n warnings.push(`validate_history_drift_missing_streams:${missingStreams.length}`);\n }\n if (unreadableStreams.length > 0) {\n warnings.push(`validate_history_drift_unreadable_streams:${unreadableStreams.length}`);\n }\n if (hashMismatches.length > 0) {\n warnings.push(`validate_history_drift_hash_mismatches:${hashMismatches.length}`);\n }\n if (chainMismatches.length > 0) {\n warnings.push(`validate_history_drift_chain_mismatches:${chainMismatches.length}`);\n }\n const summarizedDrifted = summarizeList(driftedItems);\n return {\n check: {\n name: \"history_drift\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n checked_items: items.length,\n drifted_items_count: driftedItems.length,\n drifted_items: summarizedDrifted.values,\n drifted_items_truncated: summarizedDrifted.truncated,\n counts: {\n missing_streams: missingStreams.length,\n unreadable_streams: unreadableStreams.length,\n hash_mismatches: hashMismatches.length,\n chain_mismatches: chainMismatches.length,\n },\n },\n },\n warnings,\n };\n}\n\nfunction summarizeCommandReferenceRow(ownerId: string, referencedId: string, command: string): string {\n const normalizedCommand = command.trim().replaceAll(/\\s+/g, \" \");\n const commandPreview = normalizedCommand.length > 120 ? `${normalizedCommand.slice(0, 117)}...` : normalizedCommand;\n return `${ownerId}:${referencedId}:${commandPreview}`;\n}\n\nfunction buildCommandReferencesCheck(\n items: ItemWithBody[],\n idPrefix: string,\n): { check: ValidateCheck; warnings: string[] } {\n const knownIds = new Set(items.map((item) => item.id.toLowerCase()));\n let linkedCommandsScanned = 0;\n let referencedPmIdCount = 0;\n const referencedPmIds = new Set<string>();\n const staleReferenceRows: string[] = [];\n\n for (const item of items) {\n for (const linkedTest of item.tests ?? []) {\n if (typeof linkedTest.command !== \"string\" || linkedTest.command.trim().length === 0) {\n continue;\n }\n linkedCommandsScanned += 1;\n const referencedIds = extractReferencedPmItemIdsFromCommand(linkedTest.command, idPrefix);\n if (referencedIds.length === 0) {\n continue;\n }\n referencedPmIdCount += referencedIds.length;\n for (const referencedId of referencedIds) {\n referencedPmIds.add(referencedId);\n if (!knownIds.has(referencedId.toLowerCase())) {\n staleReferenceRows.push(summarizeCommandReferenceRow(item.id, referencedId, linkedTest.command));\n }\n }\n }\n }\n\n const uniqueStaleReferenceRows = [...new Set(staleReferenceRows)].sort((left, right) => left.localeCompare(right));\n const stalePmIds = [...new Set(uniqueStaleReferenceRows.map((row) => row.split(\":\")[1] ?? \"\"))]\n .filter((value) => value.length > 0)\n .sort((left, right) => left.localeCompare(right));\n const warnings =\n uniqueStaleReferenceRows.length > 0 ? [`validate_command_references_stale_pm_ids:${uniqueStaleReferenceRows.length}`] : [];\n const summarizedRows = summarizeList(uniqueStaleReferenceRows);\n const summarizedStalePmIds = summarizeList(stalePmIds);\n const summarizedReferencedPmIds = summarizeList([...referencedPmIds].sort((left, right) => left.localeCompare(right)));\n\n return {\n check: {\n name: \"command_references\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n checked_items: items.length,\n linked_commands_scanned: linkedCommandsScanned,\n referenced_pm_ids_count: referencedPmIdCount,\n unique_referenced_pm_ids_count: referencedPmIds.size,\n unique_referenced_pm_ids: summarizedReferencedPmIds.values,\n unique_referenced_pm_ids_truncated: summarizedReferencedPmIds.truncated,\n stale_pm_id_references_count: uniqueStaleReferenceRows.length,\n stale_pm_ids_count: stalePmIds.length,\n stale_pm_ids: summarizedStalePmIds.values,\n stale_pm_ids_truncated: summarizedStalePmIds.truncated,\n stale_pm_id_reference_rows: summarizedRows.values,\n stale_pm_id_reference_rows_truncated: summarizedRows.truncated,\n },\n },\n warnings,\n };\n}\n\nexport async function runValidate(options: ValidateCommandOptions, global: GlobalOptions): Promise<ValidateResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n\n const settings = await readSettings(pmRoot);\n const statusRegistry = resolveRuntimeStatusRegistry(settings.schema);\n const typeRegistry = resolveItemTypeRegistry(settings, getActiveExtensionRegistrations());\n const itemReadWarnings: string[] = [];\n const items = await listAllFrontMatterWithBody(\n pmRoot,\n settings.item_format,\n typeRegistry.type_to_folder,\n itemReadWarnings,\n settings.schema,\n );\n const requestedChecks = resolveRequestedChecks(options);\n const metadataProfileSource: \"default\" | \"settings\" | \"option\" =\n typeof options.metadataProfile === \"string\" ? \"option\" : \"settings\";\n const metadataProfile = resolveValidateMetadataProfile(\n typeof options.metadataProfile === \"string\" ? options.metadataProfile : settings.validation.metadata_profile,\n );\n const metadataPolicy = resolveValidateMetadataPolicy(\n metadataProfile,\n metadataProfileSource,\n settings.validation.metadata_required_fields,\n );\n const lifecyclePatternPolicy = resolveLifecyclePatternPolicy(settings);\n const dependencyCycleSeverity = resolveDependencyCycleSeverity(options.dependencyCycleSeverity);\n const fileScanMode = resolveFileScanMode(options.scanMode);\n const workspaceRoot = resolveWorkspaceRoot(pmRoot);\n const checks: ValidateCheck[] = [];\n const warnings = [...new Set(itemReadWarnings)];\n\n if (requestedChecks.has(\"metadata\")) {\n const metadataCheck = buildMetadataCheck(items, metadataPolicy, statusRegistry, Boolean(options.verboseDiagnostics));\n checks.push(metadataCheck.check);\n warnings.push(...metadataCheck.warnings);\n }\n if (requestedChecks.has(\"resolution\")) {\n const resolutionCheck = buildResolutionCheck(items, statusRegistry, Boolean(options.verboseDiagnostics));\n checks.push(resolutionCheck.check);\n warnings.push(...resolutionCheck.warnings);\n }\n if (requestedChecks.has(\"lifecycle\")) {\n const lifecycleCheck = buildLifecycleCheck(\n items,\n Boolean(options.checkStaleBlockers),\n dependencyCycleSeverity,\n statusRegistry,\n lifecyclePatternPolicy,\n );\n checks.push(lifecycleCheck.check);\n warnings.push(...lifecycleCheck.warnings);\n }\n if (requestedChecks.has(\"files\")) {\n const filesCheck = await buildFilesCheck(\n items,\n workspaceRoot,\n pmRoot,\n fileScanMode,\n Boolean(options.includePmInternals),\n Boolean(options.verboseFileLists),\n );\n checks.push(filesCheck.check);\n warnings.push(...filesCheck.warnings);\n }\n if (requestedChecks.has(\"command_references\")) {\n const commandReferencesCheck = buildCommandReferencesCheck(items, settings.id_prefix);\n checks.push(commandReferencesCheck.check);\n warnings.push(...commandReferencesCheck.warnings);\n }\n if (requestedChecks.has(\"history_drift\")) {\n const historyDriftCheck = await buildHistoryDriftCheck(pmRoot, items);\n checks.push(historyDriftCheck.check);\n warnings.push(...historyDriftCheck.warnings);\n }\n\n const normalizedWarnings = [...new Set(warnings)].sort((left, right) => left.localeCompare(right));\n const hasErrors = checks.some((check) => check.status === \"error\");\n return {\n ok: !hasErrors,\n has_warnings: normalizedWarnings.length > 0,\n checks,\n warnings: normalizedWarnings,\n generated_at: nowIso(),\n };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ;AACf,SAAS,oBAAoB;AAE7B,SAAS,gBAAgB;AACzB,OAAO,UAAU;AACjB,SAAS,iBAAiB;;;;;;;;AA8B1B,IAAM,wBAAw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B;AAExB,WAAO,KAAK,eAAe,KAAK;AAChC,aAAS,KAAK,GAAG,eAAe,QAAQ;EAC1C;AACA,MAAI,gBAAgB,IAAI,OAAO,GAAG;AAChC,UAAM,aAAa,MAAM,gBACvB,OACA,eACA,QACA,cACA,QAAQ,QAAQ,kBAAkB,GAClC,QAAQ,QAAQ,gBAAgB,CAAC;AAEnC,WAAO,KAAK,WAAW,KAAK;AAC5B,aAAS,KAAK,GAAG,WAAW,QAAQ;EACtC;AACA,MAAI,gBAAgB,IAAI,oBAAoB,GAAG;AAC7C,UAAM,yBAAyB,4BAA4B,OAAO,SAAS,SAAS;AACpF,WAAO,KAAK,uBAAuB,KAAK;AACxC,aAAS,KAAK,GAAG,uBAAuB,QAAQ;EAClD;AACA,MAAI,gBAAgB,IAAI,eAAe,GAAG;AACxC,UAAM,oBAAoB,MAAM,uBAAuB,QAAQ,KAAK;AACpE,WAAO,KAAK,kBAAkB,KAAK;AACnC,aAAS,KAAK,GAAG,kBAAkB,QAAQ;EAC7C;AAEA,QAAM,qBAAqB,CAAC,GAAG,IAAI,IAAI,QAAQ,CAAC,EAAE,KAAK,CAAC,MAAM,UAAU,KAAK,cAAc,KAAK,CAAC;AACjG,QAAM,YAAY,OAAO,KAAK,CAAC,UAAU,MAAM,WAAW,OAAO;AACjE,SAAO;IACL,IAAI,CAAC;IACL,cAAc,mBAAmB,SAAS;IAC1C;IACA,UAAU;IACV,cAAc,OAAM;;AAExB;",
6
+ "names": ["path", "global"]
7
+ }
@@ -1,48 +1,66 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- migrateItemFilesToFormat,
4
- resolvePmPackageRootFromModule
5
- } from "./chunks/chunk-PB2YU2E3.js";
3
+ levenshteinDistanceWithinLimit
4
+ } from "./chunks/chunk-EAOG77HM.js";
5
+ import {
6
+ migrateItemFilesToFormat
7
+ } from "./chunks/chunk-KBQY3YG5.js";
6
8
  import {
7
9
  applyDefaultOutputFormat,
8
10
  clearResolvedGlobalOptions,
9
11
  collect,
10
- createLazyModule,
11
12
  formatHookWarnings,
12
13
  getCommandPath,
13
14
  getGlobalOptions,
14
15
  invalidateSearchCachesForMutation,
15
16
  setResolvedGlobalOptions
16
- } from "./chunks/chunk-RJONRNXN.js";
17
+ } from "./chunks/chunk-P53TN6IA.js";
18
+ import {
19
+ PM_CORE_COMMAND_NAMES,
20
+ resolveSubcommandFlagContractsForCommand
21
+ } from "./chunks/chunk-GN7IJPCD.js";
22
+ import "./chunks/chunk-6HT2F4TK.js";
23
+ import {
24
+ printError,
25
+ printResult,
26
+ writeStdout
27
+ } from "./chunks/chunk-5HSEP75M.js";
28
+ import {
29
+ resolvePmPackageRootFromModule
30
+ } from "./chunks/chunk-EGUGFSNX.js";
31
+ import "./chunks/chunk-BUPWJ3IJ.js";
32
+ import "./chunks/chunk-4AEZR5EJ.js";
33
+ import "./chunks/chunk-CEFIVZPG.js";
34
+ import "./chunks/chunk-MD7K4JYF.js";
35
+ import {
36
+ commandOptionFlagLabel,
37
+ resolveCommandOptionPolicyState,
38
+ resolveItemTypeRegistry,
39
+ resolveTypeDefinition
40
+ } from "./chunks/chunk-WDPXDQFG.js";
41
+ import {
42
+ nowIso
43
+ } from "./chunks/chunk-PVNQLCIS.js";
17
44
  import {
18
45
  BUILTIN_ITEM_TYPE_VALUES,
19
46
  EXIT_CODE,
20
- PM_CORE_COMMAND_NAMES,
21
47
  PmCliError,
22
48
  activateExtensions,
23
49
  appendLineAtomic,
24
50
  asRecordOrNull,
25
51
  clearActiveExtensionHooks,
26
- commandOptionFlagLabel,
27
52
  getActiveCommandResult,
28
53
  getActiveExtensionRegistrations,
29
54
  getSettingsPath,
30
55
  loadExtensions,
31
- nowIso,
32
56
  pathExists,
33
- printError,
34
- printResult,
35
57
  readFileIfExists,
36
58
  readSettings,
37
59
  readSettingsWithMetadata,
38
- resolveCommandOptionPolicyState,
39
60
  resolveGlobalPmRoot,
40
- resolveItemTypeRegistry,
41
61
  resolvePmRoot,
42
62
  resolveRuntimeFieldRegistry,
43
- resolveSubcommandFlagContractsForCommand,
44
63
  resolveTelemetryErrorCategory,
45
- resolveTypeDefinition,
46
64
  runActiveCommandHandler,
47
65
  runActiveParserOverride,
48
66
  runActivePreflightOverride,
@@ -60,9 +78,8 @@ import {
60
78
  setActiveExtensionServices,
61
79
  toNonEmptyStringOrUndefined,
62
80
  writeFileAtomic,
63
- writeSettings,
64
- writeStdout
65
- } from "./chunks/chunk-SW5BMMCU.js";
81
+ writeSettings
82
+ } from "./chunks/chunk-LSXGH6NE.js";
66
83
 
67
84
  // dist/cli/main.js
68
85
  import fs2 from "node:fs";
@@ -154,6 +171,7 @@ async function maybeRunFirstUseTelemetryPrompt(commandPath, globalOptions) {
154
171
  // dist/core/telemetry/runtime.js
155
172
  import crypto from "node:crypto";
156
173
  import { spawn } from "node:child_process";
174
+ import { mkdirSync, rmSync, statSync } from "node:fs";
157
175
  import { mkdir, readdir, rm, stat } from "node:fs/promises";
158
176
  import os from "node:os";
159
177
  import path from "node:path";
@@ -212,8 +230,8 @@ var DIAGNOSTICS_ROOT_COMMANDS = /* @__PURE__ */ new Set(["health", "validate", "
212
230
  function normalizeCommandPath(commandPath) {
213
231
  return commandPath.trim().replaceAll(/\s+/g, " ").toLowerCase();
214
232
  }
215
- function normalizeErrorCode(errorCode) {
216
- const normalized = errorCode?.trim().toLowerCase();
233
+ function normalizeErrorCode(errorCode2) {
234
+ const normalized = errorCode2?.trim().toLowerCase();
217
235
  return normalized && normalized.length > 0 ? normalized : void 0;
218
236
  }
219
237
  function deriveTelemetryCommandTaxonomy(commandPath) {
@@ -351,7 +369,7 @@ function deriveTelemetryCommandResolution(params) {
351
369
  !(function() {
352
370
  try {
353
371
  var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
354
- n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "e59fa9ea-8f16-5fa7-ba63-50803754d935");
372
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "b2cd9110-8de0-5e79-a029-c0902f862999");
355
373
  } catch (e2) {
356
374
  }
357
375
  })();
@@ -370,6 +388,8 @@ var TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS = 15;
370
388
  var TELEMETRY_RESULT_PREVIEW_MAX_BYTES = 8192;
371
389
  var TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS = [25, 50, 100, 200];
372
390
  var TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS = 60 * 60 * 1e3;
391
+ var TELEMETRY_FLUSH_LOCK_STALE_MS = 6e4;
392
+ var TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS = 6e4;
373
393
  var OTEL_TRACES_ENDPOINT_ENV = "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT";
374
394
  var OTEL_BASE_ENDPOINT_ENV = "OTEL_EXPORTER_OTLP_ENDPOINT";
375
395
  var OTEL_SERVICE_NAME_ENV = "OTEL_SERVICE_NAME";
@@ -416,6 +436,12 @@ function telemetryRuntimeDirectory(globalPmRoot) {
416
436
  function runtimeStatePath(globalPmRoot) {
417
437
  return path.join(globalPmRoot, TELEMETRY_STATE_RELATIVE_PATH);
418
438
  }
439
+ function flushLockPath(globalPmRoot) {
440
+ return path.join(globalPmRoot, "runtime", "telemetry", "flush.lock");
441
+ }
442
+ function flushSpawnLockPath(globalPmRoot) {
443
+ return path.join(globalPmRoot, "runtime", "telemetry", "flush.spawn.lock");
444
+ }
419
445
  function telemetryFlushRunnerPath() {
420
446
  return path.join(resolvePmPackageRootFromModule(import.meta.url, ["../../.."]), "dist", "cli", "telemetry-flush.js");
421
447
  }
@@ -669,9 +695,9 @@ function hashCommandArgs(installationId, args) {
669
695
  digest: hashWithInstallationId(installationId, args.join("\0"))
670
696
  };
671
697
  }
672
- function hashTelemetryErrorFingerprint(installationId, command, errorCode, errorMessage) {
698
+ function hashTelemetryErrorFingerprint(installationId, command, errorCode2, errorMessage) {
673
699
  const normalizedMessage = sanitizeString(errorMessage ?? "", "redacted");
674
- const fingerprintSource = `${command}\0${errorCode ?? "unknown_error"}\0${normalizedMessage}`;
700
+ const fingerprintSource = `${command}\0${errorCode2 ?? "unknown_error"}\0${normalizedMessage}`;
675
701
  return hashWithInstallationId(installationId, fingerprintSource);
676
702
  }
677
703
  function telemetryDisabledByEnvironment() {
@@ -894,8 +920,8 @@ function buildCommandStartPayload(params) {
894
920
  };
895
921
  }
896
922
  function buildCommandFinishPayload(params) {
897
- const { captureLevel, pmVersion, sourceContext, outcome, durationMs, startedAt, command, installationId, commandTaxonomy, exitCode, errorCode, errorCategory, commandResolution, resolutionStage } = params;
898
- const errorFingerprint = outcome.ok === false ? hashTelemetryErrorFingerprint(installationId, command, errorCode, outcome.error) : void 0;
923
+ const { captureLevel, pmVersion, sourceContext, outcome, durationMs, startedAt, command, installationId, commandTaxonomy, exitCode, errorCode: errorCode2, errorCategory, commandResolution, resolutionStage } = params;
924
+ const errorFingerprint = outcome.ok === false ? hashTelemetryErrorFingerprint(installationId, command, errorCode2, outcome.error) : void 0;
899
925
  if (captureLevel === "minimal") {
900
926
  return {
901
927
  capture_level: captureLevel,
@@ -907,7 +933,7 @@ function buildCommandFinishPayload(params) {
907
933
  resolution_stage: resolutionStage,
908
934
  ok: outcome.ok,
909
935
  exit_code: exitCode,
910
- error_code: errorCode,
936
+ error_code: errorCode2,
911
937
  error_category: errorCategory,
912
938
  error: outcome.error ? sanitizeString(outcome.error, "redacted") : void 0,
913
939
  error_fingerprint: errorFingerprint,
@@ -924,7 +950,7 @@ function buildCommandFinishPayload(params) {
924
950
  resolution_stage: resolutionStage,
925
951
  ok: outcome.ok,
926
952
  exit_code: exitCode,
927
- error_code: errorCode,
953
+ error_code: errorCode2,
928
954
  error_category: errorCategory,
929
955
  error: outcome.error ? sanitizeString(outcome.error, captureLevel) : void 0,
930
956
  error_fingerprint: errorFingerprint,
@@ -934,11 +960,11 @@ function buildCommandFinishPayload(params) {
934
960
  };
935
961
  }
936
962
  function buildCommandErrorPayload(params) {
937
- const { captureLevel, pmVersion, sourceContext, command, commandTaxonomy, commandResolution, resolutionStage, args, options, pmRootHash, cwdHash, installationId, errorCode, errorMessage, errorCategory, exitCode } = params;
963
+ const { captureLevel, pmVersion, sourceContext, command, commandTaxonomy, commandResolution, resolutionStage, args, options, pmRootHash, cwdHash, installationId, errorCode: errorCode2, errorMessage, errorCategory, exitCode } = params;
938
964
  const attemptedArgHashes = hashCommandArgs(installationId, args);
939
965
  const attemptedCommandDigest = hashWithInstallationId(installationId, command);
940
966
  const attemptedOptionsDigest = hashTelemetryValue(installationId, options);
941
- const errorFingerprint = hashTelemetryErrorFingerprint(installationId, command, errorCode, errorMessage);
967
+ const errorFingerprint = hashTelemetryErrorFingerprint(installationId, command, errorCode2, errorMessage);
942
968
  if (captureLevel === "minimal") {
943
969
  return {
944
970
  capture_level: captureLevel,
@@ -951,7 +977,7 @@ function buildCommandErrorPayload(params) {
951
977
  attempted_command_digest: attemptedCommandDigest,
952
978
  attempted_args_digest: attemptedArgHashes.digest,
953
979
  attempted_options_digest: attemptedOptionsDigest,
954
- error_code: errorCode,
980
+ error_code: errorCode2,
955
981
  error_category: errorCategory,
956
982
  exit_code: exitCode,
957
983
  error: sanitizeString(errorMessage, "redacted"),
@@ -973,7 +999,7 @@ function buildCommandErrorPayload(params) {
973
999
  attempted_args_digest: attemptedArgHashes.digest,
974
1000
  attempted_options: sanitizeValue(options, void 0, captureLevel),
975
1001
  attempted_options_digest: attemptedOptionsDigest,
976
- error_code: errorCode,
1002
+ error_code: errorCode2,
977
1003
  error_category: errorCategory,
978
1004
  exit_code: exitCode,
979
1005
  error: sanitizeString(errorMessage, captureLevel),
@@ -1279,6 +1305,67 @@ async function flushQueue(globalPmRoot, endpoint, retentionDays) {
1279
1305
  });
1280
1306
  }
1281
1307
  }
1308
+ function isFreshDirectoryLock(lockPath, staleMs) {
1309
+ try {
1310
+ return Date.now() - statSync(lockPath).mtimeMs < staleMs;
1311
+ } catch {
1312
+ return false;
1313
+ }
1314
+ }
1315
+ function removeDirectoryLockBestEffort(lockPath) {
1316
+ try {
1317
+ rmSync(lockPath, { recursive: true, force: true });
1318
+ } catch {
1319
+ }
1320
+ }
1321
+ function errorCode(error) {
1322
+ if (typeof error !== "object" || error === null || !("code" in error)) {
1323
+ return void 0;
1324
+ }
1325
+ const code = error.code;
1326
+ return typeof code === "string" ? code : void 0;
1327
+ }
1328
+ function createDirectoryLock(lockPath) {
1329
+ try {
1330
+ mkdirSync(lockPath);
1331
+ return true;
1332
+ } catch (error) {
1333
+ const code = errorCode(error);
1334
+ if (code === "EEXIST") {
1335
+ return false;
1336
+ }
1337
+ if (code !== "ENOENT") {
1338
+ return false;
1339
+ }
1340
+ }
1341
+ try {
1342
+ mkdirSync(path.dirname(lockPath), { recursive: true });
1343
+ mkdirSync(lockPath);
1344
+ return true;
1345
+ } catch {
1346
+ return false;
1347
+ }
1348
+ }
1349
+ function acquireTelemetryFlushSpawnGate(globalPmRoot) {
1350
+ if (isFreshDirectoryLock(flushLockPath(globalPmRoot), TELEMETRY_FLUSH_LOCK_STALE_MS)) {
1351
+ return false;
1352
+ }
1353
+ const lockPath = flushSpawnLockPath(globalPmRoot);
1354
+ try {
1355
+ if (Date.now() - statSync(lockPath).mtimeMs < TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS) {
1356
+ return false;
1357
+ }
1358
+ removeDirectoryLockBestEffort(lockPath);
1359
+ } catch (error) {
1360
+ if (errorCode(error) !== "ENOENT") {
1361
+ return false;
1362
+ }
1363
+ }
1364
+ return createDirectoryLock(lockPath);
1365
+ }
1366
+ function releaseTelemetryFlushSpawnGate(globalPmRoot) {
1367
+ removeDirectoryLockBestEffort(flushSpawnLockPath(globalPmRoot));
1368
+ }
1282
1369
  function scheduleTelemetryFlush(globalPmRoot, endpoint, retentionDays) {
1283
1370
  if (shouldFlushInline()) {
1284
1371
  const previousFlush = _lastFlushPromise;
@@ -1289,6 +1376,10 @@ function scheduleTelemetryFlush(globalPmRoot, endpoint, retentionDays) {
1289
1376
  return;
1290
1377
  }
1291
1378
  try {
1379
+ const acquiredSpawnGate = acquireTelemetryFlushSpawnGate(globalPmRoot);
1380
+ if (!acquiredSpawnGate) {
1381
+ return;
1382
+ }
1292
1383
  const child = spawn(process.execPath, [telemetryFlushRunnerPath()], {
1293
1384
  detached: true,
1294
1385
  stdio: "ignore",
@@ -1300,6 +1391,7 @@ function scheduleTelemetryFlush(globalPmRoot, endpoint, retentionDays) {
1300
1391
  });
1301
1392
  child.unref();
1302
1393
  } catch {
1394
+ releaseTelemetryFlushSpawnGate(globalPmRoot);
1303
1395
  }
1304
1396
  }
1305
1397
  async function startTelemetryCommand(context) {
@@ -3521,6 +3613,22 @@ function classifyUnknownError(rawMessage) {
3521
3613
  return guidanceToClassification(buildUnknownErrorGuidance(rawMessage));
3522
3614
  }
3523
3615
 
3616
+ // dist/core/shared/lazy-module.js
3617
+ !(function() {
3618
+ try {
3619
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
3620
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "8a197e16-769b-582e-833f-997a66d98407");
3621
+ } catch (e2) {
3622
+ }
3623
+ })();
3624
+ function createLazyModule(importer) {
3625
+ let promise = null;
3626
+ return () => {
3627
+ promise ??= importer();
3628
+ return promise;
3629
+ };
3630
+ }
3631
+
3524
3632
  // dist/cli/extension-command-help.js
3525
3633
  !(function() {
3526
3634
  try {
@@ -3897,58 +4005,6 @@ function ensureCommandPath(root, pathParts) {
3897
4005
  return current;
3898
4006
  }
3899
4007
 
3900
- // dist/core/shared/levenshtein.js
3901
- !(function() {
3902
- try {
3903
- var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
3904
- n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "6f3e0977-8505-552c-b2ff-862f2a5d5a91");
3905
- } catch (e2) {
3906
- }
3907
- })();
3908
- function levenshteinDistanceWithinLimit(left, right, limit) {
3909
- if (left === right) {
3910
- return 0;
3911
- }
3912
- if (Math.abs(left.length - right.length) > limit) {
3913
- return null;
3914
- }
3915
- const width = right.length + 1;
3916
- const beforePrevious = new Array(width);
3917
- const previous = new Array(width);
3918
- const current = new Array(width);
3919
- for (let column = 0; column < width; column += 1) {
3920
- beforePrevious[column] = 0;
3921
- previous[column] = column;
3922
- }
3923
- for (let row = 1; row <= left.length; row += 1) {
3924
- current[0] = row;
3925
- let rowMin = current[0];
3926
- for (let column = 1; column <= right.length; column += 1) {
3927
- const cost = left[row - 1] === right[column - 1] ? 0 : 1;
3928
- const substitution = previous[column - 1] + cost;
3929
- const insertion = current[column - 1] + 1;
3930
- const deletion = previous[column] + 1;
3931
- let candidate = Math.min(substitution, insertion, deletion);
3932
- if (row > 1 && column > 1 && left[row - 1] === right[column - 2] && left[row - 2] === right[column - 1]) {
3933
- candidate = Math.min(candidate, beforePrevious[column - 2] + 1);
3934
- }
3935
- current[column] = candidate;
3936
- if (candidate < rowMin) {
3937
- rowMin = candidate;
3938
- }
3939
- }
3940
- if (rowMin > limit) {
3941
- return null;
3942
- }
3943
- for (let column = 0; column < width; column += 1) {
3944
- beforePrevious[column] = previous[column];
3945
- previous[column] = current[column];
3946
- }
3947
- }
3948
- const result = previous[right.length];
3949
- return result <= limit ? result : null;
3950
- }
3951
-
3952
4008
  // dist/cli/bootstrap-args.js
3953
4009
  !(function() {
3954
4010
  try {
@@ -5409,10 +5465,10 @@ var EXPECTED_HANDLED_ERROR_EXIT_CODES = /* @__PURE__ */ new Set([
5409
5465
  EXIT_CODE.CONFLICT
5410
5466
  ]);
5411
5467
  var TRUE_LIKE_ENV_VALUES = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
5412
- var loadSetupRegistrationModule = createLazyModule(() => import("./chunks/register-setup-OZOKSMPJ.js"));
5413
- var loadListQueryRegistrationModule = createLazyModule(() => import("./chunks/register-list-query-EIVQ5FMR.js"));
5414
- var loadMutationRegistrationModule = createLazyModule(() => import("./chunks/register-mutation-RSZNPSGI.js"));
5415
- var loadOperationRegistrationModule = createLazyModule(() => import("./chunks/register-operations-APUSYDMR.js"));
5468
+ var loadSetupRegistrationModule = createLazyModule(() => import("./chunks/register-setup-V56GDRUS.js"));
5469
+ var loadListQueryRegistrationModule = createLazyModule(() => import("./chunks/register-list-query-UP3VRUFS.js"));
5470
+ var loadMutationRegistrationModule = createLazyModule(() => import("./chunks/register-mutation-YWSBF545.js"));
5471
+ var loadOperationRegistrationModule = createLazyModule(() => import("./chunks/register-operations-3BDTGSDH.js"));
5416
5472
  function describeUnknownError(error) {
5417
5473
  if (error instanceof PmCliError) {
5418
5474
  return error.message;
@@ -5617,12 +5673,12 @@ function buildPostActionTelemetryOutcome() {
5617
5673
  const resultExitCode = readRecordNumber(result, "exit_code", "exitCode");
5618
5674
  const exitCode = processExitCode ?? resultExitCode ?? EXIT_CODE.SUCCESS;
5619
5675
  const ok = exitCode === EXIT_CODE.SUCCESS;
5620
- const errorCode = readRecordString(result, "error_code", "errorCode") ?? inferPostActionErrorCode(ok, exitCode);
5621
- const errorCategory = normalizeTelemetryErrorCategory2(readRecordString(result, "error_category", "errorCategory")) ?? (!ok ? resolveTelemetryErrorCategory(errorCode) : void 0);
5676
+ const errorCode2 = readRecordString(result, "error_code", "errorCode") ?? inferPostActionErrorCode(ok, exitCode);
5677
+ const errorCategory = normalizeTelemetryErrorCategory2(readRecordString(result, "error_category", "errorCategory")) ?? (!ok ? resolveTelemetryErrorCategory(errorCode2) : void 0);
5622
5678
  const errorMessage = !ok ? inferPostActionFailureMessage(result) ?? `command_exit_${exitCode}` : void 0;
5623
5679
  const commandResolution = normalizeTelemetryCommandResolution(readRecordString(result, "command_resolution", "commandResolution")) ?? deriveTelemetryCommandResolution({
5624
5680
  ok,
5625
- errorCode,
5681
+ errorCode: errorCode2,
5626
5682
  errorCategory
5627
5683
  });
5628
5684
  const resolutionStage = normalizeTelemetryResolutionStage(readRecordString(result, "resolution_stage", "resolutionStage")) ?? "execute";
@@ -5630,7 +5686,7 @@ function buildPostActionTelemetryOutcome() {
5630
5686
  ok,
5631
5687
  error: errorMessage,
5632
5688
  exit_code: exitCode,
5633
- error_code: errorCode,
5689
+ error_code: errorCode2,
5634
5690
  error_category: errorCategory,
5635
5691
  command_resolution: commandResolution,
5636
5692
  resolution_stage: resolutionStage