@unbrained/pm-cli 2026.10.30 → 2026.11.1

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 (262) hide show
  1. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/AGENTS.md +3 -3
  4. package/CHANGELOG.md +41 -0
  5. package/README.md +1 -1
  6. package/dist/cli/commander-usage.js +2 -2
  7. package/dist/cli/error-guidance.d.ts +45 -5
  8. package/dist/cli/error-guidance.js +5 -3
  9. package/dist/cli/extension-command-help.d.ts +1 -0
  10. package/dist/cli/extension-command-help.js +2 -2
  11. package/dist/cli/main.d.ts +1 -5
  12. package/dist/cli/main.js +5 -5
  13. package/dist/cli/migration-gates.d.ts +1 -1
  14. package/dist/cli/migration-gates.js +1 -1
  15. package/dist/cli/preflight-warnings.d.ts +11 -0
  16. package/dist/cli/preflight-warnings.js +4 -0
  17. package/dist/cli/register-mutation.js +2 -2
  18. package/dist/cli/register-operations.d.ts +3 -3
  19. package/dist/cli/register-operations.js +1 -1
  20. package/dist/cli-bundle/bundle-manifest.json +1 -1
  21. package/dist/cli-bundle/chunks/chunk-2GK2IVU5.js +8 -0
  22. package/dist/cli-bundle/chunks/chunk-5KW4WUAK.js +6 -0
  23. package/dist/cli-bundle/chunks/chunk-5WVE7XBS.js +114 -0
  24. package/dist/cli-bundle/chunks/chunk-6PKWKVS6.js +8 -0
  25. package/dist/cli-bundle/chunks/chunk-E74BORFX.js +128 -0
  26. package/dist/cli-bundle/chunks/chunk-F3ECOBKA.js +2 -0
  27. package/dist/cli-bundle/chunks/chunk-ICT6E4IW.js +2 -0
  28. package/dist/cli-bundle/chunks/chunk-MP2DQJH2.js +3 -0
  29. package/dist/cli-bundle/chunks/{chunk-LWW4F4G2.js → chunk-MRUA2Z43.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-UUQX3PFD.js → chunk-MTRIGD7M.js} +76 -76
  31. package/dist/cli-bundle/chunks/{chunk-S2U7ECUJ.js → chunk-N45IXPCA.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-MVL27TAH.js → chunk-NILQ2ZMV.js} +2 -2
  33. package/dist/cli-bundle/chunks/{chunk-GRABKNFL.js → chunk-O56O7NIE.js} +2 -2
  34. package/dist/cli-bundle/chunks/chunk-O6TFUV6M.js +31 -0
  35. package/dist/cli-bundle/chunks/{chunk-TH5KPAN4.js → chunk-SBVX5CMV.js} +2 -2
  36. package/dist/cli-bundle/chunks/{chunk-Y6NC3X3E.js → chunk-TMPO4CTZ.js} +3 -3
  37. package/dist/cli-bundle/chunks/chunk-TYERATXH.js +2 -0
  38. package/dist/cli-bundle/chunks/{chunk-EHBGHX55.js → chunk-UEEG47TU.js} +2 -2
  39. package/dist/cli-bundle/chunks/chunk-UUN3WNMQ.js +20 -0
  40. package/dist/cli-bundle/chunks/chunk-WFBYKDB2.js +2 -0
  41. package/dist/cli-bundle/chunks/{chunk-RZQNFHXO.js → chunk-WX25MU4N.js} +3 -3
  42. package/dist/cli-bundle/chunks/{chunk-4BQD5SW2.js → chunk-Y7CKVU56.js} +30 -30
  43. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-LHLE7PSG.js → indexed-receipt-blobs-KGMJVFH2.js} +2 -2
  44. package/dist/cli-bundle/chunks/item-transaction-Q5S5YLEJ.js +2 -0
  45. package/dist/cli-bundle/chunks/{mutation-admission-TRGAVS7N.js → mutation-admission-BOOCJPCU.js} +2 -2
  46. package/dist/cli-bundle/chunks/{register-list-query-BH4F6M7Z.js → register-list-query-23OX36Q3.js} +3 -3
  47. package/dist/cli-bundle/chunks/register-mutation-JPJ5YNDX.js +20 -0
  48. package/dist/cli-bundle/chunks/register-operations-IGR7ERY5.js +2 -0
  49. package/dist/cli-bundle/chunks/{register-setup-QPWSVHFZ.js → register-setup-BMIFKZZP.js} +2 -2
  50. package/dist/cli-bundle/chunks/{settlement-hook-MN3Y7LVX.js → settlement-hook-YWSWFOZY.js} +2 -2
  51. package/dist/cli-bundle/chunks/{stage-RTB6RAAO.js → stage-ON7CYYPM.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-POJPJX64.js → chunk-2Y77HWIX.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-SAT7IAEB.js → chunk-3NYWMUX3.js} +3 -3
  54. package/dist/cli-bundle/focused-chunks/chunk-3Z53POXU.js +2 -0
  55. package/dist/cli-bundle/focused-chunks/chunk-5TWS5KOM.js +26 -0
  56. package/dist/cli-bundle/focused-chunks/chunk-5WCQFH6D.js +12 -0
  57. package/dist/cli-bundle/focused-chunks/{chunk-S23ZUASN.js → chunk-6GMYW42K.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-YQUZL2CK.js → chunk-6OKPYCLU.js} +5 -5
  59. package/dist/cli-bundle/focused-chunks/chunk-7WJDRZOR.js +22 -0
  60. package/dist/cli-bundle/focused-chunks/{chunk-3SRX77ES.js → chunk-AL7SOFUL.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/chunk-CIQ6YWCW.js +26 -0
  62. package/dist/cli-bundle/focused-chunks/{chunk-RKPUQDWF.js → chunk-DFUTCKUF.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{chunk-RYEZSZJ7.js → chunk-GE755ODZ.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/chunk-JCR32IAO.js +91 -0
  65. package/dist/cli-bundle/focused-chunks/{chunk-BPE6JTKL.js → chunk-JLXGRDTG.js} +3 -3
  66. package/dist/cli-bundle/focused-chunks/chunk-LVA76N27.js +6 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-YU7QOYYV.js → chunk-M22TI7LP.js} +3 -3
  68. package/dist/cli-bundle/focused-chunks/chunk-PAT6QF63.js +2 -0
  69. package/dist/cli-bundle/focused-chunks/{chunk-VFWCSQAG.js → chunk-RPUDOJVB.js} +2 -2
  70. package/dist/cli-bundle/focused-chunks/chunk-SXZM4PSS.js +44 -0
  71. package/dist/cli-bundle/focused-chunks/chunk-UQIBGLDR.js +2 -0
  72. package/dist/cli-bundle/focused-chunks/{chunk-RGQEJFXO.js → chunk-VFQAZLKO.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/{chunk-BCIUAEWX.js → chunk-VS2ZFPXD.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{chunk-FRFNGMAK.js → chunk-WX2RVS2Y.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/chunk-Z7GIVH6B.js +3 -0
  76. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-VK2363JB.js → indexed-receipt-blobs-KHWT44EK.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/item-transaction-7VLPA2SU.js +2 -0
  78. package/dist/cli-bundle/focused-chunks/{mutation-admission-7VUODEPJ.js → mutation-admission-2DH27R5Y.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/{settlement-hook-OK6A7PG2.js → settlement-hook-SJV52ZTV.js} +2 -2
  80. package/dist/cli-bundle/focused-chunks/{stage-S5RP5SZH.js → stage-FYOBWQA7.js} +2 -2
  81. package/dist/cli-bundle/main.js +26 -22
  82. package/dist/cli-bundle/sdk-authoring.js +1 -1
  83. package/dist/cli-bundle/sdk-contracts.js +4 -4
  84. package/dist/cli-bundle/sdk-core.js +1 -1
  85. package/dist/cli-bundle/sdk-governance.js +1 -1
  86. package/dist/cli-bundle/sdk-graph.js +1 -1
  87. package/dist/cli-bundle/sdk-merge.js +57 -57
  88. package/dist/cli-bundle/sdk-query.js +1 -1
  89. package/dist/cli-bundle/sdk-runtime.js +1 -1
  90. package/dist/cli-bundle/sdk-testing.js +1 -1
  91. package/dist/cli-bundle/sdk.js +11 -11
  92. package/dist/core/config/nested-settings.js +1 -1
  93. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  94. package/dist/core/extensions/extension-types.d.ts +4 -0
  95. package/dist/core/extensions/extension-types.js +1 -1
  96. package/dist/core/extensions/loader.js +1 -1
  97. package/dist/core/lock/lock.js +4 -4
  98. package/dist/core/output/mutation-projection.js +1 -1
  99. package/dist/core/output/output.js +3 -3
  100. package/dist/core/schema/fields-file.js +1 -1
  101. package/dist/core/sentry/helpers.d.ts +6 -0
  102. package/dist/core/sentry/helpers.js +1 -1
  103. package/dist/core/sentry/instrument.d.ts +1 -1
  104. package/dist/core/sentry/instrument.js +1 -1
  105. package/dist/core/shared/constants.js +1 -1
  106. package/dist/core/shared/errors.d.ts +6 -0
  107. package/dist/core/shared/errors.js +1 -1
  108. package/dist/core/shared/output-unicode.d.ts +10 -0
  109. package/dist/core/shared/output-unicode.js +2 -0
  110. package/dist/core/store/settings-validator.d.ts +1 -0
  111. package/dist/core/store/settings-validator.js +1 -1
  112. package/dist/core/store/settings.js +1 -1
  113. package/dist/core/telemetry/policy.d.ts +8 -0
  114. package/dist/core/telemetry/policy.js +1 -1
  115. package/dist/core/telemetry/runtime.js +3 -3
  116. package/dist/sdk/agent/command-recovery.d.ts +15 -0
  117. package/dist/sdk/agent/command-recovery.js +1 -1
  118. package/dist/sdk/cli-bootstrap.js +1 -1
  119. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +28 -0
  120. package/dist/sdk/cli-contracts/agent-output-contracts.js +2 -2
  121. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  122. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  123. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  124. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  125. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  126. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  127. package/dist/sdk/cli-contracts.d.ts +1 -1
  128. package/dist/sdk/cli-contracts.js +1 -1
  129. package/dist/sdk/completion/fish.js +4 -4
  130. package/dist/sdk/completion/zsh.js +3 -3
  131. package/dist/sdk/config.d.ts +1 -0
  132. package/dist/sdk/config.js +1 -1
  133. package/dist/sdk/context-intent-contracts.d.ts +17 -0
  134. package/dist/sdk/context-intent-contracts.js +1 -1
  135. package/dist/sdk/core.d.ts +2 -1
  136. package/dist/sdk/core.js +1 -1
  137. package/dist/sdk/error-runtime.d.ts +9 -0
  138. package/dist/sdk/error-runtime.js +1 -1
  139. package/dist/sdk/errors.js +1 -1
  140. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  141. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  142. package/dist/sdk/index.d.ts +3 -3
  143. package/dist/sdk/index.js +1 -1
  144. package/dist/sdk/init-agent-guidance.js +2 -2
  145. package/dist/sdk/lifecycle/claim.d.ts +27 -0
  146. package/dist/sdk/lifecycle/claim.js +1 -1
  147. package/dist/sdk/lifecycle/close.js +1 -1
  148. package/dist/sdk/lifecycle/create.js +1 -1
  149. package/dist/sdk/lifecycle/mcp-actions.d.ts +1 -1
  150. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  151. package/dist/sdk/lifecycle/plan.d.ts +2 -3
  152. package/dist/sdk/lifecycle/plan.js +1 -1
  153. package/dist/sdk/lifecycle/repeated-terminal-state.d.ts +45 -0
  154. package/dist/sdk/lifecycle/repeated-terminal-state.js +2 -0
  155. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +9 -0
  156. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  157. package/dist/sdk/lifecycle/task-composition.js +1 -1
  158. package/dist/sdk/lifecycle/update-many.d.ts +0 -1
  159. package/dist/sdk/lifecycle/update-many.js +1 -1
  160. package/dist/sdk/lifecycle/update.d.ts +29 -1
  161. package/dist/sdk/lifecycle/update.js +2 -2
  162. package/dist/sdk/output/list-envelope.d.ts +8 -0
  163. package/dist/sdk/output/list-envelope.js +1 -1
  164. package/dist/sdk/output/table-rows.d.ts +7 -1
  165. package/dist/sdk/output/table-rows.js +1 -1
  166. package/dist/sdk/output.d.ts +2 -1
  167. package/dist/sdk/output.js +2 -2
  168. package/dist/sdk/ownership-source.d.ts +18 -0
  169. package/dist/sdk/ownership-source.js +1 -1
  170. package/dist/sdk/public-surface.json +1 -1
  171. package/dist/sdk/query/context.js +2 -2
  172. package/dist/sdk/query/get.d.ts +1 -1
  173. package/dist/sdk/query/get.js +1 -1
  174. package/dist/sdk/query/next-ranking-policy.d.ts +35 -0
  175. package/dist/sdk/query/next-ranking-policy.js +2 -0
  176. package/dist/sdk/query/next.d.ts +12 -2
  177. package/dist/sdk/query/next.js +2 -2
  178. package/dist/sdk/query/projection-contracts.d.ts +4 -0
  179. package/dist/sdk/query/projection-contracts.js +1 -1
  180. package/dist/sdk/read-output/surfaces.d.ts +27 -0
  181. package/dist/sdk/read-output/surfaces.js +2 -0
  182. package/dist/sdk/read-output-contracts.js +1 -1
  183. package/dist/sdk/runtime/actions.js +1 -1
  184. package/dist/sdk/runtime-input.js +1 -1
  185. package/dist/sdk/runtime-primitives.d.ts +1 -0
  186. package/dist/sdk/runtime-primitives.js +1 -1
  187. package/dist/sdk/runtime-public-contracts.d.ts +2 -0
  188. package/dist/sdk/runtime.d.ts +2 -2
  189. package/dist/sdk/runtime.js +1 -1
  190. package/dist/sdk/start-task-status.d.ts +1 -1
  191. package/dist/sdk/start-task-status.js +1 -1
  192. package/dist/sdk/test/execution-receipts.d.ts +25 -0
  193. package/dist/sdk/test/execution-receipts.js +2 -2
  194. package/dist/sdk/test/execution.d.ts +5 -0
  195. package/dist/sdk/test/execution.js +2 -2
  196. package/dist/types.d.ts +2 -0
  197. package/dist/types.js +1 -1
  198. package/docs/AGENT_GUIDE.md +4 -4
  199. package/docs/AGENT_OUTPUT_ENCODINGS.md +12 -0
  200. package/docs/AGENT_UX_CONTRACTS.md +2 -1
  201. package/docs/COMMANDS.md +59 -5
  202. package/docs/COMMAND_NAMESPACES.md +1 -1
  203. package/docs/CONFIGURATION.md +48 -1
  204. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +26 -0
  205. package/docs/LIFECYCLE_COMMANDS.md +19 -4
  206. package/docs/PACKED_FIRST_RUN.md +2 -1
  207. package/docs/READ_OUTPUT_CONTRACTS.md +24 -6
  208. package/docs/SDK.md +82 -3
  209. package/docs/SDK_ACTION_CONFORMANCE.md +21 -0
  210. package/docs/TESTING.md +38 -2
  211. package/docs/agent-task-token-baseline.json +1 -1
  212. package/docs/agent-task-transcripts.json +1 -1
  213. package/marketplace.json +1 -1
  214. package/package.json +1 -1
  215. package/packages/pm-beads/package.json +1 -1
  216. package/packages/pm-calendar/extensions/calendar/index.ts +1 -0
  217. package/packages/pm-calendar/package.json +1 -1
  218. package/packages/pm-command-kit/package.json +1 -1
  219. package/packages/pm-digital-twin/package.json +1 -1
  220. package/packages/pm-governance-audit/package.json +1 -1
  221. package/packages/pm-guide-shell/package.json +1 -1
  222. package/packages/pm-kanban/package.json +1 -1
  223. package/packages/pm-lifecycle-hooks/package.json +1 -1
  224. package/packages/pm-linked-test-adapters/package.json +1 -1
  225. package/packages/pm-search-advanced/package.json +1 -1
  226. package/packages/pm-templates/package.json +1 -1
  227. package/packages/pm-todos/package.json +1 -1
  228. package/packages/pm-vcs/package.json +1 -1
  229. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  230. package/plugins/pm-claude/package.json +1 -1
  231. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  232. package/plugins/pm-codex/package.json +1 -1
  233. package/plugins/pm-codex/plugin.json +1 -1
  234. package/runtime-dependencies.json +1 -1
  235. package/dist/cli-bundle/chunks/chunk-34MP7WKK.js +0 -6
  236. package/dist/cli-bundle/chunks/chunk-3KMYHYJV.js +0 -2
  237. package/dist/cli-bundle/chunks/chunk-42BHHNTL.js +0 -128
  238. package/dist/cli-bundle/chunks/chunk-I5O3XZOA.js +0 -2
  239. package/dist/cli-bundle/chunks/chunk-LEIVUGDH.js +0 -8
  240. package/dist/cli-bundle/chunks/chunk-OH7WPD42.js +0 -114
  241. package/dist/cli-bundle/chunks/chunk-OOD2A7AF.js +0 -20
  242. package/dist/cli-bundle/chunks/chunk-Q5V7P6NM.js +0 -2
  243. package/dist/cli-bundle/chunks/chunk-QLPFYBXN.js +0 -2
  244. package/dist/cli-bundle/chunks/chunk-SA5NYLPE.js +0 -8
  245. package/dist/cli-bundle/chunks/chunk-VHLAVTJN.js +0 -31
  246. package/dist/cli-bundle/chunks/chunk-XAOVJG52.js +0 -3
  247. package/dist/cli-bundle/chunks/chunk-XPQ4RTSF.js +0 -2
  248. package/dist/cli-bundle/chunks/item-transaction-WIOBZW4E.js +0 -2
  249. package/dist/cli-bundle/chunks/register-mutation-5V2NANIS.js +0 -20
  250. package/dist/cli-bundle/chunks/register-operations-XSFRMUFX.js +0 -2
  251. package/dist/cli-bundle/focused-chunks/chunk-2V6NMNYN.js +0 -26
  252. package/dist/cli-bundle/focused-chunks/chunk-ASHGXMX4.js +0 -3
  253. package/dist/cli-bundle/focused-chunks/chunk-CKBN2D42.js +0 -12
  254. package/dist/cli-bundle/focused-chunks/chunk-I642DXOT.js +0 -22
  255. package/dist/cli-bundle/focused-chunks/chunk-K7DKG5HM.js +0 -91
  256. package/dist/cli-bundle/focused-chunks/chunk-NMQBXU7N.js +0 -44
  257. package/dist/cli-bundle/focused-chunks/chunk-PGM3ENGZ.js +0 -2
  258. package/dist/cli-bundle/focused-chunks/chunk-QFNV4JTA.js +0 -6
  259. package/dist/cli-bundle/focused-chunks/chunk-QVJCQMZY.js +0 -26
  260. package/dist/cli-bundle/focused-chunks/chunk-R2TPPPVU.js +0 -2
  261. package/dist/cli-bundle/focused-chunks/chunk-VJVJ2ZX2.js +0 -2
  262. package/dist/cli-bundle/focused-chunks/item-transaction-ZFDKJIP7.js +0 -2
@@ -1,3 +1,3 @@
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]="2355a6b7-2a17-586c-8dd3-182980a708d0")}catch{}})();import{SETTINGS_DEFAULTS,EXIT_CODE,PmCliError,compareTimestampStrings,nowIso,isTerminalStatus,normalizeStatusForRegistry,normalizeStatusInput,resolveRuntimeStatusRegistry,resolvePmRoot,readSettings,resolveAuthor,discoverExtensions,resolveItemTypeRegistry}from"../runtime-primitives.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{collectDependencyBlockedIds,resolveItemBlockers,resolveItemExecutionRole,computeActionabilityReport}from"../actionability.js";import{CONTEXT_DEPTH_VALUES,CONTEXT_SECTION_VALUES}from"../../types/index.js";import{parseIntegerLimit}from"./parsers.js";import{runCalendar}from"./calendar.js";import{runList}from"./list.js";import{runActivity}from"./activity.js";import{scoreContextCandidatesWithActiveExtensions}from"../context-relevance.js";import{buildItemContextRelevanceCandidates}from"../context-relevance.js";import{createQueryFingerprint,encodeQueryCursor,resolveQueryCursorStart,selectCursorSemanticOptions}from"../pagination.js";import{rememberReadOutputFocusRows,refreshReadOutputDeliveredCounts}from"../read-output-rows.js";import{CONTEXT_FLAG_CONTRACTS}from"../cli-contracts/flag-contracts.js";import{packContextCandidates}from"../context-packing.js";import{attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,readContextUsageAffinity,recordContextUsageServing}from"../context-usage.js";import{readWorkspaceContextSignals}from"../context-signal-store.js";import{readWorkspaceMemory,selectWorkspaceMemory}from"../workspace-memory.js";import{detectAgentIdentity}from"../../core/shared/author.js";import{readSessionState,semanticAttributionKey}from"../../core/session/session-state.js";import{semanticAttributionAffinity}from"../context/semantic-session-attribution.js";const CONTEXT_OUTPUT_VALUES=["markdown","toon","json","ndjson"],HIGH_LEVEL_TYPES=new Set(["Epic","Feature"]),DEFAULT_CONTEXT_LIMIT=10,CONTEXT_SCALE_THRESHOLD=1e4,STANDARD_SECTIONS=["hierarchy","activity","progress","recently_created","unparented","workload"],DEEP_SECTIONS=[...STANDARD_SECTIONS,"blockers","files","staleness","tests"],LEADING_HYPHEN_DATE=/^(\d{4})-(\d{2})-(\d{2})/,LEADING_COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})$/,COMPACT_DATETIME=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function parseOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!CONTEXT_OUTPUT_VALUES.includes(normalized))throw new PmCliError("Context format must be one of markdown|toon|json|ndjson",EXIT_CODE.USAGE);return normalized}const FOCUS_PROJECTION_FIELDS=new Set(["id","title","type","status","priority","order","deadline","assignee","tags","tags_inherited","updated_at","parent","children_total","children_closed","completion_pct","blocked","blocker_ids","created_at"]);function parseContextFocusFields(raw){if(raw===void 0)return;const fields=[];for(const token of raw.split(",")){const normalized=token.trim().toLowerCase();if(normalized.length!==0){if(!FOCUS_PROJECTION_FIELDS.has(normalized))throw new PmCliError(`Context --fields value not projectable: ${normalized} (valid: ${[...FOCUS_PROJECTION_FIELDS].join(", ")})`,EXIT_CODE.USAGE);fields.includes(normalized)||fields.push(normalized)}}if(fields.length===0)throw new PmCliError("Context --fields requires at least one field name",EXIT_CODE.USAGE);return fields}function projectContextFocusRows(rows,fields){return rows.map(row=>{const projected={},source=row;for(const field of fields)projected[field]=source[field]??null;return projected})}function resolveContextOutputFormat(options,global2){const commandFormat=parseOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json"&&commandFormat!=="ndjson")throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE);return global2.json?commandFormat==="ndjson"?"ndjson":"json":commandFormat??"toon"}function parseContextLimit(raw,depth){return parseIntegerLimit(raw,"--limit")??(depth==="full"?Number.MAX_SAFE_INTEGER:DEFAULT_CONTEXT_LIMIT)}function resolveContextTokenBudget(raw,fallback){if(raw===void 0)return fallback;const parsed=typeof raw=="number"?raw:Number(raw);if(!Number.isInteger(parsed)||parsed<1)throw new PmCliError("--token-budget must be a positive integer",EXIT_CODE.USAGE);return parsed}function resolveContextLimitAtScale(limit,itemCount){return itemCount>=CONTEXT_SCALE_THRESHOLD&&limit===Number.MAX_SAFE_INTEGER?DEFAULT_CONTEXT_LIMIT:limit}function parseContextDepth(raw,settings){if(!raw)return settings.default_depth;const normalized=raw.trim().toLowerCase();if(!CONTEXT_DEPTH_VALUES.includes(normalized))throw new PmCliError(`Context --depth must be one of ${CONTEXT_DEPTH_VALUES.join("|")}`,EXIT_CODE.USAGE);return normalized}function parseContextSections(raw,depth,settings){if(raw&&raw.length>0){const sections=[];for(const value of raw){const normalized=value.trim().toLowerCase();if(!CONTEXT_SECTION_VALUES.includes(normalized))throw new PmCliError(`Context --section must be one of ${CONTEXT_SECTION_VALUES.join("|")}`,EXIT_CODE.USAGE);sections.includes(normalized)||sections.push(normalized)}return sections}return depth==="brief"?[]:depth==="full"?[...CONTEXT_SECTION_VALUES]:(depth==="deep"?DEEP_SECTIONS:STANDARD_SECTIONS).filter(section=>settings.sections[section])}function parseActivityLimit(raw,settings){return raw?parseIntegerLimit(raw,"--activity-limit")??settings.activity_limit:settings.activity_limit}function parseStaleThresholdDays(raw,settings){if(!raw)return settings.stale_threshold_days;const trimmed=raw.trim().toLowerCase(),match=/^(\d+)d?$/.exec(trimmed);if(!match)throw new PmCliError("--stale-threshold must be a number of days (e.g. 7 or 7d)",EXIT_CODE.USAGE);const days=parseInt(match[1],10);if(days<=0)throw new PmCliError("--stale-threshold must be positive",EXIT_CODE.USAGE);return days}function statusRank(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry),blockedStatus=normalizeStatusInput("blocked",statusRegistry),draftStatus=normalizeStatusInput("draft",statusRegistry);return normalizedStatus===statusRegistry.in_progress_status?0:statusRegistry.active_statuses.has(normalizedStatus)?1:blockedStatus&&normalizedStatus===blockedStatus?2:draftStatus&&normalizedStatus===draftStatus?3:statusRegistry.blocked_statuses.has(normalizedStatus)?5:statusRegistry.terminal_statuses.has(normalizedStatus)?7:6}function isClosedStatus(status,statusRegistry){const closeStatus=normalizeStatusInput("closed",statusRegistry);return normalizeStatusForRegistry(status,statusRegistry)===closeStatus}function isInProgressStatus(status,statusRegistry){return normalizeStatusForRegistry(status,statusRegistry)===statusRegistry.in_progress_status}function isOpenStatus(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry);return normalizedStatus!==statusRegistry.in_progress_status&&statusRegistry.active_statuses.has(normalizedStatus)}function isBlockedStatus(status,statusRegistry){return statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(status,statusRegistry))}const LIST_PROJECTION_FLAGS=["compact","brief","fields","includeBody","include_body","parent"];function stripListProjectionFlags(options){const copy={...options};for(const key of LIST_PROJECTION_FLAGS)delete copy[key];return copy}function collectSubtreeIds(corpus,parentId){const target=parentId.trim().toLowerCase(),anchor=corpus.find(item=>item.id.trim().toLowerCase()===target);if(!anchor)return{ids:new Set,found:!1};const childrenByParent=buildChildrenByParent(corpus),descendants=collectDescendants(anchor.id,childrenByParent);return{ids:new Set([anchor.id,...descendants.map(item=>item.id)].map(id=>id.trim().toLowerCase())),found:!0}}function parseContextParent(raw){if(raw===void 0)return;const trimmed=raw.trim();if(trimmed.length===0)throw new PmCliError("Context --parent requires an item id",EXIT_CODE.USAGE);return trimmed}function compareOptionalOrder(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:leftValue-rightValue}function compareOptionalDeadline(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:compareTimestampStrings(leftValue,rightValue)}function daysInUtcMonth(year,monthIndex){return new Date(Date.UTC(year,monthIndex+1,0)).getUTCDate()}function hasNoInvalidDatePrefix(value){const match=LEADING_HYPHEN_DATE.exec(value)??LEADING_COMPACT_DATE.exec(value);if(!match)return!0;const year=Number.parseInt(match[1],10),month=Number.parseInt(match[2],10),day=Number.parseInt(match[3],10);return month>=1&&month<=12&&day>=1&&day<=daysInUtcMonth(year,month-1)}function normalizeTimestampCandidate(value){const compactDate=COMPACT_DATE.exec(value);if(compactDate)return`${compactDate[1]}-${compactDate[2]}-${compactDate[3]}`;const compactDateTime=COMPACT_DATETIME.exec(value);if(compactDateTime){const[,year,month,day,hour,minute,secondRaw,offsetRaw]=compactDateTime,second=secondRaw?`:${secondRaw}`:"",offset=offsetRaw&&offsetRaw.length===5&&offsetRaw!=="Z"?`${offsetRaw.slice(0,3)}:${offsetRaw.slice(3)}`:offsetRaw??"";return`${year}-${month}-${day}T${hour}:${minute}${second}${offset}`}return value}function parseContextTimestampMs(value){if(typeof value!="string")return Number.NaN;const trimmed=value.trim();if(trimmed.length===0||!hasNoInvalidDatePrefix(trimmed))return Number.NaN;const parsed=Date.parse(normalizeTimestampCandidate(trimmed));return Number.isFinite(parsed)?parsed:Number.NaN}function sortableTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString():""}function dateTokenForTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString().slice(0,10):"unknown"}function normalizedParentId(value){if(typeof value!="string")return null;const trimmed=value.trim();return trimmed.length>0?trimmed:null}function compareCriticalItems(left,right,statusRegistry){const byStatus=statusRank(left.status,statusRegistry)-statusRank(right.status,statusRegistry);if(byStatus!==0)return byStatus;const byPriority=left.priority-right.priority;if(byPriority!==0)return byPriority;const byOrder=compareOptionalOrder(left.order,right.order);if(byOrder!==0)return byOrder;const byDeadline=compareOptionalDeadline(left.deadline,right.deadline);if(byDeadline!==0)return byDeadline;const byUpdated=compareTimestampStrings(sortableTimestamp(right.updated_at),sortableTimestamp(left.updated_at)),byId=left.id.localeCompare(right.id);return byUpdated!==0?byUpdated:byId}function estimateJsonTokens(value){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(value),"utf8")/4))}function packRankedContextItems(report,tokenBudget,requiredIds=new Set,profile="context"){return packContextCandidates(report.ranked.map(entry=>({id:entry.id,item:entry.item,rank:entry.rank,score:entry.score,required:requiredIds.has(entry.id),cluster:entry.item.parent?.trim()||entry.item.type,token_costs:{identity:estimateJsonTokens({id:entry.id,title:entry.item.title}),summary:estimateJsonTokens({id:entry.id,title:entry.item.title,type:entry.item.type,status:entry.item.status,priority:entry.item.priority,parent:entry.item.parent}),full:estimateJsonTokens(entry.item)}})),{tokenBudget,profile,latencyBudgetMs:25})}function toContextPackingSummary(report){return{...report,included:report.included.map(entry=>({id:entry.id,projection:entry.projection,tokens:entry.tokens}))}}function toContextRankingSummary(report,featureStore,servedItemIds){const ranked=servedItemIds===void 0?report.ranked:report.ranked.filter(entry=>servedItemIds.has(entry.id));return{model:report.model,available_signals:report.available_signals,items:ranked.map(entry=>({id:entry.id,rank:entry.rank,baseline_rank:entry.baseline_rank,score:entry.score,contributions:entry.contributions,...entry.signal_provenance===void 0?{}:{recency:entry.signal_provenance.recency}})),candidate_count:report.ranked.length,omitted_count:report.ranked.length-ranked.length,...featureStore?{feature_store:{source:featureStore.snapshot.source,cache_status:featureStore.cache_status,source_cursor:featureStore.snapshot.source_cursor,generated_at:featureStore.snapshot.generated_at}}:{}}}function completionPct(closed,total){return total>0?Math.round(closed*100/total):0}function buildChildrenByParent(allItems){const childrenByParent=new Map;for(const item of allItems){const parent=normalizedParentId(item.parent);if(!parent)continue;const children=childrenByParent.get(parent)??[];children.push(item),childrenByParent.set(parent,children)}return childrenByParent}function toContextFocusItem(item,statusRegistry,childrenByParent){const focus={id:item.id,title:item.title,type:item.type,status:item.status,priority:item.priority,order:item.order??null,deadline:item.deadline??null,assignee:item.assignee??null,tags:Array.isArray(item.tags)?[...item.tags]:[],updated_at:item.updated_at,parent:normalizedParentId(item.parent)};if(statusRegistry&&childrenByParent){const descendants=collectDescendants(item.id,childrenByParent),total=descendants.length;if(total>0){const closed=descendants.filter(desc=>isClosedStatus(desc.status,statusRegistry)).length;focus.children_total=total,focus.children_closed=closed,focus.completion_pct=completionPct(closed,total)}}return focus}function summarizeAgenda(events){let deadlines=0,reminders=0,scheduled=0;const itemIds=new Set;for(const event of events){if(itemIds.add(event.item_id),event.kind==="deadline"){deadlines+=1;continue}if(event.kind==="reminder"){reminders+=1;continue}scheduled+=1}return{events:events.length,items:itemIds.size,deadlines,reminders,scheduled}}function mergeSortedWarnings(...warningGroups){return[...new Set(warningGroups.flatMap(group=>group??[]))].sort((left,right)=>left.localeCompare(right))}function filterTerminalCalendarEvents(events,statusRegistry){return events.filter(event=>!statusRegistry.terminal_statuses.has(normalizeStatusForRegistry(event.item_status,statusRegistry)))}function buildHierarchy(allItems,activeItems,statusRegistry,limit){const itemMap=new Map;for(const item of allItems)itemMap.set(item.id,item);const childrenByParent=buildChildrenByParent(allItems),activeHighLevelIds=new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)).map(item=>item.id)),nodes=[];for(const parentId of activeHighLevelIds){const parent=itemMap.get(parentId);if(!parent)continue;const allDescendants=collectDescendants(parentId,childrenByParent),childItems=childrenByParent.get(parentId)??[];let closedCount=0,openCount=0,inProgressCount=0,blockedCount=0;for(const desc of allDescendants)isClosedStatus(desc.status,statusRegistry)?closedCount++:isInProgressStatus(desc.status,statusRegistry)?inProgressCount++:isBlockedStatus(desc.status,statusRegistry)?blockedCount++:isOpenStatus(desc.status,statusRegistry)&&openCount++;const children=childItems.sort((a,b)=>compareCriticalItems(a,b,statusRegistry)).slice(0,limit).map(child=>{const grandchildren=collectDescendants(child.id,childrenByParent),gcClosed=grandchildren.filter(gc=>isClosedStatus(gc.status,statusRegistry)).length;return{id:child.id,title:child.title,type:child.type,status:child.status,children_total:grandchildren.length,children_closed:gcClosed}});nodes.push({id:parent.id,title:parent.title,type:parent.type,status:parent.status,children_total:allDescendants.length,children_closed:closedCount,children_open:openCount,children_in_progress:inProgressCount,children_blocked:blockedCount,children})}return nodes.sort((a,b)=>{const aParent=itemMap.get(a.id),bParent=itemMap.get(b.id);return compareCriticalItems(aParent,bParent,statusRegistry)}).slice(0,limit)}function collectDescendants(parentId,childrenByParent){const result=[],stack=[parentId],visited=new Set;for(;stack.length>0;){const current=stack.pop();if(visited.has(current))continue;visited.add(current);const children=childrenByParent.get(current)??[];for(const child of children)result.push(child),stack.push(child.id)}return result}const _testOnly={buildActivity,buildBlockers,buildChildrenByParent,buildHierarchy,buildHotFiles,buildProgress,buildRecentlyCreated,buildStaleness,buildTestHealth,buildUnparented,buildWorkload,collectDescendants,collectSubtreeIds,compareCriticalItems,compareOptionalDeadline,compareOptionalOrder,completionPct,dateTokenForTimestamp,filterTerminalCalendarEvents,formatAgendaLine,isBlockedStatus,isClosedStatus,isInProgressStatus,isOpenStatus,mergeSortedWarnings,normalizedParentId,parseActivityLimit,parseContextLimit,resolveContextLimitAtScale,parseContextParent,parseContextTimestampMs,parseStaleThresholdDays,sortableTimestamp,statusRank,stripListProjectionFlags,summarizeAgenda,toContextFocusItem};async function buildActivity(activityLimit,global2){return(await runActivity({compact:!0,limit:String(activityLimit)},global2)).compact_activity??[]}function buildProgress(allItems,activeItems,blockedIds,statusRegistry,limit){const childrenByParent=new Map;for(const item of allItems){if(!item.parent)continue;const children=childrenByParent.get(item.parent)??[];children.push(item),childrenByParent.set(item.parent,children)}const activeHighLevel=activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)),entries=[];for(const parent of activeHighLevel){const descendants=collectDescendants(parent.id,childrenByParent),total=descendants.length;if(total===0)continue;let closed=0,open=0,inProgress=0,blocked=0;for(const desc of descendants)isClosedStatus(desc.status,statusRegistry)?closed++:blockedIds.has(desc.id.trim().toLowerCase())?blocked++:isInProgressStatus(desc.status,statusRegistry)?inProgress++:isOpenStatus(desc.status,statusRegistry)&&open++;entries.push({id:parent.id,title:parent.title,type:parent.type,total,closed,open,in_progress:inProgress,blocked,completion_pct:completionPct(closed,total)})}return entries.sort((a,b)=>a.completion_pct-b.completion_pct).slice(0,limit)}function buildBlockers(blockedItems,fullCorpus,statusRegistry,limit){const itemsById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item]));return blockedItems.slice(0,limit).map(item=>{const blockers=resolveItemBlockers(item,itemsById,statusRegistry),blockedBy=blockers.find(blocker=>!blocker.resolved)?.id??blockers[0]?.id??null,blockerItem=blockedBy?itemsById.get(blockedBy.trim().toLowerCase()):void 0;return{id:item.id,title:item.title,blocked_by:blockedBy,blocked_by_title:blockerItem?.title??null,blocked_by_status:blockerItem?.status??null,blocked_reason:item.blocked_reason??null,unblock_note:item.unblock_note??null}})}function buildHotFiles(activeItems,limit){const fileMap=new Map;for(const item of activeItems)for(const file of item.files??[]){const existing=fileMap.get(file.path)??new Set;existing.add(item.id),fileMap.set(file.path,existing)}return[...fileMap.entries()].map(([filePath,itemIds])=>({path:filePath,references:itemIds.size,items:[...itemIds].sort()})).sort((a,b)=>b.references-a.references).slice(0,limit)}function buildWorkload(activeItems,statusRegistry,limit){const groups=new Map;for(const item of activeItems){const key=item.assignee??null,existing=groups.get(key)??[];existing.push(item),groups.set(key,existing)}return[...groups.entries()].map(([assignee,items])=>({assignee,active:items.length,in_progress:items.filter(item=>isInProgressStatus(item.status,statusRegistry)).length,items:items.map(item=>item.id).sort()})).sort((a,b)=>b.active-a.active).slice(0,limit)}function buildStaleness(allNonTerminal,staleThresholdDays,now,limit){const cutoffMs=new Date(now).getTime()-staleThresholdDays*24*60*60*1e3;return allNonTerminal.filter(item=>new Date(item.updated_at).getTime()<cutoffMs).map(item=>({id:item.id,title:item.title,status:item.status,updated_at:item.updated_at,stale_days:Math.floor((new Date(now).getTime()-new Date(item.updated_at).getTime())/(1440*60*1e3))})).sort((a,b)=>b.stale_days-a.stale_days).slice(0,limit)}function buildRecentlyCreated(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.map(item=>({item,sortKey:sortableTimestamp(item.created_at)})).sort((left,right)=>{const byCreated=compareTimestampStrings(right.sortKey,left.sortKey);return byCreated!==0?byCreated:left.item.id.localeCompare(right.item.id)}).slice(0,limit).map(({item})=>({...toContextFocusItem(item,statusRegistry,childrenByParent),created_at:item.created_at}))}function buildUnparented(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.filter(item=>!normalizedParentId(item.parent)&&!HIGH_LEVEL_TYPES.has(item.type)).sort((left,right)=>compareCriticalItems(left,right,statusRegistry)).slice(0,limit).map(item=>toContextFocusItem(item,statusRegistry,childrenByParent))}function buildTestHealth(activeItems){let itemsWithTests=0,itemsWithRecentRuns=0,passed=0,failed=0,skipped=0;const itemsFailing=[];for(const item of activeItems){(item.tests??[]).length>0&&itemsWithTests++;const runs=item.test_runs??[];if(runs.length>0){itemsWithRecentRuns++;let itemHasFailure=!1;for(const run of runs)passed+=run.passed??0,failed+=run.failed??0,skipped+=run.skipped??0,(run.failed??0)>0&&(itemHasFailure=!0);itemHasFailure&&itemsFailing.push(item.id)}}return{scope:"matching_active_items",total_items:activeItems.length,items_with_tests:itemsWithTests,items_with_recent_runs:itemsWithRecentRuns,recent_runs:{passed,failed,skipped},items_failing:itemsFailing.sort()}}function formatClock(timestamp){return`${new Date(timestamp).toISOString().slice(11,16)}Z`}function formatFocusLine(item){const orderToken=item.order===null?"-":String(item.order),deadlineToken=item.deadline??"-",parentToken=item.parent?` parent:${item.parent}`:"",progressToken=item.children_total!==void 0&&item.children_closed!==void 0&&item.completion_pct!==void 0?` children:${item.children_closed}/${item.children_total} done:${item.completion_pct}%`:"",blockedToken=item.blocked===!0?` blocked:${item.blocker_ids?.join(",")||"lifecycle"}`:"";return`${item.id} p${item.priority} ${item.status} ${item.type} order:${orderToken} deadline:${deadlineToken}${parentToken}${progressToken}${blockedToken} ${item.title}`}function formatProjectedFocusLine(item,fields){const source=item;return fields.map(field=>{const value=source[field];return Array.isArray(value)?`${field}:${value.join(",")}`:`${field}:${value??"-"}`}).join(" ")}function formatAgendaLine(event){if("reference_only"in event){const suffix=event.kind==="reminder"?` \u2014 ${event.reminder_text??"reminder"}`:event.kind==="event"?` \u2014 ${event.event_title??"event"}${event.event_recurring?" (recurring)":""}`:"";return`${formatClock(event.at)} [${event.kind}] ${event.item_id} (see focus item)${suffix}`}const base=`${formatClock(event.at)} [${event.kind}] ${event.item_id} p${event.item_priority} ${event.item_status} ${event.item_title}`;if(event.kind==="reminder")return`${base} \u2014 ${event.reminder_text}`;if(event.kind==="event"){const recurringSuffix=event.event_recurring?" (recurring)":"",title=event.event_title??event.item_title;return`${base} \u2014 ${title}${recurringSuffix}`}return base}function pushContextFocusSection(lines,title,rows,emptyText,renderFocus){if(lines.push(`## ${title}`),rows.length===0)lines.push(emptyText);else for(const item of rows)lines.push(`- ${renderFocus(item)}`);lines.push("")}function pushBlockedFallbackSection(lines,result,renderFocus){if(result.blocked_fallback.length!==0){lines.push("## Blocked fallback");for(const item of result.blocked_fallback)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushAgendaSection(lines,result){if(lines.push("## Agenda"),lines.push(`- events: ${result.agenda.summary.events} (deadlines: ${result.agenda.summary.deadlines}, reminders: ${result.agenda.summary.reminders}, scheduled: ${result.agenda.summary.scheduled})`),result.agenda.events.length===0)lines.push("No agenda events matched the selected filters.");else for(const event of result.agenda.events)lines.push(`- ${formatAgendaLine(event)}`);lines.push("")}function pushHierarchySection(lines,result){if(!(!result.hierarchy||result.hierarchy.length===0)){lines.push("## Hierarchy");for(const node of result.hierarchy){const pct=completionPct(node.children_closed,node.children_total);lines.push(`- ${node.id} ${node.type} ${node.status} "${node.title}" [${node.children_closed}/${node.children_total} done ${pct}%]`);for(const child of node.children){const cpct=completionPct(child.children_closed,child.children_total);lines.push(` - ${child.id} ${child.type} ${child.status} "${child.title}" [${child.children_closed}/${child.children_total} done ${cpct}%]`)}}lines.push("")}}function pushProgressSection(lines,result){if(!(!result.progress||result.progress.length===0)){lines.push("## Progress");for(const entry of result.progress)lines.push(`- ${entry.id} "${entry.title}" ${entry.completion_pct}% (${entry.closed}/${entry.total} closed, ${entry.in_progress} wip, ${entry.open} open, ${entry.blocked} blocked)`);lines.push("")}}function pushRecentlyCreatedSection(lines,result,focusFields,renderFocus){if(!(!result.recently_created||result.recently_created.length===0)){lines.push("## Recently created");for(const item of result.recently_created)lines.push(focusFields?`- ${renderFocus(item)}`:`- ${dateTokenForTimestamp(item.created_at)} ${formatFocusLine(item)}`);lines.push("")}}function pushUnparentedSection(lines,result,renderFocus){if(!(!result.unparented||result.unparented.length===0)){lines.push("## Unparented");for(const item of result.unparented)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushActivitySection(lines,result){if(!(!result.activity||result.activity.length===0)){lines.push("## Recent activity");for(const entry of result.activity){const msg=entry.msg?` ${entry.msg}`:"";lines.push(`- ${entry.ts.slice(0,16)}Z ${entry.id} ${entry.op} by:${entry.author}${msg}`)}lines.push("")}}function pushBlockersSection(lines,result){if(!(!result.blockers||result.blockers.length===0)){lines.push("## Blockers");for(const entry of result.blockers){const by=entry.blocked_by?`blocked_by:${entry.blocked_by}(${entry.blocked_by_status??"?"})`:"blocked_by:-",reason=entry.blocked_reason?` reason:"${entry.blocked_reason}"`:"",note=entry.unblock_note?` unblock:"${entry.unblock_note}"`:"";lines.push(`- ${entry.id} "${entry.title}" ${by}${reason}${note}`)}lines.push("")}}function pushFilesSection(lines,result){if(!(!result.files||result.files.length===0)){lines.push("## Hot files");for(const file of result.files)lines.push(`- ${file.path} refs:${file.references} items:[${file.items.join(",")}]`);lines.push("")}}function pushWorkloadSection(lines,result){if(!(!result.workload||result.workload.length===0)){lines.push("## Workload");for(const entry of result.workload){const who=entry.assignee??"(unassigned)";lines.push(`- ${who} active:${entry.active} wip:${entry.in_progress} items:[${entry.items.join(",")}]`)}lines.push("")}}function pushStalenessSection(lines,result){if(!(!result.staleness||result.staleness.length===0)){lines.push("## Stale items");for(const entry of result.staleness)lines.push(`- ${entry.id} ${entry.status} stale:${entry.stale_days}d last:${entry.updated_at.slice(0,10)} "${entry.title}"`);lines.push("")}}function boundedTestHealthFailures(tests,limit,tokenBudget){const included=[];let usedTokens=0;for(const id of tests.items_failing){if(included.length>=limit)break;const tokens=estimateJsonTokens(id);if(usedTokens+tokens>tokenBudget)break;included.push(id),usedTokens+=tokens}return included}function pushTestHealthSection(lines,result){if(!result.tests)return;lines.push("## Test health"),lines.push(`- ${result.tests.scope}: ${result.tests.total_items}`),lines.push(`- items_with_tests: ${result.tests.items_with_tests}`),lines.push(`- items_with_recent_runs: ${result.tests.items_with_recent_runs}`),lines.push(`- passed: ${result.tests.recent_runs.passed}, failed: ${result.tests.recent_runs.failed}, skipped: ${result.tests.recent_runs.skipped}`);const failures=boundedTestHealthFailures(result.tests,result.applied_limit??DEFAULT_CONTEXT_LIMIT,result.filters.token_budget);failures.length>0&&lines.push(`- items_failing: [${failures.join(",")}]`);const omitted=result.tests.items_failing.length-failures.length;omitted>0&&lines.push(`- items_failing_omitted: ${omitted}`),lines.push("")}function pushEmptyContextSuggestions(lines,result){result.summary.active_items===0&&result.summary.blocked===0&&result.agenda.summary.events===0&&(lines.push("## Suggestions"),lines.push("No active work items or upcoming events. Consider:"),lines.push('- `pm create --type Task --title "..."` to add a new work item'),lines.push("- `pm list --status closed --limit 5` to review recent completions"),lines.push("- `pm search <keywords>` to find related past work"),lines.push("- `pm aggregate` for a full project status overview"))}function renderContextMarkdown(result){const lines=[],focusFields=result.focus_fields,renderFocus=item=>focusFields?formatProjectedFocusLine(item,focusFields):formatFocusLine(item);if(lines.push("# pm context"),lines.push(""),lines.push(`- now: ${result.now}`),lines.push(`- depth: ${result.depth}`),result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(`- active_items: ${result.summary.active_items} (in_progress: ${result.summary.in_progress}, open: ${result.summary.open})`),result.summary.total_items!==void 0&&lines.push(`- total_items: ${result.summary.total_items} (closed: ${result.summary.closed??0}, canceled: ${result.summary.canceled??0})`),lines.push(`- agenda_events: ${result.summary.agenda_events}`),lines.push(`- blocked_fallback_used: ${result.summary.blocked_fallback_used}`),result.extension_health){const degradedNames=result.extension_health.packages.filter(entry=>entry.status==="degraded").map(entry=>entry.name);lines.push(`- extensions: ${result.extension_health.ok} ok, ${result.extension_health.degraded} degraded${degradedNames.length>0?` (${degradedNames.join(", ")})`:""}`)}const renderedSections=result.sections_included.filter(section=>section!=="blockers"||(result.blockers?.length??0)>0);if(renderedSections.length>0&&lines.push(`- sections: ${renderedSections.join(", ")}`),lines.push(""),pushContextFocusSection(lines,"High-level focus",result.high_level,"No high-level active items.",renderFocus),pushContextFocusSection(lines,"Low-level focus",result.low_level,"No low-level active items.",renderFocus),pushBlockedFallbackSection(lines,result,renderFocus),pushAgendaSection(lines,result),result.workspace_memory){lines.push("## Workspace memory");for(const rollup of result.workspace_memory.rollups)lines.push(`- ${rollup.kind}:${rollup.key} \u2014 ${rollup.label} (${rollup.item_count} completed, latest ${rollup.last_closed_at})`);lines.push("")}return pushHierarchySection(lines,result),pushProgressSection(lines,result),pushRecentlyCreatedSection(lines,result,focusFields,renderFocus),pushUnparentedSection(lines,result,renderFocus),pushActivitySection(lines,result),pushBlockersSection(lines,result),pushFilesSection(lines,result),pushWorkloadSection(lines,result),pushStalenessSection(lines,result),pushTestHealthSection(lines,result),pushEmptyContextSuggestions(lines,result),lines.join(`
2
- `)}async function resolveContextRuntime(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),settings=await readSettings(pmRoot),contextSettings=settings.context??SETTINGS_DEFAULTS.context,statusRegistry=resolveRuntimeStatusRegistry(settings.schema),depth=parseContextDepth(options.depth,contextSettings),limit=parseContextLimit(options.limit??options.maxItems,depth);return{settings,contextSettings,statusRegistry,depth,limit,sectionsIncluded:parseContextSections(options.section,depth,contextSettings),activityLimit:parseActivityLimit(options.activityLimit,contextSettings),staleThresholdDays:parseStaleThresholdDays(options.staleThreshold,contextSettings),parentScope:parseContextParent(options.parent),focusFields:parseContextFocusFields(options.fields),baseListOptions:stripListProjectionFlags(options)}}function contextNeedsAllItems(sectionsIncluded){return sectionsIncluded.some(section=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(section))}function buildUnpaginatedContextListOptions(baseListOptions,extra){return{...baseListOptions,...extra,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function loadContextCorpus(global2,runtime){const listed=await runList(void 0,buildUnpaginatedContextListOptions(runtime.baseListOptions,{excludeTerminal:!1}),global2),fullCorpus=listed.items;let listedItemMetadata=fullCorpus.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),allItems=fullCorpus;const subtreeIds=resolveContextSubtreeIds(runtime.parentScope,fullCorpus);return subtreeIds&&(listedItemMetadata=listedItemMetadata.filter(item=>subtreeIds.has(item.id.trim().toLowerCase())),allItems=allItems.filter(item=>subtreeIds.has(item.id.trim().toLowerCase()))),{listed,listedItemMetadata,allItems,fullCorpus,subtreeIds}}function resolveContextSubtreeIds(parentScope,fullCorpus){if(parentScope===void 0)return;const subtree=collectSubtreeIds(fullCorpus,parentScope);if(!subtree.found)throw new PmCliError(`Context --parent item not found: ${parentScope}`,EXIT_CODE.NOT_FOUND);return subtree.ids}function collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry){const containers=new Set(computeActionabilityReport(activeItems,fullCorpus,statusRegistry,typeRegistry).containers.map(entry=>entry.item.id));return new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)||containers.has(item.id)||resolveItemExecutionRole(item.type,typeRegistry)!=="agent").map(item=>item.id))}async function resolveContextFocusGroups(listedItemMetadata,allItems,fullCorpus,blockedIds,statusRegistry,sectionsIncluded,limit,now,author,cursor,cursorFingerprint,useBoundedPage,pmRoot,tokenBudget,claimFocus,typeRegistry){const structural=[...listedItemMetadata].sort((left,right)=>compareCriticalItems(left,right,statusRegistry)),usage=await readContextUsageAffinity({pmRoot,author,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),featureStore=await readWorkspaceContextSignals(structural,{pmRoot,storeKey:"context",statusRegistry,now,author,usageAffinity:usage.affinity,claimFocus}),ranking=await scoreContextCandidatesWithActiveExtensions("context",featureStore.candidates),ranked=ranking.ranked.map(entry=>entry.item),activeStatuses=statusRegistry.active_statuses,rankedActiveItems=ranked.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),pageStart=useBoundedPage?resolveQueryCursorStart(rankedActiveItems,cursor,cursorFingerprint,item=>item.id):0,focusPage=useBoundedPage?rankedActiveItems.slice(pageStart,pageStart+limit):rankedActiveItems,hasMore=useBoundedPage&&focusPage.length>0&&pageStart+focusPage.length<rankedActiveItems.length,nextCursor=hasMore&&focusPage.length>0?encodeQueryCursor(cursorFingerprint,focusPage[focusPage.length-1].id,pageStart+focusPage.length-1):void 0,rankedBlockedItems=ranked.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),packingIds=new Set([...focusPage.map(item=>item.id),...rankedBlockedItems.filter(item=>!activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))).slice(0,limit).map(item=>item.id)]),packing=packRankedContextItems({...ranking,ranked:ranking.ranked.filter(entry=>packingIds.has(entry.id))},tokenBudget,new Set(Object.entries(claimFocus??{}).filter(([,affinity])=>affinity>=1).map(([id])=>id))),packedItems=packing.included.map(entry=>entry.item),activeItems=packedItems.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),blockedItems=packedItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),childrenByParent=buildChildrenByParent(allItems),focusChildrenByParent=contextNeedsAllItems(sectionsIncluded)?childrenByParent:void 0,fullCorpusById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item])),projectFocusItem=item=>{const focus=toContextFocusItem(item,statusRegistry,focusChildrenByParent);return blockedIds.has(item.id.trim().toLowerCase())&&(focus.blocked=!0,focus.blocker_ids=resolveItemBlockers(item,fullCorpusById,statusRegistry).filter(blocker=>!blocker.resolved).map(blocker=>blocker.id)),focus},highLevelIds=collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry),highLevel=activeItems.filter(item=>highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),lowLevel=activeItems.filter(item=>!highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),blockedFallbackUsed=rankedActiveItems.length===0;return{activeItems,blockedItems,highLevel,lowLevel,blockedFallback:blockedFallbackUsed?blockedItems.slice(0,limit).map(projectFocusItem):[],blockedFallbackUsed,ranking,packing,featureStore,pageExtras:{...useBoundedPage?{applied_limit:limit}:{},...hasMore?{has_more:!0,truncated:!0}:{},...nextCursor?{next_cursor:nextCursor}:{}}}}function buildContextCursorFingerprint(options,pmRoot){return createQueryFingerprint("context",{pmRoot,options:selectCursorSemanticOptions(options,CONTEXT_FLAG_CONTRACTS)})}function shouldPageContextFocus(options,corpusItemCount){return options.limit!==void 0||options.maxItems!==void 0||options.after!==void 0||corpusItemCount>=CONTEXT_SCALE_THRESHOLD}async function buildContextAgenda(global2,runtime,subtreeIds,listedFocusIds){const calendarOptions={...runtime.baseListOptions,after:void 0,view:"agenda",include:"all",limit:runtime.parentScope===void 0?String(runtime.limit):void 0},agenda=await runCalendar(calendarOptions,global2),scopedAgenda=subtreeIds===void 0?agenda.events:agenda.events.filter(event=>subtreeIds.has(event.item_id.trim().toLowerCase())),fullAgendaEvents=filterTerminalCalendarEvents(scopedAgenda,runtime.statusRegistry).slice(0,runtime.limit),agendaEvents=fullAgendaEvents.map(event=>listedFocusIds.has(event.item_id)?{at:event.at,date:event.date,kind:event.kind,item_id:event.item_id,reference_only:!0,...event.kind==="reminder"?{reminder_text:event.reminder_text}:{},...event.kind==="event"?{event_title:event.event_title,event_recurring:event.event_recurring}:{}}:event);return{agenda,agendaEvents,agendaSummary:summarizeAgenda(fullAgendaEvents)}}function countContextStatus(items,status,statusRegistry){const targetStatus=String(status);return items.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===targetStatus).length}async function buildOptionalContextSections(params){const{runtime,allItems,fullCorpus,blockedIds,focusGroups,now,global:global2}=params,childrenByParent=buildChildrenByParent(allItems),allNonTerminal=allItems.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),has=section=>runtime.sectionsIncluded.includes(section);return{hierarchy:has("hierarchy")?buildHierarchy(allItems,focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,activity:has("activity")?await buildActivity(runtime.activityLimit,global2):void 0,progress:has("progress")?buildProgress(allItems,focusGroups.activeItems,blockedIds,runtime.statusRegistry,runtime.limit):void 0,blockersSection:has("blockers")?buildBlockers(focusGroups.blockedItems,fullCorpus,runtime.statusRegistry,runtime.limit):void 0,recentlyCreated:has("recently_created")?buildRecentlyCreated(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,unparented:has("unparented")?buildUnparented(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,filesSection:has("files")?buildHotFiles(focusGroups.activeItems,runtime.limit):void 0,workload:has("workload")?buildWorkload(focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,staleness:has("staleness")?buildStaleness(allNonTerminal,runtime.staleThresholdDays,now,runtime.limit):void 0,tests:has("tests")?buildTestHealth(allItems.filter(item=>runtime.statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,runtime.statusRegistry)))):void 0}}function buildContextSummaryExtras(allItems,statusRegistry,blockedIds){const canceledStatus=normalizeStatusInput("canceled",statusRegistry),activeItems=allItems.filter(item=>statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),inProgress=countContextStatus(activeItems,statusRegistry.in_progress_status,statusRegistry);return{scope:"matching_items",active_items:activeItems.length,open:activeItems.length-inProgress,in_progress:inProgress,blocked:allItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())).length,total_items:allItems.length,closed:allItems.filter(item=>isClosedStatus(item.status,statusRegistry)).length,canceled:allItems.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===canceledStatus).length}}function attachOptionalContextSections(result,sections,warningDetails){sections.hierarchy&&(result.hierarchy=sections.hierarchy),sections.activity&&(result.activity=sections.activity),sections.progress&&(result.progress=sections.progress),sections.blockersSection&&(result.blockers=sections.blockersSection),sections.recentlyCreated&&(result.recently_created=sections.recentlyCreated),sections.unparented&&(result.unparented=sections.unparented),sections.filesSection&&(result.files=sections.filesSection),sections.workload&&(result.workload=sections.workload),sections.staleness&&(result.staleness=sections.staleness),sections.tests&&(result.tests=sections.tests),warningDetails!==void 0&&warningDetails.length>0&&(result.warning_details=warningDetails)}function applyContextFocusProjection(result,focusFields){focusFields&&(result.focus_fields=focusFields,result.high_level=projectContextFocusRows(result.high_level,focusFields),result.low_level=projectContextFocusRows(result.low_level,focusFields),result.blocked_fallback=projectContextFocusRows(result.blocked_fallback,focusFields),result.recently_created&&(result.recently_created=projectContextFocusRows(result.recently_created,focusFields)),result.unparented&&(result.unparented=projectContextFocusRows(result.unparented,focusFields)))}function applyContextTagProjection(result,noTags){const rows=[result.high_level,result.low_level,result.blocked_fallback,result.recently_created??[],result.unparented??[]].flat();if(noTags){for(const row of rows)delete row.tags,delete row.tags_inherited;return}const rowsById=new Map(rows.map(row=>[row.id,row])),originalTagSignatures=new Map(rows.map(row=>[row.id,row.tags?[...row.tags].sort().join("\0"):void 0]));for(const row of rows){if(!row.parent||!row.tags)continue;const parent=rowsById.get(row.parent);parent&&originalTagSignatures.get(row.id)===originalTagSignatures.get(parent.id)&&(delete row.tags,row.tags_inherited=parent.id)}}function maybeAttachEmptyContextSuggestions(result,activeItems,blockedItems){activeItems.length>0||blockedItems.length>0||result.agenda.events.length>0||(result.suggestions=['pm create --type Task --title "..." to add a new work item',"pm list --status closed --limit 5 to review recent completions","pm search <keywords> to find related past work","pm aggregate for a full project status overview"])}async function attachContextUsageFeedback(result,focusGroups,pmRoot,author){try{const included=new Set(focusGroups.packing.included.map(entry=>entry.id)),rows=focusGroups.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)})),rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(result,"context"))rankedIds.has(id)||(rows.push({id,rank:rows.length+1,included:!1}),rankedIds.add(id));const receipt=await recordContextUsageServing({pmRoot,author,surface:"context",profile:focusGroups.packing.profile,rows,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});attachContextUsageServingReceipt(result,receipt)}catch{result.warnings=mergeSortedWarnings(result.warnings,["context_usage_feedback_write_failed"])}}async function resolveContextExtensionHealthProjection(omitted,pmRoot,settings){if(omitted)return{};const packages=(await discoverExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:!1})).discovered.map(diagnostic=>({name:diagnostic.name??diagnostic.directory,status:diagnostic.status==="ok"?"ok":"degraded"})).sort((left,right)=>left.name.localeCompare(right.name)),degraded=packages.filter(entry=>entry.status==="degraded").length;return packages.length===0?{}:{extension_health:{total:packages.length,ok:packages.length-degraded,degraded,packages:packages.slice(0,20),...packages.length>20?{truncated:!0}:{}}}}async function resolveContextSemanticAffinity(pmRoot,author){const identity=detectAgentIdentity(),semanticState=await readSessionState(pmRoot),attributionKey=identity.instance||semanticAttributionKey(author);return semanticAttributionAffinity(semanticState.semantic_attribution?.[attributionKey])}async function runContext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),resolvedRuntime=await resolveContextRuntime(options,global2),corpus=await loadContextCorpus(global2,resolvedRuntime),scaledLimit=resolveContextLimitAtScale(resolvedRuntime.limit,corpus.fullCorpus.length),runtime={...resolvedRuntime,limit:scaledLimit,tokenBudget:resolveContextTokenBudget(options.tokenBudget,Math.max(256,scaledLimit*160))},author=resolveAuthor(void 0,runtime.settings.author_default),claimFocus=await resolveContextSemanticAffinity(pmRoot,author),extensionHealthPromise=resolveContextExtensionHealthProjection(options.noExtensionHealth===!0,pmRoot,runtime.settings),blockedIds=collectDependencyBlockedIds(corpus.fullCorpus,runtime.statusRegistry),focusGroups=await resolveContextFocusGroups(corpus.listedItemMetadata,corpus.allItems,corpus.fullCorpus,blockedIds,runtime.statusRegistry,runtime.sectionsIncluded,runtime.limit,nowIso(),author,options.after,buildContextCursorFingerprint(options,pmRoot),shouldPageContextFocus(options,corpus.fullCorpus.length),pmRoot,runtime.tokenBudget,claimFocus,resolveItemTypeRegistry(runtime.settings,getActiveExtensionRegistrations())),agendaContext=await buildContextAgenda(global2,runtime,corpus.subtreeIds,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(item=>item.id))),workspaceMemory=await readWorkspaceMemory(corpus.fullCorpus,{pmRoot,statusRegistry:runtime.statusRegistry,now:agendaContext.agenda.now}),warnings=mergeSortedWarnings(corpus.listed.warnings,agendaContext.agenda.warnings,focusGroups.ranking.warnings,[...focusGroups.featureStore.warnings],workspaceMemory.warnings),inProgressCount=countContextStatus(focusGroups.activeItems,runtime.statusRegistry.in_progress_status,runtime.statusRegistry),openCount=focusGroups.activeItems.length-inProgressCount,sections=await buildOptionalContextSections({runtime,allItems:corpus.allItems,fullCorpus:corpus.fullCorpus,blockedIds,focusGroups,now:agendaContext.agenda.now,global:global2}),summaryExtras=buildContextSummaryExtras(corpus.allItems,runtime.statusRegistry,blockedIds),result={output_default:"toon",now:agendaContext.agenda.now,depth:runtime.depth,sections_included:runtime.sectionsIncluded,window:{anchor:agendaContext.agenda.anchor,start:agendaContext.agenda.range.start,end:agendaContext.agenda.range.end,past:agendaContext.agenda.range.past,from:agendaContext.agenda.range.from,to:agendaContext.agenda.range.to},filters:{type:options.type??null,tag:options.tag??null,priority:options.priority??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,limit:options.limit??options.maxItems??null,parent:runtime.parentScope??null,token_budget:runtime.tokenBudget,runtime_filters:corpus.listed.filters.runtime_filters??agendaContext.agenda.filters.runtime_filters??{}},summary:{returned_focus:{active_items:focusGroups.activeItems.length,in_progress:inProgressCount,open:openCount,blocked:focusGroups.blockedItems.length},blocked_fallback_used:focusGroups.blockedFallbackUsed,high_level:focusGroups.highLevel.length,low_level:focusGroups.lowLevel.length,agenda_events:agendaContext.agendaSummary.events,...summaryExtras},high_level:focusGroups.highLevel,low_level:focusGroups.lowLevel,blocked_fallback:focusGroups.blockedFallback,agenda:{summary:agendaContext.agendaSummary,events:agendaContext.agendaEvents},...focusGroups.pageExtras};return result.workspace_memory=selectWorkspaceMemory(workspaceMemory,Math.min(800,Math.floor(runtime.tokenBudget*.2))),Object.assign(result,await extensionHealthPromise),attachOptionalContextSections(result,sections,focusGroups.featureStore.warning_details),applyContextTagProjection(result,options.noTags===!0),options.explainRanking===!0&&(result.ranking=toContextRankingSummary(focusGroups.ranking,focusGroups.featureStore,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(entry=>entry.id))),result.packing=toContextPackingSummary(focusGroups.packing)),rememberReadOutputFocusRows(result,[...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(row=>({id:row.id,status:normalizeStatusForRegistry(row.status,runtime.statusRegistry)===runtime.statusRegistry.in_progress_status?"in_progress":"open",blocked:row.blocked}))),applyContextFocusProjection(result,runtime.focusFields),refreshReadOutputDeliveredCounts(result),warnings.length>0&&(result.warnings=warnings),maybeAttachEmptyContextSuggestions(result,focusGroups.activeItems,focusGroups.blockedItems),await attachContextUsageFeedback(result,focusGroups,pmRoot,author),result}export{CONTEXT_OUTPUT_VALUES,_testOnly,applyContextTagProjection,buildChildrenByParent,buildItemContextRelevanceCandidates,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,projectContextFocusRows,renderContextMarkdown,resolveContextExtensionHealthProjection,resolveContextOutputFormat,resolveContextTokenBudget,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary};
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]="4596ea7d-70be-5d61-bccb-66989e1555c0")}catch{}})();import{SETTINGS_DEFAULTS,EXIT_CODE,PmCliError,compareTimestampStrings,nowIso,isTerminalStatus,normalizeStatusForRegistry,normalizeStatusInput,resolveRuntimeStatusRegistry,resolvePmRoot,readSettings,resolveAuthor,discoverExtensions,resolveItemTypeRegistry}from"../runtime-primitives.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{collectDependencyBlockedIds,resolveItemBlockers,resolveItemExecutionRole,computeActionabilityReport}from"../actionability.js";import{CONTEXT_DEPTH_VALUES,CONTEXT_SECTION_VALUES}from"../../types/index.js";import{parseIntegerLimit}from"./parsers.js";import{runCalendar}from"./calendar.js";import{runList}from"./list.js";import{runActivity}from"./activity.js";import{scoreContextCandidatesWithActiveExtensions}from"../context-relevance.js";import{buildItemContextRelevanceCandidates}from"../context-relevance.js";import{createQueryFingerprint,encodeQueryCursor,resolveQueryCursorStart,selectCursorSemanticOptions}from"../pagination.js";import{rememberReadOutputFocusRows,refreshReadOutputDeliveredCounts}from"../read-output-rows.js";import{CONTEXT_FLAG_CONTRACTS}from"../cli-contracts/flag-contracts.js";import{packContextCandidates}from"../context-packing.js";import{attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,readContextUsageAffinity,recordContextUsageServing}from"../context-usage.js";import{readWorkspaceContextSignals}from"../context-signal-store.js";import{readWorkspaceMemory,selectWorkspaceMemory}from"../workspace-memory.js";import{detectAgentIdentity}from"../../core/shared/author.js";import{readSessionState,semanticAttributionKey}from"../../core/session/session-state.js";import{semanticAttributionAffinity}from"../context/semantic-session-attribution.js";const CONTEXT_OUTPUT_VALUES=["markdown","toon","json","ndjson"],HIGH_LEVEL_TYPES=new Set(["Epic","Feature"]),DEFAULT_CONTEXT_LIMIT=10,CONTEXT_SCALE_THRESHOLD=1e4,STANDARD_SECTIONS=["hierarchy","activity","progress","recently_created","unparented","workload"],DEEP_SECTIONS=[...STANDARD_SECTIONS,"blockers","files","staleness","tests"],LEADING_HYPHEN_DATE=/^(\d{4})-(\d{2})-(\d{2})/,LEADING_COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})$/,COMPACT_DATETIME=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function parseOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!CONTEXT_OUTPUT_VALUES.includes(normalized))throw new PmCliError("Context format must be one of markdown|toon|json|ndjson",EXIT_CODE.USAGE);return normalized}const FOCUS_PROJECTION_FIELDS=new Set(["id","title","type","status","priority","order","deadline","assignee","tags","tags_inherited","updated_at","parent","children_total","children_closed","completion_pct","blocked","blocker_ids","created_at"]);function parseContextFocusFields(raw){if(raw===void 0)return;const fields=[];for(const token of raw.split(",")){const normalized=token.trim().toLowerCase();if(normalized.length!==0){if(!FOCUS_PROJECTION_FIELDS.has(normalized))throw new PmCliError(`Context --fields value not projectable: ${normalized} (valid: ${[...FOCUS_PROJECTION_FIELDS].join(", ")})`,EXIT_CODE.USAGE);fields.includes(normalized)||fields.push(normalized)}}if(fields.length===0)throw new PmCliError("Context --fields requires at least one field name",EXIT_CODE.USAGE);return fields}function projectContextFocusRows(rows,fields){return rows.map(row=>{const projected={},source=row;for(const field of fields)projected[field]=source[field]??null;return projected})}function resolveContextOutputFormat(options,global2){const commandFormat=parseOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json"&&commandFormat!=="ndjson")throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE);return global2.json?commandFormat==="ndjson"?"ndjson":"json":commandFormat??"toon"}function parseContextLimit(raw,depth){return parseIntegerLimit(raw,"--limit")??(depth==="full"?Number.MAX_SAFE_INTEGER:DEFAULT_CONTEXT_LIMIT)}function resolveContextTokenBudget(raw,fallback){if(raw===void 0)return fallback;const parsed=typeof raw=="number"?raw:Number(raw);if(!Number.isInteger(parsed)||parsed<1)throw new PmCliError("--token-budget must be a positive integer",EXIT_CODE.USAGE);return parsed}function resolveContextLimitAtScale(limit,itemCount){return itemCount>=CONTEXT_SCALE_THRESHOLD&&limit===Number.MAX_SAFE_INTEGER?DEFAULT_CONTEXT_LIMIT:limit}function parseContextDepth(raw,settings){if(!raw)return settings.default_depth;const normalized=raw.trim().toLowerCase();if(!CONTEXT_DEPTH_VALUES.includes(normalized))throw new PmCliError(`Context --depth must be one of ${CONTEXT_DEPTH_VALUES.join("|")}`,EXIT_CODE.USAGE);return normalized}function parseContextSections(raw,depth,settings){if(raw&&raw.length>0){const sections=[];for(const value of raw){const normalized=value.trim().toLowerCase();if(!CONTEXT_SECTION_VALUES.includes(normalized))throw new PmCliError(`Context --section must be one of ${CONTEXT_SECTION_VALUES.join("|")}`,EXIT_CODE.USAGE);sections.includes(normalized)||sections.push(normalized)}return sections}return depth==="brief"?[]:depth==="full"?[...CONTEXT_SECTION_VALUES]:(depth==="deep"?DEEP_SECTIONS:STANDARD_SECTIONS).filter(section=>settings.sections[section])}function parseActivityLimit(raw,settings){return raw?parseIntegerLimit(raw,"--activity-limit")??settings.activity_limit:settings.activity_limit}function parseStaleThresholdDays(raw,settings){if(!raw)return settings.stale_threshold_days;const trimmed=raw.trim().toLowerCase(),match=/^(\d+)d?$/.exec(trimmed);if(!match)throw new PmCliError("--stale-threshold must be a number of days (e.g. 7 or 7d)",EXIT_CODE.USAGE);const days=parseInt(match[1],10);if(days<=0)throw new PmCliError("--stale-threshold must be positive",EXIT_CODE.USAGE);return days}function statusRank(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry),blockedStatus=normalizeStatusInput("blocked",statusRegistry),draftStatus=normalizeStatusInput("draft",statusRegistry);return normalizedStatus===statusRegistry.in_progress_status?0:statusRegistry.active_statuses.has(normalizedStatus)?1:blockedStatus&&normalizedStatus===blockedStatus?2:draftStatus&&normalizedStatus===draftStatus?3:statusRegistry.blocked_statuses.has(normalizedStatus)?5:statusRegistry.terminal_statuses.has(normalizedStatus)?7:6}function isClosedStatus(status,statusRegistry){const closeStatus=normalizeStatusInput("closed",statusRegistry);return normalizeStatusForRegistry(status,statusRegistry)===closeStatus}function isInProgressStatus(status,statusRegistry){return normalizeStatusForRegistry(status,statusRegistry)===statusRegistry.in_progress_status}function isOpenStatus(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry);return normalizedStatus!==statusRegistry.in_progress_status&&statusRegistry.active_statuses.has(normalizedStatus)}function isBlockedStatus(status,statusRegistry){return statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(status,statusRegistry))}const LIST_PROJECTION_FLAGS=["compact","brief","fields","includeBody","include_body","parent"];function stripListProjectionFlags(options){const copy={...options};for(const key of LIST_PROJECTION_FLAGS)delete copy[key];return copy}function collectSubtreeIds(corpus,parentId){const target=parentId.trim().toLowerCase(),anchor=corpus.find(item=>item.id.trim().toLowerCase()===target);if(!anchor)return{ids:new Set,found:!1};const childrenByParent=buildChildrenByParent(corpus),descendants=collectDescendants(anchor.id,childrenByParent);return{ids:new Set([anchor.id,...descendants.map(item=>item.id)].map(id=>id.trim().toLowerCase())),found:!0}}function parseContextParent(raw){if(raw===void 0)return;const trimmed=raw.trim();if(trimmed.length===0)throw new PmCliError("Context --parent requires an item id",EXIT_CODE.USAGE);return trimmed}function compareOptionalOrder(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:leftValue-rightValue}function compareOptionalDeadline(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:compareTimestampStrings(leftValue,rightValue)}function daysInUtcMonth(year,monthIndex){return new Date(Date.UTC(year,monthIndex+1,0)).getUTCDate()}function hasNoInvalidDatePrefix(value){const match=LEADING_HYPHEN_DATE.exec(value)??LEADING_COMPACT_DATE.exec(value);if(!match)return!0;const year=Number.parseInt(match[1],10),month=Number.parseInt(match[2],10),day=Number.parseInt(match[3],10);return month>=1&&month<=12&&day>=1&&day<=daysInUtcMonth(year,month-1)}function normalizeTimestampCandidate(value){const compactDate=COMPACT_DATE.exec(value);if(compactDate)return`${compactDate[1]}-${compactDate[2]}-${compactDate[3]}`;const compactDateTime=COMPACT_DATETIME.exec(value);if(compactDateTime){const[,year,month,day,hour,minute,secondRaw,offsetRaw]=compactDateTime,second=secondRaw?`:${secondRaw}`:"",offset=offsetRaw&&offsetRaw.length===5&&offsetRaw!=="Z"?`${offsetRaw.slice(0,3)}:${offsetRaw.slice(3)}`:offsetRaw??"";return`${year}-${month}-${day}T${hour}:${minute}${second}${offset}`}return value}function parseContextTimestampMs(value){if(typeof value!="string")return Number.NaN;const trimmed=value.trim();if(trimmed.length===0||!hasNoInvalidDatePrefix(trimmed))return Number.NaN;const parsed=Date.parse(normalizeTimestampCandidate(trimmed));return Number.isFinite(parsed)?parsed:Number.NaN}function sortableTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString():""}function dateTokenForTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString().slice(0,10):"unknown"}function normalizedParentId(value){if(typeof value!="string")return null;const trimmed=value.trim();return trimmed.length>0?trimmed:null}function compareCriticalItems(left,right,statusRegistry){const byStatus=statusRank(left.status,statusRegistry)-statusRank(right.status,statusRegistry);if(byStatus!==0)return byStatus;const byPriority=left.priority-right.priority;if(byPriority!==0)return byPriority;const byOrder=compareOptionalOrder(left.order,right.order);if(byOrder!==0)return byOrder;const byDeadline=compareOptionalDeadline(left.deadline,right.deadline);if(byDeadline!==0)return byDeadline;const byUpdated=compareTimestampStrings(sortableTimestamp(right.updated_at),sortableTimestamp(left.updated_at)),byId=left.id.localeCompare(right.id);return byUpdated!==0?byUpdated:byId}function estimateJsonTokens(value){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(value),"utf8")/4))}function packRankedContextItems(report,tokenBudget,requiredIds=new Set,profile="context"){return packContextCandidates(report.ranked.map(entry=>({id:entry.id,item:entry.item,rank:entry.rank,score:entry.score,required:requiredIds.has(entry.id),cluster:entry.item.parent?.trim()||entry.item.type,token_costs:{identity:estimateJsonTokens({id:entry.id,title:entry.item.title}),summary:estimateJsonTokens({id:entry.id,title:entry.item.title,type:entry.item.type,status:entry.item.status,priority:entry.item.priority,parent:entry.item.parent}),full:estimateJsonTokens(entry.item)}})),{tokenBudget,profile,latencyBudgetMs:25})}function toContextPackingSummary(report){return{...report,included:report.included.map(entry=>({id:entry.id,projection:entry.projection,tokens:entry.tokens}))}}function toContextRankingSummary(report,featureStore,servedItemIds){const ranked=servedItemIds===void 0?report.ranked:report.ranked.filter(entry=>servedItemIds.has(entry.id));return{model:report.model,available_signals:report.available_signals,items:ranked.map(entry=>({id:entry.id,rank:entry.rank,baseline_rank:entry.baseline_rank,score:entry.score,contributions:entry.contributions,...entry.signal_provenance===void 0?{}:{recency:entry.signal_provenance.recency}})),candidate_count:report.ranked.length,omitted_count:report.ranked.length-ranked.length,...featureStore?{feature_store:{source:featureStore.snapshot.source,cache_status:featureStore.cache_status,source_cursor:featureStore.snapshot.source_cursor,generated_at:featureStore.snapshot.generated_at}}:{}}}function completionPct(closed,total){return total>0?Math.round(closed*100/total):0}function buildChildrenByParent(allItems){const childrenByParent=new Map;for(const item of allItems){const parent=normalizedParentId(item.parent);if(!parent)continue;const children=childrenByParent.get(parent)??[];children.push(item),childrenByParent.set(parent,children)}return childrenByParent}function toContextFocusItem(item,statusRegistry,childrenByParent){const focus={id:item.id,title:item.title,type:item.type,status:item.status,priority:item.priority,order:item.order??null,deadline:item.deadline??null,assignee:item.assignee??null,tags:Array.isArray(item.tags)?[...item.tags]:[],updated_at:item.updated_at,parent:normalizedParentId(item.parent)};if(statusRegistry&&childrenByParent){const descendants=collectDescendants(item.id,childrenByParent),total=descendants.length;if(total>0){const closed=descendants.filter(desc=>isClosedStatus(desc.status,statusRegistry)).length;focus.children_total=total,focus.children_closed=closed,focus.completion_pct=completionPct(closed,total)}}return focus}function summarizeAgenda(events){let deadlines=0,reminders=0,scheduled=0;const itemIds=new Set;for(const event of events){if(itemIds.add(event.item_id),event.kind==="deadline"){deadlines+=1;continue}if(event.kind==="reminder"){reminders+=1;continue}scheduled+=1}return{events:events.length,items:itemIds.size,deadlines,reminders,scheduled}}function mergeSortedWarnings(...warningGroups){return[...new Set(warningGroups.flatMap(group=>group??[]))].sort((left,right)=>left.localeCompare(right))}function filterTerminalCalendarEvents(events,statusRegistry){return events.filter(event=>!statusRegistry.terminal_statuses.has(normalizeStatusForRegistry(event.item_status,statusRegistry)))}function buildHierarchy(allItems,activeItems,statusRegistry,limit){const itemMap=new Map;for(const item of allItems)itemMap.set(item.id,item);const childrenByParent=buildChildrenByParent(allItems),activeHighLevelIds=new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)).map(item=>item.id)),nodes=[];for(const parentId of activeHighLevelIds){const parent=itemMap.get(parentId);if(!parent)continue;const allDescendants=collectDescendants(parentId,childrenByParent),childItems=childrenByParent.get(parentId)??[];let closedCount=0,openCount=0,inProgressCount=0,blockedCount=0;for(const desc of allDescendants)isClosedStatus(desc.status,statusRegistry)?closedCount++:isInProgressStatus(desc.status,statusRegistry)?inProgressCount++:isBlockedStatus(desc.status,statusRegistry)?blockedCount++:isOpenStatus(desc.status,statusRegistry)&&openCount++;const children=childItems.sort((a,b)=>compareCriticalItems(a,b,statusRegistry)).slice(0,limit).map(child=>{const grandchildren=collectDescendants(child.id,childrenByParent),gcClosed=grandchildren.filter(gc=>isClosedStatus(gc.status,statusRegistry)).length;return{id:child.id,title:child.title,type:child.type,status:child.status,children_total:grandchildren.length,children_closed:gcClosed}});nodes.push({id:parent.id,title:parent.title,type:parent.type,status:parent.status,children_total:allDescendants.length,children_closed:closedCount,children_open:openCount,children_in_progress:inProgressCount,children_blocked:blockedCount,children})}return nodes.sort((a,b)=>{const aParent=itemMap.get(a.id),bParent=itemMap.get(b.id);return compareCriticalItems(aParent,bParent,statusRegistry)}).slice(0,limit)}function collectDescendants(parentId,childrenByParent){const result=[],stack=[parentId],visited=new Set;for(;stack.length>0;){const current=stack.pop();if(visited.has(current))continue;visited.add(current);const children=childrenByParent.get(current)??[];for(const child of children)result.push(child),stack.push(child.id)}return result}const _testOnly={buildActivity,buildBlockers,buildChildrenByParent,buildHierarchy,buildHotFiles,buildProgress,buildRecentlyCreated,buildStaleness,buildTestHealth,buildUnparented,buildWorkload,collectDescendants,collectSubtreeIds,compareCriticalItems,compareOptionalDeadline,compareOptionalOrder,completionPct,dateTokenForTimestamp,filterTerminalCalendarEvents,formatAgendaLine,isBlockedStatus,isClosedStatus,isInProgressStatus,isOpenStatus,mergeSortedWarnings,normalizedParentId,parseActivityLimit,parseContextLimit,resolveContextLimitAtScale,parseContextParent,parseContextTimestampMs,parseStaleThresholdDays,sortableTimestamp,statusRank,stripListProjectionFlags,summarizeAgenda,toContextFocusItem};async function buildActivity(activityLimit,global2){return(await runActivity({compact:!0,limit:String(activityLimit)},global2)).compact_activity??[]}function buildProgress(allItems,activeItems,blockedIds,statusRegistry,limit){const childrenByParent=new Map;for(const item of allItems){if(!item.parent)continue;const children=childrenByParent.get(item.parent)??[];children.push(item),childrenByParent.set(item.parent,children)}const activeHighLevel=activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)),entries=[];for(const parent of activeHighLevel){const descendants=collectDescendants(parent.id,childrenByParent),total=descendants.length;if(total===0)continue;let closed=0,open=0,inProgress=0,blocked=0;for(const desc of descendants)isClosedStatus(desc.status,statusRegistry)?closed++:blockedIds.has(desc.id.trim().toLowerCase())?blocked++:isInProgressStatus(desc.status,statusRegistry)?inProgress++:isOpenStatus(desc.status,statusRegistry)&&open++;entries.push({id:parent.id,title:parent.title,type:parent.type,total,closed,open,in_progress:inProgress,blocked,completion_pct:completionPct(closed,total)})}return entries.sort((a,b)=>a.completion_pct-b.completion_pct).slice(0,limit)}function buildBlockers(blockedItems,fullCorpus,statusRegistry,limit){const itemsById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item]));return blockedItems.slice(0,limit).map(item=>{const blockers=resolveItemBlockers(item,itemsById,statusRegistry),blockedBy=blockers.find(blocker=>!blocker.resolved)?.id??blockers[0]?.id??null,blockerItem=blockedBy?itemsById.get(blockedBy.trim().toLowerCase()):void 0;return{id:item.id,title:item.title,blocked_by:blockedBy,blocked_by_title:blockerItem?.title??null,blocked_by_status:blockerItem?.status??null,blocked_reason:item.blocked_reason??null,unblock_note:item.unblock_note??null}})}function buildHotFiles(activeItems,limit){const fileMap=new Map;for(const item of activeItems)for(const file of item.files??[]){const existing=fileMap.get(file.path)??new Set;existing.add(item.id),fileMap.set(file.path,existing)}return[...fileMap.entries()].map(([filePath,itemIds])=>({path:filePath,references:itemIds.size,items:[...itemIds].sort()})).sort((a,b)=>b.references-a.references).slice(0,limit)}function buildWorkload(activeItems,statusRegistry,limit){const groups=new Map;for(const item of activeItems){const key=item.assignee??null,existing=groups.get(key)??[];existing.push(item),groups.set(key,existing)}return[...groups.entries()].map(([assignee,items])=>({assignee,active:items.length,in_progress:items.filter(item=>isInProgressStatus(item.status,statusRegistry)).length,items:items.map(item=>item.id).sort()})).sort((a,b)=>b.active-a.active).slice(0,limit)}function buildStaleness(allNonTerminal,staleThresholdDays,now,limit){const cutoffMs=new Date(now).getTime()-staleThresholdDays*24*60*60*1e3;return allNonTerminal.filter(item=>new Date(item.updated_at).getTime()<cutoffMs).map(item=>({id:item.id,title:item.title,status:item.status,updated_at:item.updated_at,stale_days:Math.floor((new Date(now).getTime()-new Date(item.updated_at).getTime())/(1440*60*1e3))})).sort((a,b)=>b.stale_days-a.stale_days).slice(0,limit)}function buildRecentlyCreated(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.map(item=>({item,sortKey:sortableTimestamp(item.created_at)})).sort((left,right)=>{const byCreated=compareTimestampStrings(right.sortKey,left.sortKey);return byCreated!==0?byCreated:left.item.id.localeCompare(right.item.id)}).slice(0,limit).map(({item})=>({...toContextFocusItem(item,statusRegistry,childrenByParent),created_at:item.created_at}))}function buildUnparented(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.filter(item=>!normalizedParentId(item.parent)&&!HIGH_LEVEL_TYPES.has(item.type)).sort((left,right)=>compareCriticalItems(left,right,statusRegistry)).slice(0,limit).map(item=>toContextFocusItem(item,statusRegistry,childrenByParent))}function buildTestHealth(activeItems){let itemsWithTests=0,itemsWithRecentRuns=0,passed=0,failed=0,skipped=0;const itemsFailing=[];for(const item of activeItems){(item.tests??[]).length>0&&itemsWithTests++;const runs=item.test_runs??[];if(runs.length>0){itemsWithRecentRuns++;let itemHasFailure=!1;for(const run of runs)passed+=run.passed??0,failed+=run.failed??0,skipped+=run.skipped??0,(run.failed??0)>0&&(itemHasFailure=!0);itemHasFailure&&itemsFailing.push(item.id)}}return{scope:"matching_active_items",total_items:activeItems.length,items_with_tests:itemsWithTests,items_with_recent_runs:itemsWithRecentRuns,recent_runs:{passed,failed,skipped},items_failing:itemsFailing.sort()}}function formatClock(timestamp){return`${new Date(timestamp).toISOString().slice(11,16)}Z`}function formatFocusLine(item){const orderToken=item.order===null?"-":String(item.order),deadlineToken=item.deadline??"-",parentToken=item.parent?` parent:${item.parent}`:"",progressToken=item.children_total!==void 0&&item.children_closed!==void 0&&item.completion_pct!==void 0?` children:${item.children_closed}/${item.children_total} done:${item.completion_pct}%`:"",blockedToken=item.blocked===!0?` blocked:${item.blocker_ids?.join(",")||"lifecycle"}`:"";return`${item.id} p${item.priority} ${item.status} ${item.type} order:${orderToken} deadline:${deadlineToken}${parentToken}${progressToken}${blockedToken} ${item.title}`}function formatProjectedFocusLine(item,fields){const source=item;return fields.map(field=>{const value=source[field];return Array.isArray(value)?`${field}:${value.join(",")}`:`${field}:${value??"-"}`}).join(" ")}function formatAgendaLine(event){if("reference_only"in event){const suffix=event.kind==="reminder"?` \u2014 ${event.reminder_text??"reminder"}`:event.kind==="event"?` \u2014 ${event.event_title??"event"}${event.event_recurring?" (recurring)":""}`:"";return`${formatClock(event.at)} [${event.kind}] ${event.item_id} (see focus item)${suffix}`}const base=`${formatClock(event.at)} [${event.kind}] ${event.item_id} p${event.item_priority} ${event.item_status} ${event.item_title}`;if(event.kind==="reminder")return`${base} \u2014 ${event.reminder_text}`;if(event.kind==="event"){const recurringSuffix=event.event_recurring?" (recurring)":"",title=event.event_title??event.item_title;return`${base} \u2014 ${title}${recurringSuffix}`}return base}function pushContextFocusSection(lines,title,rows,emptyText,renderFocus){if(lines.push(`## ${title}`),rows.length===0)lines.push(emptyText);else for(const item of rows)lines.push(`- ${renderFocus(item)}`);lines.push("")}function pushBlockedFallbackSection(lines,result,renderFocus){if(result.blocked_fallback.length!==0){lines.push("## Blocked fallback");for(const item of result.blocked_fallback)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushAgendaSection(lines,result){if(lines.push("## Agenda"),lines.push(`- events: ${result.agenda.summary.events} (deadlines: ${result.agenda.summary.deadlines}, reminders: ${result.agenda.summary.reminders}, scheduled: ${result.agenda.summary.scheduled})`),result.agenda.events.length===0)lines.push("No agenda events matched the selected filters.");else for(const event of result.agenda.events)lines.push(`- ${formatAgendaLine(event)}`);lines.push("")}function pushHierarchySection(lines,result){if(!(!result.hierarchy||result.hierarchy.length===0)){lines.push("## Hierarchy");for(const node of result.hierarchy){const pct=completionPct(node.children_closed,node.children_total);lines.push(`- ${node.id} ${node.type} ${node.status} "${node.title}" [${node.children_closed}/${node.children_total} done ${pct}%]`);for(const child of node.children){const cpct=completionPct(child.children_closed,child.children_total);lines.push(` - ${child.id} ${child.type} ${child.status} "${child.title}" [${child.children_closed}/${child.children_total} done ${cpct}%]`)}}lines.push("")}}function pushProgressSection(lines,result){if(!(!result.progress||result.progress.length===0)){lines.push("## Progress");for(const entry of result.progress)lines.push(`- ${entry.id} "${entry.title}" ${entry.completion_pct}% (${entry.closed}/${entry.total} closed, ${entry.in_progress} wip, ${entry.open} open, ${entry.blocked} blocked)`);lines.push("")}}function pushRecentlyCreatedSection(lines,result,focusFields,renderFocus){if(!(!result.recently_created||result.recently_created.length===0)){lines.push("## Recently created");for(const item of result.recently_created)lines.push(focusFields?`- ${renderFocus(item)}`:`- ${dateTokenForTimestamp(item.created_at)} ${formatFocusLine(item)}`);lines.push("")}}function pushUnparentedSection(lines,result,renderFocus){if(!(!result.unparented||result.unparented.length===0)){lines.push("## Unparented");for(const item of result.unparented)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushActivitySection(lines,result){if(!(!result.activity||result.activity.length===0)){lines.push("## Recent activity");for(const entry of result.activity){const msg=entry.msg?` ${entry.msg}`:"";lines.push(`- ${entry.ts.slice(0,16)}Z ${entry.id} ${entry.op} by:${entry.author}${msg}`)}lines.push("")}}function pushBlockersSection(lines,result){if(!(!result.blockers||result.blockers.length===0)){lines.push("## Blockers");for(const entry of result.blockers){const by=entry.blocked_by?`blocked_by:${entry.blocked_by}(${entry.blocked_by_status??"?"})`:"blocked_by:-",reason=entry.blocked_reason?` reason:"${entry.blocked_reason}"`:"",note=entry.unblock_note?` unblock:"${entry.unblock_note}"`:"";lines.push(`- ${entry.id} "${entry.title}" ${by}${reason}${note}`)}lines.push("")}}function pushFilesSection(lines,result){if(!(!result.files||result.files.length===0)){lines.push("## Hot files");for(const file of result.files)lines.push(`- ${file.path} refs:${file.references} items:[${file.items.join(",")}]`);lines.push("")}}function pushWorkloadSection(lines,result){if(!(!result.workload||result.workload.length===0)){lines.push("## Workload");for(const entry of result.workload){const who=entry.assignee??"(unassigned)";lines.push(`- ${who} active:${entry.active} wip:${entry.in_progress} items:[${entry.items.join(",")}]`)}lines.push("")}}function pushStalenessSection(lines,result){if(!(!result.staleness||result.staleness.length===0)){lines.push("## Stale items");for(const entry of result.staleness)lines.push(`- ${entry.id} ${entry.status} stale:${entry.stale_days}d last:${entry.updated_at.slice(0,10)} "${entry.title}"`);lines.push("")}}function boundedTestHealthFailures(tests,limit,tokenBudget){const included=[];let usedTokens=0;for(const id of tests.items_failing){if(included.length>=limit)break;const tokens=estimateJsonTokens(id);if(usedTokens+tokens>tokenBudget)break;included.push(id),usedTokens+=tokens}return included}function pushTestHealthSection(lines,result){if(!result.tests)return;lines.push("## Test health"),lines.push(`- ${result.tests.scope}: ${result.tests.total_items}`),lines.push(`- items_with_tests: ${result.tests.items_with_tests}`),lines.push(`- items_with_recent_runs: ${result.tests.items_with_recent_runs}`),lines.push(`- passed: ${result.tests.recent_runs.passed}, failed: ${result.tests.recent_runs.failed}, skipped: ${result.tests.recent_runs.skipped}`);const failures=boundedTestHealthFailures(result.tests,result.applied_limit??DEFAULT_CONTEXT_LIMIT,result.filters.token_budget);failures.length>0&&lines.push(`- items_failing: [${failures.join(",")}]`);const omitted=result.tests.items_failing.length-failures.length;omitted>0&&lines.push(`- items_failing_omitted: ${omitted}`),lines.push("")}function pushEmptyContextSuggestions(lines,result){result.summary.active_items===0&&result.summary.blocked===0&&result.agenda.summary.events===0&&(lines.push("## Suggestions"),lines.push("No active work items or upcoming events. Consider:"),lines.push('- `pm create --type Task --title "..."` to add a new work item'),lines.push("- `pm list --status closed --limit 5` to review recent completions"),lines.push("- `pm search <keywords>` to find related past work"),lines.push("- `pm aggregate` for a full project status overview"))}function renderContextMarkdown(result){const lines=[],focusFields=result.focus_fields,renderFocus=item=>focusFields?formatProjectedFocusLine(item,focusFields):formatFocusLine(item);if(lines.push("# pm context"),lines.push(""),lines.push(`- now: ${result.now}`),lines.push(`- depth: ${result.depth}`),result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(`- active_items: ${result.summary.active_items} (in_progress: ${result.summary.in_progress}, open: ${result.summary.open})`),result.summary.total_items!==void 0&&lines.push(`- total_items: ${result.summary.total_items} (closed: ${result.summary.closed??0}, canceled: ${result.summary.canceled??0})`),lines.push(`- agenda_events: ${result.summary.agenda_events}`),lines.push(`- blocked_fallback_used: ${result.summary.blocked_fallback_used}`),result.extension_health){const degradedNames=result.extension_health.packages.filter(entry=>entry.status==="degraded").map(entry=>entry.name);lines.push(`- extensions: ${result.extension_health.ok} ok, ${result.extension_health.degraded} degraded${degradedNames.length>0?` (${degradedNames.join(", ")})`:""}`)}const renderedSections=result.sections_included.filter(section=>section!=="blockers"||(result.blockers?.length??0)>0);if(renderedSections.length>0&&lines.push(`- sections: ${renderedSections.join(", ")}`),lines.push(""),pushContextFocusSection(lines,"High-level focus",result.high_level,"No high-level active items.",renderFocus),pushContextFocusSection(lines,"Low-level focus",result.low_level,"No low-level active items.",renderFocus),pushBlockedFallbackSection(lines,result,renderFocus),pushAgendaSection(lines,result),result.workspace_memory){lines.push("## Workspace memory");for(const rollup of result.workspace_memory.rollups)lines.push(`- ${rollup.kind}:${rollup.key} \u2014 ${rollup.label} (${rollup.item_count} completed, latest ${rollup.last_closed_at})`);lines.push("")}return pushHierarchySection(lines,result),pushProgressSection(lines,result),pushRecentlyCreatedSection(lines,result,focusFields,renderFocus),pushUnparentedSection(lines,result,renderFocus),pushActivitySection(lines,result),pushBlockersSection(lines,result),pushFilesSection(lines,result),pushWorkloadSection(lines,result),pushStalenessSection(lines,result),pushTestHealthSection(lines,result),pushEmptyContextSuggestions(lines,result),lines.join(`
2
+ `)}const CONTEXT_UNFILTERED_LIST_ECHO_KEYS=new Set(["status","no_truncate","limit","sort","order"]);function contextListWasFiltered(filters){const{runtime_filters:runtimeFilters,...selection}=filters;return Object.keys(selection).some(key=>!CONTEXT_UNFILTERED_LIST_ECHO_KEYS.has(key))||Object.keys(Object(runtimeFilters)).length>0}async function loadContextEdgeCorpus(global2,listed){return contextListWasFiltered(listed.filters)?(await runList(void 0,buildUnpaginatedContextListOptions({},{excludeTerminal:!1}),global2)).items:listed.items}async function resolveContextRuntime(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),settings=await readSettings(pmRoot),contextSettings=settings.context??SETTINGS_DEFAULTS.context,statusRegistry=resolveRuntimeStatusRegistry(settings.schema),depth=parseContextDepth(options.depth,contextSettings),limit=parseContextLimit(options.limit??options.maxItems,depth);return{settings,contextSettings,statusRegistry,depth,limit,sectionsIncluded:parseContextSections(options.section,depth,contextSettings),activityLimit:parseActivityLimit(options.activityLimit,contextSettings),staleThresholdDays:parseStaleThresholdDays(options.staleThreshold,contextSettings),parentScope:parseContextParent(options.parent),focusFields:parseContextFocusFields(options.fields),baseListOptions:stripListProjectionFlags(options)}}function contextNeedsAllItems(sectionsIncluded){return sectionsIncluded.some(section=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(section))}function buildUnpaginatedContextListOptions(baseListOptions,extra){return{...baseListOptions,...extra,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function loadContextCorpus(global2,runtime){const listed=await runList(void 0,buildUnpaginatedContextListOptions(runtime.baseListOptions,{excludeTerminal:!1}),global2),fullCorpus=listed.items,edgeCorpus=await loadContextEdgeCorpus(global2,listed);let listedItemMetadata=fullCorpus.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),allItems=fullCorpus;const subtreeIds=resolveContextSubtreeIds(runtime.parentScope,edgeCorpus);return subtreeIds&&(listedItemMetadata=listedItemMetadata.filter(item=>subtreeIds.has(item.id.trim().toLowerCase())),allItems=allItems.filter(item=>subtreeIds.has(item.id.trim().toLowerCase()))),{listed,listedItemMetadata,allItems,fullCorpus,edgeCorpus,subtreeIds}}function resolveContextSubtreeIds(parentScope,fullCorpus){if(parentScope===void 0)return;const subtree=collectSubtreeIds(fullCorpus,parentScope);if(!subtree.found)throw new PmCliError(`Context --parent item not found: ${parentScope}`,EXIT_CODE.NOT_FOUND);return subtree.ids}function collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry){const containers=new Set(computeActionabilityReport(activeItems,fullCorpus,statusRegistry,typeRegistry).containers.map(entry=>entry.item.id));return new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)||containers.has(item.id)||resolveItemExecutionRole(item.type,typeRegistry)!=="agent").map(item=>item.id))}async function resolveContextFocusGroups(listedItemMetadata,allItems,fullCorpus,blockedIds,statusRegistry,sectionsIncluded,limit,now,author,cursor,cursorFingerprint,useBoundedPage,pmRoot,tokenBudget,claimFocus,typeRegistry){const structural=[...listedItemMetadata].sort((left,right)=>compareCriticalItems(left,right,statusRegistry)),usage=await readContextUsageAffinity({pmRoot,author,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),featureStore=await readWorkspaceContextSignals(structural,{pmRoot,storeKey:"context",statusRegistry,now,author,usageAffinity:usage.affinity,claimFocus}),ranking=await scoreContextCandidatesWithActiveExtensions("context",featureStore.candidates),ranked=ranking.ranked.map(entry=>entry.item),activeStatuses=statusRegistry.active_statuses,rankedActiveItems=ranked.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),pageStart=useBoundedPage?resolveQueryCursorStart(rankedActiveItems,cursor,cursorFingerprint,item=>item.id):0,focusPage=useBoundedPage?rankedActiveItems.slice(pageStart,pageStart+limit):rankedActiveItems,hasMore=useBoundedPage&&focusPage.length>0&&pageStart+focusPage.length<rankedActiveItems.length,nextCursor=hasMore&&focusPage.length>0?encodeQueryCursor(cursorFingerprint,focusPage[focusPage.length-1].id,pageStart+focusPage.length-1):void 0,rankedBlockedItems=ranked.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),packingIds=new Set([...focusPage.map(item=>item.id),...rankedBlockedItems.filter(item=>!activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))).slice(0,limit).map(item=>item.id)]),packing=packRankedContextItems({...ranking,ranked:ranking.ranked.filter(entry=>packingIds.has(entry.id))},tokenBudget,new Set(Object.entries(claimFocus??{}).filter(([,affinity])=>affinity>=1).map(([id])=>id))),packedItems=packing.included.map(entry=>entry.item),activeItems=packedItems.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),blockedItems=packedItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),childrenByParent=buildChildrenByParent(allItems),focusChildrenByParent=contextNeedsAllItems(sectionsIncluded)?childrenByParent:void 0,fullCorpusById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item])),projectFocusItem=item=>{const focus=toContextFocusItem(item,statusRegistry,focusChildrenByParent);return blockedIds.has(item.id.trim().toLowerCase())&&(focus.blocked=!0,focus.blocker_ids=resolveItemBlockers(item,fullCorpusById,statusRegistry).filter(blocker=>!blocker.resolved).map(blocker=>blocker.id)),focus},highLevelIds=collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry),highLevel=activeItems.filter(item=>highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),lowLevel=activeItems.filter(item=>!highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),blockedFallbackUsed=rankedActiveItems.length===0;return{activeItems,blockedItems,highLevel,lowLevel,blockedFallback:blockedFallbackUsed?blockedItems.slice(0,limit).map(projectFocusItem):[],blockedFallbackUsed,ranking,packing,featureStore,pageExtras:{...useBoundedPage?{applied_limit:limit}:{},...hasMore?{has_more:!0,truncated:!0}:{},...nextCursor?{next_cursor:nextCursor}:{}}}}function buildContextCursorFingerprint(options,pmRoot){return createQueryFingerprint("context",{pmRoot,options:selectCursorSemanticOptions(options,CONTEXT_FLAG_CONTRACTS)})}function shouldPageContextFocus(options,corpusItemCount){return options.limit!==void 0||options.maxItems!==void 0||options.after!==void 0||corpusItemCount>=CONTEXT_SCALE_THRESHOLD}async function buildContextAgenda(global2,runtime,subtreeIds,listedFocusIds){const calendarOptions={...runtime.baseListOptions,after:void 0,view:"agenda",include:"all",limit:runtime.parentScope===void 0?String(runtime.limit):void 0},agenda=await runCalendar(calendarOptions,global2),scopedAgenda=subtreeIds===void 0?agenda.events:agenda.events.filter(event=>subtreeIds.has(event.item_id.trim().toLowerCase())),fullAgendaEvents=filterTerminalCalendarEvents(scopedAgenda,runtime.statusRegistry).slice(0,runtime.limit),agendaEvents=fullAgendaEvents.map(event=>listedFocusIds.has(event.item_id)?{at:event.at,date:event.date,kind:event.kind,item_id:event.item_id,reference_only:!0,...event.kind==="reminder"?{reminder_text:event.reminder_text}:{},...event.kind==="event"?{event_title:event.event_title,event_recurring:event.event_recurring}:{}}:event);return{agenda,agendaEvents,agendaSummary:summarizeAgenda(fullAgendaEvents)}}function countContextStatus(items,status,statusRegistry){const targetStatus=String(status);return items.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===targetStatus).length}async function buildOptionalContextSections(params){const{runtime,allItems,fullCorpus,blockedIds,focusGroups,now,global:global2}=params,childrenByParent=buildChildrenByParent(allItems),allNonTerminal=allItems.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),has=section=>runtime.sectionsIncluded.includes(section);return{hierarchy:has("hierarchy")?buildHierarchy(allItems,focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,activity:has("activity")?await buildActivity(runtime.activityLimit,global2):void 0,progress:has("progress")?buildProgress(allItems,focusGroups.activeItems,blockedIds,runtime.statusRegistry,runtime.limit):void 0,blockersSection:has("blockers")?buildBlockers(focusGroups.blockedItems,fullCorpus,runtime.statusRegistry,runtime.limit):void 0,recentlyCreated:has("recently_created")?buildRecentlyCreated(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,unparented:has("unparented")?buildUnparented(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,filesSection:has("files")?buildHotFiles(focusGroups.activeItems,runtime.limit):void 0,workload:has("workload")?buildWorkload(focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,staleness:has("staleness")?buildStaleness(allNonTerminal,runtime.staleThresholdDays,now,runtime.limit):void 0,tests:has("tests")?buildTestHealth(allItems.filter(item=>runtime.statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,runtime.statusRegistry)))):void 0}}function buildContextSummaryExtras(allItems,statusRegistry,blockedIds){const canceledStatus=normalizeStatusInput("canceled",statusRegistry),activeItems=allItems.filter(item=>statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),inProgress=countContextStatus(activeItems,statusRegistry.in_progress_status,statusRegistry);return{scope:"matching_items",active_items:activeItems.length,open:activeItems.length-inProgress,in_progress:inProgress,blocked:allItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())).length,total_items:allItems.length,closed:allItems.filter(item=>isClosedStatus(item.status,statusRegistry)).length,canceled:allItems.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===canceledStatus).length}}function attachOptionalContextSections(result,sections,warningDetails){sections.hierarchy&&(result.hierarchy=sections.hierarchy),sections.activity&&(result.activity=sections.activity),sections.progress&&(result.progress=sections.progress),sections.blockersSection&&(result.blockers=sections.blockersSection),sections.recentlyCreated&&(result.recently_created=sections.recentlyCreated),sections.unparented&&(result.unparented=sections.unparented),sections.filesSection&&(result.files=sections.filesSection),sections.workload&&(result.workload=sections.workload),sections.staleness&&(result.staleness=sections.staleness),sections.tests&&(result.tests=sections.tests),warningDetails!==void 0&&warningDetails.length>0&&(result.warning_details=warningDetails)}function applyContextFocusProjection(result,focusFields){focusFields&&(result.focus_fields=focusFields,result.high_level=projectContextFocusRows(result.high_level,focusFields),result.low_level=projectContextFocusRows(result.low_level,focusFields),result.blocked_fallback=projectContextFocusRows(result.blocked_fallback,focusFields),result.recently_created&&(result.recently_created=projectContextFocusRows(result.recently_created,focusFields)),result.unparented&&(result.unparented=projectContextFocusRows(result.unparented,focusFields)))}function applyContextTagProjection(result,noTags){const rows=[result.high_level,result.low_level,result.blocked_fallback,result.recently_created??[],result.unparented??[]].flat();if(noTags){for(const row of rows)delete row.tags,delete row.tags_inherited;return}const rowsById=new Map(rows.map(row=>[row.id,row])),originalTagSignatures=new Map(rows.map(row=>[row.id,row.tags?[...row.tags].sort().join("\0"):void 0]));for(const row of rows){if(!row.parent||!row.tags)continue;const parent=rowsById.get(row.parent);parent&&originalTagSignatures.get(row.id)===originalTagSignatures.get(parent.id)&&(delete row.tags,row.tags_inherited=parent.id)}}function maybeAttachEmptyContextSuggestions(result,activeItems,blockedItems){activeItems.length>0||blockedItems.length>0||result.agenda.events.length>0||(result.suggestions=['pm create --type Task --title "..." to add a new work item',"pm list --status closed --limit 5 to review recent completions","pm search <keywords> to find related past work","pm aggregate for a full project status overview"])}async function attachContextUsageFeedback(result,focusGroups,pmRoot,author){try{const included=new Set(focusGroups.packing.included.map(entry=>entry.id)),rows=focusGroups.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)})),rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(result,"context"))rankedIds.has(id)||(rows.push({id,rank:rows.length+1,included:!1}),rankedIds.add(id));const receipt=await recordContextUsageServing({pmRoot,author,surface:"context",profile:focusGroups.packing.profile,rows,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});attachContextUsageServingReceipt(result,receipt)}catch{result.warnings=mergeSortedWarnings(result.warnings,["context_usage_feedback_write_failed"])}}async function resolveContextExtensionHealthProjection(omitted,pmRoot,settings){if(omitted)return{};const packages=(await discoverExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:!1})).discovered.map(diagnostic=>({name:diagnostic.name??diagnostic.directory,status:diagnostic.status==="ok"?"ok":"degraded"})).sort((left,right)=>left.name.localeCompare(right.name)),degraded=packages.filter(entry=>entry.status==="degraded").length;return packages.length===0?{}:{extension_health:{total:packages.length,ok:packages.length-degraded,degraded,packages:packages.slice(0,20),...packages.length>20?{truncated:!0}:{}}}}async function resolveContextSemanticAffinity(pmRoot,author){const identity=detectAgentIdentity(),semanticState=await readSessionState(pmRoot),attributionKey=identity.instance||semanticAttributionKey(author);return semanticAttributionAffinity(semanticState.semantic_attribution?.[attributionKey])}async function runContext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),resolvedRuntime=await resolveContextRuntime(options,global2),corpus=await loadContextCorpus(global2,resolvedRuntime),scaledLimit=resolveContextLimitAtScale(resolvedRuntime.limit,corpus.fullCorpus.length),runtime={...resolvedRuntime,limit:scaledLimit,tokenBudget:resolveContextTokenBudget(options.tokenBudget,Math.max(256,scaledLimit*160))},author=resolveAuthor(void 0,runtime.settings.author_default),claimFocus=await resolveContextSemanticAffinity(pmRoot,author),extensionHealthPromise=resolveContextExtensionHealthProjection(options.noExtensionHealth===!0,pmRoot,runtime.settings),blockedIds=collectDependencyBlockedIds(corpus.edgeCorpus,runtime.statusRegistry),focusGroups=await resolveContextFocusGroups(corpus.listedItemMetadata,corpus.allItems,corpus.edgeCorpus,blockedIds,runtime.statusRegistry,runtime.sectionsIncluded,runtime.limit,nowIso(),author,options.after,buildContextCursorFingerprint(options,pmRoot),shouldPageContextFocus(options,corpus.fullCorpus.length),pmRoot,runtime.tokenBudget,claimFocus,resolveItemTypeRegistry(runtime.settings,getActiveExtensionRegistrations())),agendaContext=await buildContextAgenda(global2,runtime,corpus.subtreeIds,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(item=>item.id))),workspaceMemory=await readWorkspaceMemory(corpus.fullCorpus,{pmRoot,statusRegistry:runtime.statusRegistry,now:agendaContext.agenda.now}),warnings=mergeSortedWarnings(corpus.listed.warnings,agendaContext.agenda.warnings,focusGroups.ranking.warnings,[...focusGroups.featureStore.warnings],workspaceMemory.warnings),inProgressCount=countContextStatus(focusGroups.activeItems,runtime.statusRegistry.in_progress_status,runtime.statusRegistry),openCount=focusGroups.activeItems.length-inProgressCount,sections=await buildOptionalContextSections({runtime,allItems:corpus.allItems,fullCorpus:corpus.edgeCorpus,blockedIds,focusGroups,now:agendaContext.agenda.now,global:global2}),summaryExtras=buildContextSummaryExtras(corpus.allItems,runtime.statusRegistry,blockedIds),result={output_default:"toon",now:agendaContext.agenda.now,depth:runtime.depth,sections_included:runtime.sectionsIncluded,window:{anchor:agendaContext.agenda.anchor,start:agendaContext.agenda.range.start,end:agendaContext.agenda.range.end,past:agendaContext.agenda.range.past,from:agendaContext.agenda.range.from,to:agendaContext.agenda.range.to},filters:{type:options.type??null,tag:options.tag??null,priority:options.priority??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,limit:options.limit??options.maxItems??null,parent:runtime.parentScope??null,token_budget:runtime.tokenBudget,runtime_filters:corpus.listed.filters.runtime_filters??agendaContext.agenda.filters.runtime_filters??{}},summary:{returned_focus:{active_items:focusGroups.activeItems.length,in_progress:inProgressCount,open:openCount,blocked:focusGroups.blockedItems.length},blocked_fallback_used:focusGroups.blockedFallbackUsed,high_level:focusGroups.highLevel.length,low_level:focusGroups.lowLevel.length,agenda_events:agendaContext.agendaSummary.events,...summaryExtras},high_level:focusGroups.highLevel,low_level:focusGroups.lowLevel,blocked_fallback:focusGroups.blockedFallback,agenda:{summary:agendaContext.agendaSummary,events:agendaContext.agendaEvents},...focusGroups.pageExtras};return result.workspace_memory=selectWorkspaceMemory(workspaceMemory,Math.min(800,Math.floor(runtime.tokenBudget*.2))),Object.assign(result,await extensionHealthPromise),attachOptionalContextSections(result,sections,focusGroups.featureStore.warning_details),applyContextTagProjection(result,options.noTags===!0),options.explainRanking===!0&&(result.ranking=toContextRankingSummary(focusGroups.ranking,focusGroups.featureStore,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(entry=>entry.id))),result.packing=toContextPackingSummary(focusGroups.packing)),rememberReadOutputFocusRows(result,[...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(row=>({id:row.id,status:normalizeStatusForRegistry(row.status,runtime.statusRegistry)===runtime.statusRegistry.in_progress_status?"in_progress":"open",blocked:row.blocked}))),applyContextFocusProjection(result,runtime.focusFields),refreshReadOutputDeliveredCounts(result),warnings.length>0&&(result.warnings=warnings),maybeAttachEmptyContextSuggestions(result,focusGroups.activeItems,focusGroups.blockedItems),await attachContextUsageFeedback(result,focusGroups,pmRoot,author),result}export{CONTEXT_OUTPUT_VALUES,_testOnly,applyContextTagProjection,buildChildrenByParent,buildItemContextRelevanceCandidates,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,projectContextFocusRows,renderContextMarkdown,resolveContextExtensionHealthProjection,resolveContextOutputFormat,resolveContextTokenBudget,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary};
3
3
  //# sourceMappingURL=context.js.map
