@unbrained/pm-cli 2026.10.24 → 2026.10.26

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 (222) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +48 -0
  3. package/dist/cli/error-guidance.d.ts +5 -0
  4. package/dist/cli/error-guidance.js +2 -2
  5. package/dist/cli/extension-command-help.js +2 -2
  6. package/dist/cli/register-history-activity.js +1 -1
  7. package/dist/cli/register-mutation.js +2 -2
  8. package/dist/cli-bundle/bundle-manifest.json +1 -1
  9. package/dist/cli-bundle/chunks/{chunk-3S5FLCG7.js → chunk-25MTQAHX.js} +2 -2
  10. package/dist/cli-bundle/chunks/chunk-57YPOOED.js +2 -0
  11. package/dist/cli-bundle/chunks/{chunk-YEI4N4A6.js → chunk-7UDQAINZ.js} +22 -22
  12. package/dist/cli-bundle/chunks/{chunk-ZDVTXLA6.js → chunk-ER7RLJW5.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-CSE47ZAN.js → chunk-MWCG25PO.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-N6FTEILW.js +20 -0
  15. package/dist/cli-bundle/chunks/{chunk-CDR5ES7Q.js → chunk-NGKTROAO.js} +90 -86
  16. package/dist/cli-bundle/chunks/chunk-OCDRHIVQ.js +6 -0
  17. package/dist/cli-bundle/chunks/{chunk-R7KWBFM2.js → chunk-ONC4BBQP.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-URZB3USE.js → chunk-OUDR2HWR.js} +42 -42
  19. package/dist/cli-bundle/chunks/{chunk-FASDGYQC.js → chunk-T7T4WLUY.js} +3 -3
  20. package/dist/cli-bundle/chunks/{chunk-Z62RXNHW.js → chunk-TGOG5BFM.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-UF6EXZSP.js +2 -0
  22. package/dist/cli-bundle/chunks/chunk-VS2IIV3F.js +128 -0
  23. package/dist/cli-bundle/chunks/chunk-XAIR53QZ.js +2 -0
  24. package/dist/cli-bundle/chunks/{chunk-VSSHB6XI.js → chunk-Y42DYMZX.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-MA7SNKYK.js → chunk-YJBIPNDL.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-4PNAUT2E.js → chunk-Z35XAHUN.js} +2 -2
  27. package/dist/cli-bundle/chunks/chunk-ZLVFUZI4.js +30 -0
  28. package/dist/cli-bundle/chunks/{chunk-3VI4XDP2.js → chunk-ZT64RDMF.js} +2 -2
  29. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-XANVELIV.js → indexed-receipt-blobs-NWQIDTH7.js} +2 -2
  30. package/dist/cli-bundle/chunks/{mutation-admission-NVTBZ7DH.js → mutation-admission-VTNV6JV2.js} +2 -2
  31. package/dist/cli-bundle/chunks/{register-list-query-2FE6K7FQ.js → register-list-query-LZDWUZS4.js} +3 -3
  32. package/dist/cli-bundle/chunks/register-mutation-M2A7PH42.js +20 -0
  33. package/dist/cli-bundle/chunks/register-operations-E7P2JTXM.js +2 -0
  34. package/dist/cli-bundle/chunks/{register-setup-P3VLCTDY.js → register-setup-DOV7KGSH.js} +2 -2
  35. package/dist/cli-bundle/chunks/{settlement-hook-YUVCO65H.js → settlement-hook-SVD6CO7U.js} +2 -2
  36. package/dist/cli-bundle/chunks/stage-LYLEOAQB.js +2 -0
  37. package/dist/cli-bundle/focused-chunks/chunk-226XKW3W.js +8 -0
  38. package/dist/cli-bundle/focused-chunks/chunk-ABMNYWV6.js +2 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-RSEGFZTY.js → chunk-ADSBGYLW.js} +54 -54
  40. package/dist/cli-bundle/focused-chunks/{chunk-JYXA4JIP.js → chunk-B266DDBJ.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-R536272H.js → chunk-BH7RE2ZY.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/chunk-BL77VCRB.js +22 -0
  43. package/dist/cli-bundle/focused-chunks/chunk-CSCZYSNZ.js +2 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-6HJCSHBG.js → chunk-D5YQ4KAE.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-TAHSXKAT.js → chunk-E5C24MCV.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-SHUPX6G2.js → chunk-I7H3XF25.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-IF6C43IP.js +2 -0
  48. package/dist/cli-bundle/focused-chunks/chunk-KERJNFXY.js +2 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-BUZ2Z4P3.js → chunk-KTXU5WU6.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/chunk-NE27VCU7.js +91 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-NFN2P4TW.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/{chunk-7RQOFHMH.js → chunk-NLZUI234.js} +4 -4
  53. package/dist/cli-bundle/focused-chunks/chunk-PK5FJIVA.js +12 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-IUAYTD2S.js → chunk-UHWTPOM4.js} +24 -24
  55. package/dist/cli-bundle/focused-chunks/{chunk-ES2NGVHZ.js → chunk-UP765R2V.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-POLMFGPQ.js → chunk-WDWHUJQW.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-NX7TVNUM.js → chunk-YQKLKRMW.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/chunk-YTEC2EPM.js +3 -0
  59. package/dist/cli-bundle/focused-chunks/{chunk-RVUGTIIU.js → chunk-YW5GHQN2.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-FVOA3XMI.js → indexed-receipt-blobs-YFDNGHCM.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{mutation-admission-PB6YFY7S.js → mutation-admission-L42E3U5U.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{settlement-hook-2VXEB6PP.js → settlement-hook-3CADO4XZ.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/stage-TUQHWU7N.js +2 -0
  64. package/dist/cli-bundle/main.js +19 -19
  65. package/dist/cli-bundle/sdk-authoring.js +1 -1
  66. package/dist/cli-bundle/sdk-contracts.js +2 -2
  67. package/dist/cli-bundle/sdk-core.js +23 -23
  68. package/dist/cli-bundle/sdk-governance.js +1 -1
  69. package/dist/cli-bundle/sdk-graph.js +1 -1
  70. package/dist/cli-bundle/sdk-merge.js +57 -58
  71. package/dist/cli-bundle/sdk-query.js +1 -1
  72. package/dist/cli-bundle/sdk-runtime.js +1 -1
  73. package/dist/cli-bundle/sdk-testing.js +1 -1
  74. package/dist/cli-bundle/sdk.js +9 -9
  75. package/dist/core/diagnostics/remediation.js +1 -1
  76. package/dist/core/extensions/extension-types.d.ts +3 -0
  77. package/dist/core/extensions/extension-types.js +1 -1
  78. package/dist/core/output/mutation-projection.js +1 -1
  79. package/dist/core/policy/workflow-policy-store.js +1 -1
  80. package/dist/core/shared/errors.d.ts +22 -0
  81. package/dist/core/shared/errors.js +1 -1
  82. package/dist/core/shared/secret-rules.d.ts +17 -0
  83. package/dist/core/shared/secret-rules.js +2 -1
  84. package/dist/core/store/item-mutation-precondition.d.ts +8 -0
  85. package/dist/core/store/item-mutation-precondition.js +1 -1
  86. package/dist/core/store/item-store.js +1 -1
  87. package/dist/core/store/settings.js +2 -2
  88. package/dist/sdk/agent/command-recovery.js +1 -1
  89. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  90. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  91. package/dist/sdk/cli-contracts/completeness.js +1 -1
  92. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  93. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  94. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  95. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  96. package/dist/sdk/cli-contracts/registration-helpers.d.ts +3 -1
  97. package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
  98. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  99. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +4 -0
  100. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  101. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  102. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  103. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  104. package/dist/sdk/completion/fish.js +3 -1
  105. package/dist/sdk/completion/zsh.js +3 -1
  106. package/dist/sdk/context-signal-store.js +2 -2
  107. package/dist/sdk/core.d.ts +1 -1
  108. package/dist/sdk/core.js +1 -1
  109. package/dist/sdk/extension-command-context.js +2 -2
  110. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  111. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  112. package/dist/sdk/governance/health-merge-evidence.d.ts +5 -0
  113. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  114. package/dist/sdk/governance/health.js +1 -1
  115. package/dist/sdk/index.d.ts +3 -2
  116. package/dist/sdk/index.js +1 -1
  117. package/dist/sdk/item-transaction.js +1 -1
  118. package/dist/sdk/lifecycle/close-many.d.ts +3 -0
  119. package/dist/sdk/lifecycle/close-many.js +1 -1
  120. package/dist/sdk/lifecycle/close.d.ts +3 -1
  121. package/dist/sdk/lifecycle/close.js +1 -1
  122. package/dist/sdk/lifecycle/create.d.ts +2 -0
  123. package/dist/sdk/lifecycle/create.js +1 -1
  124. package/dist/sdk/lifecycle/plan.d.ts +2 -0
  125. package/dist/sdk/lifecycle/plan.js +1 -1
  126. package/dist/sdk/lifecycle/restore.js +1 -1
  127. package/dist/sdk/lifecycle-policy.d.ts +11 -0
  128. package/dist/sdk/lifecycle-policy.js +1 -1
  129. package/dist/sdk/merge/history-scalar-rebase.d.ts +9 -0
  130. package/dist/sdk/merge/history-scalar-rebase.js +2 -0
  131. package/dist/sdk/merge/ignored-artifacts.d.ts +13 -0
  132. package/dist/sdk/merge/ignored-artifacts.js +2 -0
  133. package/dist/sdk/merge/stage.js +1 -1
  134. package/dist/sdk/merge/three-way.js +1 -1
  135. package/dist/sdk/mutation-guard.d.ts +6 -1
  136. package/dist/sdk/mutation-guard.js +1 -1
  137. package/dist/sdk/output/fit-envelope.d.ts +98 -0
  138. package/dist/sdk/output/fit-envelope.js +2 -0
  139. package/dist/sdk/public-surface.json +1 -1
  140. package/dist/sdk/query/activity.d.ts +14 -2
  141. package/dist/sdk/query/activity.js +1 -1
  142. package/dist/sdk/query/calendar.d.ts +16 -0
  143. package/dist/sdk/query/calendar.js +3 -3
  144. package/dist/sdk/query/context.js +2 -2
  145. package/dist/sdk/query/get.js +1 -1
  146. package/dist/sdk/query/list.js +1 -1
  147. package/dist/sdk/query/search-contracts.js +1 -1
  148. package/dist/sdk/query/window-pagination.d.ts +20 -0
  149. package/dist/sdk/query/window-pagination.js +2 -0
  150. package/dist/sdk/query.d.ts +1 -0
  151. package/dist/sdk/query.js +1 -1
  152. package/dist/sdk/read-output-contracts.js +1 -1
  153. package/dist/sdk/read-output-session.d.ts +1 -1
  154. package/dist/sdk/read-output-session.js +1 -1
  155. package/dist/sdk/runtime-input.js +1 -1
  156. package/dist/sdk/runtime-primitives.d.ts +1 -1
  157. package/dist/sdk/runtime-primitives.js +1 -1
  158. package/dist/sdk/runtime.d.ts +3 -3
  159. package/dist/sdk/runtime.js +1 -1
  160. package/dist/sdk/scheduling-shortcuts.d.ts +2 -0
  161. package/dist/sdk/scheduling-shortcuts.js +1 -1
  162. package/dist/sdk/schema-migration.js +2 -2
  163. package/dist/sdk/templates.d.ts +7 -1
  164. package/dist/sdk/templates.js +2 -2
  165. package/dist/sdk/workspace-transaction.d.ts +3 -1
  166. package/dist/sdk/workspace-transaction.js +2 -2
  167. package/docs/COMMANDS.md +21 -2
  168. package/docs/EXTENSIONS.md +1 -1
  169. package/docs/MERGE_SAFETY.md +28 -0
  170. package/docs/MUTATION_INTEGRITY.md +33 -0
  171. package/docs/QUALITY_EVIDENCE.md +9 -0
  172. package/docs/READ_OUTPUT_CONTRACTS.md +55 -1
  173. package/docs/SDK.md +173 -12
  174. package/docs/WORKFLOW_POLICIES.md +14 -1
  175. package/docs/agent-task-token-baseline.json +1 -1
  176. package/docs/agent-task-transcripts.json +1 -1
  177. package/docs/generated/FLAG_LEXICON_BUDGETS.md +4 -4
  178. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  179. package/marketplace.json +1 -1
  180. package/package.json +1 -1
  181. package/packages/pm-beads/package.json +1 -1
  182. package/packages/pm-calendar/extensions/calendar/index.ts +6 -0
  183. package/packages/pm-calendar/extensions/calendar/shortcuts.ts +2 -2
  184. package/packages/pm-calendar/package.json +1 -1
  185. package/packages/pm-command-kit/package.json +1 -1
  186. package/packages/pm-digital-twin/package.json +1 -1
  187. package/packages/pm-governance-audit/package.json +1 -1
  188. package/packages/pm-guide-shell/package.json +1 -1
  189. package/packages/pm-kanban/package.json +1 -1
  190. package/packages/pm-lifecycle-hooks/package.json +1 -1
  191. package/packages/pm-linked-test-adapters/package.json +1 -1
  192. package/packages/pm-search-advanced/package.json +1 -1
  193. package/packages/pm-templates/extensions/templates/runtime.ts +3 -1
  194. package/packages/pm-templates/package.json +1 -1
  195. package/packages/pm-todos/package.json +1 -1
  196. package/packages/pm-vcs/package.json +1 -1
  197. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  198. package/plugins/pm-claude/package.json +1 -1
  199. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  200. package/plugins/pm-codex/package.json +1 -1
  201. package/plugins/pm-codex/plugin.json +1 -1
  202. package/runtime-dependencies.json +1 -1
  203. package/dist/cli-bundle/chunks/chunk-CNEUJHA4.js +0 -2
  204. package/dist/cli-bundle/chunks/chunk-HZNFNETE.js +0 -127
  205. package/dist/cli-bundle/chunks/chunk-KGZGXC7T.js +0 -30
  206. package/dist/cli-bundle/chunks/chunk-TZYQ4JDZ.js +0 -6
  207. package/dist/cli-bundle/chunks/chunk-UY5UHI4I.js +0 -2
  208. package/dist/cli-bundle/chunks/chunk-VPMQEVU6.js +0 -20
  209. package/dist/cli-bundle/chunks/register-mutation-KZXQUZUH.js +0 -20
  210. package/dist/cli-bundle/chunks/register-operations-BOCBWNKJ.js +0 -2
  211. package/dist/cli-bundle/chunks/stage-WRDTMCCF.js +0 -2
  212. package/dist/cli-bundle/focused-chunks/chunk-3QYTS4OY.js +0 -12
  213. package/dist/cli-bundle/focused-chunks/chunk-5MKNVJCM.js +0 -2
  214. package/dist/cli-bundle/focused-chunks/chunk-AGCEWJ27.js +0 -21
  215. package/dist/cli-bundle/focused-chunks/chunk-CEEOWDB7.js +0 -8
  216. package/dist/cli-bundle/focused-chunks/chunk-GXAXDPD4.js +0 -2
  217. package/dist/cli-bundle/focused-chunks/chunk-NFFPNMTH.js +0 -2
  218. package/dist/cli-bundle/focused-chunks/chunk-SBJ2IKTH.js +0 -3
  219. package/dist/cli-bundle/focused-chunks/chunk-X5YRJMAY.js +0 -2
  220. package/dist/cli-bundle/focused-chunks/chunk-XTYEASIY.js +0 -2
  221. package/dist/cli-bundle/focused-chunks/chunk-ZMWLV2CE.js +0 -91
  222. package/dist/cli-bundle/focused-chunks/stage-MQE4PFWT.js +0 -2
@@ -16,6 +16,8 @@ from?:string;
16
16
  to?:string;
17
17
  /** Value that configures or reports limit for this contract. */
18
18
  limit?:string;
19
+ /** Continue the original fixed-window query with its opaque producer cursor. */
20
+ after?:string;
19
21
  /** Value that configures or reports compact for this contract. */
20
22
  compact?:boolean;
21
23
  /** Return the legacy per-event stream instead of the item-centric digest. */
@@ -101,9 +103,19 @@ count:number;
101
103
  total_count:number;
102
104
  /** Value that configures or reports limit for this contract. */
103
105
  limit:number | null;
104
- /** Number of matching rows withheld by the applied bound. */
106
+ /** Zero-based position of the first returned row in the matching set. */
107
+ page_start:number;
108
+ /** Fixed evaluation clock and normalized inclusive/exclusive time bounds. */
109
+ window:{
110
+ anchor:string;
111
+ from:string | null;
112
+ to:string | null;
113
+ };
114
+ /** Opaque producer cursor; repeat the same query with after to continue. */
115
+ next_cursor?:string;
116
+ /** Number of matching rows remaining after this page. */
105
117
  omitted_count:number;
106
- /** Whether matching rows remain available through a larger or unbounded request. */
118
+ /** Whether a subsequent bounded page is available. */
107
119
  has_more:boolean;
108
120
  /** Describes whether the effective bound came from a default, caller input, or an explicit opt-out. */
109
121
  applied_bound:{
@@ -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]="a4394793-55d4-5049-ab20-707c1c3d9f2c")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isFileMissingError}from"../../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{getActiveExtensionRegistrations,runActiveOnReadHooks,enforceHistoryStreamPolicyForItems,resolveItemTypeRegistry,EXIT_CODE,PmCliError,compareTimestampStrings,nowIso,resolveIsoOrRelative,listAllItemMetadataLight,resolvePmRoot,readSettings}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{parseLimit}from"./parsers.js";import{resolveModePairedOutputOmissionReceipt}from"../output-projection.js";import{compileHistoryProvenanceMatcher,projectHistoryProvenance,resolveHistoryProvenanceDimensions,summarizeHistoryProvenance}from"../history-provenance.js";const DEFAULT_COMPACT_ACTIVITY_LIMIT=20,DEFAULT_FULL_ACTIVITY_LIMIT=5,DEFAULT_DIGEST_ACTIVITY_LIMIT=15,DEFAULT_DIGEST_WINDOW="-24h";function normalizeActivityProjectionOptions(options){const normalized={...options};return normalized.full===!0?(normalized.raw=!0,normalized.compact=!1):normalized.raw===!0&&normalized.compact===void 0&&(normalized.compact=!0),delete normalized.full,normalized}const ACTIVITY_ROW_KEY_BY_MODE={digest:"activity_digest",compact:"compact_activity",provenance:"provenance_activity",full:"activity"};function parseNonEmptyFilter(raw,flagLabel){if(raw===void 0)return;const normalized=raw.trim();if(normalized.length===0)throw new PmCliError(`${flagLabel} must not be empty`,EXIT_CODE.USAGE);return normalized}function parseRangeBound(raw,nowValue,fieldLabel){if(raw===void 0)return;const normalized=raw.trim();if(normalized.length===0)throw new PmCliError("Activity time bounds must not be empty",EXIT_CODE.USAGE);const relativeInput=fieldLabel==="--from"&&/^\d+[hdwm]$/iu.test(normalized)?`-${normalized}`:normalized;return resolveIsoOrRelative(relativeInput,new Date(nowValue),fieldLabel)}function includeByTimeWindow(entry,from,to){return!(entry.ts.length===0&&(from||to)||from&&compareTimestampStrings(entry.ts,from)<0||to&&compareTimestampStrings(entry.ts,to)>=0)}function limitEntries(values,limit){return limit===void 0?values:values.slice(0,limit)}function readActivityString(value,fallback=""){return typeof value=="string"?value:fallback}function normalizeActivityEntry(id,entry){return{...entry,id,ts:readActivityString(entry.ts),author:readActivityString(entry.author,"unknown"),op:readActivityString(entry.op,"unknown"),patch:Array.isArray(entry.patch)?entry.patch:[],before_hash:readActivityString(entry.before_hash),after_hash:readActivityString(entry.after_hash)}}function sortActivity(entries){return[...entries].sort((a,b)=>{const byTimestamp=b.ts.localeCompare(a.ts);if(byTimestamp!==0)return byTimestamp;const byId=a.id.localeCompare(b.id);return byId!==0?byId:a.op.localeCompare(b.op)})}async function listHistoryFiles(historyDir){try{return(await fs.readdir(historyDir)).filter(entry=>entry.endsWith(".jsonl")).sort((a,b)=>a.localeCompare(b))}catch(error){if(isFileMissingError(error))return[];throw error}}function resolveActivityProjectionMode(options){return options.raw!==!0&&options.compact!==!0&&options.provenance!==!0?"digest":options.provenance===!0?"provenance":options.compact===!0||options.raw===!0&&options.compact!==!1?"compact":"full"}function resolveActivityLimit(options,explicitLimit,projectionMode){if(options.unbounded!==!0)return explicitLimit!==void 0?explicitLimit:projectionMode==="digest"?DEFAULT_DIGEST_ACTIVITY_LIMIT:projectionMode==="compact"?DEFAULT_COMPACT_ACTIVITY_LIMIT:DEFAULT_FULL_ACTIVITY_LIMIT}function resolveActivityFilters(options,projectionMode){const nowValue=nowIso(),digest=projectionMode==="digest",to=parseRangeBound(options.to??(digest?nowValue:void 0),nowValue,"--to"),from=parseRangeBound(options.from??(digest?DEFAULT_DIGEST_WINDOW:void 0),options.from===void 0&&digest?to:nowValue,"--from");if(from&&to&&compareTimestampStrings(from,to)>=0)throw new PmCliError("Activity --from must be before --to",EXIT_CODE.USAGE);const explicitLimit=parseLimit(options.limit);if(options.unbounded===!0&&explicitLimit!==void 0)throw new PmCliError("Activity --unbounded cannot be combined with --limit",EXIT_CODE.USAGE);return{id:parseNonEmptyFilter(options.id,"Activity --id"),op:parseNonEmptyFilter(options.op,"Activity --op"),author:parseNonEmptyFilter(options.author,"Activity --author"),from,to,limit:resolveActivityLimit(options,explicitLimit,projectionMode),limitSource:options.unbounded===!0||explicitLimit!==void 0?"explicit":"default",harness:options.harness,agentInstance:options.agentInstance,provenance:options.provenanceFilter}}async function resolveActivityRuntimeContext(global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);return await assertInitializedTracker(pmRoot),{pmRoot,settings:await readSettings(pmRoot)}}async function prepareActivityHistoryRead(context){const typeRegistry=resolveItemTypeRegistry(context.settings,getActiveExtensionRegistrations()),items=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,typeRegistry.type_to_folder,void 0,context.settings.schema);await enforceHistoryStreamPolicyForItems({pmRoot:context.pmRoot,settings:context.settings,itemIds:items.map(item=>item.id),commandLabel:"activity"});const historyDir=path.join(context.pmRoot,"history");return await runActiveOnReadHooks({path:historyDir,scope:"project"}),{historyDir,itemsById:new Map(items.map(item=>[item.id,{title:item.title,type:item.type,status:item.status}]))}}function includeActivityEntry(entry,candidate,filters){return filters.op&&entry.op!==filters.op||filters.author&&entry.author!==filters.author?!1:includeByTimeWindow(candidate,filters.from,filters.to)}async function collectActivityEntries(historyDir,filters){const combined=[];for(const file of await listHistoryFiles(historyDir)){const id=file.slice(0,-6);if(filters.id&&id!==filters.id)continue;const entries=await readHistoryEntries(path.join(historyDir,file),id);for(const entry of entries){const candidate=normalizeActivityEntry(id,entry);includeActivityEntry(entry,candidate,filters)&&combined.push(candidate)}}return combined}function formatCompactActivity(activity){return activity.map(entry=>({id:entry.id,op:entry.op,ts:entry.ts,author:entry.author,...entry.message?{msg:entry.message}:{}}))}function boundedOperationSummary(counts){const ordered=[...counts.entries()].sort(([leftOp,leftCount],[rightOp,rightCount])=>rightCount-leftCount||leftOp.localeCompare(rightOp)),visible=ordered.slice(0,4).map(([op,count])=>`${op}:${count}`);return ordered.length>visible.length&&visible.push(`+${ordered.length-visible.length}`),visible.join(",")}function buildActivityDigest(activity,itemsById){const grouped=new Map;for(const entry of activity){const current=grouped.get(entry.id);if(current===void 0){grouped.set(entry.id,{firstTs:entry.ts,lastTs:entry.ts,eventCount:1,operations:new Map([[entry.op,1]])});continue}current.eventCount+=1,compareTimestampStrings(entry.ts,current.firstTs)<0&&(current.firstTs=entry.ts),compareTimestampStrings(entry.ts,current.lastTs)>0&&(current.lastTs=entry.ts),current.operations.set(entry.op,(current.operations.get(entry.op)??0)+1)}return[...grouped.entries()].map(([id,summary])=>{const item=itemsById.get(id);return{id,type:item?.type??"unknown",status:item?.status??"unknown",title:(item?.title??"(item metadata unavailable)").slice(0,160),event_count:summary.eventCount,first_ts:summary.firstTs,last_ts:summary.lastTs,operations:boundedOperationSummary(summary.operations)}}).sort((left,right)=>compareTimestampStrings(right.last_ts,left.last_ts)||left.id.localeCompare(right.id))}function activityOperationCounts(activity){const counts=new Map;for(const entry of activity)counts.set(entry.op,(counts.get(entry.op)??0)+1);const ordered=[...counts.entries()].sort((left,right)=>right[1]-left[1]||left[0].localeCompare(right[0])),visible=ordered.slice(0,8);return visible.length<ordered.length&&visible.push([`+${String(ordered.length-visible.length)}`,ordered.slice(visible.length).reduce((total,[,count])=>total+count,0)]),Object.fromEntries(visible)}function projectActivityRows(projectionMode,matchingActivity,limit,itemsById,projectProvenance){if(projectionMode==="digest"){const matchingDigest=buildActivityDigest(matchingActivity,itemsById),activityDigest=limitEntries(matchingDigest,limit);return{rows:{activity_digest:activityDigest},compact:!1,totalRows:matchingDigest.length,returnedRows:activityDigest.length}}const activity=limitEntries(matchingActivity,limit);return projectionMode==="compact"?{rows:{compact_activity:formatCompactActivity(activity)},compact:!0,totalRows:matchingActivity.length,returnedRows:activity.length}:projectionMode==="provenance"?{rows:{provenance_activity:activity.map(projectProvenance)},compact:!1,totalRows:matchingActivity.length,returnedRows:activity.length}:{rows:{activity},compact:!1,totalRows:matchingActivity.length,returnedRows:activity.length}}const _testOnly={parseNonEmptyFilter,parseRangeBound,includeByTimeWindow,limitEntries,readActivityString,normalizeActivityEntry,sortActivity,listHistoryFiles,buildActivityDigest,activityOperationCounts};async function runActivity(options,global2){const context=await resolveActivityRuntimeContext(global2),projectionMode=resolveActivityProjectionMode(options),filters=resolveActivityFilters(options,projectionMode),prepared=await prepareActivityHistoryRead(context),provenanceDimensions=resolveHistoryProvenanceDimensions(context.settings.agent_identity.harness_signals),vocabulary=context.settings.agent_identity.identity_vocabulary,matchesProvenance=compileHistoryProvenanceMatcher({harness:filters.harness,agentInstance:filters.agentInstance,provenance:filters.provenance},vocabulary,provenanceDimensions),matchingActivity=sortActivity(await collectActivityEntries(prepared.historyDir,filters)).filter(matchesProvenance),projected=projectActivityRows(projectionMode,matchingActivity,filters.limit,prepared.itemsById,entry=>projectHistoryProvenance(entry,vocabulary,{itemId:entry.id})),omittedCount=projected.totalRows-projected.returnedRows;return{...projected.rows,compact:projected.compact,projection:{mode:projectionMode,row_key:ACTIVITY_ROW_KEY_BY_MODE[projectionMode]},omission_receipt:resolveModePairedOutputOmissionReceipt("activity",projectionMode),count:projected.returnedRows,total_count:projected.totalRows,limit:filters.limit??null,omitted_count:omittedCount,has_more:omittedCount>0,...projectionMode==="digest"?{activity_summary:{window:{from:filters.from,to:filters.to},event_count:matchingActivity.length,item_count:projected.totalRows,author_count:new Set(matchingActivity.map(entry=>entry.author)).size,operation_counts:activityOperationCounts(matchingActivity)}}:{},...options.provenanceSummary===!0?{provenance_summary:summarizeHistoryProvenance(matchingActivity,vocabulary,provenanceDimensions)}:{},applied_bound:{kind:filters.limit===void 0?"unbounded":"limit",source:filters.limitSource,value:filters.limit??null}}}export{_testOnly,normalizeActivityProjectionOptions,runActivity};
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]="aa1ede64-e578-57da-9194-1cd646cee915")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isFileMissingError}from"../../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{getActiveExtensionRegistrations,runActiveOnReadHooks,enforceHistoryStreamPolicyForItems,resolveItemTypeRegistry,EXIT_CODE,PmCliError,compareTimestampStrings,resolveIsoOrRelative,listAllItemMetadataLight,resolvePmRoot,readSettings}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{parseLimit}from"./parsers.js";import{fingerprintWindowRows,paginateWindowQuery,resolveWindowQueryClock}from"./window-pagination.js";import{resolveModePairedOutputOmissionReceipt}from"../output-projection.js";import{compileHistoryProvenanceMatcher,projectHistoryProvenance,resolveHistoryProvenanceDimensions,summarizeHistoryProvenance}from"../history-provenance.js";const DEFAULT_COMPACT_ACTIVITY_LIMIT=20,DEFAULT_FULL_ACTIVITY_LIMIT=5,DEFAULT_DIGEST_ACTIVITY_LIMIT=15,DEFAULT_DIGEST_WINDOW="-24h";function normalizeActivityProjectionOptions(options){const normalized={...options};return normalized.full===!0?(normalized.raw=!0,normalized.compact=!1):normalized.raw===!0&&normalized.compact===void 0&&(normalized.compact=!0),delete normalized.full,normalized}const ACTIVITY_ROW_KEY_BY_MODE={digest:"activity_digest",compact:"compact_activity",provenance:"provenance_activity",full:"activity"};function parseNonEmptyFilter(raw,flagLabel){if(raw===void 0)return;const normalized=raw.trim();if(normalized.length===0)throw new PmCliError(`${flagLabel} must not be empty`,EXIT_CODE.USAGE);return normalized}function parseRangeBound(raw,nowValue,fieldLabel){if(raw===void 0)return;const normalized=raw.trim();if(normalized.length===0)throw new PmCliError("Activity time bounds must not be empty",EXIT_CODE.USAGE);const relativeInput=fieldLabel==="--from"&&/^\d+[hdwm]$/iu.test(normalized)?`-${normalized}`:normalized;return resolveIsoOrRelative(relativeInput,new Date(nowValue),fieldLabel)}function includeByTimeWindow(entry,from,to){return!(entry.ts.length===0&&(from||to)||from&&compareTimestampStrings(entry.ts,from)<0||to&&compareTimestampStrings(entry.ts,to)>=0)}function limitEntries(values,limit){return limit===void 0?values:values.slice(0,limit)}function readActivityString(value,fallback=""){return typeof value=="string"?value:fallback}function normalizeActivityEntry(id,entry){return{...entry,id,ts:readActivityString(entry.ts),author:readActivityString(entry.author,"unknown"),op:readActivityString(entry.op,"unknown"),patch:Array.isArray(entry.patch)?entry.patch:[],before_hash:readActivityString(entry.before_hash),after_hash:readActivityString(entry.after_hash)}}function sortActivity(entries){return[...entries].sort((a,b)=>{const byTimestamp=b.ts.localeCompare(a.ts);if(byTimestamp!==0)return byTimestamp;const byId=a.id.localeCompare(b.id);return byId!==0?byId:a.op.localeCompare(b.op)})}async function listHistoryFiles(historyDir){try{return(await fs.readdir(historyDir)).filter(entry=>entry.endsWith(".jsonl")).sort((a,b)=>a.localeCompare(b))}catch(error){if(isFileMissingError(error))return[];throw error}}function resolveActivityProjectionMode(options){return options.raw!==!0&&options.compact!==!0&&options.provenance!==!0?"digest":options.provenance===!0?"provenance":options.compact===!0||options.raw===!0&&options.compact!==!1?"compact":"full"}function resolveActivityLimit(options,explicitLimit,projectionMode){if(options.unbounded!==!0)return explicitLimit!==void 0?explicitLimit:projectionMode==="digest"?DEFAULT_DIGEST_ACTIVITY_LIMIT:projectionMode==="compact"?DEFAULT_COMPACT_ACTIVITY_LIMIT:DEFAULT_FULL_ACTIVITY_LIMIT}function resolveActivityFilters(options,projectionMode,nowValue){const digest=projectionMode==="digest",to=parseRangeBound(options.to??(digest||options.unbounded!==!0?nowValue:void 0),nowValue,"--to"),from=parseRangeBound(options.from??(digest?DEFAULT_DIGEST_WINDOW:void 0),options.from===void 0&&digest?to:nowValue,"--from");if(from&&to&&compareTimestampStrings(from,to)>=0)throw new PmCliError("Activity --from must be before --to",EXIT_CODE.USAGE);const explicitLimit=parseLimit(options.limit);if(options.unbounded===!0&&explicitLimit!==void 0)throw new PmCliError("Activity --unbounded cannot be combined with --limit",EXIT_CODE.USAGE);return{id:parseNonEmptyFilter(options.id,"Activity --id"),op:parseNonEmptyFilter(options.op,"Activity --op"),author:parseNonEmptyFilter(options.author,"Activity --author"),from,to,limit:resolveActivityLimit(options,explicitLimit,projectionMode),limitSource:options.unbounded===!0||explicitLimit!==void 0?"explicit":"default",harness:options.harness,agentInstance:options.agentInstance,provenance:options.provenanceFilter}}async function resolveActivityRuntimeContext(global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);return await assertInitializedTracker(pmRoot),{pmRoot,settings:await readSettings(pmRoot)}}async function prepareActivityHistoryRead(context){const typeRegistry=resolveItemTypeRegistry(context.settings,getActiveExtensionRegistrations()),items=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,typeRegistry.type_to_folder,void 0,context.settings.schema);await enforceHistoryStreamPolicyForItems({pmRoot:context.pmRoot,settings:context.settings,itemIds:items.map(item=>item.id),commandLabel:"activity"});const historyDir=path.join(context.pmRoot,"history");return await runActiveOnReadHooks({path:historyDir,scope:"project"}),{historyDir,itemsById:new Map(items.map(item=>[item.id,{title:item.title,type:item.type,status:item.status}]))}}function includeActivityEntry(entry,candidate,filters){return filters.op&&entry.op!==filters.op||filters.author&&entry.author!==filters.author?!1:includeByTimeWindow(candidate,filters.from,filters.to)}async function collectActivityEntries(historyDir,filters){const combined=[];for(const file of await listHistoryFiles(historyDir)){const id=file.slice(0,-6);if(filters.id&&id!==filters.id)continue;const entries=await readHistoryEntries(path.join(historyDir,file),id);for(const entry of entries){const candidate=normalizeActivityEntry(id,entry);includeActivityEntry(entry,candidate,filters)&&combined.push(candidate)}}return combined}function formatCompactActivity(activity){return activity.map(entry=>({id:entry.id,op:entry.op,ts:entry.ts,author:entry.author,...entry.message?{msg:entry.message}:{}}))}function boundedOperationSummary(counts){const ordered=[...counts.entries()].sort(([leftOp,leftCount],[rightOp,rightCount])=>rightCount-leftCount||leftOp.localeCompare(rightOp)),visible=ordered.slice(0,4).map(([op,count])=>`${op}:${count}`);return ordered.length>visible.length&&visible.push(`+${ordered.length-visible.length}`),visible.join(",")}function buildActivityDigest(activity,itemsById){const grouped=new Map;for(const entry of activity){const current=grouped.get(entry.id);if(current===void 0){grouped.set(entry.id,{firstTs:entry.ts,lastTs:entry.ts,eventCount:1,operations:new Map([[entry.op,1]])});continue}current.eventCount+=1,compareTimestampStrings(entry.ts,current.firstTs)<0&&(current.firstTs=entry.ts),compareTimestampStrings(entry.ts,current.lastTs)>0&&(current.lastTs=entry.ts),current.operations.set(entry.op,(current.operations.get(entry.op)??0)+1)}return[...grouped.entries()].map(([id,summary])=>{const item=itemsById.get(id);return{id,type:item?.type??"unknown",status:item?.status??"unknown",title:(item?.title??"(item metadata unavailable)").slice(0,160),event_count:summary.eventCount,first_ts:summary.firstTs,last_ts:summary.lastTs,operations:boundedOperationSummary(summary.operations)}}).sort((left,right)=>compareTimestampStrings(right.last_ts,left.last_ts)||left.id.localeCompare(right.id))}function activityOperationCounts(activity){const counts=new Map;for(const entry of activity)counts.set(entry.op,(counts.get(entry.op)??0)+1);const ordered=[...counts.entries()].sort((left,right)=>right[1]-left[1]||left[0].localeCompare(right[0])),visible=ordered.slice(0,8);return visible.length<ordered.length&&visible.push([`+${String(ordered.length-visible.length)}`,ordered.slice(visible.length).reduce((total,[,count])=>total+count,0)]),Object.fromEntries(visible)}function projectActivityRows(projectionMode,matchingActivity,pageOptions,itemsById,projectProvenance){if(projectionMode==="digest"){const{rows,...page2}=paginateWindowQuery(buildActivityDigest(matchingActivity,itemsById),pageOptions);return{rows:{activity_digest:rows},compact:!1,page:page2}}const{rows:activity,...page}=paginateWindowQuery(matchingActivity,pageOptions);return projectionMode==="compact"?{rows:{compact_activity:formatCompactActivity(activity)},compact:!0,page}:projectionMode==="provenance"?{rows:{provenance_activity:activity.map(projectProvenance)},compact:!1,page}:{rows:{activity},compact:!1,page}}const _testOnly={parseNonEmptyFilter,parseRangeBound,includeByTimeWindow,limitEntries,readActivityString,normalizeActivityEntry,sortActivity,listHistoryFiles,buildActivityDigest,activityOperationCounts};async function runActivity(options,global2){const context=await resolveActivityRuntimeContext(global2),projectionMode=resolveActivityProjectionMode(options),clock=resolveWindowQueryClock("activity",options.after),filters=resolveActivityFilters(options,projectionMode,clock),prepared=await prepareActivityHistoryRead(context),provenanceDimensions=resolveHistoryProvenanceDimensions(context.settings.agent_identity.harness_signals),vocabulary=context.settings.agent_identity.identity_vocabulary,matchesProvenance=compileHistoryProvenanceMatcher({harness:filters.harness,agentInstance:filters.agentInstance,provenance:filters.provenance},vocabulary,provenanceDimensions),matchingActivity=sortActivity(await collectActivityEntries(prepared.historyDir,filters)).filter(matchesProvenance),projected=projectActivityRows(projectionMode,matchingActivity,{command:"activity",after:options.after,clock,limit:filters.limit,query:{pmRoot:context.pmRoot,projectionMode,filters:{...filters,limit:void 0,limitSource:void 0},matching_activity_digest:projectionMode==="digest"?fingerprintWindowRows(matchingActivity):void 0,vocabulary,provenanceDimensions}},prepared.itemsById,entry=>projectHistoryProvenance(entry,vocabulary,{itemId:entry.id}));return{...projected.rows,compact:projected.compact,projection:{mode:projectionMode,row_key:ACTIVITY_ROW_KEY_BY_MODE[projectionMode]},omission_receipt:resolveModePairedOutputOmissionReceipt("activity",projectionMode),...projected.page,window:{anchor:clock,from:filters.from??null,to:filters.to??null},limit:filters.limit??null,...projectionMode==="digest"?{activity_summary:{window:{from:filters.from,to:filters.to},event_count:matchingActivity.length,item_count:projected.page.total_count,author_count:new Set(matchingActivity.map(entry=>entry.author)).size,operation_counts:activityOperationCounts(matchingActivity)}}:{},...options.provenanceSummary===!0?{provenance_summary:summarizeHistoryProvenance(matchingActivity,vocabulary,provenanceDimensions)}:{},applied_bound:{kind:filters.limit===void 0?"unbounded":"limit",source:filters.limitSource,value:filters.limit??null}}}export{_testOnly,normalizeActivityProjectionOptions,runActivity};
2
2
  //# sourceMappingURL=activity.js.map
