@unbrained/pm-cli 2026.10.18 → 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 (146) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +10 -0
  3. package/dist/cli/help-content.js +2 -2
  4. package/dist/cli/register-mutation.js +2 -2
  5. package/dist/cli/register-setup.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/chunk-4CXQSRSP.js +126 -0
  8. package/dist/cli-bundle/chunks/{chunk-AETP4JEM.js → chunk-4ICKT4GH.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-7WIEAGDS.js → chunk-4MJ6WBMA.js} +2 -2
  10. package/dist/cli-bundle/chunks/chunk-4XFVAXA4.js +2 -0
  11. package/dist/cli-bundle/chunks/{chunk-FIJOSX2C.js → chunk-5GZSX5HU.js} +72 -66
  12. package/dist/cli-bundle/chunks/{chunk-4GA4MUTE.js → chunk-6DS5CAN2.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-6VZKYJW7.js → chunk-D3EDNAN7.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-DMFM5R4G.js +3 -0
  15. package/dist/cli-bundle/chunks/chunk-H3XYP24A.js +70 -0
  16. package/dist/cli-bundle/chunks/chunk-LBEMB3BW.js +6 -0
  17. package/dist/cli-bundle/chunks/chunk-NX7Q4LGN.js +8 -0
  18. package/dist/cli-bundle/chunks/chunk-O2ZRRLAP.js +8 -0
  19. package/dist/cli-bundle/chunks/chunk-OEJ3G7XT.js +20 -0
  20. package/dist/cli-bundle/chunks/{chunk-PYRREEUB.js → chunk-QBNEZII5.js} +28 -28
  21. package/dist/cli-bundle/chunks/chunk-QG4LMU7A.js +112 -0
  22. package/dist/cli-bundle/chunks/chunk-QKAAZWGC.js +3 -0
  23. package/dist/cli-bundle/chunks/chunk-RUKSEZE7.js +2 -0
  24. package/dist/cli-bundle/chunks/chunk-TK3G3GAP.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-VS565KBX.js +2 -0
  26. package/dist/cli-bundle/chunks/{chunk-ZZED447K.js → chunk-XH7C3A5N.js} +2 -2
  27. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BVSHK4WQ.js +4 -0
  28. package/dist/cli-bundle/chunks/{register-list-query-PUCVYYBD.js → register-list-query-WQUVDJIH.js} +2 -2
  29. package/dist/cli-bundle/chunks/register-mutation-IWIBQIO3.js +20 -0
  30. package/dist/cli-bundle/chunks/register-operations-SUWOZNDU.js +2 -0
  31. package/dist/cli-bundle/chunks/register-setup-QGM5YJW7.js +2 -0
  32. package/dist/cli-bundle/chunks/settlement-hook-UNFMCKKQ.js +7 -0
  33. package/dist/cli-bundle/chunks/stage-7DELI4Z5.js +2 -0
  34. package/dist/cli-bundle/focused-chunks/{chunk-2MPQUMTF.js → chunk-2IEWB6MB.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/chunk-3TEIACFU.js +3 -0
  36. package/dist/cli-bundle/focused-chunks/chunk-5YTOYBTZ.js +65 -0
  37. package/dist/cli-bundle/focused-chunks/chunk-AK2CI2GI.js +2 -0
  38. package/dist/cli-bundle/focused-chunks/chunk-BJMPRB7A.js +91 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-BFEMT5U3.js → chunk-ENZMATOY.js} +3 -3
  40. package/dist/cli-bundle/focused-chunks/chunk-EOQ6W25I.js +8 -0
  41. package/dist/cli-bundle/focused-chunks/{chunk-A4ZHHTEX.js → chunk-FEN7WOOP.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +2 -0
  43. package/dist/cli-bundle/focused-chunks/chunk-GWTV45SB.js +2 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-ZDBS2DCT.js → chunk-H6BVQ63U.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-IRVL4UXR.js → chunk-HYMYAGSY.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/chunk-JBJJW2WL.js +6 -0
  47. package/dist/cli-bundle/focused-chunks/chunk-JCLC6HKT.js +8 -0
  48. package/dist/cli-bundle/focused-chunks/{chunk-TB7F4FCR.js → chunk-JDBO7SMR.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-TZUIBG3P.js → chunk-KLJN44VY.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/chunk-L4PL3GZR.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-OV2WVLUR.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-PXDR77TO.js +78 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-RLRMNFLF.js +3 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-Z7YIFCNE.js → chunk-SKYLOPU2.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-VVRXF4JO.js +2 -0
  56. package/dist/cli-bundle/focused-chunks/chunk-WZTEFFQI.js +3 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-Y54ONBEX.js +25 -0
  58. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-QW2VWWJE.js +4 -0
  59. package/dist/cli-bundle/focused-chunks/settlement-hook-X4FNHTOD.js +7 -0
  60. package/dist/cli-bundle/focused-chunks/stage-MZSVQYO4.js +2 -0
  61. package/dist/cli-bundle/main.js +3 -3
  62. package/dist/cli-bundle/sdk-authoring.js +1 -1
  63. package/dist/cli-bundle/sdk-contracts.js +1 -1
  64. package/dist/cli-bundle/sdk-core.js +28 -22
  65. package/dist/cli-bundle/sdk-governance.js +1 -1
  66. package/dist/cli-bundle/sdk-graph.js +1 -1
  67. package/dist/cli-bundle/sdk-merge.js +66 -53
  68. package/dist/cli-bundle/sdk-query.js +1 -1
  69. package/dist/cli-bundle/sdk-runtime.js +1 -1
  70. package/dist/cli-bundle/sdk-testing.js +1 -1
  71. package/dist/cli-bundle/sdk.js +2 -2
  72. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  73. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  74. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  75. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +1 -0
  76. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  77. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  78. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  79. package/dist/sdk/extension/install-sources.js +3 -3
  80. package/dist/sdk/extension/shared.js +1 -1
  81. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  82. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  83. package/dist/sdk/governance/health.js +1 -1
  84. package/dist/sdk/history-repair.js +1 -1
  85. package/dist/sdk/merge/driver.js +7 -1
  86. package/dist/sdk/merge/indexed-receipt-blobs.d.ts +2 -0
  87. package/dist/sdk/merge/indexed-receipt-blobs.js +4 -0
  88. package/dist/sdk/merge/install.d.ts +8 -0
  89. package/dist/sdk/merge/install.js +3 -3
  90. package/dist/sdk/merge/receipts.d.ts +6 -0
  91. package/dist/sdk/merge/receipts.js +2 -2
  92. package/dist/sdk/merge/reconcile.d.ts +6 -0
  93. package/dist/sdk/merge/reconcile.js +1 -1
  94. package/dist/sdk/merge/settlement-hook.d.ts +12 -0
  95. package/dist/sdk/merge/settlement-hook.js +7 -0
  96. package/dist/sdk/merge/stage.d.ts +13 -0
  97. package/dist/sdk/merge/stage.js +2 -0
  98. package/dist/sdk/public-surface.json +1 -1
  99. package/dist/sdk/query/list.js +1 -1
  100. package/dist/sdk/runtime-extended-actions.js +1 -1
  101. package/docs/COMMANDS.md +13 -0
  102. package/docs/CONFIGURATION.md +14 -0
  103. package/docs/MERGE_SAFETY.md +88 -5
  104. package/docs/SDK.md +26 -0
  105. package/docs/TESTING.md +7 -0
  106. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  107. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  108. package/marketplace.json +1 -1
  109. package/package.json +1 -1
  110. package/packages/pm-beads/package.json +1 -1
  111. package/packages/pm-calendar/package.json +1 -1
  112. package/packages/pm-command-kit/package.json +1 -1
  113. package/packages/pm-digital-twin/package.json +1 -1
  114. package/packages/pm-governance-audit/package.json +1 -1
  115. package/packages/pm-guide-shell/package.json +1 -1
  116. package/packages/pm-kanban/package.json +1 -1
  117. package/packages/pm-lifecycle-hooks/package.json +1 -1
  118. package/packages/pm-linked-test-adapters/package.json +1 -1
  119. package/packages/pm-search-advanced/package.json +1 -1
  120. package/packages/pm-templates/package.json +1 -1
  121. package/packages/pm-todos/package.json +1 -1
  122. package/packages/pm-vcs/package.json +1 -1
  123. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  124. package/plugins/pm-claude/package.json +1 -1
  125. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  126. package/plugins/pm-codex/package.json +1 -1
  127. package/plugins/pm-codex/plugin.json +1 -1
  128. package/runtime-dependencies.json +1 -1
  129. package/dist/cli-bundle/chunks/chunk-4V6ONLI6.js +0 -3
  130. package/dist/cli-bundle/chunks/chunk-7PATQWTH.js +0 -20
  131. package/dist/cli-bundle/chunks/chunk-LUKVNL72.js +0 -2
  132. package/dist/cli-bundle/chunks/chunk-OJ77ZQN3.js +0 -8
  133. package/dist/cli-bundle/chunks/chunk-RHQJ6VWC.js +0 -237
  134. package/dist/cli-bundle/chunks/chunk-RNABUEFB.js +0 -80
  135. package/dist/cli-bundle/chunks/chunk-TO6CIV4C.js +0 -2
  136. package/dist/cli-bundle/chunks/register-mutation-GGGVBXD5.js +0 -20
  137. package/dist/cli-bundle/chunks/register-operations-NRZ6Q4QE.js +0 -2
  138. package/dist/cli-bundle/chunks/register-setup-MV3P3YSF.js +0 -2
  139. package/dist/cli-bundle/focused-chunks/chunk-5UKCSZWT.js +0 -2
  140. package/dist/cli-bundle/focused-chunks/chunk-B4YLP5ZB.js +0 -3
  141. package/dist/cli-bundle/focused-chunks/chunk-FW7CSSKL.js +0 -75
  142. package/dist/cli-bundle/focused-chunks/chunk-HYPRPSYD.js +0 -3
  143. package/dist/cli-bundle/focused-chunks/chunk-L55KQ2KT.js +0 -2
  144. package/dist/cli-bundle/focused-chunks/chunk-MASIOFPG.js +0 -8
  145. package/dist/cli-bundle/focused-chunks/chunk-RJ3EIHDU.js +0 -26
  146. package/dist/cli-bundle/focused-chunks/chunk-SEL4Z2OO.js +0 -167
@@ -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]="9260454d-9ece-5b5f-a812-f9865b6f4ee4")}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-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/docs/COMMANDS.md CHANGED
@@ -1095,6 +1095,19 @@ When more than one history stream is drifted, the `history_drift` remediation co
1095
1095
 