@@ -4,7 +4,7 @@ import { type ResolvedBlocker } from "../actionability.js";
4
4
  import { type ChildRollupContext } from "../item-children.js";
5
5
  import { type ItemScheduleContext } from "../item-schedule.js";
6
6
  import type { ItemMetadata,Dependency,LinkedDoc,LinkedFile,LinkedTest } from "../../types/index.js";
7
- export { GET_DEPTH_VALUES,listGetProjectionFields,} from "./projection-contracts.js";
7
+ export { GET_DEPTH_INPUT_VALUES,GET_DEPTH_VALUES,listGetProjectionFields,} from "./projection-contracts.js";
8
8
  /** Latest claim or release coordinate exposed without its mutation patch. */
9
9
  interface ClaimHistoryContext {
10
10
  ts:string;
@@ -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]="1815b206-18b5-5e76-b863-8b0f8ac2947a")}catch{}})();import{collectRegisteredItemFieldNames}from"../../core/extensions/item-fields.js";import{readdir}from"node:fs/promises";import path from"node:path";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,toItemRecord,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,TYPE_TO_FOLDER,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,getHistoryPath,resolvePmRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{renderPmCommand}from"../command-line.js";import{recordContextUsageTouches}from"../context-usage.js";import{createPmCliExpectedError}from"../errors.js";import{collectBlockedByIds,resolveItemBlockers}from"../actionability.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"../../core/item/dependency-reference.js";import{buildItemChildrenRollup}from"../item-children.js";import{buildItemSchedule}from"../item-schedule.js";import{getItemAt}from"../history-read.js";import{parseIntegerLimit}from"./parsers.js";import{runList}from"./list.js";import{registerOutputMaterialFieldGroups}from"../output-projection.js";import{GET_DEPTH_VALUES,listGetProjectionFields}from"./projection-contracts.js";import{GET_DEPTH_VALUES as GET_DEPTH_VALUES2,listGetProjectionFields as listGetProjectionFields2}from"./projection-contracts.js";const AUTOMATIC_CHILD_ROLLUP_TYPES=new Set(["epic","feature","milestone","plan"]),BUILTIN_ITEM_TYPES=new Set(Object.keys(TYPE_TO_FOLDER).map(type=>type.toLowerCase()));function itemCollectionCounts(item){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(key=>[key,item[key]?.length??0]))}function itemMaterialFieldGroups(item,body,children,currentSnapshot,projection){const collectionCounts=itemCollectionCounts(item);return[...body.length>0?["body"]:[],...Object.entries(collectionCounts).flatMap(([name,count])=>count>0?[name]:[]),...collectionCounts.files+collectionCounts.tests+collectionCounts.docs>0?["linked"]:[],...children===void 0?["children"]:children.count>0?["children"]:[],...typeof item.assignee=="string"&&item.assignee.trim().length>0?["claim_state"]:[],...buildItemSchedule(item)?["schedule"]:[],...currentSnapshot&&collectBlockedByIds(item).length>0?["blockers"]:[],...!projection.full&&item.dependencies?.some(({id:_id,kind:_kind,...provenance})=>Object.values(provenance).some(value=>value!==void 0))?["dependency_provenance"]:[]]}function shouldAutoIncludeGetChildren(itemType){const normalizedType=itemType.trim().toLowerCase();return normalizedType.length>0&&(AUTOMATIC_CHILD_ROLLUP_TYPES.has(normalizedType)||!BUILTIN_ITEM_TYPES.has(normalizedType))}function toClaimHistoryContext(entry){return{ts:entry.ts,author:entry.author,message:entry.message??null}}function resolveClaimStateContext(assigneeValue,history){const assignee=assigneeValue?.trim(),normalizedAssignee=assignee&&assignee.length>0?assignee:null,lastClaim=[...history].reverse().find(entry=>entry.op==="claim"),lastRelease=[...history].reverse().find(entry=>entry.op==="release");return{claimed:normalizedAssignee!==null,assignee:normalizedAssignee,last_claim:lastClaim?toClaimHistoryContext(lastClaim):null,last_release:lastRelease?toClaimHistoryContext(lastRelease):null}}function parseGetDepth(raw){if(raw===void 0||raw.trim().length===0)return"standard";const normalized=raw.trim().toLowerCase();if(normalized==="full")return"deep";if(GET_DEPTH_VALUES.includes(normalized))return normalized;throw new PmCliError("Get --depth must be one of brief|standard|deep|full",EXIT_CODE.USAGE,{field:"depth",value:raw,recovery:{allowed_values:[...GET_DEPTH_VALUES,"full"]}})}function projectItemForDepth(item,depth,full){const collectionCounts=itemCollectionCounts(item),projectedItem={...item};if(!full&&item.dependencies!==void 0&&(projectedItem.dependencies=item.dependencies.map(({id,kind})=>({id,kind}))),depth==="deep")return{...projectedItem,comments:item.comments??[],notes:item.notes??[],learnings:item.learnings??[],files:item.files??[],tests:item.tests??[],docs:item.docs??[],reminders:item.reminders??[],events:item.events??[],notes_count:collectionCounts.notes,tests_count:collectionCounts.tests,collection_counts:collectionCounts};const{comments:_comments,notes:_notes,learnings:_learnings,files:_files,tests:_tests,docs:_docs,reminders:_reminders,events:_events,...projected}=projectedItem;return{...projected,notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:collectionCounts}}function parseGetFields(raw){if(raw===void 0)return null;const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0)throw new PmCliError("Get --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);return fields}function normalizeGetField(field){return field.startsWith("item.")?field.slice(5):field}function validateGetFields(fields,runtimeMetadataKeys,id){if(fields===null)return;const allowedValues=listGetProjectionFields(runtimeMetadataKeys),allowed=new Set(allowedValues),unknown=fields.filter(field=>{const normalized=normalizeGetField(field);return!allowed.has(field)&&!allowed.has(normalized)});if(unknown.length>0){const suggestedRetryArguments=["get",id,"--fields",fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown get --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const EMPTY_PROJECTED_COLLECTION_FIELDS=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function projectedMetadataValue(source,counts,field){return Object.hasOwn(counts,field)?counts[field]:source[field]!==void 0?source[field]:EMPTY_PROJECTED_COLLECTION_FIELDS.has(field)?[]:void 0}function projectItemForFields(item,fields){const source=toItemRecord(item),omittedCounts={notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:itemCollectionCounts(item)},projected={id:item.id};for(const field of fields){const normalized=normalizeGetField(field);normalized==="body"||normalized==="linked"||normalized.startsWith("linked.")||normalized==="claim_state"||normalized.startsWith("claim_state.")||normalized==="children"||normalized.startsWith("children.")||normalized==="schedule"||normalized.startsWith("schedule.")||normalized==="blockers"||(projected[normalized]=projectedMetadataValue(source,omittedCounts,normalized))}return projected}function fieldsInclude(fields,name){return fields?.some(field=>field===name||field===`item.${name}`)??!1}function fieldsIncludeRoot(fields,name){return fields.some(field=>{const normalized=normalizeGetField(field);return normalized===name||normalized.startsWith(`${name}.`)})}function resolveGetProjection(options,id){if(options.full&&(options.fields!==void 0||options.depth!==void 0))throw new PmCliError("Get projection options are mutually exclusive; remove the extra projection flag and retry.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:renderPmCommand(["get",id,"--full"]),suggested_retry_args:["get",id,"--full"]}});if(options.tree!==!0&&options.treeDepth!==void 0)throw new PmCliError("Get --tree-depth requires --tree",EXIT_CODE.USAGE);if(options.at!==void 0&&options.tree===!0)throw new PmCliError("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",EXIT_CODE.USAGE);return{depth:options.full?"deep":parseGetDepth(options.depth),full:options.full===!0||options.depth?.trim().toLowerCase()==="full",treeDepth:options.tree===!0?parseIntegerLimit(options.treeDepth,"--tree-depth"):void 0,fields:parseGetFields(options.fields),fieldProjection:options.fields!==void 0}}async function loadGetItemContext(id,global2,at){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());if(at!==void 0){const historical=await getItemAt(id,at,{pmRoot:global2.path});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:historical.document.metadata.id,metadata:historical.document.metadata,body:historical.document.body,historical}}const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeRegistry.type_to_folder);const loaded=await readLocatedItem(located,{schema:settings.schema});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:located.id,metadata:loaded.document.metadata,body:loaded.document.body}}function validateGetProjectionFields(fields,settings,historical,id){const runtimeMetadataKeys=[...resolveRuntimeFieldRegistry(settings.schema).definitions.map(field=>field.metadata_key),...collectRegisteredItemFieldNames(getActiveExtensionRegistrations())];if(validateGetFields(fields,runtimeMetadataKeys,id),historical&&fieldsIncludeRoot(fields??[],"children"))throw new PmCliError("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",EXIT_CODE.USAGE);if(historical&&fieldsIncludeRoot(fields??[],"blockers"))throw new PmCliError("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",EXIT_CODE.USAGE)}function shouldIncludeGetField(params){const{fieldProjection,depth,fields,field}=params;return fieldProjection?field==="body"||field==="linked"?fieldsInclude(fields,field):fieldsIncludeRoot(fields,field):depth!=="brief"}async function resolveGetClaimState(context,includeClaimState){if(!includeClaimState)return;const historyPath=getHistoryPath(context.pmRoot,context.locatedId),history=await readHistoryEntries(historyPath,context.locatedId);return resolveClaimStateContext(context.metadata.assignee,context.historical?history.slice(0,context.historical.target.historyIndex+1):history)}function attachGetLinked(result,context,fields,includeLinked){const includeLinkedFiles=includeLinked||fieldsInclude(fields,"linked.files"),includeLinkedTests=includeLinked||fieldsInclude(fields,"linked.tests"),includeLinkedDocs=includeLinked||fieldsInclude(fields,"linked.docs");!includeLinked&&!includeLinkedFiles&&!includeLinkedTests&&!includeLinkedDocs||(result.linked={files:includeLinkedFiles?context.metadata.files??[]:[],tests:includeLinkedTests?context.metadata.tests??[]:[],docs:includeLinkedDocs?context.metadata.docs??[]:[]})}async function buildGetChildrenRollup(context,includeChildren){if(!includeChildren)return;const statusRegistry=resolveRuntimeStatusRegistry(context.settings.schema),corpus=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,context.typeToFolder,void 0,context.settings.schema);return buildItemChildrenRollup(context.locatedId,corpus,statusRegistry)}function canonicalizeDeclaredBlockers(blockers,targets){const canonical=new Map;for(const blocker of blockers){const id=blocker.external?blocker.id:targets.get(blocker.id.toLowerCase())?.id??blocker.id;canonical.set(blocker.external?`external:${id}`:`local:${id.toLowerCase()}`,{...blocker,id})}return[...canonical.values()]}async function resolvePhysicalBlockerId(itemPath,probedId){const filename=path.basename(itemPath),physicalId=(await readdir(path.dirname(itemPath)).catch(error=>{throw createPmCliExpectedError("Cannot verify the blocker's physical file identity",{exitCode:EXIT_CODE.GENERIC_FAILURE,context:{code:"blocker_identity_read_failed",required:"Restore access to the blocker item directory, then retry the item read."},cause:error})})).filter(name=>name.toLowerCase()===filename.toLowerCase()).sort((left,right)=>+(right===filename)-+(left===filename)||left.localeCompare(right)).map(name=>path.parse(name).name)[0];if(physicalId===void 0)throw new PmCliError(`Blocker canonical file disappeared during identity verification: ${probedId}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker file and validate storage integrity before retrying the item read."});return physicalId}async function attachGetBlockers(result,context,projection){if(context.historical!==void 0||!(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"blockers"):projection.depth!=="brief"))return;const ids=collectBlockedByIds(context.metadata);if(ids.length===0)return;const declaredIds=new Map([context.metadata.blocked_by,...(context.metadata.dependencies??[]).filter(dependency=>dependency.kind==="blocked_by").map(dependency=>dependency.id)].filter(id=>typeof id=="string").map(id=>[id.trim().toLowerCase(),id.trim()])),targets=new Map;for(const id of ids){if(isExternalDependencyReference(id)||!/^(?!\.{1,2}$)[^/\\:\0]+$/u.test(id)||context.metadata.dependencies?.some(dependency=>dependency.id.trim()===id&&dependency.kind==="blocked_by"&&isExternalDependencySourceKind(dependency.source_kind)))continue;const located=await locateItem(context.pmRoot,declaredIds.get(id),context.settings.id_prefix,context.settings.item_format,context.typeToFolder);if(located===null)continue;const loaded=await readLocatedItem(located,{schema:context.settings.schema});if(located.id=await resolvePhysicalBlockerId(located.itemPath,located.id),loaded.document.metadata.id!==located.id)throw new PmCliError(`Blocker identity differs from its canonical file: ${located.id}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker identity and validate storage integrity before retrying the item read."});targets.set(id.toLowerCase(),loaded.document.metadata)}const resolved=canonicalizeDeclaredBlockers(resolveItemBlockers({blocked_by:context.metadata.blocked_by,dependencies:context.metadata.dependencies,updated_at:context.metadata.updated_at},targets,resolveRuntimeStatusRegistry(context.settings.schema)),targets);result.blockers={scope:"declared",open:resolved.filter(blocker=>!blocker.resolved).map(({resolved:_resolved,...blocker})=>blocker),closed_count:resolved.filter(blocker=>blocker.resolved).length},!projection.fieldProjection&&!projection.full&&delete result.item.blocked_by}function attachGetSchedule(result,context,fields,includeSchedule){if(!includeSchedule)return;const schedule=buildItemSchedule(context.metadata);if(schedule){if(fields===null||fieldsInclude(fields,"schedule")){result.schedule=schedule;return}result.schedule=Object.fromEntries(Object.entries(schedule).filter(([key])=>fields.some(field=>normalizeGetField(field)===`schedule.${key}`)))}}async function buildGetTree(context,options,treeDepth,global2){if(options.tree!==!0)return;const subtree=await runList(void 0,{parent:context.locatedId,tree:!0,treeDepth:treeDepth===void 0?void 0:String(treeDepth),full:!0},global2);return{root_id:context.locatedId,root_title:context.metadata.title,depth_limit:treeDepth??null,count:subtree.count,items:subtree.items.map(entry=>toItemRecord(entry))}}async function runGet(id,global2,options={}){const projection=resolveGetProjection(options,id),context=await loadGetItemContext(id,global2,options.at);validateGetProjectionFields(projection.fields,context.settings,context.historical!==void 0,context.locatedId);const includeBody=shouldIncludeGetField({...projection,field:"body"}),includeLinked=shouldIncludeGetField({...projection,field:"linked"}),includeClaimState=shouldIncludeGetField({...projection,field:"claim_state"}),includeChildren=context.historical===void 0&&(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"children"):projection.depth==="deep"&&(projection.full||shouldAutoIncludeGetChildren(context.metadata.type))),includeSchedule=projection.fieldProjection?fieldsIncludeRoot(projection.fields,"schedule"):projection.depth!=="brief",claimState=await resolveGetClaimState(context,includeClaimState),result={item:projection.fieldProjection?projectItemForFields(context.metadata,projection.fields):projectItemForDepth(context.metadata,projection.depth,projection.full)};includeBody&&(result.item.body=context.body),attachGetLinked(result,context,projection.fields,includeLinked),claimState&&(result.claim_state=claimState),attachGetSchedule(result,context,projection.fields,includeSchedule),await attachGetBlockers(result,context,projection);const children=await buildGetChildrenRollup(context,includeChildren);children!==void 0&&(result.children=children);const tree=await buildGetTree(context,options,projection.treeDepth,global2);if(tree!==void 0&&(result.tree=tree),context.historical&&(result.reconstructed=!0,result.as_of_version=context.historical.as_of_version,result.as_of_timestamp=context.historical.as_of_timestamp),context.historical===void 0)try{await recordContextUsageTouches({pmRoot:context.pmRoot,author:resolveAuthor(void 0,context.settings.author_default),itemIds:[context.locatedId],intent:"get"})}catch{}return registerOutputMaterialFieldGroups(result,projection.fieldProjection?[]:itemMaterialFieldGroups(context.metadata,context.body,children,context.historical===void 0,projection)),result}const _testOnlyGetCommand={shouldAutoIncludeGetChildren};export{GET_DEPTH_VALUES2 as GET_DEPTH_VALUES,_testOnlyGetCommand,listGetProjectionFields2 as listGetProjectionFields,runGet};
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]="bf7cac44-d2fc-5e7c-a9f1-a82c7460b07c")}catch{}})();import{collectRegisteredItemFieldNames}from"../../core/extensions/item-fields.js";import{readdir}from"node:fs/promises";import path from"node:path";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,toItemRecord,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,TYPE_TO_FOLDER,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,getHistoryPath,resolvePmRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{renderPmCommand}from"../command-line.js";import{recordContextUsageTouches}from"../context-usage.js";import{createPmCliExpectedError}from"../errors.js";import{collectBlockedByIds,resolveItemBlockers}from"../actionability.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"../../core/item/dependency-reference.js";import{buildItemChildrenRollup}from"../item-children.js";import{buildItemSchedule}from"../item-schedule.js";import{getItemAt}from"../history-read.js";import{parseIntegerLimit}from"./parsers.js";import{runList}from"./list.js";import{registerOutputMaterialFieldGroups}from"../output-projection.js";import{GET_DEPTH_INPUT_VALUES,GET_DEPTH_VALUES,listGetProjectionFields}from"./projection-contracts.js";import{GET_DEPTH_INPUT_VALUES as GET_DEPTH_INPUT_VALUES2,GET_DEPTH_VALUES as GET_DEPTH_VALUES2,listGetProjectionFields as listGetProjectionFields2}from"./projection-contracts.js";const AUTOMATIC_CHILD_ROLLUP_TYPES=new Set(["epic","feature","milestone","plan"]),BUILTIN_ITEM_TYPES=new Set(Object.keys(TYPE_TO_FOLDER).map(type=>type.toLowerCase()));function itemCollectionCounts(item){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(key=>[key,item[key]?.length??0]))}function itemMaterialFieldGroups(item,body,children,currentSnapshot,projection){const collectionCounts=itemCollectionCounts(item);return[...body.length>0?["body"]:[],...Object.entries(collectionCounts).flatMap(([name,count])=>count>0?[name]:[]),...collectionCounts.files+collectionCounts.tests+collectionCounts.docs>0?["linked"]:[],...children===void 0?["children"]:children.count>0?["children"]:[],...typeof item.assignee=="string"&&item.assignee.trim().length>0?["claim_state"]:[],...buildItemSchedule(item)?["schedule"]:[],...currentSnapshot&&collectBlockedByIds(item).length>0?["blockers"]:[],...!projection.full&&item.dependencies?.some(({id:_id,kind:_kind,...provenance})=>Object.values(provenance).some(value=>value!==void 0))?["dependency_provenance"]:[]]}function shouldAutoIncludeGetChildren(itemType){const normalizedType=itemType.trim().toLowerCase();return normalizedType.length>0&&(AUTOMATIC_CHILD_ROLLUP_TYPES.has(normalizedType)||!BUILTIN_ITEM_TYPES.has(normalizedType))}function toClaimHistoryContext(entry){return{ts:entry.ts,author:entry.author,message:entry.message??null}}function resolveClaimStateContext(assigneeValue,history){const assignee=assigneeValue?.trim(),normalizedAssignee=assignee&&assignee.length>0?assignee:null,lastClaim=[...history].reverse().find(entry=>entry.op==="claim"),lastRelease=[...history].reverse().find(entry=>entry.op==="release");return{claimed:normalizedAssignee!==null,assignee:normalizedAssignee,last_claim:lastClaim?toClaimHistoryContext(lastClaim):null,last_release:lastRelease?toClaimHistoryContext(lastRelease):null}}function parseGetDepth(raw){if(raw===void 0||raw.trim().length===0)return"standard";const normalized=raw.trim().toLowerCase();if(normalized==="full")return"deep";if(GET_DEPTH_VALUES.includes(normalized))return normalized;throw new PmCliError("Get --depth must be one of brief|standard|deep|full",EXIT_CODE.USAGE,{field:"depth",value:raw,recovery:{allowed_values:[...GET_DEPTH_INPUT_VALUES]}})}function projectItemForDepth(item,depth,full){const collectionCounts=itemCollectionCounts(item),projectedItem={...item};if(!full&&item.dependencies!==void 0&&(projectedItem.dependencies=item.dependencies.map(({id,kind})=>({id,kind}))),depth==="deep")return{...projectedItem,comments:item.comments??[],notes:item.notes??[],learnings:item.learnings??[],files:item.files??[],tests:item.tests??[],docs:item.docs??[],reminders:item.reminders??[],events:item.events??[],notes_count:collectionCounts.notes,tests_count:collectionCounts.tests,collection_counts:collectionCounts};const{comments:_comments,notes:_notes,learnings:_learnings,files:_files,tests:_tests,docs:_docs,reminders:_reminders,events:_events,...projected}=projectedItem;return{...projected,notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:collectionCounts}}function parseGetFields(raw){if(raw===void 0)return null;const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0)throw new PmCliError("Get --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);return fields}function normalizeGetField(field){return field.startsWith("item.")?field.slice(5):field}function validateGetFields(fields,runtimeMetadataKeys,id){if(fields===null)return;const allowedValues=listGetProjectionFields(runtimeMetadataKeys),allowed=new Set(allowedValues),unknown=fields.filter(field=>{const normalized=normalizeGetField(field);return!allowed.has(field)&&!allowed.has(normalized)});if(unknown.length>0){const suggestedRetryArguments=["get",id,"--fields",fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown get --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const EMPTY_PROJECTED_COLLECTION_FIELDS=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function projectedMetadataValue(source,counts,field){return Object.hasOwn(counts,field)?counts[field]:source[field]!==void 0?source[field]:EMPTY_PROJECTED_COLLECTION_FIELDS.has(field)?[]:void 0}function projectItemForFields(item,fields){const source=toItemRecord(item),omittedCounts={notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:itemCollectionCounts(item)},projected={id:item.id};for(const field of fields){const normalized=normalizeGetField(field);normalized==="body"||normalized==="linked"||normalized.startsWith("linked.")||normalized==="claim_state"||normalized.startsWith("claim_state.")||normalized==="children"||normalized.startsWith("children.")||normalized==="schedule"||normalized.startsWith("schedule.")||normalized==="blockers"||(projected[normalized]=projectedMetadataValue(source,omittedCounts,normalized))}return projected}function fieldsInclude(fields,name){return fields?.some(field=>field===name||field===`item.${name}`)??!1}function fieldsIncludeRoot(fields,name){return fields.some(field=>{const normalized=normalizeGetField(field);return normalized===name||normalized.startsWith(`${name}.`)})}function resolveGetProjection(options,id){if(options.full&&(options.fields!==void 0||options.depth!==void 0))throw new PmCliError("Get projection options are mutually exclusive; remove the extra projection flag and retry.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:renderPmCommand(["get",id,"--full"]),suggested_retry_args:["get",id,"--full"]}});if(options.tree!==!0&&options.treeDepth!==void 0)throw new PmCliError("Get --tree-depth requires --tree",EXIT_CODE.USAGE);if(options.at!==void 0&&options.tree===!0)throw new PmCliError("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",EXIT_CODE.USAGE);return{depth:options.full?"deep":parseGetDepth(options.depth),full:options.full===!0||options.depth?.trim().toLowerCase()==="full",treeDepth:options.tree===!0?parseIntegerLimit(options.treeDepth,"--tree-depth"):void 0,fields:parseGetFields(options.fields),fieldProjection:options.fields!==void 0}}async function loadGetItemContext(id,global2,at){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());if(at!==void 0){const historical=await getItemAt(id,at,{pmRoot:global2.path});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:historical.document.metadata.id,metadata:historical.document.metadata,body:historical.document.body,historical}}const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeRegistry.type_to_folder);const loaded=await readLocatedItem(located,{schema:settings.schema});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:located.id,metadata:loaded.document.metadata,body:loaded.document.body}}function validateGetProjectionFields(fields,settings,historical,id){const runtimeMetadataKeys=[...resolveRuntimeFieldRegistry(settings.schema).definitions.map(field=>field.metadata_key),...collectRegisteredItemFieldNames(getActiveExtensionRegistrations())];if(validateGetFields(fields,runtimeMetadataKeys,id),historical&&fieldsIncludeRoot(fields??[],"children"))throw new PmCliError("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",EXIT_CODE.USAGE);if(historical&&fieldsIncludeRoot(fields??[],"blockers"))throw new PmCliError("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",EXIT_CODE.USAGE)}function shouldIncludeGetField(params){const{fieldProjection,depth,fields,field}=params;return fieldProjection?field==="body"||field==="linked"?fieldsInclude(fields,field):fieldsIncludeRoot(fields,field):depth!=="brief"}async function resolveGetClaimState(context,includeClaimState){if(!includeClaimState)return;const historyPath=getHistoryPath(context.pmRoot,context.locatedId),history=await readHistoryEntries(historyPath,context.locatedId);return resolveClaimStateContext(context.metadata.assignee,context.historical?history.slice(0,context.historical.target.historyIndex+1):history)}function attachGetLinked(result,context,fields,includeLinked){const includeLinkedFiles=includeLinked||fieldsInclude(fields,"linked.files"),includeLinkedTests=includeLinked||fieldsInclude(fields,"linked.tests"),includeLinkedDocs=includeLinked||fieldsInclude(fields,"linked.docs");!includeLinked&&!includeLinkedFiles&&!includeLinkedTests&&!includeLinkedDocs||(result.linked={files:includeLinkedFiles?context.metadata.files??[]:[],tests:includeLinkedTests?context.metadata.tests??[]:[],docs:includeLinkedDocs?context.metadata.docs??[]:[]})}async function buildGetChildrenRollup(context,includeChildren){if(!includeChildren)return;const statusRegistry=resolveRuntimeStatusRegistry(context.settings.schema),corpus=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,context.typeToFolder,void 0,context.settings.schema);return buildItemChildrenRollup(context.locatedId,corpus,statusRegistry)}function canonicalizeDeclaredBlockers(blockers,targets){const canonical=new Map;for(const blocker of blockers){const id=blocker.external?blocker.id:targets.get(blocker.id.toLowerCase())?.id??blocker.id;canonical.set(blocker.external?`external:${id}`:`local:${id.toLowerCase()}`,{...blocker,id})}return[...canonical.values()]}async function resolvePhysicalBlockerId(itemPath,probedId){const filename=path.basename(itemPath),physicalId=(await readdir(path.dirname(itemPath)).catch(error=>{throw createPmCliExpectedError("Cannot verify the blocker's physical file identity",{exitCode:EXIT_CODE.GENERIC_FAILURE,context:{code:"blocker_identity_read_failed",required:"Restore access to the blocker item directory, then retry the item read."},cause:error})})).filter(name=>name.toLowerCase()===filename.toLowerCase()).sort((left,right)=>+(right===filename)-+(left===filename)||left.localeCompare(right)).map(name=>path.parse(name).name)[0];if(physicalId===void 0)throw new PmCliError(`Blocker canonical file disappeared during identity verification: ${probedId}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker file and validate storage integrity before retrying the item read."});return physicalId}async function attachGetBlockers(result,context,projection){if(context.historical!==void 0||!(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"blockers"):projection.depth!=="brief"))return;const ids=collectBlockedByIds(context.metadata);if(ids.length===0)return;const declaredIds=new Map([context.metadata.blocked_by,...(context.metadata.dependencies??[]).filter(dependency=>dependency.kind==="blocked_by").map(dependency=>dependency.id)].filter(id=>typeof id=="string").map(id=>[id.trim().toLowerCase(),id.trim()])),targets=new Map;for(const id of ids){if(isExternalDependencyReference(id)||!/^(?!\.{1,2}$)[^/\\:\0]+$/u.test(id)||context.metadata.dependencies?.some(dependency=>dependency.id.trim()===id&&dependency.kind==="blocked_by"&&isExternalDependencySourceKind(dependency.source_kind)))continue;const located=await locateItem(context.pmRoot,declaredIds.get(id),context.settings.id_prefix,context.settings.item_format,context.typeToFolder);if(located===null)continue;const loaded=await readLocatedItem(located,{schema:context.settings.schema});if(located.id=await resolvePhysicalBlockerId(located.itemPath,located.id),loaded.document.metadata.id!==located.id)throw new PmCliError(`Blocker identity differs from its canonical file: ${located.id}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker identity and validate storage integrity before retrying the item read."});targets.set(id.toLowerCase(),loaded.document.metadata)}const resolved=canonicalizeDeclaredBlockers(resolveItemBlockers({blocked_by:context.metadata.blocked_by,dependencies:context.metadata.dependencies,updated_at:context.metadata.updated_at},targets,resolveRuntimeStatusRegistry(context.settings.schema)),targets);result.blockers={scope:"declared",open:resolved.filter(blocker=>!blocker.resolved).map(({resolved:_resolved,...blocker})=>blocker),closed_count:resolved.filter(blocker=>blocker.resolved).length},!projection.fieldProjection&&!projection.full&&delete result.item.blocked_by}function attachGetSchedule(result,context,fields,includeSchedule){if(!includeSchedule)return;const schedule=buildItemSchedule(context.metadata);if(schedule){if(fields===null||fieldsInclude(fields,"schedule")){result.schedule=schedule;return}result.schedule=Object.fromEntries(Object.entries(schedule).filter(([key])=>fields.some(field=>normalizeGetField(field)===`schedule.${key}`)))}}async function buildGetTree(context,options,treeDepth,global2){if(options.tree!==!0)return;const subtree=await runList(void 0,{parent:context.locatedId,tree:!0,treeDepth:treeDepth===void 0?void 0:String(treeDepth),full:!0},global2);return{root_id:context.locatedId,root_title:context.metadata.title,depth_limit:treeDepth??null,count:subtree.count,items:subtree.items.map(entry=>toItemRecord(entry))}}async function runGet(id,global2,options={}){const projection=resolveGetProjection(options,id),context=await loadGetItemContext(id,global2,options.at);validateGetProjectionFields(projection.fields,context.settings,context.historical!==void 0,context.locatedId);const includeBody=shouldIncludeGetField({...projection,field:"body"}),includeLinked=shouldIncludeGetField({...projection,field:"linked"}),includeClaimState=shouldIncludeGetField({...projection,field:"claim_state"}),includeChildren=context.historical===void 0&&(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"children"):projection.depth==="deep"&&(projection.full||shouldAutoIncludeGetChildren(context.metadata.type))),includeSchedule=projection.fieldProjection?fieldsIncludeRoot(projection.fields,"schedule"):projection.depth!=="brief",claimState=await resolveGetClaimState(context,includeClaimState),result={item:projection.fieldProjection?projectItemForFields(context.metadata,projection.fields):projectItemForDepth(context.metadata,projection.depth,projection.full)};includeBody&&(result.item.body=context.body),attachGetLinked(result,context,projection.fields,includeLinked),claimState&&(result.claim_state=claimState),attachGetSchedule(result,context,projection.fields,includeSchedule),await attachGetBlockers(result,context,projection);const children=await buildGetChildrenRollup(context,includeChildren);children!==void 0&&(result.children=children);const tree=await buildGetTree(context,options,projection.treeDepth,global2);if(tree!==void 0&&(result.tree=tree),context.historical&&(result.reconstructed=!0,result.as_of_version=context.historical.as_of_version,result.as_of_timestamp=context.historical.as_of_timestamp),context.historical===void 0)try{await recordContextUsageTouches({pmRoot:context.pmRoot,author:resolveAuthor(void 0,context.settings.author_default),itemIds:[context.locatedId],intent:"get"})}catch{}return registerOutputMaterialFieldGroups(result,projection.fieldProjection?[]:itemMaterialFieldGroups(context.metadata,context.body,children,context.historical===void 0,projection)),result}const _testOnlyGetCommand={shouldAutoIncludeGetChildren};export{GET_DEPTH_INPUT_VALUES2 as GET_DEPTH_INPUT_VALUES,GET_DEPTH_VALUES2 as GET_DEPTH_VALUES,_testOnlyGetCommand,listGetProjectionFields2 as listGetProjectionFields,runGet};
2
2
  //# sourceMappingURL=get.js.map
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @module sdk/query/next-ranking-policy
3
+ *
4
+ * Ranking policies for the `pm next` ready queue (GH-1618). The policy
5
+ * decides whether priority tiers bound the blended relevance order, and the
6
+ * reason helper names any disagreement between policy and relevance. Kept
7
+ * apart from the public `pm next` module so these pure internals stay off the
8
+ * published `./sdk/query` surface while remaining directly testable; the
9
+ * refusal for an unknown policy stays in `next.ts`, the command that owns it.
10
+ */
11
+ import type { ActionableEntry } from "../actionability.js";
12
+ import { type RuntimeStatusRegistry } from "../runtime-primitives.js";
13
+ import type { ItemMetadata } from "../../types/index.js";
14
+ /**
15
+ * Ordering policy applied to the ready queue after relevance scoring.
16
+ * `priority_floor` (default) resumes in-progress work first, then orders by
17
+ * priority tier and lets relevance order items only within a tier, so
18
+ * automated comment churn cannot lift a P2 log above ready P0 work.
19
+ * `weighted` keeps the blended relevance order (GH-1618).
20
+ */
21
+ export type NextRankingPolicy = "priority_floor" | "weighted";
22
+ /** Policies `pm next` accepts, in documentation order. */
23
+ export declare const NEXT_RANKING_POLICIES:readonly NextRankingPolicy[];
24
+ /**
25
+ * Reorder a scored ready queue under the policy. Returns each id's relevance
26
+ * rank before the policy so explanations and reasons can name it. Only the
27
+ * built-in weighted model is reordered; a project's own scorer keeps its order.
28
+ */
29
+ export declare function applyNextRankingPolicy<T extends {
30
+ id:string;
31
+ rank:number;
32
+ item:ItemMetadata;
33
+ }>(ranked:T[],statusRegistry:RuntimeStatusRegistry,policy:NextRankingPolicy,model:string):Map<string,number>;
34
+ /** Explain, in the default reasons, when policy and relevance disagree about the recommendation. */
35
+ export declare function describeRankingPolicyReason(projectedReady:readonly ActionableEntry[],relevanceRank:ReadonlyMap<string,number>,statusRegistry:RuntimeStatusRegistry,policy:NextRankingPolicy):string | undefined;
@@ -0,0 +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]="c12559a3-2703-5665-9ec2-7309589be511")}catch{}})();import{normalizeStatusForRegistry}from"../runtime-primitives.js";const NEXT_RANKING_POLICIES=["priority_floor","weighted"],DEFAULT_WEIGHTED_RELEVANCE_MODEL="default-weighted-v1";function applyNextRankingPolicy(ranked,statusRegistry,policy,model){const relevanceRank=new Map(ranked.map(entry=>[entry.id,entry.rank]));if(policy!=="priority_floor"||model!==DEFAULT_WEIGHTED_RELEVANCE_MODEL)return relevanceRank;const inProgressStatus=statusRegistry.in_progress_status,tier=entry=>normalizeStatusForRegistry(entry.item.status,statusRegistry)===inProgressStatus?-1:entry.item.priority;return ranked.sort((left,right)=>tier(left)-tier(right)||left.rank-right.rank),ranked.forEach((entry,index)=>{entry.rank=index+1}),relevanceRank}function describeRankingPolicyReason(projectedReady,relevanceRank,statusRegistry,policy){const leader=projectedReady[0];if(!leader)return;if(policy==="priority_floor"){const rank=relevanceRank.get(leader.item.id);return rank!==void 0&&rank!==1?`priority floor (relevance rank ${rank})`:void 0}const inProgressStatus=statusRegistry.in_progress_status,higherPriority=projectedReady.slice(1).filter(entry=>entry.item.priority<leader.item.priority&&normalizeStatusForRegistry(entry.item.status,statusRegistry)!==inProgressStatus).map(entry=>entry.item.priority);return higherPriority.length>0?`relevance over p${Math.min(...higherPriority)} ready work`:void 0}export{NEXT_RANKING_POLICIES,applyNextRankingPolicy,describeRankingPolicyReason};
2
+ //# sourceMappingURL=next-ranking-policy.js.map
@@ -12,6 +12,8 @@ import { type ActionableEntry } from "../actionability.js";
12
12
  import { type GlobalOptions } from "../runtime-primitives.js";