@@ -22,6 +22,8 @@ past?:boolean;
22
22
  fullPeriod?:boolean;
23
23
  /** Value that configures or reports limit for this contract. */
24
24
  limit?:string;
25
+ /** Continue the original calendar query with its opaque producer cursor. */
26
+ after?:string;
25
27
  /** Schema type that determines the shape and validation rules for this value. */
26
28
  type?:string;
27
29
  /** Value that configures or reports tag for this contract. */
@@ -155,6 +157,20 @@ by_type:Record<string,number>;
155
157
  by_status:Record<string,number>;
156
158
  recurring_events:number;
157
159
  };
160
+ /** Matching calendar rows before pagination and within recurrence expansion caps. */
161
+ total_count:number;
162
+ /** Rows returned by this page. */
163
+ count:number;
164
+ /** Zero-based position of this page in the matching set. */
165
+ page_start:number;
166
+ /** Matching rows remaining after this page. */
167
+ omitted_count:number;
168
+ /** Whether another bounded page exists. */
169
+ has_more:boolean;
170
+ /** Opaque producer cursor accepted by CalendarOptions.after. */
171
+ next_cursor?:string;
172
+ /** Summary and day buckets describe only the returned rows. */
173
+ summary_scope:"returned_rows";
158
174
  /** Value that configures or reports events for this contract. */
