@unbrained/pm-cli 2026.10.17 → 2026.10.19

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 (256) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +35 -0
  3. package/dist/cli/help-content.js +2 -2
  4. package/dist/cli/register-list-query.js +2 -2
  5. package/dist/cli/register-mutation.js +2 -2
  6. package/dist/cli/register-setup.js +1 -1
  7. package/dist/cli-bundle/bundle-manifest.json +1 -1
  8. package/dist/cli-bundle/chunks/chunk-4CXQSRSP.js +126 -0
  9. package/dist/cli-bundle/chunks/{chunk-EA2CG7UM.js → chunk-4ICKT4GH.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-W3KZ22DW.js → chunk-4MJ6WBMA.js} +2 -2
  11. package/dist/cli-bundle/chunks/chunk-4XFVAXA4.js +2 -0
  12. package/dist/cli-bundle/chunks/{chunk-6ZDKKOKM.js → chunk-5GZSX5HU.js} +72 -66
  13. package/dist/cli-bundle/chunks/{chunk-3QKI3XNX.js → chunk-6DS5CAN2.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-B5QVGCZX.js → chunk-D3EDNAN7.js} +2 -2
  15. package/dist/cli-bundle/chunks/chunk-DMFM5R4G.js +3 -0
  16. package/dist/cli-bundle/chunks/chunk-H3XYP24A.js +70 -0
  17. package/dist/cli-bundle/chunks/chunk-LBEMB3BW.js +6 -0
  18. package/dist/cli-bundle/chunks/chunk-NX7Q4LGN.js +8 -0
  19. package/dist/cli-bundle/chunks/chunk-O2ZRRLAP.js +8 -0
  20. package/dist/cli-bundle/chunks/chunk-OEJ3G7XT.js +20 -0
  21. package/dist/cli-bundle/chunks/{chunk-O4YBC3OM.js → chunk-QBNEZII5.js} +30 -30
  22. package/dist/cli-bundle/chunks/chunk-QG4LMU7A.js +112 -0
  23. package/dist/cli-bundle/chunks/chunk-QKAAZWGC.js +3 -0
  24. package/dist/cli-bundle/chunks/chunk-RUKSEZE7.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-TK3G3GAP.js +2 -0
  26. package/dist/cli-bundle/chunks/chunk-VS565KBX.js +2 -0
  27. package/dist/cli-bundle/chunks/{chunk-JS3B2M4D.js → chunk-XH7C3A5N.js} +2 -2
  28. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BVSHK4WQ.js +4 -0
  29. package/dist/cli-bundle/chunks/{register-list-query-RU3QZSAQ.js → register-list-query-WQUVDJIH.js} +7 -7
  30. package/dist/cli-bundle/chunks/register-mutation-IWIBQIO3.js +20 -0
  31. package/dist/cli-bundle/chunks/register-operations-SUWOZNDU.js +2 -0
  32. package/dist/cli-bundle/chunks/register-setup-QGM5YJW7.js +2 -0
  33. package/dist/cli-bundle/chunks/settlement-hook-UNFMCKKQ.js +7 -0
  34. package/dist/cli-bundle/chunks/stage-7DELI4Z5.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-LDKX4KYJ.js → chunk-2IEWB6MB.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/chunk-3TEIACFU.js +3 -0
  37. package/dist/cli-bundle/focused-chunks/chunk-5YTOYBTZ.js +65 -0
  38. package/dist/cli-bundle/focused-chunks/chunk-AK2CI2GI.js +2 -0
  39. package/dist/cli-bundle/focused-chunks/chunk-BJMPRB7A.js +91 -0
  40. package/dist/cli-bundle/focused-chunks/chunk-ENZMATOY.js +20 -0
  41. package/dist/cli-bundle/focused-chunks/chunk-EOQ6W25I.js +8 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-FTUZ3JF2.js → chunk-FEN7WOOP.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +2 -0
  44. package/dist/cli-bundle/focused-chunks/chunk-GWTV45SB.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-SIGIGZCG.js → chunk-H6BVQ63U.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-RBLSY6ML.js → chunk-HYMYAGSY.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-JBJJW2WL.js +6 -0
  48. package/dist/cli-bundle/focused-chunks/chunk-JCLC6HKT.js +8 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-2IOHHNRT.js → chunk-JDBO7SMR.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-UNTQE37U.js → chunk-KLJN44VY.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/chunk-L4PL3GZR.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-OV2WVLUR.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-PXDR77TO.js +78 -0
  54. package/dist/cli-bundle/focused-chunks/chunk-RLRMNFLF.js +3 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-E33QA7PK.js → chunk-SKYLOPU2.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/chunk-VVRXF4JO.js +2 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-WZTEFFQI.js +3 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-Y54ONBEX.js +25 -0
  59. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-QW2VWWJE.js +4 -0
  60. package/dist/cli-bundle/focused-chunks/settlement-hook-X4FNHTOD.js +7 -0
  61. package/dist/cli-bundle/focused-chunks/stage-MZSVQYO4.js +2 -0
  62. package/dist/cli-bundle/main.js +3 -3
  63. package/dist/cli-bundle/sdk-authoring.js +1 -1
  64. package/dist/cli-bundle/sdk-contracts.js +1 -1
  65. package/dist/cli-bundle/sdk-core.js +29 -23
  66. package/dist/cli-bundle/sdk-governance.js +1 -1
  67. package/dist/cli-bundle/sdk-graph.js +1 -1
  68. package/dist/cli-bundle/sdk-merge.js +66 -52
  69. package/dist/cli-bundle/sdk-query.js +1 -1
  70. package/dist/cli-bundle/sdk-runtime.js +1 -1
  71. package/dist/cli-bundle/sdk-testing.js +1 -1
  72. package/dist/cli-bundle/sdk.js +2 -2
  73. package/dist/core/history/event-index.d.ts +8 -1
  74. package/dist/core/history/event-index.js +19 -18
  75. package/dist/core/item/item-format.js +1 -1
  76. package/dist/core/lock/lock.d.ts +8 -1
  77. package/dist/core/lock/lock.js +3 -3
  78. package/dist/core/output/output.js +2 -2
  79. package/dist/core/store/paths.js +1 -1
  80. package/dist/core/telemetry/policy.d.ts +2 -0
  81. package/dist/core/telemetry/policy.js +1 -1
  82. package/dist/core/telemetry/runtime.d.ts +5 -3
  83. package/dist/core/telemetry/runtime.js +3 -3
  84. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  85. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  86. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  87. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +1 -0
  88. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  89. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  90. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  91. package/dist/sdk/extension/install-sources.js +3 -3
  92. package/dist/sdk/extension/shared.js +1 -1
  93. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  94. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  95. package/dist/sdk/governance/health/projection.d.ts +37 -0
  96. package/dist/sdk/governance/health/projection.js +2 -0
  97. package/dist/sdk/governance/health.d.ts +7 -18
  98. package/dist/sdk/governance/health.js +2 -2
  99. package/dist/sdk/history-repair.js +1 -1
  100. package/dist/sdk/merge/driver.js +7 -1
  101. package/dist/sdk/merge/indexed-receipt-blobs.d.ts +2 -0
  102. package/dist/sdk/merge/indexed-receipt-blobs.js +4 -0
  103. package/dist/sdk/merge/install.d.ts +8 -0
  104. package/dist/sdk/merge/install.js +3 -3
  105. package/dist/sdk/merge/receipts.d.ts +6 -0
  106. package/dist/sdk/merge/receipts.js +2 -2
  107. package/dist/sdk/merge/reconcile.d.ts +6 -0
  108. package/dist/sdk/merge/reconcile.js +1 -1
  109. package/dist/sdk/merge/settlement-hook.d.ts +12 -0
  110. package/dist/sdk/merge/settlement-hook.js +7 -0
  111. package/dist/sdk/merge/stage.d.ts +13 -0
  112. package/dist/sdk/merge/stage.js +2 -0
  113. package/dist/sdk/mutation-events.js +1 -1
  114. package/dist/sdk/public-surface.json +1 -1
  115. package/dist/sdk/query/list.d.ts +2 -0
  116. package/dist/sdk/query/list.js +1 -1
  117. package/dist/sdk/runtime-extended-actions.js +1 -1
  118. package/dist/types.d.ts +2 -2
  119. package/dist/types.js +1 -1
  120. package/docs/COMMANDS.md +39 -0
  121. package/docs/CONFIGURATION.md +36 -1
  122. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +22 -3
  123. package/docs/MERGE_SAFETY.md +88 -5
  124. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +10 -0
  125. package/docs/RELEASING.md +8 -1
  126. package/docs/SDK.md +26 -0
  127. package/docs/SDK_CONTEXT_COORDINATION.md +71 -7
  128. package/docs/SDK_STORAGE_LIFECYCLE.md +24 -2
  129. package/docs/TESTING.md +15 -0
  130. package/docs/examples/ci/github-actions-pm-extension-gate.yml +1 -1
  131. package/docs/examples/ci/gitlab-ci-pm-extension-gate.yml +1 -1
  132. package/docs/examples/ci/jenkins-pm-extension-gate.Jenkinsfile +1 -1
  133. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  134. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  135. package/marketplace.json +1 -1
  136. package/node_modules/@opentelemetry/core/package.json +2 -1
  137. package/node_modules/@opentelemetry/instrumentation/package.json +2 -1
  138. package/node_modules/@opentelemetry/resources/package.json +2 -1
  139. package/node_modules/@opentelemetry/sdk-trace/package.json +2 -1
  140. package/node_modules/@opentelemetry/sdk-trace-base/package.json +2 -1
  141. package/node_modules/@sentry/core/build/cjs/client.js +5 -4
  142. package/node_modules/@sentry/core/build/cjs/tracing/ai/gen-ai-attributes.js +0 -4
  143. package/node_modules/@sentry/core/build/cjs/tracing/ai/utils.js +33 -23
  144. package/node_modules/@sentry/core/build/cjs/tracing/anthropic-ai/index.js +7 -6
  145. package/node_modules/@sentry/core/build/cjs/tracing/anthropic-ai/streaming.js +3 -1
  146. package/node_modules/@sentry/core/build/cjs/tracing/google-genai/index.js +13 -14
  147. package/node_modules/@sentry/core/build/cjs/tracing/google-genai/streaming.js +6 -1
  148. package/node_modules/@sentry/core/build/cjs/tracing/langchain/utils.js +71 -21
  149. package/node_modules/@sentry/core/build/cjs/tracing/langgraph/utils.js +23 -33
  150. package/node_modules/@sentry/core/build/cjs/tracing/openai/streaming.js +6 -0
  151. package/node_modules/@sentry/core/build/cjs/tracing/openai/utils.js +11 -0
  152. package/node_modules/@sentry/core/build/cjs/tracing/workers-ai/utils.js +1 -1
  153. package/node_modules/@sentry/core/build/cjs/utils/eventUtils.js +4 -0
  154. package/node_modules/@sentry/core/build/cjs/utils/prepareEvent.js +2 -2
  155. package/node_modules/@sentry/core/build/cjs/utils/version.js +1 -1
  156. package/node_modules/@sentry/core/build/esm/client.js +6 -5
  157. package/node_modules/@sentry/core/build/esm/package.json +1 -1
  158. package/node_modules/@sentry/core/build/esm/tracing/ai/gen-ai-attributes.js +1 -3
  159. package/node_modules/@sentry/core/build/esm/tracing/ai/utils.js +34 -24
  160. package/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/index.js +8 -7
  161. package/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/streaming.js +3 -1
  162. package/node_modules/@sentry/core/build/esm/tracing/google-genai/index.js +15 -16
  163. package/node_modules/@sentry/core/build/esm/tracing/google-genai/streaming.js +6 -1
  164. package/node_modules/@sentry/core/build/esm/tracing/langchain/utils.js +73 -24
  165. package/node_modules/@sentry/core/build/esm/tracing/langgraph/utils.js +24 -34
  166. package/node_modules/@sentry/core/build/esm/tracing/openai/streaming.js +6 -0
  167. package/node_modules/@sentry/core/build/esm/tracing/openai/utils.js +11 -0
  168. package/node_modules/@sentry/core/build/esm/tracing/workers-ai/utils.js +2 -2
  169. package/node_modules/@sentry/core/build/esm/utils/eventUtils.js +4 -1
  170. package/node_modules/@sentry/core/build/esm/utils/prepareEvent.js +2 -2
  171. package/node_modules/@sentry/core/build/esm/utils/version.js +1 -1
  172. package/node_modules/@sentry/core/build/types/tracing/ai/utils.d.ts +3 -7
  173. package/node_modules/@sentry/core/build/types/tracing/anthropic-ai/types.d.ts +2 -2
  174. package/node_modules/@sentry/core/build/types/tracing/langchain/types.d.ts +15 -0
  175. package/node_modules/@sentry/core/build/types/tracing/langchain/utils.d.ts +1 -0
  176. package/node_modules/@sentry/core/build/types/tracing/langgraph/utils.d.ts +2 -0
  177. package/node_modules/@sentry/core/build/types/tracing/openai/types.d.ts +2 -0
  178. package/node_modules/@sentry/core/build/types/utils/eventUtils.d.ts +2 -1
  179. package/node_modules/@sentry/core/build/types-ts3.8/tracing/ai/utils.d.ts +3 -7
  180. package/node_modules/@sentry/core/build/types-ts3.8/tracing/anthropic-ai/types.d.ts +2 -2
  181. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langchain/types.d.ts +15 -0
  182. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langchain/utils.d.ts +1 -0
  183. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langgraph/utils.d.ts +2 -0
  184. package/node_modules/@sentry/core/build/types-ts3.8/tracing/openai/types.d.ts +2 -0
  185. package/node_modules/@sentry/core/build/types-ts3.8/utils/eventUtils.d.ts +2 -1
  186. package/node_modules/@sentry/core/package.json +1 -1
  187. package/node_modules/@sentry/node/build/esm/package.json +1 -1
  188. package/node_modules/@sentry/node/package.json +5 -5
  189. package/node_modules/@sentry/node-core/build/cjs/integrations/anr/index.js +1 -1
  190. package/node_modules/@sentry/node-core/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
  191. package/node_modules/@sentry/node-core/build/esm/integrations/anr/index.js +1 -1
  192. package/node_modules/@sentry/node-core/build/esm/integrations/anr/worker-script.js +2 -2
  193. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/local-variables-async.js +1 -1
  194. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/worker-script.js +1 -1
  195. package/node_modules/@sentry/node-core/build/esm/package.json +1 -1
  196. package/node_modules/@sentry/node-core/package.json +10 -4
  197. package/node_modules/@sentry/opentelemetry/build/esm/package.json +1 -1
  198. package/node_modules/@sentry/opentelemetry/package.json +5 -2
  199. package/node_modules/@sentry/server-utils/build/THIRD-PARTY-LICENSES.txt +55 -55
  200. package/node_modules/@sentry/server-utils/build/esm/package.json +1 -1
  201. package/node_modules/@sentry/server-utils/package.json +2 -2
  202. package/node_modules/@toon-format/toon/README.md +10 -41
  203. package/node_modules/@toon-format/toon/dist/index.d.mts +12 -36
  204. package/node_modules/@toon-format/toon/dist/index.mjs +134 -202
  205. package/node_modules/@toon-format/toon/package.json +2 -2
  206. package/node_modules/debug/package.json +3 -0
  207. package/node_modules/fdir/package.json +3 -0
  208. package/node_modules/has-flag/index.d.ts +39 -0
  209. package/node_modules/has-flag/index.js +8 -0
  210. package/node_modules/has-flag/license +9 -0
  211. package/node_modules/has-flag/package.json +46 -0
  212. package/node_modules/has-flag/readme.md +89 -0
  213. package/node_modules/supports-color/browser.js +5 -0
  214. package/node_modules/supports-color/index.js +135 -0
  215. package/node_modules/supports-color/license +9 -0
  216. package/node_modules/supports-color/package.json +53 -0
  217. package/node_modules/supports-color/readme.md +76 -0
  218. package/package.json +4 -4
  219. package/packages/pm-beads/package.json +1 -1
  220. package/packages/pm-calendar/package.json +1 -1
  221. package/packages/pm-command-kit/package.json +1 -1
  222. package/packages/pm-digital-twin/package.json +1 -1
  223. package/packages/pm-governance-audit/package.json +1 -1
  224. package/packages/pm-guide-shell/package.json +1 -1
  225. package/packages/pm-kanban/package.json +1 -1
  226. package/packages/pm-lifecycle-hooks/package.json +1 -1
  227. package/packages/pm-linked-test-adapters/package.json +1 -1
  228. package/packages/pm-search-advanced/package.json +1 -1
  229. package/packages/pm-templates/package.json +1 -1
  230. package/packages/pm-todos/package.json +1 -1
  231. package/packages/pm-vcs/package.json +1 -1
  232. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  233. package/plugins/pm-claude/package.json +1 -1
  234. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  235. package/plugins/pm-codex/package.json +1 -1
  236. package/plugins/pm-codex/plugin.json +1 -1
  237. package/runtime-dependencies.json +1 -1
  238. package/dist/cli-bundle/chunks/chunk-4PNPDT2N.js +0 -236
  239. package/dist/cli-bundle/chunks/chunk-HY7FQ7QX.js +0 -2
  240. package/dist/cli-bundle/chunks/chunk-J4LPQCET.js +0 -8
  241. package/dist/cli-bundle/chunks/chunk-OZCSXX4D.js +0 -80
  242. package/dist/cli-bundle/chunks/chunk-VMCSTFSO.js +0 -2
  243. package/dist/cli-bundle/chunks/chunk-X2ONXFBP.js +0 -3
  244. package/dist/cli-bundle/chunks/chunk-X53HM753.js +0 -20
  245. package/dist/cli-bundle/chunks/register-mutation-EQYMT32A.js +0 -20
  246. package/dist/cli-bundle/chunks/register-operations-VXBGE4XI.js +0 -2
  247. package/dist/cli-bundle/chunks/register-setup-UUDEGFRO.js +0 -2
  248. package/dist/cli-bundle/focused-chunks/chunk-5JEFDEL3.js +0 -166
  249. package/dist/cli-bundle/focused-chunks/chunk-AH6NX6GM.js +0 -3
  250. package/dist/cli-bundle/focused-chunks/chunk-JXR6UKFM.js +0 -3
  251. package/dist/cli-bundle/focused-chunks/chunk-MBQF6HT6.js +0 -2
  252. package/dist/cli-bundle/focused-chunks/chunk-NZO7GOXD.js +0 -20
  253. package/dist/cli-bundle/focused-chunks/chunk-PYC7BF6Z.js +0 -8
  254. package/dist/cli-bundle/focused-chunks/chunk-QOSVJDOO.js +0 -75
  255. package/dist/cli-bundle/focused-chunks/chunk-RHTH5ILM.js +0 -2
  256. package/dist/cli-bundle/focused-chunks/chunk-TRFVAWF2.js +0 -26