1096
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`).
1097
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
+
1098
1111
  ## History and Recovery
1099
1112
 
1100
1113
  After a branch merge that touched tracker history, preview and apply the
@@ -336,6 +336,20 @@ pm get <id> --full --json
336
336
  pm contracts --json
337
337
  ```
338
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
+
339
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.
340
354
 
341
355
  ## Validation Policies
@@ -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
 
package/docs/SDK.md CHANGED
@@ -210,6 +210,32 @@ follow the migration guidance for changed unions or error codes. The shared
210
210
  [primitive inventory](SDK_PRIMITIVE_INVENTORY.md) records CLI/MCP ownership:
211
211
  presentation modules import the SDK and have zero private-core edges.
212
212
 
213
+ ### Portable merge settlement
214
+
215
+ Tracked by [pm-gh1475](../.agents/pm/issues/pm-gh1475.toon) and
216
+ [pm-gh1491](../.agents/pm/issues/pm-gh1491.toon). Import `runMergeInstall`,
217
+ `runMergeReconcile`, and `inspectMergeReceiptEvidence` from
218
+ `@unbrained/pm-cli/sdk/merge`. `runMergeInstall({ preCommitHook: true }, global)`
219
+ explicitly installs the merge-aware pre-commit hook; the default installs no hook.
220
+ `runMergeReconcile({ stage: true }, global)` previews first and stages only
221
+ verified lossless history and receipt artifacts. It refuses forced acceptance,
222
+ competing values, unrelated drift, dirty reconciliation paths and unresolved Git
223
+ paths. `staged_paths` reports exactly which relative paths were added to the index.
224
+
225
+ The single-commit journey pauses Git with `git merge --no-commit --no-ff` before
226
+ reconciliation or an opted-in pre-commit hook runs. `durable_receipt_ids` on the
227
+ inspection result reports counterparts with matching immutable provenance in
228
+ the active Git index. `unstaged_durable_receipt_ids` separates valid filesystem
229
+ sidecars that a read-only preview may inspect. Guarded staging prepares new
230
+ sidecars before auditing and restores their new index entries if apply fails.
231
+ Inspection lists indexed candidates once and reads bounded object batches.
232
+ Guarded settlement resolves tracker aliases before preview, proof verification
233
+ and apply, so every phase uses the same physical tracker root.
234
+ Ordinary apply requires indexed proof first. Missing portable proof
235
+ refuses an audit write even with `force`; local receipts alone cannot authorize
236
+ committed history references. See [Merge safety](MERGE_SAFETY.md#settle-a-lossless-merge-in-one-commit)
237
+ for the complete operator workflow and recovery boundaries.
238
+
213
239
  ### Build an entire custom project tool
214
240
 
215
241
  The [SDK-only custom-tool exemplar](examples/sdk-custom-tool/README.md)
package/docs/TESTING.md CHANGED
@@ -97,6 +97,13 @@ so PR-local CodeFactor maintainability annotations fail locally before commit or
97
97
  push. Existing legacy high-complexity test fixtures are tracked separately and
98
98
  must not be used as precedent for new changed production/script code.
99
99
 
100
+ Module-usage checks share the SDK boundary's literal-specifier parser and walk
101
+ nested AST nodes, including lazy `import("./module.js")` references. Unused
102
+ modules, comment-only references, and computed paths do not gain incoming
103
+ references. The regression is tracked by
104
+ [pm-f38ovr](../.agents/pm/issues/pm-f38ovr.toon); no module allowance or threshold
105
+ increase is required to keep optional SDK capabilities lazy.
106
+
100
107
  The same required static gate validates an explicit seven-day Dependabot
101
108
  cooldown for every updater and requires both npm and GitHub Actions entries.
102
109
  Missing values, semver overrides outside 7–90 days, invalid YAML, removed
@@ -39,7 +39,7 @@ This file is generated by `listPmFlagLexicon()`. Compatibility aliases do not co
39
39
  | `history-repair` | evidence | 27 | 27 |
40
40
  | `history-compact` | evidence | 30 | 30 |
41
41
  | `history-author-acknowledge` | evidence | 28 | 28 |
42
- | `merge` | workspace | 27 | 27 |
42
+ | `merge` | workspace | 29 | 29 |
43
43
  | `schema` | workspace | 43 | 43 |
44
44
  | `profile` | workspace | 22 | 22 |
45
45
  | `activity` | context | 35 | 35 |
@@ -110,7 +110,7 @@ This file is generated by `listPmFlagLexicon()`. Compatibility aliases do not co
110
110
  | `item test worker` | internal | 20 | 20 |
111
111
  | `history acknowledge` | evidence | 28 | 28 |
112
112
  | `item copy` | intake | 24 | 24 |
113
- | `workspace merge` | workspace | 27 | 27 |
113
+ | `workspace merge` | workspace | 29 | 29 |
114
114
  | `item duplicates` | context | 25 | 25 |
115
115
  | `calendar meet` | automation | 33 | 33 |
116
116
  | `calendar event` | automation | 33 | 33 |
@@ -4,12 +4,12 @@ Tracker: `pm-f05lsg`.
4
4
 
5
5
  Every catalog code is listed. An `uncovered` row is an explicit closure obligation, never an omission or implied approval.
6
6
 
7
- - Catalog error codes: 419
7
+ - Catalog error codes: 422
8
8
  - Executable error codes: 19
9
9
  - Executable-code ratchet floor: 18
10
10
  - Required executable canonical codes: `bulk_ids_input_empty`, `bulk_ids_input_missing_path`, `bulk_ids_input_unreadable`, `invalid_argument_value`, `manifest_unknown_key`, `missing_lifecycle_target`, `missing_required_argument`, `no_version_bounds_declared`, `projection_options_mutually_exclusive`, `tracker_not_initialized`, `tracker_root_missing`, `tracker_root_not_directory`, `tracker_root_unreadable`, `unknown_context_intent`, `unknown_field_projection`, `unknown_option`, `unknown_subcommand`
11
- - Uncovered error codes: 400
12
- - Coverage fraction: 0.045346
11
+ - Uncovered error codes: 403
12
+ - Coverage fraction: 0.045024
13
13
  - Closed-domain probes: 19
14
14
  - Grammar probes: 117
15
15
 
@@ -221,9 +221,12 @@ Every catalog code is listed. An `uncovered` row is an explicit closure obligati
221
221
  | `merge_git_config_unwritable` | `merge_git_config_unwritable` | uncovered | none | 0 |
222
222
  | `merge_receipt_evidence_invalid` | `merge_receipt_evidence_invalid` | uncovered | none | 0 |
223
223
  | `merge_receipt_history_reference_missing` | `merge_receipt_history_reference_missing` | uncovered | none | 0 |
224
+ | `merge_receipt_not_portable` | `merge_receipt_not_portable` | uncovered | none | 0 |
224
225
  | `merge_receipts_pending` | `merge_receipts_pending` | uncovered | none | 0 |
225
226
  | `merge_reconcile_receipt_evidence_untrusted` | `merge_reconcile_receipt_evidence_untrusted` | uncovered | none | 0 |
226
227
  | `merge_root_not_found` | `merge_root_not_found` | uncovered | none | 0 |
228
+ | `merge_settlement_hook_conflict` | `merge_settlement_hook_conflict` | uncovered | none | 0 |
229
+ | `merge_settlement_review_required` | `merge_settlement_review_required` | uncovered | none | 0 |
227
230
  | `missing_allowed_values` | `missing_allowed_values` | uncovered | none | 0 |
228
231
  | `missing_budget` | `missing_budget` | uncovered | none | 0 |
229
232
  | `missing_cli_flag` | `missing_cli_flag` | uncovered | none | 0 |
package/marketplace.json CHANGED
@@ -1 +1 @@
1
- {"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.10.18","plugins":[{"name":"pm-claude","source":"./plugins/pm-claude","description":"Native pm CLI integration for Claude Code — 32 MCP tools, 14 workflow skills with slash invocations, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.","version":"2026.10.18","author":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"homepage":"https://github.com/unbraind/pm-cli","repository":"https://github.com/unbraind/pm-cli","license":"MIT","keywords":["pm-cli","project-management","mcp","tasks","agents","workflows","git-native","task-tracker","ai"],"category":"productivity"}]}
1
+ {"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.10.19","plugins":[{"name":"pm-claude","source":"./plugins/pm-claude","description":"Native pm CLI integration for Claude Code — 32 MCP tools, 14 workflow skills with slash invocations, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.","version":"2026.10.19","author":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"homepage":"https://github.com/unbraind/pm-cli","repository":"https://github.com/unbraind/pm-cli","license":"MIT","keywords":["pm-cli","project-management","mcp","tasks","agents","workflows","git-native","task-tracker","ai"],"category":"productivity"}]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unbrained/pm-cli",
3
- "version": "2026.10.18",
3
+ "version": "2026.10.19",
4
4
  "description": "Git-native project management CLI for humans and agents.",
5
5
  "type": "module",
6
6
  "packageManager": "pnpm@11.28.5",
@@ -1 +1 @@
1
- {"name":"@unbrained/pm-beads","version":"2026.10.18","private":true,"type":"module","description":"First-party pm package for importing Beads JSONL records.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-beads"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","beads"],"pm":{"aliases":["beads"],"extensions":["extensions/beads"],"catalog":{"display_name":"Beads Import","category":"migration","summary":"Import Beads JSONL records into pm while preserving source IDs.","tags":["migration","beads","import"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
1
+ {"name":"@unbrained/pm-beads","version":"2026.10.19","private":true,"type":"module","description":"First-party pm package for importing Beads JSONL records.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-beads"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","beads"],"pm":{"aliases":["beads"],"extensions":["extensions/beads"],"catalog":{"display_name":"Beads Import","category":"migration","summary":"Import Beads JSONL records into pm while preserving source IDs.","tags":["migration","beads","import"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
@@ -1 +1 @@
1
- {"name":"@unbrained/pm-calendar","version":"2026.10.18","private":true,"type":"module","description":"First-party pm package for calendar and agenda views.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-calendar"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","calendar","agenda"],"pm":{"aliases":["calendar"],"extensions":["extensions/calendar"],"catalog":{"display_name":"Calendar Views","category":"workflow","summary":"Show agenda, day, week, and month views for deadlines, reminders, and scheduled events.","tags":["calendar","agenda","workflow"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
1
+ {"name":"@unbrained/pm-calendar","version":"2026.10.19","private":true,"type":"module","description":"First-party pm package for calendar and agenda views.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-calendar"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","calendar","agenda"],"pm":{"aliases":["calendar"],"extensions":["extensions/calendar"],"catalog":{"display_name":"Calendar Views","category":"workflow","summary":"Show agenda, day, week, and month views for deadlines, reminders, and scheduled events.","tags":["calendar","agenda","workflow"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
@@ -1 +1 @@
1
- {"name":"@unbrained/pm-command-kit","version":"2026.10.18","private":true,"type":"module","description":"First-party pm exemplar package for the commands capability: registerCommand, registerFlags, and registerParser.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-command-kit"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","sdk","commands","exemplar"],"pm":{"aliases":["command-kit"],"extensions":["extensions/command-kit"],"catalog":{"display_name":"Command Kit Exemplar","category":"sdk","summary":"Copy-paste-able exemplar for registerCommand, registerFlags, and registerParser.","tags":["sdk","commands","parser","exemplar"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
1
+ {"name":"@unbrained/pm-command-kit","version":"2026.10.19","private":true,"type":"module","description":"First-party pm exemplar package for the commands capability: registerCommand, registerFlags, and registerParser.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-command-kit"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","sdk","commands","exemplar"],"pm":{"aliases":["command-kit"],"extensions":["extensions/command-kit"],"catalog":{"display_name":"Command Kit Exemplar","category":"sdk","summary":"Copy-paste-able exemplar for registerCommand, registerFlags, and registerParser.","tags":["sdk","commands","parser","exemplar"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
@@ -1 +1 @@
1
- {"name":"@unbrained/pm-digital-twin","version":"2026.10.18","private":true,"type":"module","description":"Beyond-PM exemplar: a temporal production-facility digital twin built entirely on public pm SDK and extension primitives.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-digital-twin"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","sdk","digital-twin","event-sourcing","temporal-graph","exemplar"],"pm":{"aliases":["digital-twin","twin"],"extensions":["extensions/digital-twin"],"catalog":{"display_name":"Digital Twin SDK Exemplar","category":"sdk","summary":"Temporal facility graph proving event replay, point-in-time state, invariants, federation, checkpoints, and compact exports through public SDK contracts.","tags":["sdk","digital-twin","event-sourcing","graph","offline-first","exemplar"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin","report":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin/GAP_REPORT.md"}},"docs":["README.md","GAP_REPORT.md"],"examples":["README.md"]}}
1
+ {"name":"@unbrained/pm-digital-twin","version":"2026.10.19","private":true,"type":"module","description":"Beyond-PM exemplar: a temporal production-facility digital twin built entirely on public pm SDK and extension primitives.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-digital-twin"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","sdk","digital-twin","event-sourcing","temporal-graph","exemplar"],"pm":{"aliases":["digital-twin","twin"],"extensions":["extensions/digital-twin"],"catalog":{"display_name":"Digital Twin SDK Exemplar","category":"sdk","summary":"Temporal facility graph proving event replay, point-in-time state, invariants, federation, checkpoints, and compact exports through public SDK contracts.","tags":["sdk","digital-twin","event-sourcing","graph","offline-first","exemplar"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin","report":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin/GAP_REPORT.md"}},"docs":["README.md","GAP_REPORT.md"],"examples":["README.md"]}}
@@ -1 +1 @@
1
- {"name":"@unbrained/pm-governance-audit","version":"2026.10.18","private":true,"type":"module","description":"First-party pm package for governance audit and normalization workflows.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-governance-audit#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-governance-audit"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","governance","audit","normalize","hooks"],"pm":{"aliases":["governance-audit","audit"],"extensions":["extensions/governance-audit"],"catalog":{"display_name":"Governance Audit","category":"governance","summary":"Run dedupe audits, comments audits, and normalize sweeps as package-owned workflows.","tags":["governance","audit","normalize","hooks"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-governance-audit#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-governance-audit","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
1
+ {"name":"@unbrained/pm-governance-audit","version":"2026.10.19","private":true,"type":"module","description":"First-party pm package for governance audit and normalization workflows.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-governance-audit#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-governance-audit"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","governance","audit","normalize","hooks"],"pm":{"aliases":["governance-audit","audit"],"extensions":["extensions/governance-audit"],"catalog":{"display_name":"Governance Audit","category":"governance","summary":"Run dedupe audits, comments audits, and normalize sweeps as package-owned workflows.","tags":["governance","audit","normalize","hooks"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-governance-audit#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-governance-audit","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
@@ -1 +1 @@
1
- {"name":"@unbrained/pm-guide-shell","version":"2026.10.18","private":true,"type":"module","description":"First-party pm package for guide and shell completion workflows.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-guide-shell#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-guide-shell"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","guide","completion","shell"],"pm":{"aliases":["guide-shell"],"extensions":["extensions/guide-shell"],"catalog":{"display_name":"Guide + Shell UX","category":"workflow","summary":"Restore guide documentation and shell completion commands as package-owned UX surfaces.","tags":["guide","completion","shell"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-guide-shell#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-guide-shell","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
1
+ {"name":"@unbrained/pm-guide-shell","version":"2026.10.19","private":true,"type":"module","description":"First-party pm package for guide and shell completion workflows.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-guide-shell#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-guide-shell"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","guide","completion","shell"],"pm":{"aliases":["guide-shell"],"extensions":["extensions/guide-shell"],"catalog":{"display_name":"Guide + Shell UX","category":"workflow","summary":"Restore guide documentation and shell completion commands as package-owned UX surfaces.","tags":["guide","completion","shell"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-guide-shell#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-guide-shell","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}