159
175
  events:CalendarRow[];
160
176
  /** Value that configures or reports days for this contract. */
@@ -1,5 +1,5 @@
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]="809a4d75-4915-585d-9fc8-ad3e9ef15b1f")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{encode as encodeToon}from"@toon-format/toon";import{getActiveExtensionRegistrations,resolveItemTypeRegistry,normalizeStatusInput,collectRuntimeFilterValues,matchesRuntimeFilters,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,PmCliError,levenshteinDistanceWithinLimit,compareTimestampStrings,nowIso,resolveIsoOrRelative,listAllItemMetadataLight,resolvePmRoot,readSettings}from"../runtime-primitives.js";import{parseIntegerLimit,parsePriority,parseType}from"./parsers.js";import{weekdayOrderIndex}from"../../types/index.js";const CALENDAR_VIEW_VALUES=["agenda","day","week","month"],CALENDAR_OUTPUT_VALUES=["markdown","toon","json"],UTC_DAY_TO_WEEKDAY=["sun","mon","tue","wed","thu","fri","sat"],DEFAULT_RECURRENCE_LOOKAHEAD_DAYS=365,DEFAULT_RECURRENCE_LOOKBACK_DAYS=365,DEFAULT_EVENTS_ONLY_LOOKAHEAD_DAYS=28,MAX_RECURRENCE_OCCURRENCES=1e3;function parseNonNegativeInteger(raw,label){if(raw===void 0)return;const parsed=Number(raw);if(!Number.isInteger(parsed)||parsed<0)throw new PmCliError(`${label} must be a non-negative integer`,EXIT_CODE.USAGE);return parsed}function parseIncludeSources(raw){if(!raw)return new Set(["deadlines","reminders","events"]);const normalized=raw.trim().toLowerCase();if(normalized==="all")return new Set(["deadlines","reminders","events"]);const values=normalized.split(/[|,]/).map(value=>value.trim()).filter(value=>value.length>0);if(values.length===0)throw new PmCliError("Calendar include filter must not be empty",EXIT_CODE.USAGE);const include=new Set;for(const value of values){if(value==="deadlines"||value==="deadline"){include.add("deadlines");continue}if(value==="reminders"||value==="reminder"){include.add("reminders");continue}if(value==="events"||value==="event"||value==="scheduled"){include.add("events");continue}throw new PmCliError("Calendar include filter must be deadlines|reminders|events|scheduled|all",EXIT_CODE.USAGE)}return include}function suggestClosestChoice(value,choices){let best;for(const choice of choices){const distance=levenshteinDistanceWithinLimit(value,choice,2);distance!==null&&(best===void 0||distance<best.distance)&&(best={choice,distance})}return best?.choice}function parseView(raw){if(!raw)return"agenda";const normalized=raw.trim().toLowerCase();if(!CALENDAR_VIEW_VALUES.includes(normalized)){const suggestion=suggestClosestChoice(normalized,CALENDAR_VIEW_VALUES);throw new PmCliError(`Calendar view must be one of ${CALENDAR_VIEW_VALUES.join("|")}${suggestion?`. Did you mean "${suggestion}"?`:"."}`,EXIT_CODE.USAGE)}return normalized}function parseOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!CALENDAR_OUTPUT_VALUES.includes(normalized)){const suggestion=suggestClosestChoice(normalized,CALENDAR_OUTPUT_VALUES);throw new PmCliError(`Calendar format must be one of ${CALENDAR_OUTPUT_VALUES.join("|")}${suggestion?`. Did you mean "${suggestion}"?`:"."}`,EXIT_CODE.USAGE)}return normalized}function resolveCalendarOutputFormat(options,global2){const commandFormat=parseOutputFormat(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??"markdown"}function parseStatus(raw,statusRegistry){if(raw===void 0)return;const normalized=normalizeStatusInput(raw,statusRegistry);if(!normalized){const allowedStatuses=statusRegistry.definitions.map(definition=>definition.id);throw new PmCliError(`Calendar status filter must be one of ${allowedStatuses.join("|")}`,EXIT_CODE.USAGE)}return normalized}function parseAssigneeFilter(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(!normalized)throw new PmCliError("Calendar assignee filter must be one of assigned|unassigned",EXIT_CODE.USAGE);if(normalized!=="assigned"&&normalized!=="unassigned")throw new PmCliError(`Invalid calendar assignee filter "${raw}". Allowed: assigned|unassigned`,EXIT_CODE.USAGE);return normalized}function toUtcDayKey(timestamp){return new Date(timestamp).toISOString().slice(0,10)}function toLocalDayKey(timestamp,timezone){if(!timezone||timezone==="UTC")return toUtcDayKey(timestamp);try{const parts=new Intl.DateTimeFormat("en-CA",{timeZone:timezone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(timestamp)),year=parts.find(part=>part.type==="year")?.value,month=parts.find(part=>part.type==="month")?.value,day=parts.find(part=>part.type==="day")?.value;if(year&&month&&day)return`${year}-${month}-${day}`}catch{}return toUtcDayKey(timestamp)}function startOfUtcDay(timestamp){const date=new Date(timestamp);return new Date(Date.UTC(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate(),0,0,0,0)).toISOString()}function addUtcDays(timestamp,days){const date=new Date(timestamp);return new Date(date.getTime()+days*24*60*60*1e3).toISOString()}function startOfUtcWeekMonday(timestamp){const base=new Date(startOfUtcDay(timestamp)),day=base.getUTCDay(),delta=day===0?-6:1-day;return addUtcDays(base.toISOString(),delta)}function startOfUtcMonth(timestamp){const date=new Date(timestamp);return new Date(Date.UTC(date.getUTCFullYear(),date.getUTCMonth(),1,0,0,0,0)).toISOString()}function startOfNextUtcMonth(timestamp){const date=new Date(timestamp);return new Date(Date.UTC(date.getUTCFullYear(),date.getUTCMonth()+1,1,0,0,0,0)).toISOString()}function maxTimestamp(left,right){return compareTimestampStrings(left,right)>=0?left:right}function toSortedCountRecord(values){return Object.fromEntries([...values.entries()].sort(([left],[right])=>left.localeCompare(right)))}function incrementCount(values,key){values.set(key,(values.get(key)??0)+1)}function formatRecurrenceRuleForSummary(rule){if(!rule)return null;const parts=[`freq=${rule.freq}`];if(rule.interval!==void 0&&parts.push(`interval=${rule.interval}`),rule.count!==void 0&&parts.push(`count=${rule.count}`),rule.until&&parts.push(`until=${rule.until}`),rule.by_weekday&&rule.by_weekday.length>0){const weekdays=[...rule.by_weekday].sort((left,right)=>weekdayOrderIndex(left)-weekdayOrderIndex(right));parts.push(`by_weekday=${weekdays.join("|")}`)}if(rule.by_month_day&&rule.by_month_day.length>0){const monthDays=[...rule.by_month_day].sort((left,right)=>left-right);parts.push(`by_month_day=${monthDays.join("|")}`)}if(rule.exdates&&rule.exdates.length>0){const exdates=[...rule.exdates].sort((left,right)=>left.localeCompare(right));parts.push(`exdates=${exdates.join("|")}`)}return parts.join(",")}function buildUtcTimestamp(year,month,day,timeSource){const candidate=new Date(Date.UTC(year,month,day,timeSource.getUTCHours(),timeSource.getUTCMinutes(),timeSource.getUTCSeconds(),timeSource.getUTCMilliseconds()));if(!(candidate.getUTCFullYear()!==year||candidate.getUTCMonth()!==month||candidate.getUTCDate()!==day))return candidate.toISOString()}function weekdayToken(timestamp){return UTC_DAY_TO_WEEKDAY[new Date(timestamp).getUTCDay()]}function normalizeInstantKey(timestamp){const parsed=Date.parse(timestamp);return Number.isFinite(parsed)?new Date(parsed).toISOString():null}function buildExcludedInstantSet(exdates){const excluded=new Set;for(const exdate of exdates??[]){const instantKey=normalizeInstantKey(exdate);instantKey&&excluded.add(instantKey)}return excluded}function buildRecurringEventWindow(start,end,nowValue,lookbackDays,lookaheadDays){const windowStart=start??addUtcDays(nowValue,-(lookbackDays??DEFAULT_RECURRENCE_LOOKBACK_DAYS)),windowEnd=end??addUtcDays(start??nowValue,lookaheadDays??DEFAULT_RECURRENCE_LOOKAHEAD_DAYS);return{start:windowStart,end:compareTimestampStrings(windowEnd,windowStart)>0?windowEnd:addUtcDays(windowStart,1)}}function buildRecurrenceExpansionContext(startAt,recurrence,window2,occurrenceLimit){const recurrenceWeekdays=recurrence.by_weekday!==void 0?[...recurrence.by_weekday]:[weekdayToken(startAt)],recurrenceMonthDays=recurrence.by_month_day!==void 0?[...recurrence.by_month_day]:[new Date(startAt).getUTCDate()];return{startAt,startDate:new Date(startAt),window:window2,maxOccurrences:occurrenceLimit??MAX_RECURRENCE_OCCURRENCES,interval:recurrence.interval??1,countLimit:recurrence.count??Number.POSITIVE_INFINITY,until:recurrence.until,excluded:buildExcludedInstantSet(recurrence.exdates),weekdayFilter:recurrence.by_weekday!==void 0?new Set(recurrence.by_weekday):void 0,monthDayFilter:recurrence.by_month_day!==void 0?new Set(recurrence.by_month_day):void 0,sortedWeekdays:[...new Set(recurrenceWeekdays)].sort((left,right)=>weekdayOrderIndex(left)-weekdayOrderIndex(right)),sortedMonthDays:[...new Set(recurrenceMonthDays)].sort((left,right)=>left-right),occurrences:[],produced:0}}function consumeRecurrenceCandidate(context,candidateAt){return compareTimestampStrings(candidateAt,context.startAt)<0?"continue":context.until&&compareTimestampStrings(candidateAt,context.until)>0||compareTimestampStrings(candidateAt,context.window.end)>=0?"stop":context.excluded.has(candidateAt)?"continue":(context.produced+=1,compareTimestampStrings(candidateAt,context.window.start)>=0&&context.occurrences.push(candidateAt),context.produced>=context.countLimit||context.occurrences.length>=context.maxOccurrences?"stop":"continue")}function recurrenceDayMatchesFilters(context,candidateAt){const candidateWeekday=weekdayToken(candidateAt),candidateMonthDay=new Date(candidateAt).getUTCDate(),weekdayMatches=!context.weekdayFilter||context.weekdayFilter.has(candidateWeekday),monthDayMatches=!context.monthDayFilter||context.monthDayFilter.has(candidateMonthDay);return weekdayMatches&&monthDayMatches}function expandDailyOccurrences(context){let candidateAt=context.startAt;for(let iteration=0;iteration<context.maxOccurrences&&!(recurrenceDayMatchesFilters(context,candidateAt)&&consumeRecurrenceCandidate(context,candidateAt)==="stop");iteration+=1)candidateAt=addUtcDays(candidateAt,context.interval);return context.occurrences}function buildWeeklyCandidateAt(context,candidateWeekStart,weekday){const dayOffset=weekdayOrderIndex(weekday),candidateDay=addUtcDays(candidateWeekStart,dayOffset),dayDate=new Date(candidateDay);return new Date(Date.UTC(dayDate.getUTCFullYear(),dayDate.getUTCMonth(),dayDate.getUTCDate(),context.startDate.getUTCHours(),context.startDate.getUTCMinutes(),context.startDate.getUTCSeconds(),context.startDate.getUTCMilliseconds())).toISOString()}function expandWeeklyOccurrences(context){const weekStart=startOfUtcWeekMonday(context.startAt);for(let step=0;step<context.maxOccurrences;step+=1){const candidateWeekStart=addUtcDays(weekStart,step*context.interval*7);for(const weekday of context.sortedWeekdays){const candidateAt=buildWeeklyCandidateAt(context,candidateWeekStart,weekday);if(recurrenceDayMatchesFilters(context,candidateAt)&&consumeRecurrenceCandidate(context,candidateAt)==="stop")return context.occurrences}}return context.occurrences}function expandMonthlyOccurrences(context){const startYear=context.startDate.getUTCFullYear(),startMonth=context.startDate.getUTCMonth();for(let step=0;step<context.maxOccurrences;step+=1){const monthAnchor=new Date(Date.UTC(startYear,startMonth+step*context.interval,1,0,0,0,0));for(const monthDay of context.sortedMonthDays){const candidateAt=buildUtcTimestamp(monthAnchor.getUTCFullYear(),monthAnchor.getUTCMonth(),monthDay,context.startDate);if(!(!candidateAt||!recurrenceDayMatchesFilters(context,candidateAt))&&consumeRecurrenceCandidate(context,candidateAt)==="stop")return context.occurrences}}return context.occurrences}function expandYearlyOccurrences(context){const year=context.startDate.getUTCFullYear(),month=context.startDate.getUTCMonth();for(let step=0;step<context.maxOccurrences;step+=1){const candidateYear=year+step*context.interval;for(const monthDay of context.sortedMonthDays){const candidateAt=buildUtcTimestamp(candidateYear,month,monthDay,context.startDate);if(!(!candidateAt||!recurrenceDayMatchesFilters(context,candidateAt))&&consumeRecurrenceCandidate(context,candidateAt)==="stop")return context.occurrences}}return context.occurrences}function expandRecurringOccurrences(startAt,recurrence,window2,occurrenceLimit){const context=buildRecurrenceExpansionContext(startAt,recurrence,window2,occurrenceLimit);return recurrence.freq==="daily"?expandDailyOccurrences(context):recurrence.freq==="weekly"?expandWeeklyOccurrences(context):recurrence.freq==="monthly"?expandMonthlyOccurrences(context):expandYearlyOccurrences(context)}function sortEvents(values){return[...values].sort((a,b)=>{const byAt=compareTimestampStrings(a.at,b.at);if(byAt!==0)return byAt;const byPriority=a.item_priority-b.item_priority;if(byPriority!==0)return byPriority;const byId=a.item_id.localeCompare(b.item_id);if(byId!==0)return byId;const byKind=a.kind.localeCompare(b.kind);if(byKind!==0)return byKind;const byEventTitle=String(a.event_title).localeCompare(String(b.event_title));return byEventTitle!==0?byEventTitle:String(a.reminder_text).localeCompare(String(b.reminder_text))})}function buildItemCalendarRowBase(item){return{item_id:item.id,item_title:item.title,item_type:item.type,item_status:item.status,item_priority:item.priority,item_assignee:item.assignee??null,item_deadline:item.deadline??null,item_tags:item.tags}}function buildDeadlineRow(item){return item.deadline?{at:item.deadline,date:toUtcDayKey(item.deadline),kind:"deadline",reminder_text:null,event_title:null,event_end:null,event_location:null,event_all_day:null,event_timezone:null,event_recurring:null,event_recurrence_rule:null,...buildItemCalendarRowBase(item),item_deadline:item.deadline}:null}function buildReminderRows(item){return(item.reminders??[]).map(reminder=>({at:reminder.at,date:toUtcDayKey(reminder.at),kind:"reminder",reminder_text:reminder.text,event_title:null,event_end:null,event_location:null,event_all_day:null,event_timezone:null,event_recurring:null,event_recurrence_rule:null,...buildItemCalendarRowBase(item)}))}function recurringDurationMs(startAt,endAt){if(!endAt)return null;const duration=Date.parse(endAt)-Date.parse(startAt);return Number.isFinite(duration)&&duration>0?duration:null}function eventOccurrenceEnd(occurrenceAt,event,durationMs){return event.recurrence&&durationMs!==null?new Date(new Date(occurrenceAt).getTime()+durationMs).toISOString():event.end_at??null}function buildScheduledEventRows(item,event,recurringWindow,occurrenceLimit){const recurrenceRuleSummary=formatRecurrenceRuleForSummary(event.recurrence),durationMs=recurringDurationMs(event.start_at,event.end_at);return(event.recurrence?expandRecurringOccurrences(event.start_at,event.recurrence,recurringWindow,occurrenceLimit):[event.start_at]).map(occurrenceAt=>({at:occurrenceAt,date:event.all_day===!0?occurrenceAt.slice(0,10):toLocalDayKey(occurrenceAt,event.timezone),kind:"event",reminder_text:event.description??null,event_title:event.title??item.title,event_end:eventOccurrenceEnd(occurrenceAt,event,durationMs),event_location:event.location??null,event_all_day:event.all_day??null,event_timezone:event.timezone??null,event_recurring:!!event.recurrence,event_recurrence_rule:recurrenceRuleSummary,...buildItemCalendarRowBase(item)}))}function buildEventSeed(items,recurringWindow,includeSources,occurrenceLimit){const events=[];for(const item of items){const deadlineRow=includeSources.has("deadlines")?buildDeadlineRow(item):null;deadlineRow&&events.push(deadlineRow),includeSources.has("reminders")&&events.push(...buildReminderRows(item));for(const event of includeSources.has("events")?item.events??[]:[])events.push(...buildScheduledEventRows(item,event,recurringWindow,occurrenceLimit))}return sortEvents(events)}function filterItems(items,options,typeRegistry,statusRegistry,runtimeFieldFilters){const typeFilter=parseType(options.type,typeRegistry),tagFilter=options.tag?.trim().toLowerCase(),priorityFilter=parsePriority(options.priority),statusFilter=parseStatus(options.status,statusRegistry),assigneeFilter=options.assignee?.trim(),assigneeModeFilter=parseAssigneeFilter(options.assigneeFilter),sprintFilter=options.sprint?.trim(),releaseFilter=options.release?.trim();if(assigneeFilter&&(assigneeFilter.toLowerCase()==="none"||assigneeFilter.toLowerCase()==="null"))throw new PmCliError('--assignee no longer accepts "none" or "null". Use --assignee-filter unassigned.',EXIT_CODE.USAGE);if(assigneeFilter!==void 0&&assigneeModeFilter==="unassigned")throw new PmCliError("Cannot combine --assignee with --assignee-filter unassigned",EXIT_CODE.USAGE);return items.filter(item=>itemMatchesCalendarFilters(item,{typeFilter,tagFilter,priorityFilter,statusFilter,assigneeFilter,assigneeModeFilter,sprintFilter,releaseFilter,runtimeFieldFilters}))}function itemMatchesCalendarFilters(item,filters){return itemMatchesCalendarIdentityFilters(item,filters)&&itemMatchesCalendarOwnerFilters(item,filters)&&matchesRuntimeFilters(item,filters.runtimeFieldFilters)}function itemMatchesCalendarIdentityFilters(item,filters){return!(filters.typeFilter&&item.type!==filters.typeFilter||filters.tagFilter&&!item.tags.some(tag=>tag.trim().toLowerCase()===filters.tagFilter)||filters.priorityFilter!==void 0&&item.priority!==filters.priorityFilter||filters.statusFilter&&item.status!==filters.statusFilter)}function itemMatchesCalendarOwnerFilters(item,filters){return!(filters.assigneeModeFilter==="assigned"&&!item.assignee||filters.assigneeModeFilter==="unassigned"&&item.assignee||filters.assigneeFilter!==void 0&&item.assignee!==filters.assigneeFilter||filters.sprintFilter!==void 0&&item.sprint!==filters.sprintFilter||filters.releaseFilter!==void 0&&item.release!==filters.releaseFilter)}function includeEventInWindow(event,start,end){return!(start&&compareTimestampStrings(event.at,start)<0||end&&compareTimestampStrings(event.at,end)>=0)}function resolveCalendarBoundaryInput(raw,nowValue,fieldLabel){return raw.trim().toLowerCase()==="today"?startOfUtcDay(nowValue):resolveIsoOrRelative(raw,new Date(nowValue),fieldLabel)}function buildRange(view,options,nowValue){const anchor=options.date?resolveCalendarBoundaryInput(options.date,nowValue,"--date"):nowValue,includePast=options.past===!0,fullPeriodRequested=options.fullPeriod===!0,from=options.from?resolveCalendarBoundaryInput(options.from,nowValue,"--from"):void 0,to=options.to?resolveCalendarBoundaryInput(options.to,nowValue,"--to"):void 0;if(from&&to&&compareTimestampStrings(from,to)>=0)throw new PmCliError("Calendar --from must be before --to",EXIT_CODE.USAGE);if(view!=="agenda"&&(options.from!==void 0||options.to!==void 0))throw new PmCliError("--from and --to are only supported for --view agenda",EXIT_CODE.USAGE);if(view==="agenda")return buildAgendaRange(anchor,options,nowValue,includePast,fullPeriodRequested,from,to);if(view==="day"){const dayStart=startOfUtcDay(anchor);return buildFixedPeriodRange(anchor,nowValue,includePast,fullPeriodRequested,dayStart,addUtcDays(dayStart,1))}if(view==="week"){const weekStart=startOfUtcWeekMonday(anchor);return buildFixedPeriodRange(anchor,nowValue,includePast,fullPeriodRequested,weekStart,addUtcDays(weekStart,7))}const monthStart=startOfUtcMonth(anchor);return buildFixedPeriodRange(anchor,nowValue,includePast,fullPeriodRequested,monthStart,startOfNextUtcMonth(anchor))}function buildAgendaRange(anchor,options,nowValue,includePast,fullPeriodRequested,from,to){if(fullPeriodRequested)throw new PmCliError("--full-period is only supported for --view day|week|month. For agenda windows, use --from and --to.",EXIT_CODE.USAGE);return{anchor,start:from??(options.date?anchor:includePast?void 0:nowValue),end:to,fullPeriod:!1}}function buildFixedPeriodRange(anchor,nowValue,includePast,fullPeriodRequested,periodStart,periodEnd){const fullPeriod=includePast||fullPeriodRequested;return{anchor,start:fullPeriod?periodStart:maxTimestamp(periodStart,nowValue),end:periodEnd,periodStart,periodEnd,fullPeriod}}function bucketEventsByDay(events){const dayMap=new Map;for(const event of events){const list=dayMap.get(event.date)??[];list.push(event),dayMap.set(event.date,list)}return[...dayMap.entries()].sort(([left],[right])=>left.localeCompare(right)).map(([date,dayEvents])=>({date,count:dayEvents.length,events:sortEvents(dayEvents)}))}function summarize(events){const itemIds=new Set,byType=new Map,byStatus=new Map;let deadlines=0,reminders=0,scheduled=0,recurringEvents=0;for(const event of events)itemIds.add(event.item_id),incrementCount(byType,event.item_type),incrementCount(byStatus,event.item_status),event.kind==="deadline"?deadlines+=1:event.kind==="reminder"?reminders+=1:(scheduled+=1,event.event_recurring===!0&&(recurringEvents+=1));return{events:events.length,items:itemIds.size,deadlines,reminders,scheduled,by_kind:{deadline:deadlines,reminder:reminders,event:scheduled},by_type:toSortedCountRecord(byType),by_status:toSortedCountRecord(byStatus),recurring_events:recurringEvents}}function formatWindow(range){const start=range.start??"unbounded",end=range.end??"unbounded";return`${start} -> ${end}`}function formatClock(timestamp,timezone){if(timezone&&timezone!=="UTC")try{const parts=new Intl.DateTimeFormat("en-GB",{timeZone:timezone,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(new Date(timestamp)),hour=parts.find(part=>part.type==="hour")?.value,minute=parts.find(part=>part.type==="minute")?.value;if(hour&&minute)return`${hour}:${minute}`}catch{}return`${new Date(timestamp).toISOString().slice(11,16)}Z`}function formatSummaryCountRecord(values){const entries=Object.entries(values);return entries.length===0?"empty":entries.map(([key,value])=>`${key}=${value}`).join(", ")}function formatEventEnd(event){return event.event_end?event.event_all_day===!0?event.event_end.slice(0,10):event.date===toLocalDayKey(event.event_end,event.event_timezone)?formatClock(event.event_end,event.event_timezone):event.event_end:null}function formatEventLine(event){const core=`${formatClock(event.at,event.event_timezone)} [${event.kind}] ${event.item_id} type=${event.item_type} p${event.item_priority} ${event.item_status} ${event.item_title}`;if(event.kind==="reminder"){const reminderText=event.reminder_text??"";return`${core} \u2014 ${reminderText} reminder=${JSON.stringify(reminderText)}`}if(event.kind==="event"){const details=[],title=event.event_title??event.item_title;event.event_title!==null&&event.event_title!==event.item_title&&(details.push(title),details.push(`title=${JSON.stringify(title)}`)),event.event_recurring&&(details.push("(recurring)"),details.push("recurring=true"));const end=formatEventEnd(event);return end&&details.push(`end=${end}`),event.event_all_day!==null&&details.push(`all_day=${event.event_all_day?"true":"false"}`),event.event_timezone&&details.push(`timezone=${event.event_timezone}`),event.event_location&&(details.push(`@ ${event.event_location}`),details.push(`location=${JSON.stringify(event.event_location)}`)),event.event_recurrence_rule&&details.push(`recurrence=${event.event_recurrence_rule}`),event.reminder_text&&details.push(`description=${JSON.stringify(event.reminder_text)}`),`${core} \u2014 ${details.join(" ")}`}return core}function renderCalendarMarkdown(result){const lines=[];if(lines.push(`# pm calendar (${result.view})`),lines.push(""),lines.push(`- now: ${result.now}`),lines.push(`- window: ${formatWindow(result.range)}`),result.range.period_start&&result.range.period_end&&(lines.push(`- period: ${result.range.period_start} -> ${result.range.period_end}`),lines.push(`- period-mode: ${result.range.full_period?"full-period":"active-window"}`)),lines.push(`- events: ${result.summary.events} (deadlines: ${result.summary.deadlines}, reminders: ${result.summary.reminders}, scheduled: ${result.summary.scheduled})`),lines.push(`- items: ${result.summary.items}`),lines.push(`- by-kind: ${formatSummaryCountRecord(result.summary.by_kind)}`),lines.push(`- by-type: ${formatSummaryCountRecord(result.summary.by_type)}`),lines.push(`- by-status: ${formatSummaryCountRecord(result.summary.by_status)}`),lines.push(`- recurring-events: ${result.summary.recurring_events}`),lines.push(""),result.events.length===0)return lines.push("No calendar events matched the selected filters."),lines.join(`
2
- `);for(const day of result.days){lines.push(`## ${day.date} (${day.count})`);for(const event of day.events)lines.push(`- ${formatEventLine(event)}`);lines.push("")}if(result.warnings&&result.warnings.length>0){lines.push("### warnings");for(const warning of result.warnings)lines.push(`- ${warning}`);lines.push("")}return trimTrailingNewlines(lines.join(`
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]="351df2b3-3a1a-528c-96b9-72bb3e2f27fc")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{encode as encodeToon}from"@toon-format/toon";import{getActiveExtensionRegistrations,resolveItemTypeRegistry,normalizeStatusInput,collectRuntimeFilterValues,matchesRuntimeFilters,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,PmCliError,levenshteinDistanceWithinLimit,compareTimestampStrings,resolveIsoOrRelative,listAllItemMetadataLight,resolvePmRoot,readSettings}from"../runtime-primitives.js";import{parseIntegerLimit,parsePriority,parseType}from"./parsers.js";import{weekdayOrderIndex}from"../../types/index.js";import{paginateWindowQuery,resolveWindowQueryClock}from"./window-pagination.js";const CALENDAR_VIEW_VALUES=["agenda","day","week","month"],CALENDAR_OUTPUT_VALUES=["markdown","toon","json"],UTC_DAY_TO_WEEKDAY=["sun","mon","tue","wed","thu","fri","sat"],DEFAULT_RECURRENCE_LOOKAHEAD_DAYS=365,DEFAULT_RECURRENCE_LOOKBACK_DAYS=365,DEFAULT_EVENTS_ONLY_LOOKAHEAD_DAYS=28,MAX_RECURRENCE_OCCURRENCES=1e3;function parseNonNegativeInteger(raw,label){if(raw===void 0)return;const parsed=Number(raw);if(!Number.isInteger(parsed)||parsed<0)throw new PmCliError(`${label} must be a non-negative integer`,EXIT_CODE.USAGE);return parsed}function parseIncludeSources(raw){if(!raw)return new Set(["deadlines","reminders","events"]);const normalized=raw.trim().toLowerCase();if(normalized==="all")return new Set(["deadlines","reminders","events"]);const values=normalized.split(/[|,]/).map(value=>value.trim()).filter(value=>value.length>0);if(values.length===0)throw new PmCliError("Calendar include filter must not be empty",EXIT_CODE.USAGE);const include=new Set;for(const value of values){if(value==="deadlines"||value==="deadline"){include.add("deadlines");continue}if(value==="reminders"||value==="reminder"){include.add("reminders");continue}if(value==="events"||value==="event"||value==="scheduled"){include.add("events");continue}throw new PmCliError("Calendar include filter must be deadlines|reminders|events|scheduled|all",EXIT_CODE.USAGE)}return include}function suggestClosestChoice(value,choices){let best;for(const choice of choices){const distance=levenshteinDistanceWithinLimit(value,choice,2);distance!==null&&(best===void 0||distance<best.distance)&&(best={choice,distance})}return best?.choice}function parseView(raw){if(!raw)return"agenda";const normalized=raw.trim().toLowerCase();if(!CALENDAR_VIEW_VALUES.includes(normalized)){const suggestion=suggestClosestChoice(normalized,CALENDAR_VIEW_VALUES);throw new PmCliError(`Calendar view must be one of ${CALENDAR_VIEW_VALUES.join("|")}${suggestion?`. Did you mean "${suggestion}"?`:"."}`,EXIT_CODE.USAGE)}return normalized}function parseOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!CALENDAR_OUTPUT_VALUES.includes(normalized)){const suggestion=suggestClosestChoice(normalized,CALENDAR_OUTPUT_VALUES);throw new PmCliError(`Calendar format must be one of ${CALENDAR_OUTPUT_VALUES.join("|")}${suggestion?`. Did you mean "${suggestion}"?`:"."}`,EXIT_CODE.USAGE)}return normalized}function resolveCalendarOutputFormat(options,global2){const commandFormat=parseOutputFormat(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??"markdown"}function parseStatus(raw,statusRegistry){if(raw===void 0)return;const normalized=normalizeStatusInput(raw,statusRegistry);if(!normalized){const allowedStatuses=statusRegistry.definitions.map(definition=>definition.id);throw new PmCliError(`Calendar status filter must be one of ${allowedStatuses.join("|")}`,EXIT_CODE.USAGE)}return normalized}function parseAssigneeFilter(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(!normalized)throw new PmCliError("Calendar assignee filter must be one of assigned|unassigned",EXIT_CODE.USAGE);if(normalized!=="assigned"&&normalized!=="unassigned")throw new PmCliError(`Invalid calendar assignee filter "${raw}". Allowed: assigned|unassigned`,EXIT_CODE.USAGE);return normalized}function toUtcDayKey(timestamp){return new Date(timestamp).toISOString().slice(0,10)}function toLocalDayKey(timestamp,timezone){if(!timezone||timezone==="UTC")return toUtcDayKey(timestamp);try{const parts=new Intl.DateTimeFormat("en-CA",{timeZone:timezone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(timestamp)),year=parts.find(part=>part.type==="year")?.value,month=parts.find(part=>part.type==="month")?.value,day=parts.find(part=>part.type==="day")?.value;if(year&&month&&day)return`${year}-${month}-${day}`}catch{}return toUtcDayKey(timestamp)}function startOfUtcDay(timestamp){const date=new Date(timestamp);return new Date(Date.UTC(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate(),0,0,0,0)).toISOString()}function addUtcDays(timestamp,days){const date=new Date(timestamp);return new Date(date.getTime()+days*24*60*60*1e3).toISOString()}function startOfUtcWeekMonday(timestamp){const base=new Date(startOfUtcDay(timestamp)),day=base.getUTCDay(),delta=day===0?-6:1-day;return addUtcDays(base.toISOString(),delta)}function startOfUtcMonth(timestamp){const date=new Date(timestamp);return new Date(Date.UTC(date.getUTCFullYear(),date.getUTCMonth(),1,0,0,0,0)).toISOString()}function startOfNextUtcMonth(timestamp){const date=new Date(timestamp);return new Date(Date.UTC(date.getUTCFullYear(),date.getUTCMonth()+1,1,0,0,0,0)).toISOString()}function maxTimestamp(left,right){return compareTimestampStrings(left,right)>=0?left:right}function toSortedCountRecord(values){return Object.fromEntries([...values.entries()].sort(([left],[right])=>left.localeCompare(right)))}function incrementCount(values,key){values.set(key,(values.get(key)??0)+1)}function formatRecurrenceRuleForSummary(rule){if(!rule)return null;const parts=[`freq=${rule.freq}`];if(rule.interval!==void 0&&parts.push(`interval=${rule.interval}`),rule.count!==void 0&&parts.push(`count=${rule.count}`),rule.until&&parts.push(`until=${rule.until}`),rule.by_weekday&&rule.by_weekday.length>0){const weekdays=[...rule.by_weekday].sort((left,right)=>weekdayOrderIndex(left)-weekdayOrderIndex(right));parts.push(`by_weekday=${weekdays.join("|")}`)}if(rule.by_month_day&&rule.by_month_day.length>0){const monthDays=[...rule.by_month_day].sort((left,right)=>left-right);parts.push(`by_month_day=${monthDays.join("|")}`)}if(rule.exdates&&rule.exdates.length>0){const exdates=[...rule.exdates].sort((left,right)=>left.localeCompare(right));parts.push(`exdates=${exdates.join("|")}`)}return parts.join(",")}function buildUtcTimestamp(year,month,day,timeSource){const candidate=new Date(Date.UTC(year,month,day,timeSource.getUTCHours(),timeSource.getUTCMinutes(),timeSource.getUTCSeconds(),timeSource.getUTCMilliseconds()));if(!(candidate.getUTCFullYear()!==year||candidate.getUTCMonth()!==month||candidate.getUTCDate()!==day))return candidate.toISOString()}function weekdayToken(timestamp){return UTC_DAY_TO_WEEKDAY[new Date(timestamp).getUTCDay()]}function normalizeInstantKey(timestamp){const parsed=Date.parse(timestamp);return Number.isFinite(parsed)?new Date(parsed).toISOString():null}function buildExcludedInstantSet(exdates){const excluded=new Set;for(const exdate of exdates??[]){const instantKey=normalizeInstantKey(exdate);instantKey&&excluded.add(instantKey)}return excluded}function buildRecurringEventWindow(start,end,nowValue,lookbackDays,lookaheadDays){const windowStart=start??addUtcDays(nowValue,-(lookbackDays??DEFAULT_RECURRENCE_LOOKBACK_DAYS)),windowEnd=end??addUtcDays(start??nowValue,lookaheadDays??DEFAULT_RECURRENCE_LOOKAHEAD_DAYS);return{start:windowStart,end:compareTimestampStrings(windowEnd,windowStart)>0?windowEnd:addUtcDays(windowStart,1)}}function buildRecurrenceExpansionContext(startAt,recurrence,window2,occurrenceLimit){const recurrenceWeekdays=recurrence.by_weekday!==void 0?[...recurrence.by_weekday]:[weekdayToken(startAt)],recurrenceMonthDays=recurrence.by_month_day!==void 0?[...recurrence.by_month_day]:[new Date(startAt).getUTCDate()];return{startAt,startDate:new Date(startAt),window:window2,maxOccurrences:occurrenceLimit??MAX_RECURRENCE_OCCURRENCES,interval:recurrence.interval??1,countLimit:recurrence.count??Number.POSITIVE_INFINITY,until:recurrence.until,excluded:buildExcludedInstantSet(recurrence.exdates),weekdayFilter:recurrence.by_weekday!==void 0?new Set(recurrence.by_weekday):void 0,monthDayFilter:recurrence.by_month_day!==void 0?new Set(recurrence.by_month_day):void 0,sortedWeekdays:[...new Set(recurrenceWeekdays)].sort((left,right)=>weekdayOrderIndex(left)-weekdayOrderIndex(right)),sortedMonthDays:[...new Set(recurrenceMonthDays)].sort((left,right)=>left-right),occurrences:[],produced:0}}function consumeRecurrenceCandidate(context,candidateAt){return compareTimestampStrings(candidateAt,context.startAt)<0?"continue":context.until&&compareTimestampStrings(candidateAt,context.until)>0||compareTimestampStrings(candidateAt,context.window.end)>=0?"stop":context.excluded.has(candidateAt)?"continue":(context.produced+=1,compareTimestampStrings(candidateAt,context.window.start)>=0&&context.occurrences.push(candidateAt),context.produced>=context.countLimit||context.occurrences.length>=context.maxOccurrences?"stop":"continue")}function recurrenceDayMatchesFilters(context,candidateAt){const candidateWeekday=weekdayToken(candidateAt),candidateMonthDay=new Date(candidateAt).getUTCDate(),weekdayMatches=!context.weekdayFilter||context.weekdayFilter.has(candidateWeekday),monthDayMatches=!context.monthDayFilter||context.monthDayFilter.has(candidateMonthDay);return weekdayMatches&&monthDayMatches}function expandDailyOccurrences(context){let candidateAt=context.startAt;for(let iteration=0;iteration<context.maxOccurrences&&!(recurrenceDayMatchesFilters(context,candidateAt)&&consumeRecurrenceCandidate(context,candidateAt)==="stop");iteration+=1)candidateAt=addUtcDays(candidateAt,context.interval);return context.occurrences}function buildWeeklyCandidateAt(context,candidateWeekStart,weekday){const dayOffset=weekdayOrderIndex(weekday),candidateDay=addUtcDays(candidateWeekStart,dayOffset),dayDate=new Date(candidateDay);return new Date(Date.UTC(dayDate.getUTCFullYear(),dayDate.getUTCMonth(),dayDate.getUTCDate(),context.startDate.getUTCHours(),context.startDate.getUTCMinutes(),context.startDate.getUTCSeconds(),context.startDate.getUTCMilliseconds())).toISOString()}function expandWeeklyOccurrences(context){const weekStart=startOfUtcWeekMonday(context.startAt);for(let step=0;step<context.maxOccurrences;step+=1){const candidateWeekStart=addUtcDays(weekStart,step*context.interval*7);for(const weekday of context.sortedWeekdays){const candidateAt=buildWeeklyCandidateAt(context,candidateWeekStart,weekday);if(recurrenceDayMatchesFilters(context,candidateAt)&&consumeRecurrenceCandidate(context,candidateAt)==="stop")return context.occurrences}}return context.occurrences}function expandMonthlyOccurrences(context){const startYear=context.startDate.getUTCFullYear(),startMonth=context.startDate.getUTCMonth();for(let step=0;step<context.maxOccurrences;step+=1){const monthAnchor=new Date(Date.UTC(startYear,startMonth+step*context.interval,1,0,0,0,0));for(const monthDay of context.sortedMonthDays){const candidateAt=buildUtcTimestamp(monthAnchor.getUTCFullYear(),monthAnchor.getUTCMonth(),monthDay,context.startDate);if(!(!candidateAt||!recurrenceDayMatchesFilters(context,candidateAt))&&consumeRecurrenceCandidate(context,candidateAt)==="stop")return context.occurrences}}return context.occurrences}function expandYearlyOccurrences(context){const year=context.startDate.getUTCFullYear(),month=context.startDate.getUTCMonth();for(let step=0;step<context.maxOccurrences;step+=1){const candidateYear=year+step*context.interval;for(const monthDay of context.sortedMonthDays){const candidateAt=buildUtcTimestamp(candidateYear,month,monthDay,context.startDate);if(!(!candidateAt||!recurrenceDayMatchesFilters(context,candidateAt))&&consumeRecurrenceCandidate(context,candidateAt)==="stop")return context.occurrences}}return context.occurrences}function expandRecurringOccurrences(startAt,recurrence,window2,occurrenceLimit){const context=buildRecurrenceExpansionContext(startAt,recurrence,window2,occurrenceLimit);return recurrence.freq==="daily"?expandDailyOccurrences(context):recurrence.freq==="weekly"?expandWeeklyOccurrences(context):recurrence.freq==="monthly"?expandMonthlyOccurrences(context):expandYearlyOccurrences(context)}function sortEvents(values){return[...values].sort((a,b)=>{const byAt=compareTimestampStrings(a.at,b.at);if(byAt!==0)return byAt;const byPriority=a.item_priority-b.item_priority;if(byPriority!==0)return byPriority;const byId=a.item_id.localeCompare(b.item_id);if(byId!==0)return byId;const byKind=a.kind.localeCompare(b.kind);if(byKind!==0)return byKind;const byEventTitle=String(a.event_title).localeCompare(String(b.event_title));return byEventTitle!==0?byEventTitle:String(a.reminder_text).localeCompare(String(b.reminder_text))})}function buildItemCalendarRowBase(item){return{item_id:item.id,item_title:item.title,item_type:item.type,item_status:item.status,item_priority:item.priority,item_assignee:item.assignee??null,item_deadline:item.deadline??null,item_tags:item.tags}}function buildDeadlineRow(item){return item.deadline?{at:item.deadline,date:toUtcDayKey(item.deadline),kind:"deadline",reminder_text:null,event_title:null,event_end:null,event_location:null,event_all_day:null,event_timezone:null,event_recurring:null,event_recurrence_rule:null,...buildItemCalendarRowBase(item),item_deadline:item.deadline}:null}function buildReminderRows(item){return(item.reminders??[]).map(reminder=>({at:reminder.at,date:toUtcDayKey(reminder.at),kind:"reminder",reminder_text:reminder.text,event_title:null,event_end:null,event_location:null,event_all_day:null,event_timezone:null,event_recurring:null,event_recurrence_rule:null,...buildItemCalendarRowBase(item)}))}function recurringDurationMs(startAt,endAt){if(!endAt)return null;const duration=Date.parse(endAt)-Date.parse(startAt);return Number.isFinite(duration)&&duration>0?duration:null}function eventOccurrenceEnd(occurrenceAt,event,durationMs){return event.recurrence&&durationMs!==null?new Date(new Date(occurrenceAt).getTime()+durationMs).toISOString():event.end_at??null}function buildScheduledEventRows(item,event,recurringWindow,occurrenceLimit){const recurrenceRuleSummary=formatRecurrenceRuleForSummary(event.recurrence),durationMs=recurringDurationMs(event.start_at,event.end_at);return(event.recurrence?expandRecurringOccurrences(event.start_at,event.recurrence,recurringWindow,occurrenceLimit):[event.start_at]).map(occurrenceAt=>({at:occurrenceAt,date:event.all_day===!0?occurrenceAt.slice(0,10):toLocalDayKey(occurrenceAt,event.timezone),kind:"event",reminder_text:event.description??null,event_title:event.title??item.title,event_end:eventOccurrenceEnd(occurrenceAt,event,durationMs),event_location:event.location??null,event_all_day:event.all_day??null,event_timezone:event.timezone??null,event_recurring:!!event.recurrence,event_recurrence_rule:recurrenceRuleSummary,...buildItemCalendarRowBase(item)}))}function buildEventSeed(items,recurringWindow,includeSources,occurrenceLimit){const events=[];for(const item of items){const deadlineRow=includeSources.has("deadlines")?buildDeadlineRow(item):null;deadlineRow&&events.push(deadlineRow),includeSources.has("reminders")&&events.push(...buildReminderRows(item));for(const event of includeSources.has("events")?item.events??[]:[])events.push(...buildScheduledEventRows(item,event,recurringWindow,occurrenceLimit))}return sortEvents(events)}function filterItems(items,options,typeRegistry,statusRegistry,runtimeFieldFilters){const typeFilter=parseType(options.type,typeRegistry),tagFilter=options.tag?.trim().toLowerCase(),priorityFilter=parsePriority(options.priority),statusFilter=parseStatus(options.status,statusRegistry),assigneeFilter=options.assignee?.trim(),assigneeModeFilter=parseAssigneeFilter(options.assigneeFilter),sprintFilter=options.sprint?.trim(),releaseFilter=options.release?.trim();if(assigneeFilter&&(assigneeFilter.toLowerCase()==="none"||assigneeFilter.toLowerCase()==="null"))throw new PmCliError('--assignee no longer accepts "none" or "null". Use --assignee-filter unassigned.',EXIT_CODE.USAGE);if(assigneeFilter!==void 0&&assigneeModeFilter==="unassigned")throw new PmCliError("Cannot combine --assignee with --assignee-filter unassigned",EXIT_CODE.USAGE);return items.filter(item=>itemMatchesCalendarFilters(item,{typeFilter,tagFilter,priorityFilter,statusFilter,assigneeFilter,assigneeModeFilter,sprintFilter,releaseFilter,runtimeFieldFilters}))}function itemMatchesCalendarFilters(item,filters){return itemMatchesCalendarIdentityFilters(item,filters)&&itemMatchesCalendarOwnerFilters(item,filters)&&matchesRuntimeFilters(item,filters.runtimeFieldFilters)}function itemMatchesCalendarIdentityFilters(item,filters){return!(filters.typeFilter&&item.type!==filters.typeFilter||filters.tagFilter&&!item.tags.some(tag=>tag.trim().toLowerCase()===filters.tagFilter)||filters.priorityFilter!==void 0&&item.priority!==filters.priorityFilter||filters.statusFilter&&item.status!==filters.statusFilter)}function itemMatchesCalendarOwnerFilters(item,filters){return!(filters.assigneeModeFilter==="assigned"&&!item.assignee||filters.assigneeModeFilter==="unassigned"&&item.assignee||filters.assigneeFilter!==void 0&&item.assignee!==filters.assigneeFilter||filters.sprintFilter!==void 0&&item.sprint!==filters.sprintFilter||filters.releaseFilter!==void 0&&item.release!==filters.releaseFilter)}function includeEventInWindow(event,start,end){return!(start&&compareTimestampStrings(event.at,start)<0||end&&compareTimestampStrings(event.at,end)>=0)}function resolveCalendarBoundaryInput(raw,nowValue,fieldLabel){return raw.trim().toLowerCase()==="today"?startOfUtcDay(nowValue):resolveIsoOrRelative(raw,new Date(nowValue),fieldLabel)}function buildRange(view,options,nowValue){const anchor=options.date?resolveCalendarBoundaryInput(options.date,nowValue,"--date"):nowValue,includePast=options.past===!0,fullPeriodRequested=options.fullPeriod===!0,from=options.from?resolveCalendarBoundaryInput(options.from,nowValue,"--from"):void 0,to=options.to?resolveCalendarBoundaryInput(options.to,nowValue,"--to"):void 0;if(from&&to&&compareTimestampStrings(from,to)>=0)throw new PmCliError("Calendar --from must be before --to",EXIT_CODE.USAGE);if(view!=="agenda"&&(options.from!==void 0||options.to!==void 0))throw new PmCliError("--from and --to are only supported for --view agenda",EXIT_CODE.USAGE);if(view==="agenda")return buildAgendaRange(anchor,options,nowValue,includePast,fullPeriodRequested,from,to);if(view==="day"){const dayStart=startOfUtcDay(anchor);return buildFixedPeriodRange(anchor,nowValue,includePast,fullPeriodRequested,dayStart,addUtcDays(dayStart,1))}if(view==="week"){const weekStart=startOfUtcWeekMonday(anchor);return buildFixedPeriodRange(anchor,nowValue,includePast,fullPeriodRequested,weekStart,addUtcDays(weekStart,7))}const monthStart=startOfUtcMonth(anchor);return buildFixedPeriodRange(anchor,nowValue,includePast,fullPeriodRequested,monthStart,startOfNextUtcMonth(anchor))}function buildAgendaRange(anchor,options,nowValue,includePast,fullPeriodRequested,from,to){if(fullPeriodRequested)throw new PmCliError("--full-period is only supported for --view day|week|month. For agenda windows, use --from and --to.",EXIT_CODE.USAGE);return{anchor,start:from??(options.date?anchor:includePast?void 0:nowValue),end:to,fullPeriod:!1}}function buildFixedPeriodRange(anchor,nowValue,includePast,fullPeriodRequested,periodStart,periodEnd){const fullPeriod=includePast||fullPeriodRequested;return{anchor,start:fullPeriod?periodStart:maxTimestamp(periodStart,nowValue),end:periodEnd,periodStart,periodEnd,fullPeriod}}function bucketEventsByDay(events){const dayMap=new Map;for(const event of events){const list=dayMap.get(event.date)??[];list.push(event),dayMap.set(event.date,list)}return[...dayMap.entries()].sort(([left],[right])=>left.localeCompare(right)).map(([date,dayEvents])=>({date,count:dayEvents.length,events:sortEvents(dayEvents)}))}function summarize(events){const itemIds=new Set,byType=new Map,byStatus=new Map;let deadlines=0,reminders=0,scheduled=0,recurringEvents=0;for(const event of events)itemIds.add(event.item_id),incrementCount(byType,event.item_type),incrementCount(byStatus,event.item_status),event.kind==="deadline"?deadlines+=1:event.kind==="reminder"?reminders+=1:(scheduled+=1,event.event_recurring===!0&&(recurringEvents+=1));return{events:events.length,items:itemIds.size,deadlines,reminders,scheduled,by_kind:{deadline:deadlines,reminder:reminders,event:scheduled},by_type:toSortedCountRecord(byType),by_status:toSortedCountRecord(byStatus),recurring_events:recurringEvents}}function formatWindow(range){const start=range.start??"unbounded",end=range.end??"unbounded";return`${start} -> ${end}`}function formatClock(timestamp,timezone){if(timezone&&timezone!=="UTC")try{const parts=new Intl.DateTimeFormat("en-GB",{timeZone:timezone,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(new Date(timestamp)),hour=parts.find(part=>part.type==="hour")?.value,minute=parts.find(part=>part.type==="minute")?.value;if(hour&&minute)return`${hour}:${minute}`}catch{}return`${new Date(timestamp).toISOString().slice(11,16)}Z`}function formatSummaryCountRecord(values){const entries=Object.entries(values);return entries.length===0?"empty":entries.map(([key,value])=>`${key}=${value}`).join(", ")}function formatEventEnd(event){return event.event_end?event.event_all_day===!0?event.event_end.slice(0,10):event.date===toLocalDayKey(event.event_end,event.event_timezone)?formatClock(event.event_end,event.event_timezone):event.event_end:null}function formatEventLine(event){const core=`${formatClock(event.at,event.event_timezone)} [${event.kind}] ${event.item_id} type=${event.item_type} p${event.item_priority} ${event.item_status} ${event.item_title}`;if(event.kind==="reminder"){const reminderText=event.reminder_text??"";return`${core} \u2014 ${reminderText} reminder=${JSON.stringify(reminderText)}`}if(event.kind==="event"){const details=[],title=event.event_title??event.item_title;event.event_title!==null&&event.event_title!==event.item_title&&(details.push(title),details.push(`title=${JSON.stringify(title)}`)),event.event_recurring&&(details.push("(recurring)"),details.push("recurring=true"));const end=formatEventEnd(event);return end&&details.push(`end=${end}`),event.event_all_day!==null&&details.push(`all_day=${event.event_all_day?"true":"false"}`),event.event_timezone&&details.push(`timezone=${event.event_timezone}`),event.event_location&&(details.push(`@ ${event.event_location}`),details.push(`location=${JSON.stringify(event.event_location)}`)),event.event_recurrence_rule&&details.push(`recurrence=${event.event_recurrence_rule}`),event.reminder_text&&details.push(`description=${JSON.stringify(event.reminder_text)}`),`${core} \u2014 ${details.join(" ")}`}return core}function appendCalendarMarkdownWarnings(lines,warnings){if(warnings&&warnings.length>0){lines.push("### warnings");for(const warning of warnings)lines.push(`- ${warning}`);lines.push("")}}function renderCalendarMarkdown(result){const lines=[];if(lines.push(`# pm calendar (${result.view})`),lines.push(""),lines.push(`- now: ${result.now}`),lines.push(`- window: ${formatWindow(result.range)}`),result.range.period_start&&result.range.period_end&&(lines.push(`- period: ${result.range.period_start} -> ${result.range.period_end}`),lines.push(`- period-mode: ${result.range.full_period?"full-period":"active-window"}`)),lines.push(`- events: ${result.summary.events} (deadlines: ${result.summary.deadlines}, reminders: ${result.summary.reminders}, scheduled: ${result.summary.scheduled})`),lines.push(`- items: ${result.summary.items}`),lines.push(`- matching-events: ${result.total_count}; returned: ${result.count}; remaining: ${result.omitted_count} (summary: ${result.summary_scope})`),result.next_cursor&&lines.push(`- continue: repeat the same query with --after ${result.next_cursor}`),lines.push(`- by-kind: ${formatSummaryCountRecord(result.summary.by_kind)}`),lines.push(`- by-type: ${formatSummaryCountRecord(result.summary.by_type)}`),lines.push(`- by-status: ${formatSummaryCountRecord(result.summary.by_status)}`),lines.push(`- recurring-events: ${result.summary.recurring_events}`),lines.push(""),result.events.length===0)return lines.push(result.total_count===0?"No calendar events matched the selected filters.":"No calendar events returned on this page. Repeat the same query with --limit 1 or greater to retrieve matching events."),lines.push(""),appendCalendarMarkdownWarnings(lines,result.warnings),trimTrailingNewlines(lines.join(`
2
+ `));for(const day of result.days){lines.push(`## ${day.date} (${day.count})`);for(const event of day.events)lines.push(`- ${formatEventLine(event)}`);lines.push("")}return appendCalendarMarkdownWarnings(lines,result.warnings),trimTrailingNewlines(lines.join(`
3
3
  `))}function renderCalendarToon(result){return encodeToon(result)}function trimTrailingNewlines(value){let end=value.length;for(;end>0&&value[end-1]===`
4
- `;)end-=1;return value.slice(0,end)}function resolveCalendarExecutionInputs(options){const nowValue=nowIso(),view=parseView(options.view),rangeBounds=buildRange(view,options,nowValue),limit=parseIntegerLimit(options.limit),includeSources=parseIncludeSources(options.include),explicitLookahead=parseNonNegativeInteger(options.recurrenceLookaheadDays,"Calendar recurrence lookahead days"),recurrenceLookbackDays=parseNonNegativeInteger(options.recurrenceLookbackDays,"Calendar recurrence lookback days"),occurrenceLimit=parseNonNegativeInteger(options.occurrenceLimit,"Calendar occurrence limit");if(occurrenceLimit!==void 0&&occurrenceLimit<1)throw new PmCliError("Calendar occurrence limit must be >= 1",EXIT_CODE.USAGE);const eventsOnly=includeSources.has("events")&&!includeSources.has("deadlines")&&!includeSources.has("reminders"),hasExplicitBounds=options.to!==void 0||explicitLookahead!==void 0||recurrenceLookbackDays!==void 0||occurrenceLimit!==void 0,eventsOnlyCapApplied=eventsOnly&&!hasExplicitBounds;return{nowValue,view,rangeBounds,limit,includeSources,occurrenceLimit,recurrenceLookaheadDays:eventsOnlyCapApplied?DEFAULT_EVENTS_ONLY_LOOKAHEAD_DAYS:explicitLookahead,recurrenceLookbackWindowDays:eventsOnlyCapApplied&&recurrenceLookbackDays===void 0?0:recurrenceLookbackDays,eventsOnlyCapApplied}}function appendCalendarCapWarning(warnings,capApplied){capApplied&&warnings.push(`recurring_events_default_cap_applied:lookback=0d,lookahead=${DEFAULT_EVENTS_ONLY_LOOKAHEAD_DAYS}d -- use --recurrence-lookback-days/--recurrence-lookahead-days or --to for wider range`)}function buildCalendarFiltersResult(options,runtimeFieldFilters){return{type:options.type??null,tag:options.tag??null,priority:options.priority??null,status:options.status??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,runtime_filters:runtimeFieldFilters,limit:options.limit??null,include:options.include??null,full_period:options.fullPeriod===!0?"true":null,recurrence_lookahead_days:options.recurrenceLookaheadDays??null,recurrence_lookback_days:options.recurrenceLookbackDays??null,occurrence_limit:options.occurrenceLimit??null}}function buildCalendarRangeResult(options,rangeBounds){return{start:rangeBounds.start??null,end:rangeBounds.end??null,period_start:rangeBounds.periodStart??null,period_end:rangeBounds.periodEnd??null,full_period:rangeBounds.fullPeriod,past:options.past===!0,from:options.from??null,to:options.to??null}}async function runCalendar(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const inputs=resolveCalendarExecutionInputs(options),settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),runtimeFieldRegistry=resolveRuntimeFieldRegistry(settings.schema),runtimeFieldFilters=collectRuntimeFilterValues(options,runtimeFieldRegistry,"calendar"),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),listWarnings=[];appendCalendarCapWarning(listWarnings,inputs.eventsOnlyCapApplied);const items=await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,listWarnings,settings.schema),filteredItems=filterItems(items,options,typeRegistry,statusRegistry,runtimeFieldFilters),recurringWindow=buildRecurringEventWindow(inputs.rangeBounds.start,inputs.rangeBounds.end,inputs.nowValue,inputs.recurrenceLookbackWindowDays,inputs.recurrenceLookaheadDays),rangedEvents=buildEventSeed(filteredItems,recurringWindow,inputs.includeSources,inputs.occurrenceLimit).filter(event=>includeEventInWindow(event,inputs.rangeBounds.start,inputs.rangeBounds.end)),limitedEvents=inputs.limit===void 0?rangedEvents:rangedEvents.slice(0,inputs.limit),days=bucketEventsByDay(limitedEvents),warnings=[...new Set(listWarnings)].sort((left,right)=>left.localeCompare(right));return{view:inputs.view,output_default:"markdown",now:inputs.nowValue,anchor:inputs.rangeBounds.anchor,range:buildCalendarRangeResult(options,inputs.rangeBounds),filters:buildCalendarFiltersResult(options,runtimeFieldFilters),summary:summarize(limitedEvents),events:limitedEvents,days,...warnings.length>0?{warnings}:{}}}export{renderCalendarMarkdown,renderCalendarToon,resolveCalendarOutputFormat,runCalendar};
4
+ `;)end-=1;return value.slice(0,end)}function resolveCalendarExecutionInputs(options){const nowValue=resolveWindowQueryClock("calendar",options.after),view=parseView(options.view),rangeBounds=buildRange(view,options,nowValue),limit=parseIntegerLimit(options.limit),includeSources=parseIncludeSources(options.include),explicitLookahead=parseNonNegativeInteger(options.recurrenceLookaheadDays,"Calendar recurrence lookahead days"),recurrenceLookbackDays=parseNonNegativeInteger(options.recurrenceLookbackDays,"Calendar recurrence lookback days"),occurrenceLimit=parseNonNegativeInteger(options.occurrenceLimit,"Calendar occurrence limit");if(occurrenceLimit!==void 0&&occurrenceLimit<1)throw new PmCliError("Calendar occurrence limit must be >= 1",EXIT_CODE.USAGE);const eventsOnly=includeSources.has("events")&&!includeSources.has("deadlines")&&!includeSources.has("reminders"),hasExplicitBounds=options.to!==void 0||explicitLookahead!==void 0||recurrenceLookbackDays!==void 0||occurrenceLimit!==void 0,eventsOnlyCapApplied=eventsOnly&&!hasExplicitBounds;return{nowValue,view,rangeBounds,limit,includeSources,occurrenceLimit,recurrenceLookaheadDays:eventsOnlyCapApplied?DEFAULT_EVENTS_ONLY_LOOKAHEAD_DAYS:explicitLookahead,recurrenceLookbackWindowDays:eventsOnlyCapApplied&&recurrenceLookbackDays===void 0?0:recurrenceLookbackDays,eventsOnlyCapApplied}}function appendCalendarCapWarning(warnings,capApplied){capApplied&&warnings.push(`recurring_events_default_cap_applied:lookback=0d,lookahead=${DEFAULT_EVENTS_ONLY_LOOKAHEAD_DAYS}d -- use --recurrence-lookback-days/--recurrence-lookahead-days or --to for wider range`)}function buildCalendarFiltersResult(options,runtimeFieldFilters){return{type:options.type??null,tag:options.tag??null,priority:options.priority??null,status:options.status??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,runtime_filters:runtimeFieldFilters,limit:options.limit??null,include:options.include??null,full_period:options.fullPeriod===!0?"true":null,recurrence_lookahead_days:options.recurrenceLookaheadDays??null,recurrence_lookback_days:options.recurrenceLookbackDays??null,occurrence_limit:options.occurrenceLimit??null}}function buildCalendarRangeResult(options,rangeBounds){return{start:rangeBounds.start??null,end:rangeBounds.end??null,period_start:rangeBounds.periodStart??null,period_end:rangeBounds.periodEnd??null,full_period:rangeBounds.fullPeriod,past:options.past===!0,from:options.from??null,to:options.to??null}}async function runCalendar(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const inputs=resolveCalendarExecutionInputs(options),settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),runtimeFieldRegistry=resolveRuntimeFieldRegistry(settings.schema),runtimeFieldFilters=collectRuntimeFilterValues(options,runtimeFieldRegistry,"calendar"),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),listWarnings=[];appendCalendarCapWarning(listWarnings,inputs.eventsOnlyCapApplied);const items=await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,listWarnings,settings.schema),filteredItems=filterItems(items,options,typeRegistry,statusRegistry,runtimeFieldFilters),recurringWindow=buildRecurringEventWindow(inputs.rangeBounds.start,inputs.rangeBounds.end,inputs.nowValue,inputs.recurrenceLookbackWindowDays,inputs.recurrenceLookaheadDays),rangedEvents=buildEventSeed(filteredItems,recurringWindow,inputs.includeSources,inputs.occurrenceLimit).filter(event=>includeEventInWindow(event,inputs.rangeBounds.start,inputs.rangeBounds.end)),{rows:limitedEvents,...page}=paginateWindowQuery(rangedEvents,{command:"calendar",after:options.after,clock:inputs.nowValue,limit:inputs.limit,query:{pmRoot,view:inputs.view,range:inputs.rangeBounds,filters:{...buildCalendarFiltersResult(options,runtimeFieldFilters),limit:void 0},recurringWindow,occurrenceLimit:inputs.occurrenceLimit}}),days=bucketEventsByDay(limitedEvents),warnings=[...new Set(listWarnings)].sort((left,right)=>left.localeCompare(right));return{view:inputs.view,output_default:"markdown",now:inputs.nowValue,anchor:inputs.rangeBounds.anchor,range:buildCalendarRangeResult(options,inputs.rangeBounds),filters:buildCalendarFiltersResult(options,runtimeFieldFilters),...page,summary_scope:"returned_rows",summary:summarize(limitedEvents),events:limitedEvents,days,...warnings.length>0?{warnings}:{}}}export{renderCalendarMarkdown,renderCalendarToon,resolveCalendarOutputFormat,runCalendar};
5
5
  //# sourceMappingURL=calendar.js.map
@@ -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]="e25fa213-1da3-576c-a2a5-2828a70d262d")}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,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]="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};
3
3
  //# sourceMappingURL=context.js.map