@@ -234,8 +234,10 @@ declare function resolveListUpdatedAfter(options:ListOptions):string | undefined
234
234
  declare function parseIdsFilter(raw:unknown):Set<string> | undefined;
235
235
  declare function parseOffset(raw:string | undefined):number | undefined;
236
236
  declare function parseFieldSelectors(raw:string | undefined):string[] | undefined;
237
+ /** Resolve one explicit projection and keep requested sort context visible in brief rows. */
237
238
  declare function parseProjectionConfig(options:ListRuntimeOptions,invokedCommand?:ListCommandName):ListProjectionConfig;
238
239
  declare function normalizeProjectionField(field:string):string;
240
+ /** Resolve friendly timestamp aliases before checking the canonical sortable field set. */
239
241
  declare function parseSortField(raw:string | undefined):ListSortField | undefined;
240
242
  declare function parseSortOrder(raw:string | undefined):ListSortOrder | undefined;
241
243
  declare function parseAssigneeFilter(raw:string | undefined):"assigned" | "unassigned" | undefined;
@@ -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]="bf7ab12b-2cc6-5266-8da9-c49ef805e3fd")}catch{}})();import{renderPmCommand}from"../command-line.js";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,hasActiveOnReadHooks}from"../../core/extensions/index.js";import{toItemRecord}from"../../core/item/item-record.js";import{isTerminalStatus}from"../../core/item/status.js";import{collectDependencyBlockedIds}from"../actionability.js";import{isStatusAllFilterInput,parseStatusFilterCsv}from"../../core/item/status-filter.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{parseIntegerLimit}from"./parsers.js";import{parsePriorityFilterSet,parseStringFilterSet,parseTypeFilterSet}from"./multi-value-filters.js";import{collectRuntimeFilterValues,matchesRuntimeFilters}from"../../core/schema/runtime-field-filters.js";import{hasMissingMetadataFilter,itemMatchesMissingMetadata,lifecycleClassifierFromStatusRegistry}from"../../core/governance/metadata-coverage.js";import{contentFiltersNeedBody,contentFiltersNeedCollections,hasContentFieldFilter,itemMatchesContentFilters}from"../../core/governance/content-fields.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../../core/schema/runtime-schema.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{compareTimestampStrings,matchesTimestampFilters,nowIso,resolveIsoOrRelative}from"../../core/shared/time.js";import{listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody}from"../../core/store/item-store.js";import{HEAVY_METADATA_KEYS,readItemMetadataDerivedIndexState}from"../../core/store/item-metadata-cache.js";import{queryItemMetadataIndex}from"../../core/store/item-metadata-query-index.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{LIST_FILTER_FLAG_CONTRACTS}from"../cli-contracts/flag-contracts.js";import{resolveWorkspaceRelationshipKindRegistry}from"../graph/assembly.js";import{collectHierarchyRelations,indexHierarchyRelations}from"../graph/hierarchy-integrity.js";import{createQueryFingerprint,encodeQueryCursor,resolveQueryCursorStart,selectCursorSemanticOptions}from"../pagination.js";import{BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS,listListProjectionFields}from"./projection-contracts.js";import{BRIEF_LIST_FIELDS as BRIEF_LIST_FIELDS2,DEFAULT_COMPACT_LIST_FIELDS as DEFAULT_COMPACT_LIST_FIELDS2,LIST_COMMAND_DEFAULT_PROJECTIONS,listListProjectionFields as listListProjectionFields2}from"./projection-contracts.js";const resolveMissingMetadataFilters=options=>({acMissing:options.filterAcMissing===!0,estimatesMissing:options.filterEstimatesMissing===!0,resolutionMissing:options.filterResolutionMissing===!0,metadataMissing:options.filterMetadataMissing===!0,reviewerMissing:options.filterReviewerMissing===!0,riskMissing:options.filterRiskMissing===!0,confidenceMissing:options.filterConfidenceMissing===!0,sprintMissing:options.filterSprintMissing===!0,releaseMissing:options.filterReleaseMissing===!0}),CONTENT_FIELD_FLAG_MAPPINGS=[{field:"notes",presentKey:"hasNotes",absentKey:"noNotes",presentFlag:"--has-notes",absentFlag:"--no-notes"},{field:"learnings",presentKey:"hasLearnings",absentKey:"noLearnings",presentFlag:"--has-learnings",absentFlag:"--no-learnings"},{field:"files",presentKey:"hasFiles",absentKey:"noFiles",presentFlag:"--has-files",absentFlag:"--no-files"},{field:"docs",presentKey:"hasDocs",absentKey:"noDocs",presentFlag:"--has-docs",absentFlag:"--no-docs"},{field:"tests",presentKey:"hasTests",absentKey:"noTests",presentFlag:"--has-tests",absentFlag:"--no-tests"},{field:"comments",presentKey:"hasComments",absentKey:"noComments",presentFlag:"--has-comments",absentFlag:"--no-comments"},{field:"deps",presentKey:"hasDeps",absentKey:"noDeps",presentFlag:"--has-deps",absentFlag:"--no-deps"},{field:"body",presentKey:"hasBody",absentKey:"emptyBody",presentFlag:"--has-body",absentFlag:"--empty-body"},{field:"linked_command",presentKey:"hasLinkedCommand",absentKey:"noLinkedCommand",presentFlag:"--has-linked-command",absentFlag:"--no-linked-command"}],resolveContentFieldFilters=options=>{const conflict=CONTENT_FIELD_FLAG_MAPPINGS.find(mapping=>options[mapping.presentKey]===!0&&options[mapping.absentKey]===!0);if(conflict)throw new PmCliError(`Cannot combine ${conflict.presentFlag} with ${conflict.absentFlag} for the same field.`,EXIT_CODE.USAGE);return Object.fromEntries(CONTENT_FIELD_FLAG_MAPPINGS.flatMap(mapping=>options[mapping.presentKey]===!0?[[mapping.field,"present"]]:options[mapping.absentKey]===!0?[[mapping.field,"absent"]]:[]))},LIST_SORT_FIELDS=["priority","deadline","updated_at","created_at","title","parent"],LIST_SORT_ORDER_VALUES=["asc","desc"],HEAVY_PROJECTION_FIELDS=new Set(HEAVY_METADATA_KEYS);function resolveListCompleteness(warnings,indexed,strict){const unreadableItemCount=warnings.filter(warning=>warning.startsWith("item_list_item_read_failed:")).length,unreadableDirectoryCount=warnings.filter(warning=>warning.startsWith("item_list_directory_read_failed:")).length,completeness={status:indexed?"unchecked":unreadableItemCount+unreadableDirectoryCount>0?"partial":"complete",unreadable_item_count:unreadableItemCount,unreadable_directory_count:unreadableDirectoryCount};if(strict&&completeness.status==="partial")throw new PmCliError(`List source is incomplete: ${unreadableItemCount} item document(s) and ${unreadableDirectoryCount} item directory/directories could not be read.`,EXIT_CODE.GENERIC_FAILURE,{code:"list_source_incomplete",why:"Strict list reads fail closed so agents and SDK consumers never treat an omitted item as a complete workspace.",nextSteps:["Run pm validate --check-storage-integrity to locate unreadable tracker artifacts.","Repair the reported files or align the installed decoder version, then retry."]});return completeness}function isNonEmptyRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length>0}const CONTENT_FILTER_ECHO_ENTRIES=[{key:"hasNotes",summaryKey:"has_notes"},{key:"hasLearnings",summaryKey:"has_learnings"},{key:"hasFiles",summaryKey:"has_files"},{key:"hasDocs",summaryKey:"has_docs"},{key:"hasTests",summaryKey:"has_tests"},{key:"hasComments",summaryKey:"has_comments"},{key:"hasDeps",summaryKey:"has_deps"},{key:"hasBody",summaryKey:"has_body"},{key:"hasLinkedCommand",summaryKey:"has_linked_command"},{key:"noNotes",summaryKey:"no_notes"},{key:"noLearnings",summaryKey:"no_learnings"},{key:"noFiles",summaryKey:"no_files"},{key:"noDocs",summaryKey:"no_docs"},{key:"noTests",summaryKey:"no_tests"},{key:"noComments",summaryKey:"no_comments"},{key:"noDeps",summaryKey:"no_deps"},{key:"emptyBody",summaryKey:"empty_body"},{key:"noLinkedCommand",summaryKey:"no_linked_command"}],GOVERNANCE_MISSING_ECHO_ENTRIES=[{key:"filterReviewerMissing",summaryKey:"filter_reviewer_missing"},{key:"filterRiskMissing",summaryKey:"filter_risk_missing"},{key:"filterConfidenceMissing",summaryKey:"filter_confidence_missing"},{key:"filterSprintMissing",summaryKey:"filter_sprint_missing"},{key:"filterReleaseMissing",summaryKey:"filter_release_missing"}];function applyContentFilterEcho(filters,options){for(const entry of CONTENT_FILTER_ECHO_ENTRIES)options[entry.key]===!0&&(filters[entry.summaryKey]=!0)}function applyGovernanceMissingFilterEcho(filters,options){for(const entry of GOVERNANCE_MISSING_ECHO_ENTRIES)options[entry.key]===!0&&(filters[entry.summaryKey]=!0)}function applyFilterValueEcho(filters,options,entries){for(const entry of entries){const value=options[entry.optionKey];value!==void 0&&(filters[entry.summaryKey]=entry.normalize?entry.normalize(value):value)}}function buildContentFilterEcho(options){const echo={};return applyContentFilterEcho(echo,options),echo}function buildGovernanceMissingFilterEcho(options){const echo={};return applyGovernanceMissingFilterEcho(echo,options),echo}const COMPACT_LIST_VALUE_FILTER_ECHO_ENTRIES=[{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"ids",summaryKey:"ids"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"assigneeFilter",summaryKey:"assignee_filter"},{optionKey:"parent",summaryKey:"parent"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"}],VERBOSE_LIST_VALUE_FILTER_ECHO_ENTRIES=[{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"ids",summaryKey:"ids"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"assigneeFilter",summaryKey:"assignee_filter"},{optionKey:"parent",summaryKey:"parent"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"},{optionKey:"limit",summaryKey:"limit"},{optionKey:"offset",summaryKey:"offset"},{optionKey:"includeBody",summaryKey:"include_body"},{optionKey:"compact",summaryKey:"compact"},{optionKey:"fields",summaryKey:"fields"}],VERBOSE_LIST_BOOLEAN_FILTER_ECHO_ENTRIES=[{key:"filterAcMissing",summaryKey:"filter_ac_missing"},{key:"filterEstimatesMissing",summaryKey:"filter_estimates_missing"},{key:"filterResolutionMissing",summaryKey:"filter_resolution_missing"},{key:"filterMetadataMissing",summaryKey:"filter_metadata_missing"}],LIST_RECENT_WINDOW="-7d";function buildCompactListFilterSummary(params){const{filtersStatus,options,treeEnabled,treeDepth,sortField,sortOrder,runtimeFieldFilters}=params,filters={};return filtersStatus!==null&&(filters.status=filtersStatus),options.dependencyBlocked===!0&&(filters.blocked_semantics="status_or_dependency"),applyFilterValueEcho(filters,options,COMPACT_LIST_VALUE_FILTER_ECHO_ENTRIES),applyListWindowFilterEcho(filters,options),options.filterAcMissing===!0&&(filters.filter_ac_missing=!0),options.filterEstimatesMissing===!0&&(filters.filter_estimates_missing=!0),options.filterResolutionMissing===!0&&(filters.filter_resolution_missing=!0),options.filterMetadataMissing===!0&&(filters.filter_metadata_missing=!0),applyGovernanceMissingFilterEcho(filters,options),applyContentFilterEcho(filters,options),options.limit!==void 0&&(filters.limit=options.limit),options.offset!==void 0&&(filters.offset=options.offset),options.includeBody===!0&&(filters.include_body=!0),options.fields!==void 0&&(filters.fields=options.fields),treeEnabled&&(filters.tree=!0,treeDepth!==void 0&&(filters.tree_depth=treeDepth)),sortField!==void 0&&(filters.sort=sortField,filters.order=sortOrder),isNonEmptyRecord(runtimeFieldFilters)&&(filters.runtime_filters=runtimeFieldFilters),filters}function compareDefaultSort(left,right,statusRegistry){const leftTerminal=isTerminalStatus(left.status,statusRegistry),rightTerminal=isTerminalStatus(right.status,statusRegistry);if(leftTerminal!==rightTerminal)return leftTerminal?1:-1;const byPriority=left.priority-right.priority;if(byPriority!==0)return byPriority;const byUpdated=compareTimestampStrings(right.updated_at,left.updated_at);return byUpdated!==0?byUpdated:(left.id??"").localeCompare(right.id??"")}function sortItemsDefault(items,statusRegistry){return[...items].sort((left,right)=>compareDefaultSort(left,right,statusRegistry))}function parseDeadline(raw,fieldLabel){if(raw!==void 0)return resolveIsoOrRelative(raw,new Date,fieldLabel)}function parseTimestampWindow(raw,fieldLabel){if(raw==null)return;const value=String(raw).trim();if(value.length!==0)return resolveIsoOrRelative(value,new Date,fieldLabel)}function resolveListUpdatedAfter(options){const hasUpdatedAfter=options.updatedAfter!=null&&String(options.updatedAfter).trim().length>0;if([options.today===!0,options.recent===!0,hasUpdatedAfter].filter(selected=>selected).length>1)throw new PmCliError("Choose only one updated_at window: --today, --recent, or --updated-after.",EXIT_CODE.USAGE);if(options.today===!0){const today=new Date;return today.setHours(0,0,0,0),today.toISOString()}return options.recent===!0?parseTimestampWindow(LIST_RECENT_WINDOW,"recent"):parseTimestampWindow(options.updatedAfter,"updated-after")}function applyListWindowFilterEcho(filters,options){options.today===!0&&(filters.today=!0),options.recent===!0&&(filters.recent=!0)}function parseIdsFilter(raw){if(raw==null)return;const value=String(raw).trim();if(value.length===0)throw new PmCliError("--ids requires at least one non-empty item ID",EXIT_CODE.USAGE);const ids=value.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(ids.length===0)throw new PmCliError("--ids requires at least one non-empty item ID",EXIT_CODE.USAGE);return new Set(ids)}function parseOffset(raw){if(raw===void 0)return;const normalized=String(raw).trim(),parsed=normalized.length===0?Number.NaN:Number(normalized);if(!Number.isInteger(parsed)||parsed<0)throw new PmCliError("Offset filter must be a non-negative integer",EXIT_CODE.USAGE);return parsed}function parseFieldSelectors(raw){if(raw===void 0)return;const selectors=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(selectors.length===0)throw new PmCliError("List --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);return[...new Set(selectors)]}function parseProjectionConfig(options,invokedCommand=options.projectionCommand??"list"){const compactRequested=options.compact===!0,briefRequested=options.brief===!0,fullRequested=options.full===!0,fieldSelectors=parseFieldSelectors(options.fields);if(Number(compactRequested)+Number(briefRequested)+Number(fullRequested)+ +(fieldSelectors!==void 0)>1)throw new PmCliError("List projection options are mutually exclusive. Use one of --compact, --brief, --full, or --fields.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:`pm ${invokedCommand} --brief`,suggested_retry_args:[invokedCommand,"--brief"]}});return fullRequested?{mode:"full",fields:[]}:briefRequested?{mode:"brief",fields:[...BRIEF_LIST_FIELDS]}:compactRequested?{mode:"compact",fields:[...DEFAULT_COMPACT_LIST_FIELDS]}:fieldSelectors?{mode:"fields",fields:[...new Set(fieldSelectors.map(field=>normalizeProjectionField(field)))]}:{mode:"full",fields:[]}}function normalizeProjectionField(field){return field.startsWith("item.")?field.slice(5):field}function validateListProjectionFields(projection,runtimeMetadataKeys,invokedCommand){if(projection.mode!=="fields")return;const allowedValues=listListProjectionFields(runtimeMetadataKeys),allowed=new Set(allowedValues.map(field=>normalizeProjectionField(field))),unknown=projection.fields.filter(field=>!allowed.has(normalizeProjectionField(field)));if(unknown.length>0){const suggestedRetryArguments=[invokedCommand,"--fields",projection.fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown list --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm list-open --fields id,title,status,type,updated_at","pm list --fields id,title,parent,priority --limit 10","pm list-all --fields id,title,body --limit 5"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const LIST_SORT_FIELD_ALIASES=new Map([["updated","updated_at"],["update","updated_at"],["modified","updated_at"],["created","created_at"],["create","created_at"]]);function parseSortField(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase(),aliased=LIST_SORT_FIELD_ALIASES.get(normalized);if(aliased)return aliased;if(!LIST_SORT_FIELDS.includes(normalized))throw new PmCliError(`Sort field must be one of ${LIST_SORT_FIELDS.join("|")} (aliases: updated->updated_at, created->created_at)`,EXIT_CODE.USAGE);return normalized}function parseSortOrder(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(!LIST_SORT_ORDER_VALUES.includes(normalized))throw new PmCliError(`Sort order must be one of ${LIST_SORT_ORDER_VALUES.join("|")}`,EXIT_CODE.USAGE);return normalized}function parseTreeDepth(raw){return parseIntegerLimit(raw,"--tree-depth")}function parseAssigneeFilter(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(!normalized)throw new PmCliError("Assignee filter must be one of assigned|unassigned",EXIT_CODE.USAGE);if(normalized!=="assigned"&&normalized!=="unassigned")throw new PmCliError(`Invalid assignee filter "${raw}". Allowed: assigned|unassigned`,EXIT_CODE.USAGE);return normalized}function resolveStatusFilter(status,statusRegistry){return parseStatusFilterCsv(status,statusRegistry,{strict:!0})}function parseListTagFilters(raw){return parseStringFilterSet(raw,{label:"--tag",normalize:tag=>tag.toLowerCase()})}function appendUnknownTagWarning(items,rawTags,warnings){const requestedTags=parseListTagFilters(rawTags);if(requestedTags===void 0)return;const knownTags=new Set(items.flatMap(item=>item.tags.map(tag=>tag.trim().toLowerCase()))),unknownTags=[...requestedTags].filter(tag=>!knownTags.has(tag));unknownTags.length>0&&warnings.push(`unknown_tags:${unknownTags.join(",")}`)}function assertListAssigneeFilters(assigneeFilter,assigneeModeFilter){if(assigneeFilter&&[...assigneeFilter].some(value=>value.toLowerCase()==="none"||value.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)}function resolveListFilterSet(status,options,typeRegistry,statusRegistry){const assigneeFilter=parseStringFilterSet(options.assignee,{label:"--assignee"}),assigneeModeFilter=parseAssigneeFilter(options.assigneeFilter);assertListAssigneeFilters(assigneeFilter,assigneeModeFilter);const missingMetadataFilters=resolveMissingMetadataFilters(options),contentFieldFilters=resolveContentFieldFilters(options);return{idsFilter:parseIdsFilter(options.ids),statusSet:status&&status.length>0?new Set(status):void 0,excludeTerminal:options.excludeTerminal===!0,typeFilter:parseTypeFilterSet(options.type,typeRegistry),tagFilters:parseListTagFilters(options.tag),priorityFilter:parsePriorityFilterSet(options.priority),deadlineBefore:parseDeadline(options.deadlineBefore,"deadline-before"),deadlineAfter:parseDeadline(options.deadlineAfter,"deadline-after"),updatedAfter:resolveListUpdatedAfter(options),updatedBefore:parseTimestampWindow(options.updatedBefore,"updated-before"),createdAfter:parseTimestampWindow(options.createdAfter,"created-after"),createdBefore:parseTimestampWindow(options.createdBefore,"created-before"),assigneeFilter,assigneeModeFilter,parentFilter:options.parent?.trim(),treeEnabled:options.tree===!0,sprintFilter:parseStringFilterSet(options.sprint,{label:"--sprint"}),releaseFilter:parseStringFilterSet(options.release,{label:"--release"}),missingMetadataFilters,missingMetadataActive:hasMissingMetadataFilter(missingMetadataFilters),lifecycleClassifier:lifecycleClassifierFromStatusRegistry(statusRegistry),contentFieldFilters,contentFiltersActive:hasContentFieldFilter(contentFieldFilters)}}function matchesListIdentityFilters(item,filters,statusRegistry){return filters.idsFilter&&!filters.idsFilter.has(item.id)||filters.statusSet&&!filters.statusSet.has(item.status)||filters.excludeTerminal&&isTerminalStatus(item.status,statusRegistry)||filters.typeFilter&&!filters.typeFilter.has(item.type)||filters.tagFilters&&![...filters.tagFilters].some(tag=>(item.tags??[]).some(candidate=>candidate.trim().toLowerCase()===tag))?!1:filters.priorityFilter===void 0||filters.priorityFilter.has(item.priority)}function matchesListDateFilters(item,filters){return matchesTimestampFilters(item,filters)}function matchesListAssigneeFilterSet(item,filters){return filters.assigneeModeFilter==="assigned"&&!item.assignee||filters.assigneeModeFilter==="unassigned"&&item.assignee?!1:filters.assigneeFilter===void 0||item.assignee!==void 0&&filters.assigneeFilter.has(item.assignee)}function matchesListScopeFilters(item,filters,parentsByChild){const scalarParent=item.parent?.trim().toLowerCase(),logicalParentIds=[...new Set([...parentsByChild?.get(item.id.trim().toLowerCase())??[],...scalarParent?[scalarParent]:[]])];return filters.parentFilter!==void 0&&!filters.treeEnabled&&!logicalParentIds.includes(filters.parentFilter.trim().toLowerCase())||filters.sprintFilter!==void 0&&(item.sprint===void 0||!filters.sprintFilter.has(item.sprint))?!1:filters.releaseFilter===void 0||item.release!==void 0&&filters.releaseFilter.has(item.release)}function matchesListFilterSet(item,filters,statusRegistry,runtimeFieldFilters,parentsByChild){return!(!matchesListIdentityFilters(item,filters,statusRegistry)||!matchesListDateFilters(item,filters)||!matchesListAssigneeFilterSet(item,filters)||!matchesListScopeFilters(item,filters,parentsByChild)||filters.missingMetadataActive&&!itemMatchesMissingMetadata(item,filters.missingMetadataFilters,filters.lifecycleClassifier)||filters.contentFiltersActive&&!itemMatchesContentFilters(item,filters.contentFieldFilters)||!matchesRuntimeFilters(item,runtimeFieldFilters))}function applyFilters(items,status,options,typeRegistry,statusRegistry,runtimeFieldFilters,parentsByChild){const filters=resolveListFilterSet(status,options,typeRegistry,statusRegistry);return items.filter(item=>matchesListFilterSet(item,filters,statusRegistry,runtimeFieldFilters,parentsByChild))}function trimNonEmpty(value){if(typeof value!="string")return;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function withTreeMetadata(item,depth,childCount,parentId){const itemRecord=toItemRecord(item),title=typeof itemRecord.title=="string"?itemRecord.title:"",parent=parentId??trimNonEmpty(typeof itemRecord.parent=="string"?itemRecord.parent:void 0)??null;return{...item,tree_depth:depth,tree_parent:parent,tree_children:childCount,tree_title:`${" ".repeat(depth)}${title}`}}function buildListTreeIndexes(sortedItems,hierarchyIndexes){const byId=new Map,childrenByParent=new Map;for(const item of sortedItems){const itemId=item.id.trim().toLowerCase();byId.set(itemId,item);const parentIds=hierarchyIndexes?hierarchyIndexes.parents_by_child.get(itemId)??[]:[trimNonEmpty(item.parent)?.toLowerCase()].filter(value=>value!==void 0);for(const parentId of parentIds){const children=childrenByParent.get(parentId)??[];children.push(item),childrenByParent.set(parentId,children)}}return{byId,childrenByParent}}function resolveListTreeRoots(sortedItems,parentRoot,byId,childrenByParent,hierarchyIndexes){return parentRoot?[...childrenByParent.get(parentRoot.toLowerCase())??[]]:sortedItems.filter(item=>(hierarchyIndexes?hierarchyIndexes.parents_by_child.get(item.id.trim().toLowerCase())??[]:[trimNonEmpty(item.parent)?.toLowerCase()].filter(value=>value!==void 0)).every(parentId=>!byId.has(parentId)))}function orderItemsAsTree(sortedItems,parentRoot,maxDepth,hierarchyIndexes,completeItems=sortedItems){const{byId,childrenByParent}=buildListTreeIndexes(sortedItems,hierarchyIndexes),roots=resolveListTreeRoots(sortedItems,parentRoot,byId,childrenByParent,hierarchyIndexes),ordered=[],visited=new Set,canonicalIdByLowercase=new Map(completeItems.map(item=>[item.id.trim().toLowerCase(),item.id.trim()])),pending=[...roots].reverse().map(node=>({node,depth:0,parentId:parentRoot===void 0?void 0:canonicalIdByLowercase.get(parentRoot.trim().toLowerCase())??parentRoot.trim()}));for(;pending.length>0;){const{node,depth,parentId}=pending.pop(),nodeId=node.id.trim().toLowerCase();if(visited.has(nodeId))continue;visited.add(nodeId);const children=childrenByParent.get(nodeId)??[];if(ordered.push(withTreeMetadata(node,depth,children.length,parentId)),!(maxDepth!==void 0&&depth>=maxDepth))for(const child of[...children].reverse())pending.push({node:child,depth:depth+1,parentId:canonicalIdByLowercase.get(nodeId)})}if(parentRoot===void 0&&maxDepth===void 0)for(const item of sortedItems){const itemId=item.id.trim().toLowerCase();visited.has(itemId)||(visited.add(itemId),ordered.push(withTreeMetadata(item,0,childrenByParent.get(itemId)?.length??0)))}return ordered}function compareNullableString(left,right){return left===right?0:left===null?1:right===null?-1:left.localeCompare(right)}function compareNullableTimestamp(left,right){return left===right?0:left===null?1:right===null?-1:compareTimestampStrings(left,right)}function compareBySortField(left,right,field){switch(field){case"priority":return left.priority-right.priority;case"deadline":return compareNullableTimestamp(left.deadline??null,right.deadline??null);case"updated_at":return compareTimestampStrings(left.updated_at,right.updated_at);case"created_at":return compareTimestampStrings(left.created_at,right.created_at);case"title":return(left.title??"").localeCompare(right.title??"");case"parent":return compareNullableString(left.parent??null,right.parent??null);default:return 0}}function sortItems(items,sortField,sortOrder,statusRegistry){return sortField?[...items].sort((left,right)=>{const byField=compareBySortField(left,right,sortField);if(byField!==0)return sortOrder==="desc"?-byField:byField;const fallback=compareDefaultSort(left,right,statusRegistry);return sortOrder==="desc"?-fallback:fallback}):sortItemsDefault(items,statusRegistry)}function readListFieldValue(item,field,treeMode=!1){const normalized=normalizeProjectionField(field.trim());if(normalized.length===0)return null;const itemRecord=toItemRecord(item);return treeMode&&normalized==="title"&&typeof itemRecord.tree_title=="string"?itemRecord.tree_title:Object.prototype.hasOwnProperty.call(itemRecord,normalized)?itemRecord[normalized]??null:null}function projectListItems(items,projection,treeMode=!1){return projection.mode==="full"?items:items.map(item=>{const projected={};for(const field of projection.fields)projected[field]=readListFieldValue(item,field,treeMode);return projected})}function runtimeMetadataKeysForProjection(definitions){const keys=[];for(const field of definitions)keys.push(field.metadata_key);return keys}function resolveListPageLimit(options,totalRows){const explicitLimit=parseIntegerLimit(options.limit);if(explicitLimit!==void 0)return explicitLimit;if(options.noTruncate!==!0)return totalRows>=1e4?20:void 0}function resolveListPageStart(ordered,options,cursorFingerprint){return options.after===void 0?parseOffset(options.offset)??0:resolveQueryCursorStart(ordered,options.after,cursorFingerprint,item=>item.id)}function buildListPageExtras(limit,hasMore,nextCursor){return{...limit!==void 0?{applied_limit:limit}:{},has_more:hasMore,truncated:hasMore,next_cursor:nextCursor??null}}async function resolveListRuntimeContext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),runtimeFieldRegistry=resolveRuntimeFieldRegistry(settings.schema),invokedCommand=options.projectionCommand??"list",projection=parseProjectionConfig(options,invokedCommand);return validateListProjectionFields(projection,runtimeMetadataKeysForProjection(runtimeFieldRegistry.definitions),invokedCommand),{pmRoot,settings,statusRegistry,runtimeFieldFilters:collectRuntimeFilterValues(options,runtimeFieldRegistry,"list"),typeRegistry:resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),projection}}async function loadListItems(options,runtime,listWarnings){const projectionNeedsBody=runtime.projection.fields.some(field=>normalizeProjectionField(field)==="body"),projectionNeedsCollections=runtime.projection.mode==="full"||runtime.projection.fields.some(field=>HEAVY_PROJECTION_FIELDS.has(normalizeProjectionField(field))),contentFieldFilters=resolveContentFieldFilters(options),contentNeedsCollections=contentFiltersNeedCollections(contentFieldFilters),contentNeedsBody=contentFiltersNeedBody(contentFieldFilters);return options.includeBody||projectionNeedsBody||contentNeedsBody?await listAllItemMetadataWithBody(runtime.pmRoot,runtime.settings.item_format,runtime.typeRegistry.type_to_folder,listWarnings,runtime.settings.schema):projectionNeedsCollections||contentNeedsCollections?await listAllItemMetadata(runtime.pmRoot,runtime.settings.item_format,runtime.typeRegistry.type_to_folder,listWarnings,runtime.settings.schema):await listAllItemMetadataLight(runtime.pmRoot,runtime.settings.item_format,runtime.typeRegistry.type_to_folder,listWarnings,runtime.settings.schema)}function resolveListOrderingOptions(options){const sortField=parseSortField(options.sort),sortOrder=parseSortOrder(options.order)??"asc",treeEnabled=options.tree===!0;if(!treeEnabled&&options.treeDepth!==void 0)throw new PmCliError("List --tree-depth requires --tree",EXIT_CODE.USAGE);if(!sortField&&options.order!==void 0)throw new PmCliError("List --order requires --sort",EXIT_CODE.USAGE);return{sortField,sortOrder,treeEnabled,treeDepth:treeEnabled?parseTreeDepth(options.treeDepth):void 0,parentRoot:treeEnabled?trimNonEmpty(options.parent):void 0}}function resolveListStatusSelection(status,options,statusRegistry){const explicitStatus=resolveStatusFilter(options.status,statusRegistry);let lifecycleStatus;options.lifecycleBucket==="in_progress"?lifecycleStatus=[statusRegistry.in_progress_status]:options.lifecycleBucket==="open"&&(lifecycleStatus=[...statusRegistry.active_statuses].filter(entry=>entry!==statusRegistry.in_progress_status).sort((left,right)=>left.localeCompare(right)));const resolvedStatus=explicitStatus??lifecycleStatus??resolveStatusFilter(status,statusRegistry),explicitAllStatuses=isStatusAllFilterInput(options.status),effectiveOptions=explicitStatus||explicitAllStatuses?{...options,excludeTerminal:!1}:options;let filtersStatus="all";return explicitAllStatuses?filtersStatus="all":explicitStatus!==void 0?filtersStatus=explicitStatus.length===1?explicitStatus[0]:explicitStatus:options.lifecycleBucket!==void 0?filtersStatus=options.lifecycleBucket:resolvedStatus!==void 0?filtersStatus=resolvedStatus.length===1?resolvedStatus[0]:resolvedStatus:effectiveOptions.excludeTerminal===!0&&(filtersStatus=null),{resolvedStatus,explicitAllStatuses,effectiveOptions,filtersStatus}}function pageAndProjectListItems(ordered,options,projection,treeEnabled,cursorFingerprint){if(options.after!==void 0&&options.offset!==void 0)throw new PmCliError("List --after cannot be combined with --offset.",EXIT_CODE.USAGE);const limit=resolveListPageLimit(options,ordered.length),offset=resolveListPageStart(ordered,options,cursorFingerprint),limited=limit===void 0?ordered.slice(offset):ordered.slice(offset,offset+limit),projected=projectListItems(limited,projection,treeEnabled),totalMatched=ordered.length,hasMore=limited.length>0&&offset+limited.length<totalMatched,nextCursor=hasMore&&limited.length>0?encodeQueryCursor(cursorFingerprint,limited[limited.length-1].id,offset+limited.length-1):void 0;return{projected,totalMatched,pageExtras:buildListPageExtras(limit,hasMore,nextCursor)}}function buildListCursorFingerprint(status,options,ordering,pmRoot){return createQueryFingerprint("list",{pmRoot,status,options:selectCursorSemanticOptions(options,LIST_FILTER_FLAG_CONTRACTS),sort:ordering.sortField??"default",order:ordering.sortOrder,tree:ordering.treeEnabled,tree_depth:ordering.treeDepth??null})}async function tryLoadIndexedListPage(params){const{options,runtime,statusSelection,ordering}=params,supportedOptionKeys=new Set(["status","limit","offset","compact","brief","full","fields","format","stream","includeBody","excludeTerminal","dependencyBlocked","lifecycleBucket","noTruncate","projectionCommand","truncate","notes","learnings","files","docs","tests","comments","deps","linkedCommand"]),projectionNeedsHeavyData=[runtime.projection.mode==="full",runtime.projection.fields.some(field=>{const normalized=normalizeProjectionField(field);return normalized==="body"||HEAVY_PROJECTION_FIELDS.has(normalized)})].includes(!0);if([options.limit===void 0,options.after!==void 0,options.noTruncate===!0,options.includeBody===!0,options.dependencyBlocked===!0,options.strictRead===!0,ordering.treeEnabled,ordering.sortField!==void 0,projectionNeedsHeavyData,hasActiveOnReadHooks(),Object.keys(runtime.runtimeFieldFilters).length>0,Object.entries(options).some(([key,value])=>value!==void 0&&!supportedOptionKeys.has(key))].includes(!0))return null;const indexState=await readItemMetadataDerivedIndexState(runtime.pmRoot,[...new Set(Object.values(runtime.typeRegistry.type_to_folder))]);if(!indexState)return null;const limit=parseIntegerLimit(options.limit),offset=parseOffset(options.offset)??0,indexed=await queryItemMetadataIndex({pmRoot:runtime.pmRoot,expectedSourceCursor:indexState.source_cursor,query:{statuses:statusSelection.resolvedStatus,excludeStatuses:statusSelection.resolvedStatus===void 0&&statusSelection.effectiveOptions.excludeTerminal===!0?[...runtime.statusRegistry.terminal_statuses]:void 0,terminalStatuses:[...runtime.statusRegistry.terminal_statuses],limit,offset}});if(!indexed)return null;const hasMore=indexed.items.length>0&&offset+indexed.items.length<indexed.total,nextCursor=hasMore?encodeQueryCursor(buildListCursorFingerprint(statusSelection.filtersStatus,options,ordering,runtime.pmRoot),indexed.items.at(-1).id,offset+indexed.items.length-1):void 0;return{projected:projectListItems(indexed.items,runtime.projection,!1),totalMatched:indexed.total,pageExtras:buildListPageExtras(limit,hasMore,nextCursor)}}function buildVerboseListFilters(params){const{filtersStatus,options,noTruncate,treeEnabled,treeDepth,sortField,sortOrder,runtimeFieldFilters}=params,filters={};filtersStatus!==null&&(filters.status=filtersStatus),options.dependencyBlocked===!0&&(filters.blocked_semantics="status_or_dependency");const optionRecord=options;for(const entry of VERBOSE_LIST_VALUE_FILTER_ECHO_ENTRIES){const value=optionRecord[entry.optionKey];value!=null&&(filters[entry.summaryKey]=value)}for(const entry of VERBOSE_LIST_BOOLEAN_FILTER_ECHO_ENTRIES)optionRecord[entry.key]===!0&&(filters[entry.summaryKey]=!0);return Object.assign(filters,buildGovernanceMissingFilterEcho(options),buildContentFilterEcho(options)),applyListWindowFilterEcho(filters,options),noTruncate&&(filters.no_truncate=!0),options.strictRead===!0&&(filters.strict_read=!0),treeEnabled&&(filters.tree=!0,treeDepth!==void 0&&(filters.tree_depth=treeDepth)),sortField!==void 0&&(filters.sort=sortField,filters.order=sortOrder),filters.runtime_filters=runtimeFieldFilters,filters}async function runList(status,options,global2){const runtime=await resolveListRuntimeContext(options,global2),listWarnings=[],ordering=resolveListOrderingOptions(options),statusSelection=resolveListStatusSelection(status,options,runtime.statusRegistry),noTruncate=options.noTruncate===!0,indexedPage=await tryLoadIndexedListPage({options,runtime,statusSelection,ordering});let page=indexedPage;if(!page){const items=await loadListItems(options,runtime,listWarnings),hierarchyIndexes=ordering.treeEnabled||trimNonEmpty(options.parent)!==void 0?indexHierarchyRelations(collectHierarchyRelations(items,resolveWorkspaceRelationshipKindRegistry())):void 0;appendUnknownTagWarning(items,options.tag,listWarnings);const filtered=applyFilters(items,statusSelection.resolvedStatus,statusSelection.effectiveOptions,runtime.typeRegistry,runtime.statusRegistry,runtime.runtimeFieldFilters,hierarchyIndexes?.parents_by_child),scoped=options.dependencyBlocked===!0?(()=>{const blockedIds=collectDependencyBlockedIds(items,runtime.statusRegistry);return filtered.filter(item=>blockedIds.has(item.id.trim().toLowerCase()))})():filtered,sorted=sortItems(scoped,ordering.sortField,ordering.sortOrder,runtime.statusRegistry),ordered=ordering.treeEnabled?orderItemsAsTree(sorted,ordering.parentRoot,ordering.treeDepth,hierarchyIndexes,items):sorted;page=pageAndProjectListItems(ordered,options,runtime.projection,ordering.treeEnabled,buildListCursorFingerprint(statusSelection.filtersStatus,options,ordering,runtime.pmRoot))}const now=nowIso(),warnings=[...new Set(listWarnings)].sort((left,right)=>left.localeCompare(right)),completeness=resolveListCompleteness(warnings,indexedPage!==null,options.strictRead===!0),projectionFields=runtime.projection.mode==="full"?null:[...runtime.projection.fields];if(runtime.projection.mode==="compact"&&options.compact===!0){const compactFilters=buildCompactListFilterSummary({filtersStatus:statusSelection.filtersStatus,options,treeEnabled:ordering.treeEnabled,treeDepth:ordering.treeDepth,sortField:ordering.sortField,sortOrder:ordering.sortOrder,runtimeFieldFilters:runtime.runtimeFieldFilters});return{items:page.projected,count:page.projected.length,total:page.totalMatched,...page.pageExtras,completeness,filters:compactFilters,projection:{mode:"compact",fields:projectionFields},...warnings.length>0?{warnings}:{}}}return{items:page.projected,count:page.projected.length,total:page.totalMatched,...page.pageExtras,completeness,filters:buildVerboseListFilters({filtersStatus:statusSelection.filtersStatus,options,noTruncate,treeEnabled:ordering.treeEnabled,treeDepth:ordering.treeDepth,sortField:ordering.sortField,sortOrder:ordering.sortOrder,runtimeFieldFilters:runtime.runtimeFieldFilters}),projection:{mode:runtime.projection.mode,fields:projectionFields},sorting:{sort:ordering.sortField??"default",order:ordering.sortField?ordering.sortOrder:"asc"},now,...warnings.length>0?{warnings}:{}}}const _testOnly={applyFilters,buildCompactListFilterSummary,buildContentFilterEcho,buildGovernanceMissingFilterEcho,resolveContentFieldFilters,resolveMissingMetadataFilters,compareBySortField,compareDefaultSort,compareNullableString,compareNullableTimestamp,normalizeProjectionField,parseAssigneeFilter,parseFieldSelectors,parseIdsFilter,parseOffset,parseProjectionConfig,resolveListUpdatedAfter,resolveListPageLimit,parseSortField,parseSortOrder,orderItemsAsTree,projectListItems,readListFieldValue,runtimeMetadataKeysForProjection,sortItems,trimNonEmpty,withTreeMetadata};export{BRIEF_LIST_FIELDS2 as BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS2 as DEFAULT_COMPACT_LIST_FIELDS,LIST_COMMAND_DEFAULT_PROJECTIONS,LIST_SORT_FIELDS,LIST_SORT_ORDER_VALUES,_testOnly,applyFilterValueEcho,buildContentFilterEcho,buildGovernanceMissingFilterEcho,listListProjectionFields2 as listListProjectionFields,resolveContentFieldFilters,resolveMissingMetadataFilters,runList};
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]="8c315632-500b-53c4-a8ed-99865c8c0246")}catch{}})();import{renderPmCommand}from"../command-line.js";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,hasActiveOnReadHooks}from"../../core/extensions/index.js";import{toItemRecord}from"../../core/item/item-record.js";import{isTerminalStatus}from"../../core/item/status.js";import{collectDependencyBlockedIds}from"../actionability.js";import{isStatusAllFilterInput,parseStatusFilterCsv}from"../../core/item/status-filter.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{parseIntegerLimit}from"./parsers.js";import{parsePriorityFilterSet,parseStringFilterSet,parseTypeFilterSet}from"./multi-value-filters.js";import{collectRuntimeFilterValues,matchesRuntimeFilters}from"../../core/schema/runtime-field-filters.js";import{hasMissingMetadataFilter,itemMatchesMissingMetadata,lifecycleClassifierFromStatusRegistry}from"../../core/governance/metadata-coverage.js";import{contentFiltersNeedBody,contentFiltersNeedCollections,hasContentFieldFilter,itemMatchesContentFilters}from"../../core/governance/content-fields.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../../core/schema/runtime-schema.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{compareTimestampStrings,matchesTimestampFilters,nowIso,resolveIsoOrRelative}from"../../core/shared/time.js";import{listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody}from"../../core/store/item-store.js";import{HEAVY_METADATA_KEYS,readItemMetadataDerivedIndexState}from"../../core/store/item-metadata-cache.js";import{queryItemMetadataIndex}from"../../core/store/item-metadata-query-index.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{LIST_FILTER_FLAG_CONTRACTS}from"../cli-contracts/flag-contracts.js";import{resolveWorkspaceRelationshipKindRegistry}from"../graph/assembly.js";import{collectHierarchyRelations,indexHierarchyRelations}from"../graph/hierarchy-integrity.js";import{createQueryFingerprint,encodeQueryCursor,resolveQueryCursorStart,selectCursorSemanticOptions}from"../pagination.js";import{BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS,listListProjectionFields}from"./projection-contracts.js";import{BRIEF_LIST_FIELDS as BRIEF_LIST_FIELDS2,DEFAULT_COMPACT_LIST_FIELDS as DEFAULT_COMPACT_LIST_FIELDS2,LIST_COMMAND_DEFAULT_PROJECTIONS,listListProjectionFields as listListProjectionFields2}from"./projection-contracts.js";const resolveMissingMetadataFilters=options=>({acMissing:options.filterAcMissing===!0,estimatesMissing:options.filterEstimatesMissing===!0,resolutionMissing:options.filterResolutionMissing===!0,metadataMissing:options.filterMetadataMissing===!0,reviewerMissing:options.filterReviewerMissing===!0,riskMissing:options.filterRiskMissing===!0,confidenceMissing:options.filterConfidenceMissing===!0,sprintMissing:options.filterSprintMissing===!0,releaseMissing:options.filterReleaseMissing===!0}),CONTENT_FIELD_FLAG_MAPPINGS=[{field:"notes",presentKey:"hasNotes",absentKey:"noNotes",presentFlag:"--has-notes",absentFlag:"--no-notes"},{field:"learnings",presentKey:"hasLearnings",absentKey:"noLearnings",presentFlag:"--has-learnings",absentFlag:"--no-learnings"},{field:"files",presentKey:"hasFiles",absentKey:"noFiles",presentFlag:"--has-files",absentFlag:"--no-files"},{field:"docs",presentKey:"hasDocs",absentKey:"noDocs",presentFlag:"--has-docs",absentFlag:"--no-docs"},{field:"tests",presentKey:"hasTests",absentKey:"noTests",presentFlag:"--has-tests",absentFlag:"--no-tests"},{field:"comments",presentKey:"hasComments",absentKey:"noComments",presentFlag:"--has-comments",absentFlag:"--no-comments"},{field:"deps",presentKey:"hasDeps",absentKey:"noDeps",presentFlag:"--has-deps",absentFlag:"--no-deps"},{field:"body",presentKey:"hasBody",absentKey:"emptyBody",presentFlag:"--has-body",absentFlag:"--empty-body"},{field:"linked_command",presentKey:"hasLinkedCommand",absentKey:"noLinkedCommand",presentFlag:"--has-linked-command",absentFlag:"--no-linked-command"}],resolveContentFieldFilters=options=>{const conflict=CONTENT_FIELD_FLAG_MAPPINGS.find(mapping=>options[mapping.presentKey]===!0&&options[mapping.absentKey]===!0);if(conflict)throw new PmCliError(`Cannot combine ${conflict.presentFlag} with ${conflict.absentFlag} for the same field.`,EXIT_CODE.USAGE);return Object.fromEntries(CONTENT_FIELD_FLAG_MAPPINGS.flatMap(mapping=>options[mapping.presentKey]===!0?[[mapping.field,"present"]]:options[mapping.absentKey]===!0?[[mapping.field,"absent"]]:[]))},LIST_SORT_FIELDS=["priority","deadline","updated_at","created_at","title","parent"],LIST_SORT_ORDER_VALUES=["asc","desc"],HEAVY_PROJECTION_FIELDS=new Set(HEAVY_METADATA_KEYS);function resolveListCompleteness(warnings,indexed,strict){const unreadableItemCount=warnings.filter(warning=>warning.startsWith("item_list_item_read_failed:")).length,unreadableDirectoryCount=warnings.filter(warning=>warning.startsWith("item_list_directory_read_failed:")).length,completeness={status:indexed?"unchecked":unreadableItemCount+unreadableDirectoryCount>0?"partial":"complete",unreadable_item_count:unreadableItemCount,unreadable_directory_count:unreadableDirectoryCount};if(strict&&completeness.status==="partial")throw new PmCliError(`List source is incomplete: ${unreadableItemCount} item document(s) and ${unreadableDirectoryCount} item directory/directories could not be read.`,EXIT_CODE.GENERIC_FAILURE,{code:"list_source_incomplete",why:"Strict list reads fail closed so agents and SDK consumers never treat an omitted item as a complete workspace.",nextSteps:["Run pm validate --check-storage-integrity to locate unreadable tracker artifacts.","Repair the reported files or align the installed decoder version, then retry."]});return completeness}function isNonEmptyRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length>0}const CONTENT_FILTER_ECHO_ENTRIES=[{key:"hasNotes",summaryKey:"has_notes"},{key:"hasLearnings",summaryKey:"has_learnings"},{key:"hasFiles",summaryKey:"has_files"},{key:"hasDocs",summaryKey:"has_docs"},{key:"hasTests",summaryKey:"has_tests"},{key:"hasComments",summaryKey:"has_comments"},{key:"hasDeps",summaryKey:"has_deps"},{key:"hasBody",summaryKey:"has_body"},{key:"hasLinkedCommand",summaryKey:"has_linked_command"},{key:"noNotes",summaryKey:"no_notes"},{key:"noLearnings",summaryKey:"no_learnings"},{key:"noFiles",summaryKey:"no_files"},{key:"noDocs",summaryKey:"no_docs"},{key:"noTests",summaryKey:"no_tests"},{key:"noComments",summaryKey:"no_comments"},{key:"noDeps",summaryKey:"no_deps"},{key:"emptyBody",summaryKey:"empty_body"},{key:"noLinkedCommand",summaryKey:"no_linked_command"}],GOVERNANCE_MISSING_ECHO_ENTRIES=[{key:"filterReviewerMissing",summaryKey:"filter_reviewer_missing"},{key:"filterRiskMissing",summaryKey:"filter_risk_missing"},{key:"filterConfidenceMissing",summaryKey:"filter_confidence_missing"},{key:"filterSprintMissing",summaryKey:"filter_sprint_missing"},{key:"filterReleaseMissing",summaryKey:"filter_release_missing"}];function applyContentFilterEcho(filters,options){for(const entry of CONTENT_FILTER_ECHO_ENTRIES)options[entry.key]===!0&&(filters[entry.summaryKey]=!0)}function applyGovernanceMissingFilterEcho(filters,options){for(const entry of GOVERNANCE_MISSING_ECHO_ENTRIES)options[entry.key]===!0&&(filters[entry.summaryKey]=!0)}function applyFilterValueEcho(filters,options,entries){for(const entry of entries){const value=options[entry.optionKey];value!==void 0&&(filters[entry.summaryKey]=entry.normalize?entry.normalize(value):value)}}function buildContentFilterEcho(options){const echo={};return applyContentFilterEcho(echo,options),echo}function buildGovernanceMissingFilterEcho(options){const echo={};return applyGovernanceMissingFilterEcho(echo,options),echo}const COMPACT_LIST_VALUE_FILTER_ECHO_ENTRIES=[{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"ids",summaryKey:"ids"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"assigneeFilter",summaryKey:"assignee_filter"},{optionKey:"parent",summaryKey:"parent"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"}],VERBOSE_LIST_VALUE_FILTER_ECHO_ENTRIES=[{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"ids",summaryKey:"ids"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"assigneeFilter",summaryKey:"assignee_filter"},{optionKey:"parent",summaryKey:"parent"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"},{optionKey:"limit",summaryKey:"limit"},{optionKey:"offset",summaryKey:"offset"},{optionKey:"includeBody",summaryKey:"include_body"},{optionKey:"compact",summaryKey:"compact"},{optionKey:"fields",summaryKey:"fields"}],VERBOSE_LIST_BOOLEAN_FILTER_ECHO_ENTRIES=[{key:"filterAcMissing",summaryKey:"filter_ac_missing"},{key:"filterEstimatesMissing",summaryKey:"filter_estimates_missing"},{key:"filterResolutionMissing",summaryKey:"filter_resolution_missing"},{key:"filterMetadataMissing",summaryKey:"filter_metadata_missing"}],LIST_RECENT_WINDOW="-7d";function buildCompactListFilterSummary(params){const{filtersStatus,options,treeEnabled,treeDepth,sortField,sortOrder,runtimeFieldFilters}=params,filters={};return filtersStatus!==null&&(filters.status=filtersStatus),options.dependencyBlocked===!0&&(filters.blocked_semantics="status_or_dependency"),applyFilterValueEcho(filters,options,COMPACT_LIST_VALUE_FILTER_ECHO_ENTRIES),applyListWindowFilterEcho(filters,options),options.filterAcMissing===!0&&(filters.filter_ac_missing=!0),options.filterEstimatesMissing===!0&&(filters.filter_estimates_missing=!0),options.filterResolutionMissing===!0&&(filters.filter_resolution_missing=!0),options.filterMetadataMissing===!0&&(filters.filter_metadata_missing=!0),applyGovernanceMissingFilterEcho(filters,options),applyContentFilterEcho(filters,options),options.limit!==void 0&&(filters.limit=options.limit),options.offset!==void 0&&(filters.offset=options.offset),options.includeBody===!0&&(filters.include_body=!0),options.fields!==void 0&&(filters.fields=options.fields),treeEnabled&&(filters.tree=!0,treeDepth!==void 0&&(filters.tree_depth=treeDepth)),sortField!==void 0&&(filters.sort=sortField,filters.order=sortOrder),isNonEmptyRecord(runtimeFieldFilters)&&(filters.runtime_filters=runtimeFieldFilters),filters}function compareDefaultSort(left,right,statusRegistry){const leftTerminal=isTerminalStatus(left.status,statusRegistry),rightTerminal=isTerminalStatus(right.status,statusRegistry);if(leftTerminal!==rightTerminal)return leftTerminal?1:-1;const byPriority=left.priority-right.priority;if(byPriority!==0)return byPriority;const byUpdated=compareTimestampStrings(right.updated_at,left.updated_at);return byUpdated!==0?byUpdated:(left.id??"").localeCompare(right.id??"")}function sortItemsDefault(items,statusRegistry){return[...items].sort((left,right)=>compareDefaultSort(left,right,statusRegistry))}function parseDeadline(raw,fieldLabel){if(raw!==void 0)return resolveIsoOrRelative(raw,new Date,fieldLabel)}function parseTimestampWindow(raw,fieldLabel){if(raw==null)return;const value=String(raw).trim();if(value.length!==0)return resolveIsoOrRelative(value,new Date,fieldLabel)}function resolveListUpdatedAfter(options){const hasUpdatedAfter=options.updatedAfter!=null&&String(options.updatedAfter).trim().length>0;if([options.today===!0,options.recent===!0,hasUpdatedAfter].filter(selected=>selected).length>1)throw new PmCliError("Choose only one updated_at window: --today, --recent, or --updated-after.",EXIT_CODE.USAGE);if(options.today===!0){const today=new Date;return today.setHours(0,0,0,0),today.toISOString()}return options.recent===!0?parseTimestampWindow(LIST_RECENT_WINDOW,"recent"):parseTimestampWindow(options.updatedAfter,"updated-after")}function applyListWindowFilterEcho(filters,options){options.today===!0&&(filters.today=!0),options.recent===!0&&(filters.recent=!0)}function parseIdsFilter(raw){if(raw==null)return;const value=String(raw).trim();if(value.length===0)throw new PmCliError("--ids requires at least one non-empty item ID",EXIT_CODE.USAGE);const ids=value.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(ids.length===0)throw new PmCliError("--ids requires at least one non-empty item ID",EXIT_CODE.USAGE);return new Set(ids)}function parseOffset(raw){if(raw===void 0)return;const normalized=String(raw).trim(),parsed=normalized.length===0?Number.NaN:Number(normalized);if(!Number.isInteger(parsed)||parsed<0)throw new PmCliError("Offset filter must be a non-negative integer",EXIT_CODE.USAGE);return parsed}function parseFieldSelectors(raw){if(raw===void 0)return;const selectors=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(selectors.length===0)throw new PmCliError("List --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);return[...new Set(selectors)]}function parseProjectionConfig(options,invokedCommand=options.projectionCommand??"list"){const compactRequested=options.compact===!0,briefRequested=options.brief===!0,fullRequested=options.full===!0,fieldSelectors=parseFieldSelectors(options.fields);if(Number(compactRequested)+Number(briefRequested)+Number(fullRequested)+ +(fieldSelectors!==void 0)>1)throw new PmCliError("List projection options are mutually exclusive. Use one of --compact, --brief, --full, or --fields.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:`pm ${invokedCommand} --brief`,suggested_retry_args:[invokedCommand,"--brief"]}});if(fullRequested)return{mode:"full",fields:[]};if(briefRequested){const sortField=parseSortField(options.sort);return{mode:"brief",fields:[...new Set([...BRIEF_LIST_FIELDS,...sortField?[sortField]:[]])]}}return compactRequested?{mode:"compact",fields:[...DEFAULT_COMPACT_LIST_FIELDS]}:fieldSelectors?{mode:"fields",fields:[...new Set(fieldSelectors.map(field=>normalizeProjectionField(field)))]}:{mode:"full",fields:[]}}function normalizeProjectionField(field){return field.startsWith("item.")?field.slice(5):field}function validateListProjectionFields(projection,runtimeMetadataKeys,invokedCommand){if(projection.mode!=="fields")return;const allowedValues=listListProjectionFields(runtimeMetadataKeys),allowed=new Set(allowedValues.map(field=>normalizeProjectionField(field))),unknown=projection.fields.filter(field=>!allowed.has(normalizeProjectionField(field)));if(unknown.length>0){const suggestedRetryArguments=[invokedCommand,"--fields",projection.fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown list --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm list --status open --fields id,title,status","pm list --fields id,title,parent,priority --limit 10","pm list --all --fields id,title,body --limit 5"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const LIST_SORT_FIELD_ALIASES=new Map([["updated","updated_at"],["update","updated_at"],["modified","updated_at"],["created","created_at"],["create","created_at"]]);function parseSortField(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase(),aliased=LIST_SORT_FIELD_ALIASES.get(normalized);if(aliased)return aliased;if(!LIST_SORT_FIELDS.includes(normalized))throw new PmCliError(`Sort field must be one of ${LIST_SORT_FIELDS.join("|")} (aliases: updated->updated_at, created->created_at)`,EXIT_CODE.USAGE);return normalized}function parseSortOrder(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(!LIST_SORT_ORDER_VALUES.includes(normalized))throw new PmCliError(`Sort order must be one of ${LIST_SORT_ORDER_VALUES.join("|")}`,EXIT_CODE.USAGE);return normalized}function parseTreeDepth(raw){return parseIntegerLimit(raw,"--tree-depth")}function parseAssigneeFilter(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(!normalized)throw new PmCliError("Assignee filter must be one of assigned|unassigned",EXIT_CODE.USAGE);if(normalized!=="assigned"&&normalized!=="unassigned")throw new PmCliError(`Invalid assignee filter "${raw}". Allowed: assigned|unassigned`,EXIT_CODE.USAGE);return normalized}function resolveStatusFilter(status,statusRegistry){return parseStatusFilterCsv(status,statusRegistry,{strict:!0})}function parseListTagFilters(raw){return parseStringFilterSet(raw,{label:"--tag",normalize:tag=>tag.toLowerCase()})}function appendUnknownTagWarning(items,rawTags,warnings){const requestedTags=parseListTagFilters(rawTags);if(requestedTags===void 0)return;const knownTags=new Set(items.flatMap(item=>item.tags.map(tag=>tag.trim().toLowerCase()))),unknownTags=[...requestedTags].filter(tag=>!knownTags.has(tag));unknownTags.length>0&&warnings.push(`unknown_tags:${unknownTags.join(",")}`)}function assertListAssigneeFilters(assigneeFilter,assigneeModeFilter){if(assigneeFilter&&[...assigneeFilter].some(value=>value.toLowerCase()==="none"||value.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)}function resolveListFilterSet(status,options,typeRegistry,statusRegistry){const assigneeFilter=parseStringFilterSet(options.assignee,{label:"--assignee"}),assigneeModeFilter=parseAssigneeFilter(options.assigneeFilter);assertListAssigneeFilters(assigneeFilter,assigneeModeFilter);const missingMetadataFilters=resolveMissingMetadataFilters(options),contentFieldFilters=resolveContentFieldFilters(options);return{idsFilter:parseIdsFilter(options.ids),statusSet:status&&status.length>0?new Set(status):void 0,excludeTerminal:options.excludeTerminal===!0,typeFilter:parseTypeFilterSet(options.type,typeRegistry),tagFilters:parseListTagFilters(options.tag),priorityFilter:parsePriorityFilterSet(options.priority),deadlineBefore:parseDeadline(options.deadlineBefore,"deadline-before"),deadlineAfter:parseDeadline(options.deadlineAfter,"deadline-after"),updatedAfter:resolveListUpdatedAfter(options),updatedBefore:parseTimestampWindow(options.updatedBefore,"updated-before"),createdAfter:parseTimestampWindow(options.createdAfter,"created-after"),createdBefore:parseTimestampWindow(options.createdBefore,"created-before"),assigneeFilter,assigneeModeFilter,parentFilter:options.parent?.trim(),treeEnabled:options.tree===!0,sprintFilter:parseStringFilterSet(options.sprint,{label:"--sprint"}),releaseFilter:parseStringFilterSet(options.release,{label:"--release"}),missingMetadataFilters,missingMetadataActive:hasMissingMetadataFilter(missingMetadataFilters),lifecycleClassifier:lifecycleClassifierFromStatusRegistry(statusRegistry),contentFieldFilters,contentFiltersActive:hasContentFieldFilter(contentFieldFilters)}}function matchesListIdentityFilters(item,filters,statusRegistry){return filters.idsFilter&&!filters.idsFilter.has(item.id)||filters.statusSet&&!filters.statusSet.has(item.status)||filters.excludeTerminal&&isTerminalStatus(item.status,statusRegistry)||filters.typeFilter&&!filters.typeFilter.has(item.type)||filters.tagFilters&&![...filters.tagFilters].some(tag=>(item.tags??[]).some(candidate=>candidate.trim().toLowerCase()===tag))?!1:filters.priorityFilter===void 0||filters.priorityFilter.has(item.priority)}function matchesListDateFilters(item,filters){return matchesTimestampFilters(item,filters)}function matchesListAssigneeFilterSet(item,filters){return filters.assigneeModeFilter==="assigned"&&!item.assignee||filters.assigneeModeFilter==="unassigned"&&item.assignee?!1:filters.assigneeFilter===void 0||item.assignee!==void 0&&filters.assigneeFilter.has(item.assignee)}function matchesListScopeFilters(item,filters,parentsByChild){const scalarParent=item.parent?.trim().toLowerCase(),logicalParentIds=[...new Set([...parentsByChild?.get(item.id.trim().toLowerCase())??[],...scalarParent?[scalarParent]:[]])];return filters.parentFilter!==void 0&&!filters.treeEnabled&&!logicalParentIds.includes(filters.parentFilter.trim().toLowerCase())||filters.sprintFilter!==void 0&&(item.sprint===void 0||!filters.sprintFilter.has(item.sprint))?!1:filters.releaseFilter===void 0||item.release!==void 0&&filters.releaseFilter.has(item.release)}function matchesListFilterSet(item,filters,statusRegistry,runtimeFieldFilters,parentsByChild){return!(!matchesListIdentityFilters(item,filters,statusRegistry)||!matchesListDateFilters(item,filters)||!matchesListAssigneeFilterSet(item,filters)||!matchesListScopeFilters(item,filters,parentsByChild)||filters.missingMetadataActive&&!itemMatchesMissingMetadata(item,filters.missingMetadataFilters,filters.lifecycleClassifier)||filters.contentFiltersActive&&!itemMatchesContentFilters(item,filters.contentFieldFilters)||!matchesRuntimeFilters(item,runtimeFieldFilters))}function applyFilters(items,status,options,typeRegistry,statusRegistry,runtimeFieldFilters,parentsByChild){const filters=resolveListFilterSet(status,options,typeRegistry,statusRegistry);return items.filter(item=>matchesListFilterSet(item,filters,statusRegistry,runtimeFieldFilters,parentsByChild))}function trimNonEmpty(value){if(typeof value!="string")return;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function withTreeMetadata(item,depth,childCount,parentId){const itemRecord=toItemRecord(item),title=typeof itemRecord.title=="string"?itemRecord.title:"",parent=parentId??trimNonEmpty(typeof itemRecord.parent=="string"?itemRecord.parent:void 0)??null;return{...item,tree_depth:depth,tree_parent:parent,tree_children:childCount,tree_title:`${" ".repeat(depth)}${title}`}}function buildListTreeIndexes(sortedItems,hierarchyIndexes){const byId=new Map,childrenByParent=new Map;for(const item of sortedItems){const itemId=item.id.trim().toLowerCase();byId.set(itemId,item);const parentIds=hierarchyIndexes?hierarchyIndexes.parents_by_child.get(itemId)??[]:[trimNonEmpty(item.parent)?.toLowerCase()].filter(value=>value!==void 0);for(const parentId of parentIds){const children=childrenByParent.get(parentId)??[];children.push(item),childrenByParent.set(parentId,children)}}return{byId,childrenByParent}}function resolveListTreeRoots(sortedItems,parentRoot,byId,childrenByParent,hierarchyIndexes){return parentRoot?[...childrenByParent.get(parentRoot.toLowerCase())??[]]:sortedItems.filter(item=>(hierarchyIndexes?hierarchyIndexes.parents_by_child.get(item.id.trim().toLowerCase())??[]:[trimNonEmpty(item.parent)?.toLowerCase()].filter(value=>value!==void 0)).every(parentId=>!byId.has(parentId)))}function orderItemsAsTree(sortedItems,parentRoot,maxDepth,hierarchyIndexes,completeItems=sortedItems){const{byId,childrenByParent}=buildListTreeIndexes(sortedItems,hierarchyIndexes),roots=resolveListTreeRoots(sortedItems,parentRoot,byId,childrenByParent,hierarchyIndexes),ordered=[],visited=new Set,canonicalIdByLowercase=new Map(completeItems.map(item=>[item.id.trim().toLowerCase(),item.id.trim()])),pending=[...roots].reverse().map(node=>({node,depth:0,parentId:parentRoot===void 0?void 0:canonicalIdByLowercase.get(parentRoot.trim().toLowerCase())??parentRoot.trim()}));for(;pending.length>0;){const{node,depth,parentId}=pending.pop(),nodeId=node.id.trim().toLowerCase();if(visited.has(nodeId))continue;visited.add(nodeId);const children=childrenByParent.get(nodeId)??[];if(ordered.push(withTreeMetadata(node,depth,children.length,parentId)),!(maxDepth!==void 0&&depth>=maxDepth))for(const child of[...children].reverse())pending.push({node:child,depth:depth+1,parentId:canonicalIdByLowercase.get(nodeId)})}if(parentRoot===void 0&&maxDepth===void 0)for(const item of sortedItems){const itemId=item.id.trim().toLowerCase();visited.has(itemId)||(visited.add(itemId),ordered.push(withTreeMetadata(item,0,childrenByParent.get(itemId)?.length??0)))}return ordered}function compareNullableString(left,right){return left===right?0:left===null?1:right===null?-1:left.localeCompare(right)}function compareNullableTimestamp(left,right){return left===right?0:left===null?1:right===null?-1:compareTimestampStrings(left,right)}function compareBySortField(left,right,field){switch(field){case"priority":return left.priority-right.priority;case"deadline":return compareNullableTimestamp(left.deadline??null,right.deadline??null);case"updated_at":return compareTimestampStrings(left.updated_at,right.updated_at);case"created_at":return compareTimestampStrings(left.created_at,right.created_at);case"title":return(left.title??"").localeCompare(right.title??"");case"parent":return compareNullableString(left.parent??null,right.parent??null);default:return 0}}function sortItems(items,sortField,sortOrder,statusRegistry){return sortField?[...items].sort((left,right)=>{const byField=compareBySortField(left,right,sortField);if(byField!==0)return sortOrder==="desc"?-byField:byField;const fallback=compareDefaultSort(left,right,statusRegistry);return sortOrder==="desc"?-fallback:fallback}):sortItemsDefault(items,statusRegistry)}function readListFieldValue(item,field,treeMode=!1){const normalized=normalizeProjectionField(field.trim());if(normalized.length===0)return null;const itemRecord=toItemRecord(item);return treeMode&&normalized==="title"&&typeof itemRecord.tree_title=="string"?itemRecord.tree_title:Object.prototype.hasOwnProperty.call(itemRecord,normalized)?itemRecord[normalized]??null:null}function projectListItems(items,projection,treeMode=!1){return projection.mode==="full"?items:items.map(item=>{const projected={};for(const field of projection.fields)projected[field]=readListFieldValue(item,field,treeMode);return projected})}function runtimeMetadataKeysForProjection(definitions){const keys=[];for(const field of definitions)keys.push(field.metadata_key);return keys}function resolveListPageLimit(options,totalRows){const explicitLimit=parseIntegerLimit(options.limit);if(explicitLimit!==void 0)return explicitLimit;if(options.noTruncate!==!0)return totalRows>=1e4?20:void 0}function resolveListPageStart(ordered,options,cursorFingerprint){return options.after===void 0?parseOffset(options.offset)??0:resolveQueryCursorStart(ordered,options.after,cursorFingerprint,item=>item.id)}function buildListPageExtras(limit,hasMore,nextCursor){return{...limit!==void 0?{applied_limit:limit}:{},has_more:hasMore,truncated:hasMore,next_cursor:nextCursor??null}}async function resolveListRuntimeContext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),runtimeFieldRegistry=resolveRuntimeFieldRegistry(settings.schema),invokedCommand=options.projectionCommand??"list",projection=parseProjectionConfig(options,invokedCommand);return validateListProjectionFields(projection,runtimeMetadataKeysForProjection(runtimeFieldRegistry.definitions),invokedCommand),{pmRoot,settings,statusRegistry,runtimeFieldFilters:collectRuntimeFilterValues(options,runtimeFieldRegistry,"list"),typeRegistry:resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),projection}}async function loadListItems(options,runtime,listWarnings){const projectionNeedsBody=runtime.projection.fields.some(field=>normalizeProjectionField(field)==="body"),projectionNeedsCollections=runtime.projection.mode==="full"||runtime.projection.fields.some(field=>HEAVY_PROJECTION_FIELDS.has(normalizeProjectionField(field))),contentFieldFilters=resolveContentFieldFilters(options),contentNeedsCollections=contentFiltersNeedCollections(contentFieldFilters),contentNeedsBody=contentFiltersNeedBody(contentFieldFilters);return options.includeBody||projectionNeedsBody||contentNeedsBody?await listAllItemMetadataWithBody(runtime.pmRoot,runtime.settings.item_format,runtime.typeRegistry.type_to_folder,listWarnings,runtime.settings.schema):projectionNeedsCollections||contentNeedsCollections?await listAllItemMetadata(runtime.pmRoot,runtime.settings.item_format,runtime.typeRegistry.type_to_folder,listWarnings,runtime.settings.schema):await listAllItemMetadataLight(runtime.pmRoot,runtime.settings.item_format,runtime.typeRegistry.type_to_folder,listWarnings,runtime.settings.schema)}function resolveListOrderingOptions(options){const sortField=parseSortField(options.sort),sortOrder=parseSortOrder(options.order)??"asc",treeEnabled=options.tree===!0;if(!treeEnabled&&options.treeDepth!==void 0)throw new PmCliError("List --tree-depth requires --tree",EXIT_CODE.USAGE);if(!sortField&&options.order!==void 0)throw new PmCliError("List --order requires --sort",EXIT_CODE.USAGE);return{sortField,sortOrder,treeEnabled,treeDepth:treeEnabled?parseTreeDepth(options.treeDepth):void 0,parentRoot:treeEnabled?trimNonEmpty(options.parent):void 0}}function resolveListStatusSelection(status,options,statusRegistry){const explicitStatus=resolveStatusFilter(options.status,statusRegistry);let lifecycleStatus;options.lifecycleBucket==="in_progress"?lifecycleStatus=[statusRegistry.in_progress_status]:options.lifecycleBucket==="open"&&(lifecycleStatus=[...statusRegistry.active_statuses].filter(entry=>entry!==statusRegistry.in_progress_status).sort((left,right)=>left.localeCompare(right)));const resolvedStatus=explicitStatus??lifecycleStatus??resolveStatusFilter(status,statusRegistry),explicitAllStatuses=isStatusAllFilterInput(options.status),effectiveOptions=explicitStatus||explicitAllStatuses?{...options,excludeTerminal:!1}:options;let filtersStatus="all";return explicitAllStatuses?filtersStatus="all":explicitStatus!==void 0?filtersStatus=explicitStatus.length===1?explicitStatus[0]:explicitStatus:options.lifecycleBucket!==void 0?filtersStatus=options.lifecycleBucket:resolvedStatus!==void 0?filtersStatus=resolvedStatus.length===1?resolvedStatus[0]:resolvedStatus:effectiveOptions.excludeTerminal===!0&&(filtersStatus=null),{resolvedStatus,explicitAllStatuses,effectiveOptions,filtersStatus}}function pageAndProjectListItems(ordered,options,projection,treeEnabled,cursorFingerprint){if(options.after!==void 0&&options.offset!==void 0)throw new PmCliError("List --after cannot be combined with --offset.",EXIT_CODE.USAGE);const limit=resolveListPageLimit(options,ordered.length),offset=resolveListPageStart(ordered,options,cursorFingerprint),limited=limit===void 0?ordered.slice(offset):ordered.slice(offset,offset+limit),projected=projectListItems(limited,projection,treeEnabled),totalMatched=ordered.length,hasMore=limited.length>0&&offset+limited.length<totalMatched,nextCursor=hasMore&&limited.length>0?encodeQueryCursor(cursorFingerprint,limited[limited.length-1].id,offset+limited.length-1):void 0;return{projected,totalMatched,pageExtras:buildListPageExtras(limit,hasMore,nextCursor)}}function buildListCursorFingerprint(status,options,ordering,pmRoot){return createQueryFingerprint("list",{pmRoot,status,options:selectCursorSemanticOptions(options,LIST_FILTER_FLAG_CONTRACTS),sort:ordering.sortField??"default",order:ordering.sortOrder,tree:ordering.treeEnabled,tree_depth:ordering.treeDepth??null})}async function tryLoadIndexedListPage(params){const{options,runtime,statusSelection,ordering}=params,supportedOptionKeys=new Set(["status","limit","offset","compact","brief","full","fields","format","stream","includeBody","excludeTerminal","dependencyBlocked","lifecycleBucket","noTruncate","projectionCommand","truncate","notes","learnings","files","docs","tests","comments","deps","linkedCommand"]),projectionNeedsHeavyData=[runtime.projection.mode==="full",runtime.projection.fields.some(field=>{const normalized=normalizeProjectionField(field);return normalized==="body"||HEAVY_PROJECTION_FIELDS.has(normalized)})].includes(!0);if([options.limit===void 0,options.after!==void 0,options.noTruncate===!0,options.includeBody===!0,options.dependencyBlocked===!0,options.strictRead===!0,ordering.treeEnabled,ordering.sortField!==void 0,projectionNeedsHeavyData,hasActiveOnReadHooks(),Object.keys(runtime.runtimeFieldFilters).length>0,Object.entries(options).some(([key,value])=>value!==void 0&&!supportedOptionKeys.has(key))].includes(!0))return null;const indexState=await readItemMetadataDerivedIndexState(runtime.pmRoot,[...new Set(Object.values(runtime.typeRegistry.type_to_folder))]);if(!indexState)return null;const limit=parseIntegerLimit(options.limit),offset=parseOffset(options.offset)??0,indexed=await queryItemMetadataIndex({pmRoot:runtime.pmRoot,expectedSourceCursor:indexState.source_cursor,query:{statuses:statusSelection.resolvedStatus,excludeStatuses:statusSelection.resolvedStatus===void 0&&statusSelection.effectiveOptions.excludeTerminal===!0?[...runtime.statusRegistry.terminal_statuses]:void 0,terminalStatuses:[...runtime.statusRegistry.terminal_statuses],limit,offset}});if(!indexed)return null;const hasMore=indexed.items.length>0&&offset+indexed.items.length<indexed.total,nextCursor=hasMore?encodeQueryCursor(buildListCursorFingerprint(statusSelection.filtersStatus,options,ordering,runtime.pmRoot),indexed.items.at(-1).id,offset+indexed.items.length-1):void 0;return{projected:projectListItems(indexed.items,runtime.projection,!1),totalMatched:indexed.total,pageExtras:buildListPageExtras(limit,hasMore,nextCursor)}}function buildVerboseListFilters(params){const{filtersStatus,options,noTruncate,treeEnabled,treeDepth,sortField,sortOrder,runtimeFieldFilters}=params,filters={};filtersStatus!==null&&(filters.status=filtersStatus),options.dependencyBlocked===!0&&(filters.blocked_semantics="status_or_dependency");const optionRecord=options;for(const entry of VERBOSE_LIST_VALUE_FILTER_ECHO_ENTRIES){const value=optionRecord[entry.optionKey];value!=null&&(filters[entry.summaryKey]=value)}for(const entry of VERBOSE_LIST_BOOLEAN_FILTER_ECHO_ENTRIES)optionRecord[entry.key]===!0&&(filters[entry.summaryKey]=!0);return Object.assign(filters,buildGovernanceMissingFilterEcho(options),buildContentFilterEcho(options)),applyListWindowFilterEcho(filters,options),noTruncate&&(filters.no_truncate=!0),options.strictRead===!0&&(filters.strict_read=!0),treeEnabled&&(filters.tree=!0,treeDepth!==void 0&&(filters.tree_depth=treeDepth)),sortField!==void 0&&(filters.sort=sortField,filters.order=sortOrder),filters.runtime_filters=runtimeFieldFilters,filters}async function runList(status,options,global2){const runtime=await resolveListRuntimeContext(options,global2),listWarnings=[],ordering=resolveListOrderingOptions(options),statusSelection=resolveListStatusSelection(status,options,runtime.statusRegistry),noTruncate=options.noTruncate===!0,indexedPage=await tryLoadIndexedListPage({options,runtime,statusSelection,ordering});let page=indexedPage;if(!page){const items=await loadListItems(options,runtime,listWarnings),hierarchyIndexes=ordering.treeEnabled||trimNonEmpty(options.parent)!==void 0?indexHierarchyRelations(collectHierarchyRelations(items,resolveWorkspaceRelationshipKindRegistry())):void 0;appendUnknownTagWarning(items,options.tag,listWarnings);const filtered=applyFilters(items,statusSelection.resolvedStatus,statusSelection.effectiveOptions,runtime.typeRegistry,runtime.statusRegistry,runtime.runtimeFieldFilters,hierarchyIndexes?.parents_by_child),scoped=options.dependencyBlocked===!0?(()=>{const blockedIds=collectDependencyBlockedIds(items,runtime.statusRegistry);return filtered.filter(item=>blockedIds.has(item.id.trim().toLowerCase()))})():filtered,sorted=sortItems(scoped,ordering.sortField,ordering.sortOrder,runtime.statusRegistry),ordered=ordering.treeEnabled?orderItemsAsTree(sorted,ordering.parentRoot,ordering.treeDepth,hierarchyIndexes,items):sorted;page=pageAndProjectListItems(ordered,options,runtime.projection,ordering.treeEnabled,buildListCursorFingerprint(statusSelection.filtersStatus,options,ordering,runtime.pmRoot))}const now=nowIso(),warnings=[...new Set(listWarnings)].sort((left,right)=>left.localeCompare(right)),completeness=resolveListCompleteness(warnings,indexedPage!==null,options.strictRead===!0),projectionFields=runtime.projection.mode==="full"?null:[...runtime.projection.fields];if(runtime.projection.mode==="compact"&&options.compact===!0){const compactFilters=buildCompactListFilterSummary({filtersStatus:statusSelection.filtersStatus,options,treeEnabled:ordering.treeEnabled,treeDepth:ordering.treeDepth,sortField:ordering.sortField,sortOrder:ordering.sortOrder,runtimeFieldFilters:runtime.runtimeFieldFilters});return{items:page.projected,count:page.projected.length,total:page.totalMatched,...page.pageExtras,completeness,filters:compactFilters,projection:{mode:"compact",fields:projectionFields},...warnings.length>0?{warnings}:{}}}return{items:page.projected,count:page.projected.length,total:page.totalMatched,...page.pageExtras,completeness,filters:buildVerboseListFilters({filtersStatus:statusSelection.filtersStatus,options,noTruncate,treeEnabled:ordering.treeEnabled,treeDepth:ordering.treeDepth,sortField:ordering.sortField,sortOrder:ordering.sortOrder,runtimeFieldFilters:runtime.runtimeFieldFilters}),projection:{mode:runtime.projection.mode,fields:projectionFields},sorting:{sort:ordering.sortField??"default",order:ordering.sortField?ordering.sortOrder:"asc"},now,...warnings.length>0?{warnings}:{}}}const _testOnly={applyFilters,buildCompactListFilterSummary,buildContentFilterEcho,buildGovernanceMissingFilterEcho,resolveContentFieldFilters,resolveMissingMetadataFilters,compareBySortField,compareDefaultSort,compareNullableString,compareNullableTimestamp,normalizeProjectionField,parseAssigneeFilter,parseFieldSelectors,parseIdsFilter,parseOffset,parseProjectionConfig,resolveListUpdatedAfter,resolveListPageLimit,parseSortField,parseSortOrder,orderItemsAsTree,projectListItems,readListFieldValue,runtimeMetadataKeysForProjection,sortItems,trimNonEmpty,withTreeMetadata};export{BRIEF_LIST_FIELDS2 as BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS2 as DEFAULT_COMPACT_LIST_FIELDS,LIST_COMMAND_DEFAULT_PROJECTIONS,LIST_SORT_FIELDS,LIST_SORT_ORDER_VALUES,_testOnly,applyFilterValueEcho,buildContentFilterEcho,buildGovernanceMissingFilterEcho,listListProjectionFields2 as listListProjectionFields,resolveContentFieldFilters,resolveMissingMetadataFilters,runList};
2
2
  //# sourceMappingURL=list.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="01f25e4f-09a1-554f-9e0b-a999fcce5c55")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{transferMutationStdinTokenPolicy}from"./runtime-primitives.js";import{createUnknownSubcommandError}from"./agent/subcommand-recovery.js";import{resolvePmRoot}from"../core/store/paths.js";import{runEval}from"./eval.js";import{runMergeDriver}from"./merge/driver.js";import{runMergeInstall}from"./merge/install.js";import{runMergeReconcile}from"./merge/reconcile.js";import{runMergeReceiptEvidenceReport}from"./merge/receipts.js";import{listMutationEvents}from"./mutation-events.js";import{parseRuntimeInteger,readRuntimeString,readRuntimeStringArray}from"./runtime-input.js";import{runEvent,runMeet,runRemind}from"./scheduling-shortcuts.js";import{createWorkspaceSnapshot,deleteWorkspaceSnapshot,inspectWorkspaceSnapshot,listWorkspaceSnapshots,planWorkspaceSnapshotRestore,restoreWorkspaceSnapshotWithRecovery}from"./workspace-snapshot.js";import{readWorkspacePosition}from"./governance/workspace-position.js";function mergedInput(context){const input={...context.args,...context.options};return transferMutationStdinTokenPolicy(context.options,input)}function requiredString(input,key){const value=readRuntimeString(input,key);if(value!==void 0)return value;throw new PmCliError(`Missing required parameter: ${key}`,EXIT_CODE.USAGE)}function stringList(value){return typeof value=="string"?[value]:readRuntimeStringArray(value)}function runRuntimeEvalAction(context){return runEval(mergedInput(context),context.global)}function runRuntimeEventsAction(context){const input=mergedInput(context),rawCursorMode=input.cursorMode;if(rawCursorMode!==void 0&&rawCursorMode!=="batch"&&rawCursorMode!=="row")throw new PmCliError("Mutation event cursor mode must be batch or row.",EXIT_CODE.USAGE,{code:"invalid_event_cursor_mode"});const cursorMode=rawCursorMode;return listMutationEvents({cwd:readRuntimeString(input,"cwd"),pmRoot:readRuntimeString(input,"path"),since:readRuntimeString(input,"since"),type:stringList(input.type),author:stringList(input.author),item:stringList(input.item),limit:input.limit===void 0?void 0:parseRuntimeInteger(input.limit,"limit"),full:input.full===!0,cursorMode,...input.provenance===void 0?{}:{provenance:input.provenance===!0},...input.provenanceSummary===void 0?{}:{provenanceSummary:input.provenanceSummary===!0},...input.harness===void 0?{}:{harness:stringList(input.harness)},...input.agentInstance===void 0?{}:{agentInstance:stringList(input.agentInstance)},...input.provenanceFilter===void 0?{}:{provenanceFilter:stringList(input.provenanceFilter)}})}function runRuntimeMergeAction(context){const input=mergedInput(context),subcommand=requiredString(input,"subcommand");if(subcommand==="install")return runMergeInstall({dryRun:input.dryRun===!0},context.global);if(subcommand==="reconcile")return runMergeReconcile({dryRun:input.dryRun===!0,author:readRuntimeString(input,"author"),message:readRuntimeString(input,"message"),force:input.force===!0},context.global);if(subcommand==="report")return runMergeReceiptEvidenceReport({includeReconciled:input.includeReconciled===!0,cwd:readRuntimeString(input,"cwd")});if(subcommand==="driver")return runMergeDriver({artifact:requiredString(input,"artifact"),basePath:requiredString(input,"basePath"),oursPath:requiredString(input,"oursPath"),theirsPath:requiredString(input,"theirsPath"),outputPath:readRuntimeString(input,"outputPath")??readRuntimeString(input,"output"),itemPath:readRuntimeString(input,"itemPath"),prefer:readRuntimeString(input,"prefer")},context.global);throw createUnknownSubcommandError({command_path:"merge",token:subcommand,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function runRuntimeWorkspaceAction(context){const input=mergedInput(context),subcommand=requiredString(input,"subcommand");if(subcommand==="position")return readWorkspacePosition(context.global);if(subcommand!=="snapshot")throw createUnknownSubcommandError({command_path:"workspace",token:subcommand,allowed:["position","snapshot"],display_name:"workspace"});const snapshotAction=readRuntimeString(input,"snapshotAction")??requiredString(input,"snapshot_action"),pmRoot=resolvePmRoot(process.cwd(),context.global.path);if(snapshotAction==="create")return createWorkspaceSnapshot(pmRoot,{name:readRuntimeString(input,"name")});if(snapshotAction==="list")return listWorkspaceSnapshots(pmRoot);const target=requiredString(input,"target");if(snapshotAction==="inspect")return inspectWorkspaceSnapshot(pmRoot,target);if(snapshotAction==="delete")return deleteWorkspaceSnapshot(pmRoot,target);if(snapshotAction==="restore")return input.dryRun===!0?planWorkspaceSnapshotRestore(pmRoot,target):restoreWorkspaceSnapshotWithRecovery(pmRoot,target,{force:input.force===!0,author:readRuntimeString(input,"author"),message:readRuntimeString(input,"message"),lockTtlSeconds:parseRuntimeInteger(input.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:parseRuntimeInteger(input.lockWaitMs,"lockWaitMs")});throw createUnknownSubcommandError({command_path:"workspace snapshot",token:snapshotAction,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function runRuntimeSchedulingAction(context){const input=mergedInput(context),title=requiredString(input,"title");return context.action==="meet"?runMeet(title,input,context.global):context.action==="event"?runEvent(title,input,context.global):runRemind(title,input,context.global)}export{runRuntimeEvalAction,runRuntimeEventsAction,runRuntimeMergeAction,runRuntimeSchedulingAction,runRuntimeWorkspaceAction};
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]="e3fe4357-da47-54d5-99d7-62e4b6f86b2b")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{transferMutationStdinTokenPolicy}from"./runtime-primitives.js";import{createUnknownSubcommandError}from"./agent/subcommand-recovery.js";import{resolvePmRoot}from"../core/store/paths.js";import{runEval}from"./eval.js";import{runMergeDriver}from"./merge/driver.js";import{runMergeInstall}from"./merge/install.js";import{runMergeReconcile}from"./merge/reconcile.js";import{runMergeReceiptEvidenceReport}from"./merge/receipts.js";import{listMutationEvents}from"./mutation-events.js";import{parseRuntimeInteger,readRuntimeString,readRuntimeStringArray}from"./runtime-input.js";import{runEvent,runMeet,runRemind}from"./scheduling-shortcuts.js";import{createWorkspaceSnapshot,deleteWorkspaceSnapshot,inspectWorkspaceSnapshot,listWorkspaceSnapshots,planWorkspaceSnapshotRestore,restoreWorkspaceSnapshotWithRecovery}from"./workspace-snapshot.js";import{readWorkspacePosition}from"./governance/workspace-position.js";function mergedInput(context){const input={...context.args,...context.options};return transferMutationStdinTokenPolicy(context.options,input)}function requiredString(input,key){const value=readRuntimeString(input,key);if(value!==void 0)return value;throw new PmCliError(`Missing required parameter: ${key}`,EXIT_CODE.USAGE)}function stringList(value){return typeof value=="string"?[value]:readRuntimeStringArray(value)}function runRuntimeEvalAction(context){return runEval(mergedInput(context),context.global)}function runRuntimeEventsAction(context){const input=mergedInput(context),rawCursorMode=input.cursorMode;if(rawCursorMode!==void 0&&rawCursorMode!=="batch"&&rawCursorMode!=="row")throw new PmCliError("Mutation event cursor mode must be batch or row.",EXIT_CODE.USAGE,{code:"invalid_event_cursor_mode"});const cursorMode=rawCursorMode;return listMutationEvents({cwd:readRuntimeString(input,"cwd"),pmRoot:readRuntimeString(input,"path"),since:readRuntimeString(input,"since"),type:stringList(input.type),author:stringList(input.author),item:stringList(input.item),limit:input.limit===void 0?void 0:parseRuntimeInteger(input.limit,"limit"),full:input.full===!0,cursorMode,...input.provenance===void 0?{}:{provenance:input.provenance===!0},...input.provenanceSummary===void 0?{}:{provenanceSummary:input.provenanceSummary===!0},...input.harness===void 0?{}:{harness:stringList(input.harness)},...input.agentInstance===void 0?{}:{agentInstance:stringList(input.agentInstance)},...input.provenanceFilter===void 0?{}:{provenanceFilter:stringList(input.provenanceFilter)}})}function runRuntimeMergeAction(context){const input=mergedInput(context),subcommand=requiredString(input,"subcommand");if(subcommand==="install")return runMergeInstall({dryRun:input.dryRun===!0,preCommitHook:input.preCommitHook===!0},context.global);if(subcommand==="reconcile")return runMergeReconcile({dryRun:input.dryRun===!0,author:readRuntimeString(input,"author"),message:readRuntimeString(input,"message"),force:input.force===!0,stage:input.stage===!0},context.global);if(subcommand==="report")return runMergeReceiptEvidenceReport({includeReconciled:input.includeReconciled===!0,cwd:readRuntimeString(input,"cwd")});if(subcommand==="driver")return runMergeDriver({artifact:requiredString(input,"artifact"),basePath:requiredString(input,"basePath"),oursPath:requiredString(input,"oursPath"),theirsPath:requiredString(input,"theirsPath"),outputPath:readRuntimeString(input,"outputPath")??readRuntimeString(input,"output"),itemPath:readRuntimeString(input,"itemPath"),prefer:readRuntimeString(input,"prefer")},context.global);throw createUnknownSubcommandError({command_path:"merge",token:subcommand,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function runRuntimeWorkspaceAction(context){const input=mergedInput(context),subcommand=requiredString(input,"subcommand");if(subcommand==="position")return readWorkspacePosition(context.global);if(subcommand!=="snapshot")throw createUnknownSubcommandError({command_path:"workspace",token:subcommand,allowed:["position","snapshot"],display_name:"workspace"});const snapshotAction=readRuntimeString(input,"snapshotAction")??requiredString(input,"snapshot_action"),pmRoot=resolvePmRoot(process.cwd(),context.global.path);if(snapshotAction==="create")return createWorkspaceSnapshot(pmRoot,{name:readRuntimeString(input,"name")});if(snapshotAction==="list")return listWorkspaceSnapshots(pmRoot);const target=requiredString(input,"target");if(snapshotAction==="inspect")return inspectWorkspaceSnapshot(pmRoot,target);if(snapshotAction==="delete")return deleteWorkspaceSnapshot(pmRoot,target);if(snapshotAction==="restore")return input.dryRun===!0?planWorkspaceSnapshotRestore(pmRoot,target):restoreWorkspaceSnapshotWithRecovery(pmRoot,target,{force:input.force===!0,author:readRuntimeString(input,"author"),message:readRuntimeString(input,"message"),lockTtlSeconds:parseRuntimeInteger(input.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:parseRuntimeInteger(input.lockWaitMs,"lockWaitMs")});throw createUnknownSubcommandError({command_path:"workspace snapshot",token:snapshotAction,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function runRuntimeSchedulingAction(context){const input=mergedInput(context),title=requiredString(input,"title");return context.action==="meet"?runMeet(title,input,context.global):context.action==="event"?runEvent(title,input,context.global):runRemind(title,input,context.global)}export{runRuntimeEvalAction,runRuntimeEventsAction,runRuntimeMergeAction,runRuntimeSchedulingAction,runRuntimeWorkspaceAction};
2
2
  //# sourceMappingURL=runtime-extended-actions.js.map
package/dist/types.d.ts CHANGED
@@ -113,8 +113,8 @@ export interface Dependency {
113
113
  id:string;
114
114
  /** Value that configures or reports kind for this contract. */
115
115
  kind:DependencyKind;
116
- /** ISO 8601 timestamp recording when created occurred. */
117
- created_at:string;
116
+ /** Creation timestamp when provenance is available; legacy dependency reads may omit it. New edge writers supply it. */
117
+ created_at?:string;
118
118
  /** Value that configures or reports author for this contract. */
119
119
  author?:string;
120
120
  /** Value that configures or reports source kind for this contract. */
package/dist/types.js CHANGED
@@ -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]="459c0cce-212f-5285-9c3b-13676d2388af")}catch{}})();const BUILTIN_ITEM_TYPE_VALUES=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],ITEM_TYPE_VALUES=BUILTIN_ITEM_TYPE_VALUES,STATUS_VALUES=["draft","open","in_progress","blocked","closed","canceled"],RUNTIME_STATUS_ROLE_VALUES=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],RUNTIME_FIELD_TYPE_VALUES=["string","number","boolean","string_array","array","object"],RUNTIME_FIELD_COMMAND_VALUES=["create","update","update_many","list","search","calendar","context"],RUNTIME_UNKNOWN_FIELD_POLICY_VALUES=["allow","warn","reject"],DEPENDENCY_KIND_VALUES=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],SCOPE_VALUES=["project","global"],RISK_VALUES=["low","medium","high","critical"],ISSUE_SEVERITY_VALUES=["low","medium","high","critical"],CONFIDENCE_TEXT_VALUES=["low","medium","high"],ITEM_FORMAT_VALUES=["toon","json_markdown"],SPRINT_RELEASE_FORMAT_POLICY_VALUES=["warn","strict_error"],PARENT_REFERENCE_POLICY_VALUES=["warn","strict_error"],VALIDATE_METADATA_PROFILE_VALUES=["core","strict","custom"],GOVERNANCE_PRESET_VALUES=["minimal","default","strict","custom"],GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES=["none","warn","strict"],GOVERNANCE_CREATE_MODE_DEFAULT_VALUES=["progressive","strict"],GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES=["off","warn","strict"],GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES=["off","warn","strict"],GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES=["off","advisory","strict"],VALIDATE_METADATA_REQUIRED_FIELD_VALUES=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"],RECURRENCE_FREQUENCY_VALUES=["daily","weekly","monthly","yearly"],RECURRENCE_WEEKDAY_VALUES=["mon","tue","wed","thu","fri","sat","sun"];function weekdayOrderIndex(value){return RECURRENCE_WEEKDAY_VALUES.indexOf(value)}const PLAN_MODE_VALUES=["draft","research","review","approved","executing","paused","completed","superseded"],PLAN_STEP_STATUS_VALUES=["pending","in_progress","completed","blocked","skipped","superseded"],PLAN_HARNESS_VALUES=["codex","claude-code","cursor","generic"],PLAN_STEP_LINK_KIND_VALUES=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],CONTEXT_DEPTH_VALUES=["brief","standard","deep","full"],CONTEXT_SECTION_VALUES=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];export{BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CONTEXT_DEPTH_VALUES,CONTEXT_SECTION_VALUES,DEPENDENCY_KIND_VALUES,GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES,GOVERNANCE_CREATE_MODE_DEFAULT_VALUES,GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES,GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES,GOVERNANCE_PRESET_VALUES,GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES,ISSUE_SEVERITY_VALUES,ITEM_FORMAT_VALUES,ITEM_TYPE_VALUES,PARENT_REFERENCE_POLICY_VALUES,PLAN_HARNESS_VALUES,PLAN_MODE_VALUES,PLAN_STEP_LINK_KIND_VALUES,PLAN_STEP_STATUS_VALUES,RECURRENCE_FREQUENCY_VALUES,RECURRENCE_WEEKDAY_VALUES,RISK_VALUES,RUNTIME_FIELD_COMMAND_VALUES,RUNTIME_FIELD_TYPE_VALUES,RUNTIME_STATUS_ROLE_VALUES,RUNTIME_UNKNOWN_FIELD_POLICY_VALUES,SCOPE_VALUES,SPRINT_RELEASE_FORMAT_POLICY_VALUES,STATUS_VALUES,VALIDATE_METADATA_PROFILE_VALUES,VALIDATE_METADATA_REQUIRED_FIELD_VALUES,weekdayOrderIndex};
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]="c05a5a9e-282c-5ca7-97dc-e48c8df7977e")}catch{}})();const BUILTIN_ITEM_TYPE_VALUES=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],ITEM_TYPE_VALUES=BUILTIN_ITEM_TYPE_VALUES,STATUS_VALUES=["draft","open","in_progress","blocked","closed","canceled"],RUNTIME_STATUS_ROLE_VALUES=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],RUNTIME_FIELD_TYPE_VALUES=["string","number","boolean","string_array","array","object"],RUNTIME_FIELD_COMMAND_VALUES=["create","update","update_many","list","search","calendar","context"],RUNTIME_UNKNOWN_FIELD_POLICY_VALUES=["allow","warn","reject"],DEPENDENCY_KIND_VALUES=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],SCOPE_VALUES=["project","global"],RISK_VALUES=["low","medium","high","critical"],ISSUE_SEVERITY_VALUES=["low","medium","high","critical"],CONFIDENCE_TEXT_VALUES=["low","medium","high"],ITEM_FORMAT_VALUES=["toon","json_markdown"],SPRINT_RELEASE_FORMAT_POLICY_VALUES=["warn","strict_error"],PARENT_REFERENCE_POLICY_VALUES=["warn","strict_error"],VALIDATE_METADATA_PROFILE_VALUES=["core","strict","custom"],GOVERNANCE_PRESET_VALUES=["minimal","default","strict","custom"],GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES=["none","warn","strict"],GOVERNANCE_CREATE_MODE_DEFAULT_VALUES=["progressive","strict"],GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES=["off","warn","strict"],GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES=["off","warn","strict"],GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES=["off","advisory","strict"],VALIDATE_METADATA_REQUIRED_FIELD_VALUES=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"],RECURRENCE_FREQUENCY_VALUES=["daily","weekly","monthly","yearly"],RECURRENCE_WEEKDAY_VALUES=["mon","tue","wed","thu","fri","sat","sun"];function weekdayOrderIndex(value){return RECURRENCE_WEEKDAY_VALUES.indexOf(value)}const PLAN_MODE_VALUES=["draft","research","review","approved","executing","paused","completed","superseded"],PLAN_STEP_STATUS_VALUES=["pending","in_progress","completed","blocked","skipped","superseded"],PLAN_HARNESS_VALUES=["codex","claude-code","cursor","generic"],PLAN_STEP_LINK_KIND_VALUES=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],CONTEXT_DEPTH_VALUES=["brief","standard","deep","full"],CONTEXT_SECTION_VALUES=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];export{BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CONTEXT_DEPTH_VALUES,CONTEXT_SECTION_VALUES,DEPENDENCY_KIND_VALUES,GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES,GOVERNANCE_CREATE_MODE_DEFAULT_VALUES,GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES,GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES,GOVERNANCE_PRESET_VALUES,GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES,ISSUE_SEVERITY_VALUES,ITEM_FORMAT_VALUES,ITEM_TYPE_VALUES,PARENT_REFERENCE_POLICY_VALUES,PLAN_HARNESS_VALUES,PLAN_MODE_VALUES,PLAN_STEP_LINK_KIND_VALUES,PLAN_STEP_STATUS_VALUES,RECURRENCE_FREQUENCY_VALUES,RECURRENCE_WEEKDAY_VALUES,RISK_VALUES,RUNTIME_FIELD_COMMAND_VALUES,RUNTIME_FIELD_TYPE_VALUES,RUNTIME_STATUS_ROLE_VALUES,RUNTIME_UNKNOWN_FIELD_POLICY_VALUES,SCOPE_VALUES,SPRINT_RELEASE_FORMAT_POLICY_VALUES,STATUS_VALUES,VALIDATE_METADATA_PROFILE_VALUES,VALIDATE_METADATA_REQUIRED_FIELD_VALUES,weekdayOrderIndex};
2
2
  //# sourceMappingURL=types.js.map