13
13
  import type { ItemTypeRegistry } from "../../core/item/type-registry.js";
14
14
  import type { ItemStatus } from "../../types/index.js";
15
+ import { type NextRankingPolicy } from "./next-ranking-policy.js";
16
+ export { NEXT_RANKING_POLICIES,type NextRankingPolicy } from "./next-ranking-policy.js";
15
17
  import { type ContextFocusItem,type ContextRankingSummary,type ContextPackingSummary } from "./context.js";
16
18
  import { type NextReadyBudgetReceipt } from "./next-ready-budget.js";
17
19
  /** Supported values accepted by the next output contract. */
@@ -46,6 +48,8 @@ readyOnly?:boolean;
46
48
  format?:string;
47
49
  /** Value that configures or reports explain ranking for this contract. */
48
50
  explainRanking?:boolean;
51
+ /** Ready-queue ordering policy; defaults to the `context.next_ranking_policy` setting (GH-1618). */
52
+ rankingPolicy?:NextRankingPolicy;
49
53
  /** Maximum rendered tokens for the recommendation and ready alternatives; companion queues use outputBudget. */
50
54
  tokenBudget?:string | number;
51
55
  /** Include human-gated Decision items in the claimable ready queue. */
@@ -145,7 +149,14 @@ ready_only:boolean;
145
149
  include_decisions:boolean;
146
150
  include_gates?:boolean;
147
151
  include_containers?:boolean;
148
- token_budget:number;
152
+ /**
153
+ * Requested recommended+ready selection ceiling, or null when none was
154
+ * requested. The complete response is bounded by the universal output
155
+ * budget and disclosed by its `read_output` receipt (GH-1627).
156
+ */
157
+ token_budget:number | null;
158
+ /** Ordering policy that produced the ready queue (GH-1618). */
159
+ ranking_policy:NextRankingPolicy;
149
160
  };
150
161
  /** Value that configures or reports suggestions for this contract. */
151
162
  suggestions?:string[];
@@ -194,4 +205,3 @@ export declare function runNext(options:NextOptions,global:GlobalOptions):Promis
194
205
  * `--ready-only`) the blocked queue annotated with each item's open blockers.
195
206
  */
196
207
  export declare function renderNextMarkdown(result:NextResult):string;
197
- export {};
@@ -1,3 +1,3 @@
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]="f610c3be-8212-56de-86d4-2b5b9752b87c")}catch{}})();import{collectBlockedByIds,computeActionabilityReport,resolveItemExecutionRole,selectActionableEntries}from"../actionability.js";import{resolveRuntimeStatusRegistry,EXIT_CODE,PmCliError,nowIso,normalizeStatusInput,normalizeStatusForRegistry,resolvePmRoot,readSettings,resolveAuthor,resolveItemTypeRegistry}from"../runtime-primitives.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{parseIntegerLimit}from"./parsers.js";import{buildChildrenByParent,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,resolveContextTokenBudget,toContextPackingSummary,toContextRankingSummary,toContextFocusItem}from"./context.js";import{runList}from"./list.js";import{scoreContextCandidatesWithActiveExtensions}from"../context-relevance.js";import{attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,readContextUsageAffinity,recordContextUsageServing}from"../context-usage.js";import{applyNextReadyBudget}from"./next-ready-budget.js";import{readWorkspaceContextSignals}from"../context-signal-store.js";const NEXT_OUTPUT_VALUES=["markdown","toon","json"],DEFAULT_NEXT_LIMIT=5,MS_PER_DAY=1440*60*1e3;function parseNextOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!NEXT_OUTPUT_VALUES.includes(normalized))throw new PmCliError("Next format must be one of markdown|toon|json",EXIT_CODE.USAGE);return normalized}function resolveNextOutputFormat(options,global2){const commandFormat=parseNextOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json")throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE);return global2.json?"json":commandFormat??"toon"}function parseNextLimit(raw,flag,fallback){const parsed=parseIntegerLimit(raw,flag);return parsed===void 0||parsed<=0?fallback:parsed}function toNextActionableItem(entry,statusRegistry,childrenByParent,rank){return{...toContextFocusItem(entry.item,statusRegistry,childrenByParent),open_blocker_count:entry.open_blockers.length,blockers:entry.open_blockers.map(blocker=>({id:blocker.id,title:blocker.title,status:blocker.status,...blocker.external?{external:!0}:{},...blocker.blocked_since?{blocked_since:blocker.blocked_since}:{},...blocker.external?{resolver:blocker.resolver??null}:{}})),unblocks:entry.unblocks,rank}}function buildRecommendationReasons(entry,statusRegistry,now,completedContainer){const item=entry.item,reasons=[],inProgressStatus=normalizeStatusInput("in_progress",statusRegistry);return reasons.push(normalizeStatusForRegistry(item.status,statusRegistry)===inProgressStatus?"resume work":"ready"),completedContainer&&reasons.push("completed container \u2014 governance closeout"),reasons.push(`p${item.priority}${item.priority===0?" (highest)":""}`),typeof item.deadline=="string"&&item.deadline.trim().length>0&&reasons.push(describeDeadline(item.deadline,now)),reasons.push(collectBlockedByIds(item).length>0?"all blockers resolved":"no blockers"),typeof item.parent=="string"&&item.parent.trim().length>0&&reasons.push(`advances ${item.parent.trim()}`),entry.unblocks.length>0&&reasons.push(`unblocks ${entry.unblocks.length} item(s)`),reasons}function partitionCallerOwnedReady(ready,fallbackAuthor,explicitAuthor){const caller=resolveAuthor(explicitAuthor,fallbackAuthor),available=[],held=[];for(const entry of ready){const assignee=typeof entry.item.assignee=="string"?entry.item.assignee.trim():"";assignee.length>0&&assignee!==caller?held.push({id:entry.item.id,assignee}):available.push(entry)}return{available,held}}const _testOnlyNextCommand={partitionCallerOwnedReady,resolveNextCallerAuthor:(options,settingsAuthor)=>resolveNextCallerAuthor(options,settingsAuthor)};function partitionDecisionEntries(ready,includeDecisions,typeRegistry){const decisions=ready.filter(entry=>resolveItemExecutionRole(entry.item.type,typeRegistry)==="human");return{agent:includeDecisions?ready:ready.filter(entry=>resolveItemExecutionRole(entry.item.type,typeRegistry)!=="human"),decisions:includeDecisions?[]:decisions}}function describeDeadline(deadline,now){const deadlineMs=Date.parse(deadline);if(!Number.isFinite(deadlineMs))return`deadline ${deadline.trim()}`;const dateToken=new Date(deadlineMs).toISOString().slice(0,10),nowToken=new Date(Date.parse(now)).toISOString().slice(0,10),days=Math.round((Date.parse(dateToken)-Date.parse(nowToken))/MS_PER_DAY);return days<0?`deadline ${dateToken} (overdue ${-days}d)`:days===0?`deadline ${dateToken} (due today)`:`deadline ${dateToken} (in ${days}d)`}function inProgressReadyCount(ready,statusRegistry){const inProgressStatus=normalizeStatusInput("in_progress",statusRegistry);return ready.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===inProgressStatus).length}function hasCompletedDescendants(item,childrenByParent){return(childrenByParent.get(item.id.trim().toLowerCase())??[]).length>0}function nextListOptions(options,extra){return{type:options.type,tag:options.tag,priority:typeof options.priority=="number"?String(options.priority):options.priority,assignee:options.assignee,assigneeFilter:options.assigneeFilter,sprint:options.sprint,release:options.release,noTruncate:!0,...extra}}function rankNextReadyEntries(ready,childrenByParent,statusRegistry){return[...ready].sort((left,right)=>{const leftCompletedContainer=hasCompletedDescendants(left.item,childrenByParent),rightCompletedContainer=hasCompletedDescendants(right.item,childrenByParent);return leftCompletedContainer!==rightCompletedContainer?Number(leftCompletedContainer)-Number(rightCompletedContainer):compareCriticalItems(left.item,right.item,statusRegistry)})}function buildNextRecommendation(params){return params.projectedReady.length===0?null:{...params.readyRows[0],reasons:buildRecommendationReasons(params.projectedReady[0],params.statusRegistry,params.now,params.completedContainer)}}function buildNextSuggestions(recommended,blockedRows,gateCount){if(recommended!==null)return;const gateGuidance=gateCount>0?["No executable recommendation: outcome gates require verification. Inspect gate_needed, or use pm next --include-gates to opt in."]:[];if(blockedRows.length>0){const blockedWithReferences=blockedRows.find(item=>item.blockers.length>0);return[...gateGuidance,blockedWithReferences?`${blockedRows.length} item(s) are blocked; unblock the top one by closing ${blockedWithReferences.blockers.map(blocker=>blocker.id).join(", ")}`:`${blockedRows.length} item(s) are blocked; add blocker context or move the top item back to an active status`,"pm next --ready-only after a blocker closes to re-check ready work",'pm create --type Task --title "..." to add new ready work']}return[...gateGuidance,'pm create --type Task --title "..." to add a new work item',"pm list --status in_progress to review work already underway","pm context --depth deep for the full project snapshot"]}function buildNextTruncation(decisionCount,heldCount,readyCount,limit){const truncation={};return decisionCount>limit&&(truncation.decision_needed_total=decisionCount),heldCount>limit&&(truncation.held_by_others_total=heldCount),readyCount>limit+1&&(truncation.ready_total=readyCount),Object.keys(truncation).length>0?truncation:void 0}async function attachNextUsageFeedback(params){try{const included=new Set([...params.result.recommended?[params.result.recommended.id]:[],...params.result.ready.map(entry=>entry.id)]),rows=params.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)})),rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(params.result,"next"))rankedIds.has(id)||(rows.push({id,rank:rows.length+1,included:!1}),rankedIds.add(id));const receipt=await recordContextUsageServing({pmRoot:params.pmRoot,author:params.author,surface:"next",profile:"next",rows,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});attachContextUsageServingReceipt(params.result,receipt)}catch{params.result.warnings=mergeSortedWarnings(params.result.warnings,["context_usage_feedback_write_failed"])}}async function finalizeNextResult(params){const warnings=[...new Set([...params.candidatesWarnings??[],...params.corpusWarnings??[],...params.readyRanking.warnings??[],...params.featureStore.warnings])].sort((left,right)=>left.localeCompare(right));return warnings.length>0&&(params.result.warnings=warnings),params.result.suggestions=buildNextSuggestions(params.recommended,params.blockedRows,params.gateCount),params.tokenBudget!==void 0&&applyNextReadyBudget(params.result,params.tokenBudget,params.hasIntentBudget),params.explainRanking&&(params.result.ranking=toContextRankingSummary(params.readyRanking,params.featureStore,new Set([...params.result.recommended?[params.result.recommended.id]:[],...params.result.ready.map(entry=>entry.id)])),params.result.packing=toContextPackingSummary(packRankedContextItems(params.readyRanking,params.packingBudget,new Set,"next"))),await attachNextUsageFeedback({result:params.result,pmRoot:params.pmRoot,author:params.author,ranking:params.readyRanking}),params.result}function filterCandidatesByParentScope(candidates,corpus,parentScope){if(!parentScope)return candidates;const subtree=collectSubtreeIds(corpus,parentScope);if(!subtree.found)throw new PmCliError(`Next --parent item not found: ${parentScope}`,EXIT_CODE.NOT_FOUND);return candidates.filter(item=>subtree.ids.has(item.id.trim().toLowerCase()))}async function rankReadyEntriesWithRelevance(rankedReady,childrenByParent,statusRegistry,now,callerAuthor,pmRoot,includeContainers){const concreteReady=rankedReady.filter(entry=>!hasCompletedDescendants(entry.item,childrenByParent)),structuralReady=includeContainers||concreteReady.length===0?rankedReady:concreteReady,usage=await readContextUsageAffinity({pmRoot,author:callerAuthor,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),featureStore=await readWorkspaceContextSignals(structuralReady.map(entry=>entry.item),{pmRoot,storeKey:"next",statusRegistry,now,author:callerAuthor,usageAffinity:usage.affinity}),ranking=await scoreContextCandidatesWithActiveExtensions("next",featureStore.candidates),readyById=new Map(structuralReady.map(entry=>[entry.item.id,entry]));return{projectedReady:ranking.ranked.map(entry=>readyById.get(entry.id)).filter(entry=>entry!==void 0),ranking,completedContainer:concreteReady.length===0&&!includeContainers,featureStore}}function resolveNextCallerAuthor(options,settingsAuthor){const requestedAssignee=options.assignee?.trim();return resolveAuthor(options.callerAuthor??(requestedAssignee&&requestedAssignee.length>0?requestedAssignee:void 0),settingsAuthor)}async function runNext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),settings=await readSettings(pmRoot),callerAuthor=resolveNextCallerAuthor(options,settings.author_default),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),now=nowIso(),limit=parseNextLimit(options.limit,"--limit",DEFAULT_NEXT_LIMIT),tokenBudget=resolveContextTokenBudget(options.tokenBudget,Math.max(192,limit*128)),blockedLimit=parseNextLimit(options.blockedLimit,"--blocked-limit",limit),readyOnly=options.readyOnly===!0,parentScope=typeof options.parent=="string"?options.parent.trim():"",candidatesList=await runList(void 0,nextListOptions(options,{excludeTerminal:!0}),global2),corpusList=await runList(void 0,{excludeTerminal:!1,noTruncate:!0},global2),candidates=filterCandidatesByParentScope(candidatesList.items,corpusList.items,parentScope),corpus=corpusList.items,report=computeActionabilityReport(candidates,corpus,statusRegistry,typeRegistry),childrenByParent=buildChildrenByParent(corpus),selected=selectActionableEntries(report,statusRegistry,options,typeRegistry),callerPartition=partitionCallerOwnedReady(selected.ready,settings.author_default,callerAuthor),rankedReady=rankNextReadyEntries(callerPartition.available,childrenByParent,statusRegistry),rankedBlocked=[...report.blocked].sort((left,right)=>compareCriticalItems(left.item,right.item,statusRegistry)),{projectedReady,ranking:readyRanking,completedContainer,featureStore}=await rankReadyEntriesWithRelevance(rankedReady,childrenByParent,statusRegistry,now,callerAuthor,pmRoot,options.includeContainers===!0),readyRows=projectedReady.map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),blockedRows=rankedBlocked.map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),decisionRows=rankNextReadyEntries(selected.decisions,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),gateRows=rankNextReadyEntries(selected.gates,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),containerRows=rankNextReadyEntries(report.containers,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),recommended=buildNextRecommendation({projectedReady,readyRows,statusRegistry,now,completedContainer}),truncation=buildNextTruncation(decisionRows.length,callerPartition.held.length,readyRows.length,limit)??{};gateRows.length>limit&&(truncation.gate_needed_total=gateRows.length),containerRows.length>limit&&(truncation.containers_total=containerRows.length);const result={output_default:"toon",now,recommended,ready:readyRows.slice(1,limit+1),decision_needed:decisionRows.slice(0,limit),gate_needed:gateRows.slice(0,limit),containers:containerRows.slice(0,limit),blocked:readyOnly?[]:blockedRows.slice(0,blockedLimit),held_by_others:callerPartition.held.slice(0,limit),summary:{recommended:recommended!==null,ready:readyRows.length,blocked:blockedRows.length,in_progress:inProgressReadyCount(readyRows,statusRegistry),candidates:report.active_count,containers:report.container_count,decision_needed:decisionRows.length,gate_needed:gateRows.length,held_by_others:callerPartition.held.length},filters:{type:options.type??null,tag:options.tag??null,priority:options.priority??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,parent:parentScope.length>0?parentScope:null,limit,blocked_limit:blockedLimit,ready_only:readyOnly,include_decisions:options.includeDecisions===!0,include_gates:options.includeGates===!0,include_containers:options.includeContainers===!0,token_budget:tokenBudget},truncation:Object.keys(truncation).length>0?truncation:void 0};return finalizeNextResult({result,recommended,blockedRows,gateCount:gateRows.length,candidatesWarnings:candidatesList.warnings,corpusWarnings:corpusList.warnings,readyRanking,explainRanking:options.explainRanking===!0,pmRoot,author:callerAuthor,packingBudget:tokenBudget,featureStore,tokenBudget:options.tokenBudget===void 0?void 0:tokenBudget,hasIntentBudget:typeof options.for=="string"})}function renderNextMarkdown(result){const lines=["# pm next","",...renderNextSummaryLines(result)];for(const[title,rows]of[["Gate verification needed",result.gate_needed],["Containers",result.containers]])rows&&rows.length>0&&lines.push(...renderNextSection(title,rows.map(item=>`- ${formatNextLine(item)}`),""));if(lines.push(...renderNextSection("Recommended",renderNextRecommendedRows(result.recommended),result.truncation?.ready_budget?.recommendation_omitted?"Recommendation omitted by the selection budget; ready work still exists.":"No ready work.")),lines.push(...renderNextSection("Decision needed",(result.decision_needed??[]).map(item=>`- ${formatNextLine(item)}`),"No human-gated decisions.")),lines.push(...renderNextSection("Ready",result.ready.map(item=>`- ${formatNextLine(item)}`),"No ready items.")),result.filters.ready_only||lines.push(...renderNextSection("Blocked",result.blocked.map(item=>`- ${formatNextBlockedLine(item)}`),"No blocked items.")),result.suggestions&&result.suggestions.length>0){lines.push("## Suggestions");for(const suggestion of result.suggestions)lines.push(`- ${suggestion}`)}return lines.join(`
2
- `).trimEnd()}function renderNextSummaryLines(result){const lines=[`- now: ${result.now}`,`- ready: ${result.summary.ready} (in_progress: ${result.summary.in_progress}), blocked: ${result.summary.blocked}, candidates: ${result.summary.candidates}`];return result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(""),lines}function renderNextRecommendedRows(recommended){return recommended?[`- ${formatNextLine(recommended)}`,` why: ${recommended.reasons.join("; ")}`]:[]}function renderNextSection(header,rows,emptyMessage){return[`## ${header}`,...rows.length===0?[emptyMessage]:rows,""]}function formatNextBlockedLine(item){const by=item.blockers.map(blocker=>`${blocker.id}(${blocker.status??"?"})`).join(", ");return`${formatNextLine(item)} blocked_by:${by}`}function formatNextLine(item){const deadlineToken=item.deadline??"-",parentToken=item.parent?` parent:${item.parent}`:"",unblocksToken=item.unblocks.length>0?` unblocks:${item.unblocks.length}`:"";return`${Number.isInteger(item.rank)?`#${item.rank} `:""}${item.id} p${item.priority} ${item.status} ${item.type} deadline:${deadlineToken}${parentToken}${unblocksToken} ${item.title}`}export{NEXT_OUTPUT_VALUES,_testOnlyNextCommand,partitionDecisionEntries,renderNextMarkdown,resolveNextOutputFormat,runNext};
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]="b01faffe-d88f-5095-8d28-167943ec5067")}catch{}})();import{collectBlockedByIds,computeActionabilityReport,resolveItemExecutionRole,selectActionableEntries}from"../actionability.js";import{resolveRuntimeStatusRegistry,EXIT_CODE,PmCliError,nowIso,normalizeStatusInput,normalizeStatusForRegistry,resolvePmRoot,readSettings,resolveAuthor,resolveItemTypeRegistry}from"../runtime-primitives.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{parseIntegerLimit}from"./parsers.js";import{NEXT_RANKING_POLICIES,applyNextRankingPolicy,describeRankingPolicyReason}from"./next-ranking-policy.js";import{NEXT_RANKING_POLICIES as NEXT_RANKING_POLICIES2}from"./next-ranking-policy.js";import{buildChildrenByParent,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,resolveContextTokenBudget,toContextPackingSummary,toContextRankingSummary,toContextFocusItem}from"./context.js";import{runList}from"./list.js";import{scoreContextCandidatesWithActiveExtensions}from"../context-relevance.js";import{attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,readContextUsageAffinity,recordContextUsageServing}from"../context-usage.js";import{applyNextReadyBudget}from"./next-ready-budget.js";import{readWorkspaceContextSignals}from"../context-signal-store.js";const NEXT_OUTPUT_VALUES=["markdown","toon","json"],DEFAULT_NEXT_LIMIT=5,MS_PER_DAY=1440*60*1e3;function resolveNextRankingPolicy(requested,configured){const candidate=requested??configured;if(typeof candidate=="string"&&NEXT_RANKING_POLICIES.includes(candidate))return candidate;throw new PmCliError(`Unknown next ranking policy ${JSON.stringify(candidate)}. Accepted values: ${NEXT_RANKING_POLICIES.join(", ")}.`,EXIT_CODE.USAGE,{code:"invalid_argument_value",value:String(candidate),recovery:{allowed_values:[...NEXT_RANKING_POLICIES]}})}function parseNextOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!NEXT_OUTPUT_VALUES.includes(normalized))throw new PmCliError("Next format must be one of markdown|toon|json",EXIT_CODE.USAGE);return normalized}function resolveNextOutputFormat(options,global2){const commandFormat=parseNextOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json")throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE);return global2.json?"json":commandFormat??"toon"}function parseNextLimit(raw,flag,fallback){const parsed=parseIntegerLimit(raw,flag);return parsed===void 0||parsed<=0?fallback:parsed}function toNextActionableItem(entry,statusRegistry,childrenByParent,rank){return{...toContextFocusItem(entry.item,statusRegistry,childrenByParent),open_blocker_count:entry.open_blockers.length,blockers:entry.open_blockers.map(blocker=>({id:blocker.id,title:blocker.title,status:blocker.status,...blocker.external?{external:!0}:{},...blocker.blocked_since?{blocked_since:blocker.blocked_since}:{},...blocker.external?{resolver:blocker.resolver??null}:{}})),unblocks:entry.unblocks,rank}}function buildRecommendationReasons(entry,statusRegistry,now,completedContainer){const item=entry.item,reasons=[],inProgressStatus=normalizeStatusInput("in_progress",statusRegistry);return reasons.push(normalizeStatusForRegistry(item.status,statusRegistry)===inProgressStatus?"resume work":"ready"),completedContainer&&reasons.push("completed container \u2014 governance closeout"),reasons.push(`p${item.priority}${item.priority===0?" (highest)":""}`),typeof item.deadline=="string"&&item.deadline.trim().length>0&&reasons.push(describeDeadline(item.deadline,now)),reasons.push(collectBlockedByIds(item).length>0?"all blockers resolved":"no blockers"),typeof item.parent=="string"&&item.parent.trim().length>0&&reasons.push(`advances ${item.parent.trim()}`),entry.unblocks.length>0&&reasons.push(`unblocks ${entry.unblocks.length} item(s)`),reasons}function partitionCallerOwnedReady(ready,fallbackAuthor,explicitAuthor){const caller=resolveAuthor(explicitAuthor,fallbackAuthor),available=[],held=[];for(const entry of ready){const assignee=typeof entry.item.assignee=="string"?entry.item.assignee.trim():"";assignee.length>0&&assignee!==caller?held.push({id:entry.item.id,assignee}):available.push(entry)}return{available,held}}const _testOnlyNextCommand={partitionCallerOwnedReady,resolveNextCallerAuthor:(options,settingsAuthor)=>resolveNextCallerAuthor(options,settingsAuthor)};function partitionDecisionEntries(ready,includeDecisions,typeRegistry){const decisions=ready.filter(entry=>resolveItemExecutionRole(entry.item.type,typeRegistry)==="human");return{agent:includeDecisions?ready:ready.filter(entry=>resolveItemExecutionRole(entry.item.type,typeRegistry)!=="human"),decisions:includeDecisions?[]:decisions}}function describeDeadline(deadline,now){const deadlineMs=Date.parse(deadline);if(!Number.isFinite(deadlineMs))return`deadline ${deadline.trim()}`;const dateToken=new Date(deadlineMs).toISOString().slice(0,10),nowToken=new Date(Date.parse(now)).toISOString().slice(0,10),days=Math.round((Date.parse(dateToken)-Date.parse(nowToken))/MS_PER_DAY);return days<0?`deadline ${dateToken} (overdue ${-days}d)`:days===0?`deadline ${dateToken} (due today)`:`deadline ${dateToken} (in ${days}d)`}function inProgressReadyCount(ready,statusRegistry){const inProgressStatus=normalizeStatusInput("in_progress",statusRegistry);return ready.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===inProgressStatus).length}function hasCompletedDescendants(item,childrenByParent){return(childrenByParent.get(item.id.trim().toLowerCase())??[]).length>0}function nextListOptions(options,extra){return{type:options.type,tag:options.tag,priority:typeof options.priority=="number"?String(options.priority):options.priority,assignee:options.assignee,assigneeFilter:options.assigneeFilter,sprint:options.sprint,release:options.release,noTruncate:!0,...extra}}function rankNextReadyEntries(ready,childrenByParent,statusRegistry){return[...ready].sort((left,right)=>{const leftCompletedContainer=hasCompletedDescendants(left.item,childrenByParent),rightCompletedContainer=hasCompletedDescendants(right.item,childrenByParent);return leftCompletedContainer!==rightCompletedContainer?Number(leftCompletedContainer)-Number(rightCompletedContainer):compareCriticalItems(left.item,right.item,statusRegistry)})}function buildNextRecommendation(params){return params.projectedReady.length===0?null:{...params.readyRows[0],reasons:[...buildRecommendationReasons(params.projectedReady[0],params.statusRegistry,params.now,params.completedContainer),...params.policyReason?[params.policyReason]:[]]}}function buildNextSuggestions(recommended,blockedRows,gateCount){if(recommended!==null)return;const gateGuidance=gateCount>0?["No executable recommendation: outcome gates require verification. Inspect gate_needed, or use pm next --include-gates to opt in."]:[];if(blockedRows.length>0){const blockedWithReferences=blockedRows.find(item=>item.blockers.length>0);return[...gateGuidance,blockedWithReferences?`${blockedRows.length} item(s) are blocked; unblock the top one by closing ${blockedWithReferences.blockers.map(blocker=>blocker.id).join(", ")}`:`${blockedRows.length} item(s) are blocked; add blocker context or move the top item back to an active status`,"pm next --ready-only after a blocker closes to re-check ready work",'pm create --type Task --title "..." to add new ready work']}return[...gateGuidance,'pm create --type Task --title "..." to add a new work item',"pm list --status in_progress to review work already underway","pm context --depth deep for the full project snapshot"]}function buildNextTruncation(decisionCount,heldCount,readyCount,limit){const truncation={};return decisionCount>limit&&(truncation.decision_needed_total=decisionCount),heldCount>limit&&(truncation.held_by_others_total=heldCount),readyCount>limit+1&&(truncation.ready_total=readyCount),Object.keys(truncation).length>0?truncation:void 0}async function attachNextUsageFeedback(params){try{const included=new Set([...params.result.recommended?[params.result.recommended.id]:[],...params.result.ready.map(entry=>entry.id)]),rows=params.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)})),rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(params.result,"next"))rankedIds.has(id)||(rows.push({id,rank:rows.length+1,included:!1}),rankedIds.add(id));const receipt=await recordContextUsageServing({pmRoot:params.pmRoot,author:params.author,surface:"next",profile:"next",rows,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});attachContextUsageServingReceipt(params.result,receipt)}catch{params.result.warnings=mergeSortedWarnings(params.result.warnings,["context_usage_feedback_write_failed"])}}async function finalizeNextResult(params){const warnings=[...new Set([...params.candidatesWarnings??[],...params.corpusWarnings??[],...params.readyRanking.warnings??[],...params.featureStore.warnings])].sort((left,right)=>left.localeCompare(right));return warnings.length>0&&(params.result.warnings=warnings),params.result.suggestions=buildNextSuggestions(params.recommended,params.blockedRows,params.gateCount),params.tokenBudget!==null&&applyNextReadyBudget(params.result,params.tokenBudget,params.hasIntentBudget),params.explainRanking&&(params.result.ranking=toContextRankingSummary(params.readyRanking,params.featureStore,new Set([...params.result.recommended?[params.result.recommended.id]:[],...params.result.ready.map(entry=>entry.id)])),params.result.packing=toContextPackingSummary(packRankedContextItems(params.readyRanking,params.packingBudget,new Set,"next"))),await attachNextUsageFeedback({result:params.result,pmRoot:params.pmRoot,author:params.author,ranking:params.readyRanking}),params.result}function filterCandidatesByParentScope(candidates,corpus,parentScope){if(!parentScope)return candidates;const subtree=collectSubtreeIds(corpus,parentScope);if(!subtree.found)throw new PmCliError(`Next --parent item not found: ${parentScope}`,EXIT_CODE.NOT_FOUND);return candidates.filter(item=>subtree.ids.has(item.id.trim().toLowerCase()))}async function rankReadyEntriesWithRelevance(rankedReady,childrenByParent,statusRegistry,now,callerAuthor,pmRoot,includeContainers,rankingPolicy){const concreteReady=rankedReady.filter(entry=>!hasCompletedDescendants(entry.item,childrenByParent)),structuralReady=includeContainers||concreteReady.length===0?rankedReady:concreteReady,usage=await readContextUsageAffinity({pmRoot,author:callerAuthor,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),featureStore=await readWorkspaceContextSignals(structuralReady.map(entry=>entry.item),{pmRoot,storeKey:"next",statusRegistry,now,author:callerAuthor,usageAffinity:usage.affinity}),ranking=await scoreContextCandidatesWithActiveExtensions("next",featureStore.candidates),relevanceRank=applyNextRankingPolicy(ranking.ranked,statusRegistry,rankingPolicy,ranking.model),readyById=new Map(structuralReady.map(entry=>[entry.item.id,entry]));return{projectedReady:ranking.ranked.map(entry=>readyById.get(entry.id)).filter(entry=>entry!==void 0),ranking,completedContainer:concreteReady.length===0&&!includeContainers,featureStore,relevanceRank}}function resolveNextCallerAuthor(options,settingsAuthor){const requestedAssignee=options.assignee?.trim();return resolveAuthor(options.callerAuthor??(requestedAssignee&&requestedAssignee.length>0?requestedAssignee:void 0),settingsAuthor)}function requestedSelectionBudget(options,resolved){return options.tokenBudget===void 0?null:resolved}async function runNext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),settings=await readSettings(pmRoot),callerAuthor=resolveNextCallerAuthor(options,settings.author_default),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),rankingPolicy=resolveNextRankingPolicy(options.rankingPolicy,settings.context.next_ranking_policy),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),now=nowIso(),limit=parseNextLimit(options.limit,"--limit",DEFAULT_NEXT_LIMIT),tokenBudget=resolveContextTokenBudget(options.tokenBudget,Math.max(192,limit*128)),requestedTokenBudget=requestedSelectionBudget(options,tokenBudget),blockedLimit=parseNextLimit(options.blockedLimit,"--blocked-limit",limit),readyOnly=options.readyOnly===!0,parentScope=typeof options.parent=="string"?options.parent.trim():"",candidatesList=await runList(void 0,nextListOptions(options,{excludeTerminal:!0}),global2),corpusList=await runList(void 0,{excludeTerminal:!1,noTruncate:!0},global2),candidates=filterCandidatesByParentScope(candidatesList.items,corpusList.items,parentScope),corpus=corpusList.items,report=computeActionabilityReport(candidates,corpus,statusRegistry,typeRegistry),childrenByParent=buildChildrenByParent(corpus),selected=selectActionableEntries(report,statusRegistry,options,typeRegistry),callerPartition=partitionCallerOwnedReady(selected.ready,settings.author_default,callerAuthor),rankedReady=rankNextReadyEntries(callerPartition.available,childrenByParent,statusRegistry),rankedBlocked=[...report.blocked].sort((left,right)=>compareCriticalItems(left.item,right.item,statusRegistry)),{projectedReady,ranking:readyRanking,completedContainer,featureStore,relevanceRank}=await rankReadyEntriesWithRelevance(rankedReady,childrenByParent,statusRegistry,now,callerAuthor,pmRoot,options.includeContainers===!0,rankingPolicy),readyRows=projectedReady.map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),blockedRows=rankedBlocked.map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),decisionRows=rankNextReadyEntries(selected.decisions,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),gateRows=rankNextReadyEntries(selected.gates,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),containerRows=rankNextReadyEntries(report.containers,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),recommended=buildNextRecommendation({projectedReady,readyRows,statusRegistry,now,completedContainer,policyReason:describeRankingPolicyReason(projectedReady,relevanceRank,statusRegistry,rankingPolicy)}),truncation=buildNextTruncation(decisionRows.length,callerPartition.held.length,readyRows.length,limit)??{};gateRows.length>limit&&(truncation.gate_needed_total=gateRows.length),containerRows.length>limit&&(truncation.containers_total=containerRows.length);const result={output_default:"toon",now,recommended,ready:readyRows.slice(1,limit+1),decision_needed:decisionRows.slice(0,limit),gate_needed:gateRows.slice(0,limit),containers:containerRows.slice(0,limit),blocked:readyOnly?[]:blockedRows.slice(0,blockedLimit),held_by_others:callerPartition.held.slice(0,limit),summary:{recommended:recommended!==null,ready:readyRows.length,blocked:blockedRows.length,in_progress:inProgressReadyCount(readyRows,statusRegistry),candidates:report.active_count,containers:report.container_count,decision_needed:decisionRows.length,gate_needed:gateRows.length,held_by_others:callerPartition.held.length},filters:{type:options.type??null,tag:options.tag??null,priority:options.priority??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,parent:parentScope.length>0?parentScope:null,limit,blocked_limit:blockedLimit,ready_only:readyOnly,include_decisions:options.includeDecisions===!0,include_gates:options.includeGates===!0,include_containers:options.includeContainers===!0,token_budget:requestedTokenBudget,ranking_policy:rankingPolicy},truncation:Object.keys(truncation).length>0?truncation:void 0};return finalizeNextResult({result,recommended,blockedRows,gateCount:gateRows.length,candidatesWarnings:candidatesList.warnings,corpusWarnings:corpusList.warnings,readyRanking,explainRanking:options.explainRanking===!0,pmRoot,author:callerAuthor,packingBudget:tokenBudget,featureStore,tokenBudget:requestedTokenBudget,hasIntentBudget:typeof options.for=="string"})}function renderNextMarkdown(result){const lines=["# pm next","",...renderNextSummaryLines(result)];for(const[title,rows]of[["Gate verification needed",result.gate_needed],["Containers",result.containers]])rows&&rows.length>0&&lines.push(...renderNextSection(title,rows.map(item=>`- ${formatNextLine(item)}`),""));if(lines.push(...renderNextSection("Recommended",renderNextRecommendedRows(result.recommended),result.truncation?.ready_budget?.recommendation_omitted?"Recommendation omitted by the selection budget; ready work still exists.":"No ready work.")),lines.push(...renderNextSection("Decision needed",(result.decision_needed??[]).map(item=>`- ${formatNextLine(item)}`),"No human-gated decisions.")),lines.push(...renderNextSection("Ready",result.ready.map(item=>`- ${formatNextLine(item)}`),"No ready items.")),result.filters.ready_only||lines.push(...renderNextSection("Blocked",result.blocked.map(item=>`- ${formatNextBlockedLine(item)}`),"No blocked items.")),result.suggestions&&result.suggestions.length>0){lines.push("## Suggestions");for(const suggestion of result.suggestions)lines.push(`- ${suggestion}`)}return lines.join(`
2
+ `).trimEnd()}function renderNextSummaryLines(result){const lines=[`- now: ${result.now}`,`- ready: ${result.summary.ready} (in_progress: ${result.summary.in_progress}), blocked: ${result.summary.blocked}, candidates: ${result.summary.candidates}`];return result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(""),lines}function renderNextRecommendedRows(recommended){return recommended?[`- ${formatNextLine(recommended)}`,` why: ${recommended.reasons.join("; ")}`]:[]}function renderNextSection(header,rows,emptyMessage){return[`## ${header}`,...rows.length===0?[emptyMessage]:rows,""]}function formatNextBlockedLine(item){const by=item.blockers.map(blocker=>`${blocker.id}(${blocker.status??"?"})`).join(", ");return`${formatNextLine(item)} blocked_by:${by}`}function formatNextLine(item){const deadlineToken=item.deadline??"-",parentToken=item.parent?` parent:${item.parent}`:"",unblocksToken=item.unblocks.length>0?` unblocks:${item.unblocks.length}`:"";return`${Number.isInteger(item.rank)?`#${item.rank} `:""}${item.id} p${item.priority} ${item.status} ${item.type} deadline:${deadlineToken}${parentToken}${unblocksToken} ${item.title}`}export{NEXT_OUTPUT_VALUES,NEXT_RANKING_POLICIES2 as NEXT_RANKING_POLICIES,_testOnlyNextCommand,partitionDecisionEntries,renderNextMarkdown,resolveNextOutputFormat,runNext};
3
3
  //# sourceMappingURL=next.js.map
@@ -21,6 +21,10 @@ export type ListCommandName = keyof typeof LIST_COMMAND_DEFAULT_PROJECTIONS;
21
21
  export declare function listListProjectionFields(runtimeMetadataKeys?:Iterable<string>):string[];
22
22
  /** Canonical get depth values. The CLI also accepts full as an alias for deep. */
23
23
  export declare const GET_DEPTH_VALUES:readonly ["brief","standard","deep"];
24
+ /** Every get `--depth` spelling the CLI accepts, including the full alias. */
25
+ export declare const GET_DEPTH_INPUT_VALUES:readonly ["brief","standard","deep","full"];
26
+ /** Supported values accepted by the plan show depth contract. */
27
+ export declare const PLAN_SHOW_DEPTH_VALUES:readonly ["brief","standard","deep"];
24
28
  /** Return every accepted get projection selector for core and runtime metadata. */
25
29
  export declare function listGetProjectionFields(runtimeMetadataKeys?:Iterable<string>):string[];
26
30
  /** Stable field order for compact search results. */
@@ -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]="dc76b081-02dc-5b09-ab40-cd57c733b3ad")}catch{}})();import{ITEM_METADATA_KEY_ORDER}from"../../core/shared/item-metadata-contract.js";const DEFAULT_COMPACT_LIST_FIELDS=["id","title","status","type","priority","parent","updated_at"],BRIEF_LIST_FIELDS=["id","status","type","title"],LIST_COMMAND_DEFAULT_PROJECTIONS={list:"brief","list-all":"full","list-draft":"full","list-open":"brief","list-in-progress":"brief","list-blocked":"brief","list-closed":"brief","list-canceled":"full"},TREE_METADATA_FIELDS=["tree_depth","tree_parent","tree_children","tree_title"];function listListProjectionFields(runtimeMetadataKeys=[]){return[...new Set([...ITEM_METADATA_KEY_ORDER,"body",...TREE_METADATA_FIELDS,...runtimeMetadataKeys])].flatMap(field=>[field,`item.${field}`]).sort()}const GET_DEPTH_VALUES=["brief","standard","deep"],GET_ROOT_PROJECTION_FIELDS=["body","linked","claim_state","children","schedule","blockers"],GET_LINKED_PROJECTION_FIELDS=["linked.files","linked.tests","linked.docs"],GET_CLAIM_STATE_PROJECTION_FIELDS=["claim_state.claimed","claim_state.assignee","claim_state.last_claim","claim_state.last_release"],GET_SCHEDULE_PROJECTION_FIELDS=["schedule.deadline","schedule.start_at","schedule.end_at","schedule.location","schedule.reminders","schedule.events"];function listGetProjectionFields(runtimeMetadataKeys=[]){return[...[...new Set([...ITEM_METADATA_KEY_ORDER,...runtimeMetadataKeys,"notes_count","tests_count","collection_counts"])].flatMap(field=>[field,`item.${field}`]),...GET_ROOT_PROJECTION_FIELDS,...GET_LINKED_PROJECTION_FIELDS,...GET_CLAIM_STATE_PROJECTION_FIELDS,...GET_SCHEDULE_PROJECTION_FIELDS].sort()}const DEFAULT_COMPACT_SEARCH_FIELDS=["id","title","status","type","priority","updated_at","score","matched_fields"],SEARCH_HIT_FIELD_KEYS=["score","matched_fields","highlights"],SEARCH_ITEM_FIELD_KEYS=["id","title","description","type","status","priority","tags","created_at","updated_at","deadline","assignee","author","estimated_minutes","acceptance_criteria","dependencies","comments","notes","learnings","reminders","events","files","tests","docs","close_reason","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result","affected_version","fixed_version","component","regression","customer_impact","definition_of_ready","order","rank","goal","objective","value","impact","outcome","why_now","plan"];function listSearchProjectionFields(runtimeMetadataKeys=[]){const runtimeKeys=[...new Set(runtimeMetadataKeys)];return[...SEARCH_HIT_FIELD_KEYS,...SEARCH_ITEM_FIELD_KEYS,...SEARCH_ITEM_FIELD_KEYS.map(field=>`item.${field}`),...runtimeKeys,...runtimeKeys.map(field=>`item.${field}`)].sort()}export{BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS,DEFAULT_COMPACT_SEARCH_FIELDS,GET_DEPTH_VALUES,LIST_COMMAND_DEFAULT_PROJECTIONS,SEARCH_HIT_FIELD_KEYS,SEARCH_ITEM_FIELD_KEYS,listGetProjectionFields,listListProjectionFields,listSearchProjectionFields};
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]="88ed7e44-a3a0-5a23-9d7b-b00087bff331")}catch{}})();import{ITEM_METADATA_KEY_ORDER}from"../../core/shared/item-metadata-contract.js";const DEFAULT_COMPACT_LIST_FIELDS=["id","title","status","type","priority","parent","updated_at"],BRIEF_LIST_FIELDS=["id","status","type","title"],LIST_COMMAND_DEFAULT_PROJECTIONS={list:"brief","list-all":"full","list-draft":"full","list-open":"brief","list-in-progress":"brief","list-blocked":"brief","list-closed":"brief","list-canceled":"full"},TREE_METADATA_FIELDS=["tree_depth","tree_parent","tree_children","tree_title"];function listListProjectionFields(runtimeMetadataKeys=[]){return[...new Set([...ITEM_METADATA_KEY_ORDER,"body",...TREE_METADATA_FIELDS,...runtimeMetadataKeys])].flatMap(field=>[field,`item.${field}`]).sort()}const GET_DEPTH_VALUES=["brief","standard","deep"],GET_DEPTH_INPUT_VALUES=[...GET_DEPTH_VALUES,"full"],PLAN_SHOW_DEPTH_VALUES=["brief","standard","deep"],GET_ROOT_PROJECTION_FIELDS=["body","linked","claim_state","children","schedule","blockers"],GET_LINKED_PROJECTION_FIELDS=["linked.files","linked.tests","linked.docs"],GET_CLAIM_STATE_PROJECTION_FIELDS=["claim_state.claimed","claim_state.assignee","claim_state.last_claim","claim_state.last_release"],GET_SCHEDULE_PROJECTION_FIELDS=["schedule.deadline","schedule.start_at","schedule.end_at","schedule.location","schedule.reminders","schedule.events"];function listGetProjectionFields(runtimeMetadataKeys=[]){return[...[...new Set([...ITEM_METADATA_KEY_ORDER,...runtimeMetadataKeys,"notes_count","tests_count","collection_counts"])].flatMap(field=>[field,`item.${field}`]),...GET_ROOT_PROJECTION_FIELDS,...GET_LINKED_PROJECTION_FIELDS,...GET_CLAIM_STATE_PROJECTION_FIELDS,...GET_SCHEDULE_PROJECTION_FIELDS].sort()}const DEFAULT_COMPACT_SEARCH_FIELDS=["id","title","status","type","priority","updated_at","score","matched_fields"],SEARCH_HIT_FIELD_KEYS=["score","matched_fields","highlights"],SEARCH_ITEM_FIELD_KEYS=["id","title","description","type","status","priority","tags","created_at","updated_at","deadline","assignee","author","estimated_minutes","acceptance_criteria","dependencies","comments","notes","learnings","reminders","events","files","tests","docs","close_reason","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result","affected_version","fixed_version","component","regression","customer_impact","definition_of_ready","order","rank","goal","objective","value","impact","outcome","why_now","plan"];function listSearchProjectionFields(runtimeMetadataKeys=[]){const runtimeKeys=[...new Set(runtimeMetadataKeys)];return[...SEARCH_HIT_FIELD_KEYS,...SEARCH_ITEM_FIELD_KEYS,...SEARCH_ITEM_FIELD_KEYS.map(field=>`item.${field}`),...runtimeKeys,...runtimeKeys.map(field=>`item.${field}`)].sort()}export{BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS,DEFAULT_COMPACT_SEARCH_FIELDS,GET_DEPTH_INPUT_VALUES,GET_DEPTH_VALUES,LIST_COMMAND_DEFAULT_PROJECTIONS,PLAN_SHOW_DEPTH_VALUES,SEARCH_HIT_FIELD_KEYS,SEARCH_ITEM_FIELD_KEYS,listGetProjectionFields,listListProjectionFields,listSearchProjectionFields};
2
2
  //# sourceMappingURL=projection-contracts.js.map