package/docs/COMMANDS.md CHANGED
@@ -209,6 +209,32 @@ Each aggregate row carries an explicit `group_label`: a blank/null group value (
209
209
  pm list --all --sort updated --order desc
210
210
  ```
211
211
 
212
+ Brief list rows include an explicitly selected sort field (including normalized
213
+ aliases such as `updated_at`) and declare it in `projection.fields`. Explicit
214
+ `--fields`, compact and full projections retain their requested fields.
215
+ This rule is shared by SDK list queries.
216
+
217
+ Lifecycle filters such as `--all` and `--status all` retain the canonical `list`
218
+ command's brief default; they select rows without expanding item fields. Use
219
+ `--full`, `--compact`, `--brief`, `--fields` or `--include-body` to choose more
220
+ evidence explicitly. Raw SDK list calls keep their full default, and explicit
221
+ `--all --full --strict-read` remains a complete corpus read.
222
+ The implementation records
223
+ [pm-gh1481](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1481.toon)
224
+ and [pm-gh1489](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1489.toon)
225
+ are repository-only tracker files, excluded from the npm package.
226
+
227
+ New dependency writes record `created_at`. Supplied values must be calendar-valid
228
+ RFC 3339 date-times. SDK dependency reads expose this field as optional because
229
+ legacy rows without a timestamp remain readable: they sort before timestamped
230
+ rows, with deterministic id/kind/source
231
+ tie-breakers and no invented provenance. An invalid supplied timestamp produces
232
+ `item_document_invalid` with the item path and dependency field.
233
+ `pm validate --check-storage-integrity` and `pm health --check-only --full` expose
234
+ that malformed item. The implementation record
235
+ [pm-gh1482](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1482.toon)
236
+ is a repository-only tracker file, excluded from the npm package.
237
+
212
238
  ### Incremental "what changed since" filters
213
239
 
214
240
  Every `list*` command accepts `--updated-after`/`--updated-before`/`--created-after`/`--created-before`. `pm search` now supports the SAME filter surface as `pm list` (full parity): `--status`, `--type`, `--tag`, `--priority`, `--deadline-before`/`--deadline-after`, `--updated-after`/`--updated-before`, `--created-after`/`--created-before`, `--assignee`, `--sprint`, `--release`, and `--parent`, all with identical semantics. These keep a long-running agent's context focused on the slice it cares about instead of re-scanning the whole tracker:
@@ -1069,6 +1095,19 @@ When more than one history stream is drifted, the `history_drift` remediation co
1069
1095
 
1070
1096
  `pm health` also runs a read-only `locks` check alongside the storage check: it classifies every file in `locks/` with the exact policy `pm gc --scope locks` acts on and reports `active_lock_count`, `stale_lock_count`, `unreadable_lock_count`, and `unparseable_lock_count` (counts appear in all projection modes; nothing is ever removed). It warns with `locks_stale_count:<n>` when stale locks exist (fix: `pm gc --scope locks`) and `locks_unreadable:<n>` when lock files cannot be read (inspect first: `pm gc --scope locks --dry-run`).
1071
1097
 
1098
+ ## Single-commit merge settlement
1099
+
1100
+ Tracked by [pm-gh1475](../.agents/pm/issues/pm-gh1475.toon).
1101
+ Use `git merge --no-commit --no-ff <branch>`, then
1102
+ `pm merge reconcile --stage` and `git commit` to include authenticated lossless
1103
+ audit history in the original merge commit. `--stage --dry-run` previews without
1104
+ writing. Automatic staging refuses competing values, forced acceptance,
1105
+ non-history validation failures, unstaged edits to reconciliation artifacts,
1106
+ and unresolved index entries. `pm merge install --pre-commit-hook` explicitly
1107
+ installs a merge-aware hook for that paused-merge workflow and preserves existing
1108
+ unowned hooks. Default installation remains hook-free. See
1109
+ [Merge safety](MERGE_SAFETY.md#settle-a-lossless-merge-in-one-commit).
1110
+
1072
1111
  ## History and Recovery
1073
1112
 
1074
1113
  After a branch merge that touched tracker history, preview and apply the
@@ -148,6 +148,18 @@ For command-level tracker targeting, prefer `--pm-path <tracker-root>`. The old
148
148
  itself, not the repository workspace. During `pm init`, explicit tracker paths
149
149
  that look like workspace roots are rejected unless `--force` is provided.
150
150
 
151
+ Implicit discovery checks the current directory and its ancestors up to the
152
+ nearest `.git` directory or file, including worktrees and submodules. An
153
+ uninitialized repository selects its own `.agents/pm` and returns initialization
154
+ recovery instead of reading or changing an enclosing repository's tracker.
155
+ Ordinary subdirectories still share their repository's tracker, including
156
+ root-layout trackers. To deliberately share a tracker across repository
157
+ boundaries, pass `--pm-path <tracker-root>` or set `PM_PATH` explicitly.
158
+ This shared SDK discovery policy also applies to CLI and MCP commands.
159
+ Directory aliases follow physical ancestry, including missing descendants of
160
+ an existing alias. Unexpected directory or `.git` lookup errors stop discovery
161
+ instead of falling through to an enclosing tracker.
162
+
151
163
  Tests should set both `PM_PATH` and `PM_GLOBAL_PATH` to temporary directories. The wrapper `node scripts/run-tests.mjs ...` does that automatically.
152
164
 
153
165
  ### Telemetry environment variables
@@ -212,7 +224,16 @@ Interaction rules:
212
224
  - `pm health --check-telemetry --json` surfaces flush and OTLP export diagnostics (`pending_otel_spans`, `last_otel_attempt_at`, `last_otel_success_at`, `last_otel_failure_at`, `last_otel_failure_error`) and the active `env_overrides` (including `telemetry_inline_flush` and `telemetry_source_context`) so agents can self-diagnose a stalled endpoint.
213
225
  - An explicit `PM_AUTHOR` override adds a privacy-preserving agent-identity dimension to `command_start`/`command_finish` events so overridden invocations can be segmented in dashboards without leaking the raw author string. At `redacted`/`max` capture the events carry `author_context_hash` — the same installation-id-keyed one-way SHA-256 used for `pm_root_hash`/`cwd_hash`, so the same author hashes consistently within an installation but differently across installations. At `minimal` capture only a boolean `has_author_context` is emitted. The raw `PM_AUTHOR` value is never exported.
214
226
 
215
- Test environments inferred from `VITEST`, `VITEST_WORKER_ID`, or `NODE_ENV=test` suppress telemetry before identity creation. A valid explicit `PM_TELEMETRY_SOURCE_CONTEXT` or `PM_TELEMETRY_SEND_TEST_EVENTS=1` permits intentional test delivery. Point such tests at a local collector. Neither setting overrides a hard opt-out. `pm telemetry status` exposes effective `enabled`, persisted `configured_enabled`, and `env_overrides` so an empty queue is distinguishable from disabled delivery.
227
+ Test environments inferred from `VITEST`, `VITEST_WORKER_ID`, `NODE_TEST_CONTEXT`
228
+ (native `node --test` children), or `NODE_ENV=test` suppress telemetry and Sentry
229
+ before identity creation. A valid explicit `PM_TELEMETRY_SOURCE_CONTEXT` or
230
+ `PM_TELEMETRY_SEND_TEST_EVENTS=1` permits intentional test delivery. Point such
231
+ tests at a local collector. Inferred tests use inline telemetry flushing even
232
+ after an opt in, so CLI delivery settles before process exit and disposable-root
233
+ cleanup. SDK telemetry completion also awaits inline delivery before returning.
234
+ Neither setting overrides a hard opt-out. `pm telemetry status` exposes effective `enabled`, persisted
235
+ `configured_enabled`, and `env_overrides` so an empty queue is distinguishable
236
+ from disabled delivery.
216
237
 
217
238
  SDK consumers that previously used `TelemetryStatusSummary.enabled` to display the saved preference should read `configured_enabled` instead. Use `enabled` to determine whether this process permits delivery.
218
239
 
@@ -315,6 +336,20 @@ pm get <id> --full --json
315
336
  pm contracts --json
316
337
  ```
317
338
 
339
+ `--output-format json|toon` selects encoding on both reads and mutations.
340
+ Item collection and lifecycle commands accept `--format json|toon` as a
341
+ compatibility alias, before or after the command:
342
+
343
+ ```bash
344
+ pm comments <id> --format json
345
+ pm --format json create Task "Follow up" --create-mode progressive
346
+ ```
347
+
348
+ Command-specific formats retain their meaning, including `list --format csv`,
349
+ `deps --format graph`, and `config set item-format --format toon`. Use
350
+ `--output-format` to select the envelope encoding alongside those options.
351
+ Package commands retain their declared flag vocabulary.
352
+
318
353
  `pm calendar` (provided by the optional `calendar` package — `pm install calendar --project`) defaults to markdown because date-centric summaries are easier to scan in that format.
319
354
 
320
355
  ## Validation Policies
@@ -20,6 +20,13 @@ nightly quality and release paths enforce it. The registry-owned local
20
20
  preflight also requires the static gate and permits no skip. Trivy separately
21
21
  includes development dependencies in its required repository scan.
22
22
 
23
+ Composite action refs and their executed tool versions need separate review.
24
+ [pm-38w3ii](../.agents/pm/chores/pm-38w3ii.toon) pins TruffleHog's action
25
+ commit and explicitly selects scanner version `3.98.0`; the action otherwise
26
+ defaults to the `latest` image. The workflow contract checks both values on
27
+ every TruffleHog step. Recheck the action's executable selectors when renewing
28
+ its commit pin.
29
+
23
30
  ## Indexed source-map offsets
24
31
 
25
32
  [pm-dba47](../.agents/pm/issues/pm-dba47.toon) tracks Dependabot alert 47 and
@@ -109,9 +116,21 @@ program matches the reviewed [shim templates](../config/codspeed-shims/), with
109
116
  targets and module paths derived from the audited installed dependency. Arbitrary
110
117
  names, nested payloads, links, altered programs and forged target markers fail;
111
118
  these shims are outside the twelve package-owned hashes but are independently
112
- validated. The shell template records pnpm 11.10.0's installed output; the CMD
113
- and PowerShell templates come from `@zkochan/cmd-shim` 9.0.7. Template changes
114
- require renewed real installation evidence on both POSIX and native Windows.
119
+ validated. [pm-rnpmtp](../.agents/pm/chores/pm-rnpmtp.toon) renews the installer
120
+ to pnpm 11.28.5 and its bundled `bins/cmd-shim` generator. Separate complete shell
121
+ templates describe POSIX and Windows installations; only the host's template is
122
+ accepted. Windows shells pass Windows `NODE_PATH` values to native Node, and
123
+ Cygwin targets use Windows paths. CMD and PowerShell programs retain their
124
+ complete comparisons. Template changes require renewed real installation and
125
+ dependency-resolution evidence on POSIX, Git Bash and Cygwin, plus CMD and
126
+ PowerShell. The Windows script cohort downloads the archived Cygwin setup 2.937
127
+ installer and verifies its pinned SHA-512 before execution. To renew it, select
128
+ an eligible version from the official [setup archive](https://cygwin.com/setup/),
129
+ verify the executable against the archive's `sha512.sum`, and update the
130
+ versioned URL, pinned digest and workflow contract together. Preserve setup's
131
+ default package-signature verification and repeat native launcher acceptance.
132
+ Literal percent paths are exercised in disposable launcher fixtures;
133
+ the audited CodSpeed installation still refuses shell interpolation paths.
115
134
  The CMD suffix follows the installed `PATHEXT` spelling, including `.CMD`;
116
135
  format lookup folds its case while validating the complete program. All three
117
136
  shell launchers are required, together with the CMD and PowerShell sets on
@@ -286,6 +286,28 @@ receipt file that the older writer never created. Incomplete, contradictory, or
286
286
  modern summaries still fail closed. `runMergeReceiptReport` remains the
287
287
  compatible valid-only report.
288
288
 
289
+ ## Portable receipt proof
290
+
291
+ Reconciliation refuses `merge_receipt_not_portable` before any audit write when
292
+ an active clone-local receipt lacks a validated tracked counterpart. `--force`
293
+ does not bypass this boundary, including for direct SDK history-repair calls.
294
+ An earlier aborted operation can leave an unreferenced local receipt whose field
295
+ hashes happen to match a later merge; those hashes do not make its evidence
296
+ portable. Review and preserve unrelated stale receipts outside the active store,
297
+ or restore the original valid durable sidecar. Never copy private local receipt
298
+ values into tracked evidence as a substitute.
299
+
300
+ `inspectMergeReceiptEvidence().durable_receipt_ids` identifies validated durable
301
+ counterparts whose immutable provenance matches the stored blob referenced by the Git index;
302
+ clone-local replacement refs cannot substitute different evidence.
303
+ Untracked files and mismatched staged versions cannot authorize an audit write.
304
+ `unstaged_durable_receipt_ids` reports valid disk candidates for a read-only
305
+ preview; clone-local-only evidence remains refused even in preview. Current readers
306
+ return both arrays; their optional interface properties preserve structural compatibility,
307
+ and a missing property provides no evidence. Health resolves committed history
308
+ references against these durable identities, so a local copy cannot hide evidence
309
+ that a fresh clone will lack. Receipt summaries remain privacy-safe.
310
+
289
311
  ## Historical receipt reader compatibility
290
312
 
291
313
  Tracked by [pm-2xtv84](../.agents/pm/issues/pm-2xtv84.toon) and
@@ -388,8 +410,13 @@ pm config project set ids_token_length 8
388
410
 
389
411
  The SDK item merge refuses an empty common ancestor with
390
412
  `item_identity_conflict`, even for equal item content: document equality alone
391
- cannot prove a common creation. It leaves the driver output untouched instead
392
- of combining two identities through scalar preference. The history merge also
413
+ cannot prove a common creation. The pure merge primitive leaves inputs unchanged.
414
+ The Git driver preserves both original snapshots in visible conflict markers
415
+ and names the item in its refusal, tracked by
416
+ [pm-gh1491](../.agents/pm/issues/pm-gh1491.toon). Staging these files does not
417
+ clear the conflict-marker health and storage failures. A copied creation or
418
+ history prefix alone never authorizes fusion of two independently introduced
419
+ identities. The history merge also
393
420
  refuses different create events across its inputs, multiple creates in either
394
421
  input, or creations on both sides when the ancestor lacks a create event even
395
422
  when their bytes match, before fast-forwarding or reanchoring. A common ancestor
@@ -432,6 +459,54 @@ N-branch conflict fixture compares competing writes to the same scalar set.
432
459
  Arbitrary histories, ordered executable test definitions with receiving-clone
433
460
  trust, and relationship-event ordering retain their separate conformance contracts.
434
461
 
462
+ ## Settle a lossless merge in one commit
463
+
464
+ Tracked by [pm-gh1475](../.agents/pm/issues/pm-gh1475.toon).
465
+ Pause Git before it creates the merge commit, then stage the audited settlement:
466
+
467
+ ```bash
468
+ git merge --no-commit --no-ff <branch>
469
+ pm merge reconcile --stage
470
+ git diff --cached
471
+ git commit
472
+ ```
473
+
474
+ `--stage` first previews reconciliation. It refuses discarded-value decisions,
475
+ untrusted or unrelated repairs, invalid storage, missing durable evidence,
476
+ unresolved Git paths, alternate Git indices, and unstaged edits to the reconciliation paths. It never
477
+ accepts `--force`. Only the verified history streams and receipt sidecars are
478
+ added to the index; unrelated staged changes retain their existing state.
479
+ Validated new sidecars enter the index before any audit history is written.
480
+ If apply fails, their new index entries are reverted while their files and
481
+ unrelated staged work remain available for review. Staged receipt deletions
482
+ remain operator decisions and are refused.
483
+ `--stage --dry-run` checks this boundary without applying or staging anything.
484
+ The result's `staged_paths` lists the repository-relative artifacts added.
485
+ Tracker aliases resolve before preview, so proof verification, repair and staging
486
+ use the same physical tracker root.
487
+
488
+ Repositories can explicitly opt into a merge-aware `pre-commit` hook:
489
+
490
+ ```bash
491
+ pm merge install --pre-commit-hook --dry-run
492
+ pm merge install --pre-commit-hook
493
+ git merge --no-commit --no-ff <branch>
494
+ git commit
495
+ ```
496
+
497
+ The hook runs guarded settlement only when `MERGE_HEAD` exists; ordinary commits
498
+ are unchanged. Installation honors Git's hooks directory, including
499
+ `core.hooksPath`, and preserves any hook without the pm ownership header. For
500
+ an existing hook, integrate `pm merge reconcile --stage` into the reviewed merge
501
+ path yourself. The installation result reports `settlement_hook.path`; removing
502
+ that owned hook restores the manual workflow. Hooks are clone-local and must be
503
+ installed explicitly in each clone. No hook is installed by default.
504
+
505
+ The explicit `--no-commit --no-ff` step is required. Git's automatic merge commit
506
+ can capture its tree before a `pre-merge-commit` hook stages new audit artifacts;
507
+ that hook cannot provide this single-commit guarantee. Rebase and already
508
+ committed merges continue to use the explicit reconciliation gate below.
509
+
435
510
  ## Required post-merge gate
436
511
 
437
512
  Reconciliation resolves receipt discovery and settlement from the requested
@@ -443,12 +518,20 @@ After every branch merge that touches `.agents/pm`, run:
443
518
 
444
519
  ```bash
445
520
  pm merge reconcile --dry-run --json
521
+ # When the preview lists unstaged sidecars, review and stage those files first.
446
522
  pm merge reconcile --message "Reconcile merged tracker histories" --json
447
523
  # Required only to accept a receipt that lacks qualifying exact hash proof:
448
524
  pm merge reconcile --force --message "Accept reviewed merge decisions" --json
449
525
  ```
450
526
 
451
527
  The preview reports every drifted stream and pending receipt without mutation.
528
+ `unstaged_durable_receipt_ids` identifies valid filesystem sidecars awaiting
529
+ matching immutable evidence in the Git index. The preview can inspect those
530
+ sidecars, but ordinary apply refuses to cite them until they are staged. For the
531
+ default tracker their paths are `.agents/pm/merge-receipts/<receipt-id>.json`;
532
+ use `git add -- <reviewed sidecar paths>` followed by `git diff --cached`. Use
533
+ `--stage` for the guarded lossless workflow above. After ordinary apply, stage
534
+ the updated history and receipt lifecycle files together before committing.
452
535
  It applies the same exact-snapshot proof requirement as apply: stale or
453
536
  unprovable receipts appear as failed streams in both modes, tracked by
454
537
  [pm-ao0bu9](../.agents/pm/issues/pm-ao0bu9.toon).
@@ -514,9 +597,9 @@ The apply pass uses the audited history rewrite boundary to append a
514
597
  event includes privacy-safe receipt provenance; a clean receipt-bearing stream
515
598
  gets a no-op merge event so the merge remains addressable even when replay
516
599
  already matches. The command immediately validates history drift plus storage
517
- integrity and exits nonzero when an invariant remains red. Default Git hooks
518
- remain unchanged: repositories that want automatic enforcement must opt in by
519
- invoking this command from their own post-merge hook.
600
+ integrity and exits nonzero when an invariant remains red. Default Git hooks remain unchanged. The explicit merge-aware pre-commit option
601
+ above includes settlement before committing; a repository-owned post-merge hook
602
+ can still enforce reconciliation after an already-created merge commit.
520
603
 
521
604
  The default validation surface includes `storage_integrity`. It fails on unreadable item documents, history conflict markers, malformed history tails, live items whose latest history operation is `delete` (a delete/modify resurrection candidate), and unparseable settings/schema files. This prevents the ordinary tolerant read path from turning corruption into a green gate.
522
605
 
@@ -1,5 +1,15 @@
1
1
  # Output Projection and Omission Contracts
2
2
 
3
+ Passing extension health defaults are tracked by
4
+ [pm-gh1486](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1486.toon),
5
+ a repository-only tracker file excluded from the npm package. Standard `pm health` output
6
+ reports healthy extension counts and `restore_with: "pm health --full"` rather
7
+ than the command registry. Its `standard` projection declares the omitted full
8
+ check details. Warning and failure details remain available by default.
9
+ `--full` restores structured evidence; `--brief` never expands an individual
10
+ check's serialized detail beyond the standard projection. Summary and check-only
11
+ verdict semantics remain unchanged. SDK `runHealth` and MCP use the same engine.
12
+
3
13
  Tracker references: [pm-p258tx](../.agents/pm/features/pm-p258tx.toon),
4
14
  [pm-cyrfjq](../.agents/pm/issues/pm-cyrfjq.toon), and
5
15
  [pm-qhnq6t](../.agents/pm/issues/pm-qhnq6t.toon). The universal row and
package/docs/RELEASING.md CHANGED
@@ -304,7 +304,14 @@ The release workflow publishes this staged tarball with provenance; CI and
304
304
  packed smoke tests use the same staging command. Application distribution and
305
305
  bundled runtime have separate committed size and file-count limits, so runtime
306
306
  payload cannot hide application growth. The ledger ships with the tarball for
307
- installed-version verification. npm 12 ignores published shrinkwraps; shipping
307
+ installed-version verification. [pm-iceees](../.agents/pm/issues/pm-iceees.toon)
308
+ keeps selected optional-peer subtrees complete: npm deliberately skips peer edges
309
+ when gathering bundled files, so staged runtime manifests record the exact tested
310
+ peer bindings as ordinary or optional dependency entries. Package code, source
311
+ and installed manifests, peer declarations, and the root public dependency
312
+ inventory remain intact. A real archive regression resolves the peer's descendant
313
+ from an extracted package and the installed-runtime verifier still refuses any
314
+ missing locked package. npm 12 ignores published shrinkwraps; shipping
308
315
  a shrinkwrap alone therefore cannot enforce this contract. SDK consumers
309
316
  supply the bounded optional Node types peer themselves.
310
317