@unbrained/pm-cli 2026.10.23 → 2026.10.24

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 (137) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +21 -0
  3. package/dist/cli/error-guidance.js +2 -2
  4. package/dist/cli-bundle/bundle-manifest.json +1 -1
  5. package/dist/cli-bundle/chunks/{chunk-MTRYEVZR.js → chunk-3VI4XDP2.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-AAX7CNL7.js → chunk-4PNAUT2E.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-2UX2TAN2.js → chunk-CDR5ES7Q.js} +54 -54
  8. package/dist/cli-bundle/chunks/chunk-CNEUJHA4.js +2 -0
  9. package/dist/cli-bundle/chunks/{chunk-AXGFNNI3.js → chunk-CSE47ZAN.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-ZEI3DC5E.js → chunk-FASDGYQC.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-5DKCD4KV.js → chunk-HZNFNETE.js} +35 -34
  12. package/dist/cli-bundle/chunks/{chunk-KY34HTT2.js → chunk-KGZGXC7T.js} +29 -29
  13. package/dist/cli-bundle/chunks/{chunk-REXCO5AG.js → chunk-MA7SNKYK.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-ZNDYAZZ6.js → chunk-TZYQ4JDZ.js} +3 -3
  15. package/dist/cli-bundle/chunks/{chunk-F76ZUP73.js → chunk-URZB3USE.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-UY5UHI4I.js +2 -0
  17. package/dist/cli-bundle/chunks/{chunk-MMVX5L32.js → chunk-VPMQEVU6.js} +14 -14
  18. package/dist/cli-bundle/chunks/{chunk-ZMJF5HQW.js → chunk-VSSHB6XI.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-5V4HU6GK.js → chunk-YEI4N4A6.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-HDKY2YX3.js → chunk-Z62RXNHW.js} +2 -2
  21. package/dist/cli-bundle/chunks/{mutation-admission-P6LOBNLO.js → mutation-admission-NVTBZ7DH.js} +2 -2
  22. package/dist/cli-bundle/chunks/{register-list-query-JOB65KDN.js → register-list-query-2FE6K7FQ.js} +2 -2
  23. package/dist/cli-bundle/chunks/{register-mutation-QMNIN3RJ.js → register-mutation-KZXQUZUH.js} +2 -2
  24. package/dist/cli-bundle/chunks/{register-operations-Z4VET3I7.js → register-operations-BOCBWNKJ.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-setup-GNKWL3VL.js → register-setup-P3VLCTDY.js} +2 -2
  26. package/dist/cli-bundle/chunks/{stage-FW5OXCCR.js → stage-WRDTMCCF.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-LEHGCPZ6.js → chunk-3QYTS4OY.js} +4 -4
  28. package/dist/cli-bundle/focused-chunks/{chunk-I2USTQNQ.js → chunk-5MKNVJCM.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-CGL36F6I.js → chunk-6HJCSHBG.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-OMXMYTEX.js → chunk-7RQOFHMH.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/chunk-AGCEWJ27.js +21 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-BM652VCB.js → chunk-CEEOWDB7.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-NSMZY6IK.js → chunk-ES2NGVHZ.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/chunk-GXAXDPD4.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-P7DPS5M4.js → chunk-IUAYTD2S.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-DWQMYLFM.js → chunk-JYXA4JIP.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-XIZYJDYW.js → chunk-NFFPNMTH.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-MLET6I3I.js → chunk-NX7TVNUM.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-UNTCCJPL.js → chunk-POLMFGPQ.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-ZHMF34DT.js → chunk-RSEGFZTY.js} +52 -52
  41. package/dist/cli-bundle/focused-chunks/{chunk-4MNUQCGR.js → chunk-RVUGTIIU.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-6GTZ24YV.js → chunk-SBJ2IKTH.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-EDXTOAXP.js → chunk-SHUPX6G2.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-KI5YFKNN.js → chunk-TAHSXKAT.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/chunk-X5YRJMAY.js +2 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-XTYEASIY.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/chunk-ZMWLV2CE.js +91 -0
  48. package/dist/cli-bundle/focused-chunks/{mutation-admission-HTFAIHJL.js → mutation-admission-PB6YFY7S.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{stage-X3BUGEJT.js → stage-MQE4PFWT.js} +2 -2
  50. package/dist/cli-bundle/main.js +21 -21
  51. package/dist/cli-bundle/sdk-authoring.js +1 -1
  52. package/dist/cli-bundle/sdk-contracts.js +1 -1
  53. package/dist/cli-bundle/sdk-core.js +24 -24
  54. package/dist/cli-bundle/sdk-governance.js +1 -1
  55. package/dist/cli-bundle/sdk-graph.js +1 -1
  56. package/dist/cli-bundle/sdk-merge.js +53 -53
  57. package/dist/cli-bundle/sdk-query.js +1 -1
  58. package/dist/cli-bundle/sdk-runtime.js +1 -1
  59. package/dist/cli-bundle/sdk-testing.js +1 -1
  60. package/dist/cli-bundle/sdk.js +9 -9
  61. package/dist/core/checkpoint/mutation-checkpoint.d.ts +6 -3
  62. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  63. package/dist/core/checkpoint/mutation-context.d.ts +10 -0
  64. package/dist/core/checkpoint/mutation-context.js +2 -0
  65. package/dist/core/store/item-store.js +1 -1
  66. package/dist/sdk/agent/command-recovery.d.ts +1 -0
  67. package/dist/sdk/agent/command-recovery.js +1 -1
  68. package/dist/sdk/agent/linked-resource-recovery.d.ts +13 -0
  69. package/dist/sdk/agent/linked-resource-recovery.js +2 -0
  70. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  71. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +3 -2
  72. package/dist/sdk/core.d.ts +1 -1
  73. package/dist/sdk/core.js +1 -1
  74. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  75. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  76. package/dist/sdk/index.d.ts +1 -0
  77. package/dist/sdk/index.js +1 -1
  78. package/dist/sdk/lifecycle/checkpoint-rollback.d.ts +7 -0
  79. package/dist/sdk/lifecycle/checkpoint-rollback.js +2 -0
  80. package/dist/sdk/lifecycle/close-many.d.ts +1 -1
  81. package/dist/sdk/lifecycle/close-many.js +1 -1
  82. package/dist/sdk/lifecycle/update-many.d.ts +1 -1
  83. package/dist/sdk/lifecycle/update-many.js +1 -1
  84. package/dist/sdk/public-surface.json +1 -1
  85. package/dist/sdk/query/context.d.ts +2 -1
  86. package/dist/sdk/query/context.js +1 -1
  87. package/dist/sdk/query/get.d.ts +2 -1
  88. package/dist/sdk/query/get.js +1 -1
  89. package/dist/sdk/query/list.d.ts +2 -1
  90. package/dist/sdk/query/list.js +1 -1
  91. package/dist/sdk/query/search/types.d.ts +2 -1
  92. package/dist/sdk/query.d.ts +1 -0
  93. package/dist/sdk/query.js +1 -1
  94. package/dist/sdk/read-output-contracts.d.ts +10 -2
  95. package/dist/sdk/read-output-contracts.js +1 -1
  96. package/dist/sdk/runtime-input.js +1 -1
  97. package/dist/sdk/runtime-primitives.d.ts +1 -0
  98. package/dist/sdk/runtime-primitives.js +1 -1
  99. package/dist/sdk/runtime.d.ts +10 -10
  100. package/dist/sdk/runtime.js +1 -1
  101. package/dist/sdk/test/batch.js +2 -2
  102. package/dist/sdk/test/entry.d.ts +5 -1
  103. package/dist/sdk/test/entry.js +2 -1
  104. package/dist/sdk/test/execution.js +2 -2
  105. package/docs/COMMANDS.md +21 -2
  106. package/docs/READ_OUTPUT_CONTRACTS.md +15 -0
  107. package/docs/SDK.md +45 -0
  108. package/docs/TESTING.md +28 -0
  109. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +5 -3
  110. package/marketplace.json +1 -1
  111. package/package.json +1 -1
  112. package/packages/pm-beads/package.json +1 -1
  113. package/packages/pm-calendar/package.json +1 -1
  114. package/packages/pm-command-kit/package.json +1 -1
  115. package/packages/pm-digital-twin/package.json +1 -1
  116. package/packages/pm-governance-audit/package.json +1 -1
  117. package/packages/pm-guide-shell/package.json +1 -1
  118. package/packages/pm-kanban/package.json +1 -1
  119. package/packages/pm-lifecycle-hooks/package.json +1 -1
  120. package/packages/pm-linked-test-adapters/package.json +1 -1
  121. package/packages/pm-search-advanced/package.json +1 -1
  122. package/packages/pm-templates/package.json +1 -1
  123. package/packages/pm-todos/package.json +1 -1
  124. package/packages/pm-vcs/package.json +1 -1
  125. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  126. package/plugins/pm-claude/package.json +1 -1
  127. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  128. package/plugins/pm-codex/package.json +1 -1
  129. package/plugins/pm-codex/plugin.json +1 -1
  130. package/runtime-dependencies.json +1 -1
  131. package/dist/cli-bundle/chunks/chunk-2LTGJ5DL.js +0 -2
  132. package/dist/cli-bundle/chunks/chunk-QSY55FTA.js +0 -2
  133. package/dist/cli-bundle/focused-chunks/chunk-FO4U3FIP.js +0 -91
  134. package/dist/cli-bundle/focused-chunks/chunk-GXKP56W7.js +0 -2
  135. package/dist/cli-bundle/focused-chunks/chunk-JDN34LEZ.js +0 -2
  136. package/dist/cli-bundle/focused-chunks/chunk-Z5LDTMZ3.js +0 -2
  137. package/dist/cli-bundle/focused-chunks/chunk-ZR6ZKQUK.js +0 -20
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Implements the pm context command surface and its agent-facing runtime behavior.
5
5
  */
6
+ import type { PmReadOutputMetadata } from "../read-output-contracts.js";
6
7
  import { type GlobalOptions,type RuntimeStatusRegistry } from "../runtime-primitives.js";
7
8
  import type { ContextDepth,ContextSectionName,ContextSettings,ItemMetadata,ItemStatus,PmSettings } from "../../types/index.js";
8
9
  import { type CalendarRow } from "./calendar.js";
@@ -295,7 +296,7 @@ closed?:number;
295
296
  canceled?:number;
296
297
  }
297
298
  /** Documents the context result payload exchanged by command, SDK, and package integrations. */
298
- export interface ContextResult {
299
+ export interface ContextResult extends Partial<PmReadOutputMetadata> {
299
300
  /** Value that configures or reports output default for this contract. */
300
301
  output_default:"toon";
301
302
  /** Value that configures or reports now for this contract. */
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8aaef318-d703-5287-bb14-d7b7f7f9179f")}catch{}})();import{SETTINGS_DEFAULTS,EXIT_CODE,PmCliError,compareTimestampStrings,nowIso,isTerminalStatus,normalizeStatusForRegistry,normalizeStatusInput,resolveRuntimeStatusRegistry,resolvePmRoot,readSettings,resolveAuthor,discoverExtensions,resolveItemTypeRegistry}from"../runtime-primitives.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{collectDependencyBlockedIds,resolveItemBlockers,resolveItemExecutionRole,computeActionabilityReport}from"../actionability.js";import{CONTEXT_DEPTH_VALUES,CONTEXT_SECTION_VALUES}from"../../types/index.js";import{parseIntegerLimit}from"./parsers.js";import{runCalendar}from"./calendar.js";import{runList}from"./list.js";import{runActivity}from"./activity.js";import{scoreContextCandidatesWithActiveExtensions}from"../context-relevance.js";import{buildItemContextRelevanceCandidates}from"../context-relevance.js";import{createQueryFingerprint,encodeQueryCursor,resolveQueryCursorStart,selectCursorSemanticOptions}from"../pagination.js";import{rememberReadOutputFocusRows,refreshReadOutputDeliveredCounts}from"../read-output-rows.js";import{CONTEXT_FLAG_CONTRACTS}from"../cli-contracts/flag-contracts.js";import{packContextCandidates}from"../context-packing.js";import{attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,readContextUsageAffinity,recordContextUsageServing}from"../context-usage.js";import{readWorkspaceContextSignals}from"../context-signal-store.js";import{readWorkspaceMemory,selectWorkspaceMemory}from"../workspace-memory.js";import{detectAgentIdentity}from"../../core/shared/author.js";import{readSessionState,semanticAttributionKey}from"../../core/session/session-state.js";import{semanticAttributionAffinity}from"../context/semantic-session-attribution.js";const CONTEXT_OUTPUT_VALUES=["markdown","toon","json","ndjson"],HIGH_LEVEL_TYPES=new Set(["Epic","Feature"]),DEFAULT_CONTEXT_LIMIT=10,CONTEXT_SCALE_THRESHOLD=1e4,STANDARD_SECTIONS=["hierarchy","activity","progress","recently_created","unparented","workload"],DEEP_SECTIONS=[...STANDARD_SECTIONS,"blockers","files","staleness","tests"],LEADING_HYPHEN_DATE=/^(\d{4})-(\d{2})-(\d{2})/,LEADING_COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})$/,COMPACT_DATETIME=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function parseOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!CONTEXT_OUTPUT_VALUES.includes(normalized))throw new PmCliError("Context format must be one of markdown|toon|json|ndjson",EXIT_CODE.USAGE);return normalized}const FOCUS_PROJECTION_FIELDS=new Set(["id","title","type","status","priority","order","deadline","assignee","tags","tags_inherited","updated_at","parent","children_total","children_closed","completion_pct","blocked","blocker_ids","created_at"]);function parseContextFocusFields(raw){if(raw===void 0)return;const fields=[];for(const token of raw.split(",")){const normalized=token.trim().toLowerCase();if(normalized.length!==0){if(!FOCUS_PROJECTION_FIELDS.has(normalized))throw new PmCliError(`Context --fields value not projectable: ${normalized} (valid: ${[...FOCUS_PROJECTION_FIELDS].join(", ")})`,EXIT_CODE.USAGE);fields.includes(normalized)||fields.push(normalized)}}if(fields.length===0)throw new PmCliError("Context --fields requires at least one field name",EXIT_CODE.USAGE);return fields}function projectContextFocusRows(rows,fields){return rows.map(row=>{const projected={},source=row;for(const field of fields)projected[field]=source[field]??null;return projected})}function resolveContextOutputFormat(options,global2){const commandFormat=parseOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json"&&commandFormat!=="ndjson")throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE);return global2.json?commandFormat==="ndjson"?"ndjson":"json":commandFormat??"toon"}function parseContextLimit(raw,depth){return parseIntegerLimit(raw,"--limit")??(depth==="full"?Number.MAX_SAFE_INTEGER:DEFAULT_CONTEXT_LIMIT)}function resolveContextTokenBudget(raw,fallback){if(raw===void 0)return fallback;const parsed=typeof raw=="number"?raw:Number(raw);if(!Number.isInteger(parsed)||parsed<1)throw new PmCliError("--token-budget must be a positive integer",EXIT_CODE.USAGE);return parsed}function resolveContextLimitAtScale(limit,itemCount){return itemCount>=CONTEXT_SCALE_THRESHOLD&&limit===Number.MAX_SAFE_INTEGER?DEFAULT_CONTEXT_LIMIT:limit}function parseContextDepth(raw,settings){if(!raw)return settings.default_depth;const normalized=raw.trim().toLowerCase();if(!CONTEXT_DEPTH_VALUES.includes(normalized))throw new PmCliError(`Context --depth must be one of ${CONTEXT_DEPTH_VALUES.join("|")}`,EXIT_CODE.USAGE);return normalized}function parseContextSections(raw,depth,settings){if(raw&&raw.length>0){const sections=[];for(const value of raw){const normalized=value.trim().toLowerCase();if(!CONTEXT_SECTION_VALUES.includes(normalized))throw new PmCliError(`Context --section must be one of ${CONTEXT_SECTION_VALUES.join("|")}`,EXIT_CODE.USAGE);sections.includes(normalized)||sections.push(normalized)}return sections}return depth==="brief"?[]:depth==="full"?[...CONTEXT_SECTION_VALUES]:(depth==="deep"?DEEP_SECTIONS:STANDARD_SECTIONS).filter(section=>settings.sections[section])}function parseActivityLimit(raw,settings){return raw?parseIntegerLimit(raw,"--activity-limit")??settings.activity_limit:settings.activity_limit}function parseStaleThresholdDays(raw,settings){if(!raw)return settings.stale_threshold_days;const trimmed=raw.trim().toLowerCase(),match=/^(\d+)d?$/.exec(trimmed);if(!match)throw new PmCliError("--stale-threshold must be a number of days (e.g. 7 or 7d)",EXIT_CODE.USAGE);const days=parseInt(match[1],10);if(days<=0)throw new PmCliError("--stale-threshold must be positive",EXIT_CODE.USAGE);return days}function statusRank(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry),blockedStatus=normalizeStatusInput("blocked",statusRegistry),draftStatus=normalizeStatusInput("draft",statusRegistry);return normalizedStatus===statusRegistry.in_progress_status?0:statusRegistry.active_statuses.has(normalizedStatus)?1:blockedStatus&&normalizedStatus===blockedStatus?2:draftStatus&&normalizedStatus===draftStatus?3:statusRegistry.blocked_statuses.has(normalizedStatus)?5:statusRegistry.terminal_statuses.has(normalizedStatus)?7:6}function isClosedStatus(status,statusRegistry){const closeStatus=normalizeStatusInput("closed",statusRegistry);return normalizeStatusForRegistry(status,statusRegistry)===closeStatus}function isInProgressStatus(status,statusRegistry){return normalizeStatusForRegistry(status,statusRegistry)===statusRegistry.in_progress_status}function isOpenStatus(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry);return normalizedStatus!==statusRegistry.in_progress_status&&statusRegistry.active_statuses.has(normalizedStatus)}function isBlockedStatus(status,statusRegistry){return statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(status,statusRegistry))}const LIST_PROJECTION_FLAGS=["compact","brief","fields","includeBody","include_body","parent"];function stripListProjectionFlags(options){const copy={...options};for(const key of LIST_PROJECTION_FLAGS)delete copy[key];return copy}function collectSubtreeIds(corpus,parentId){const target=parentId.trim().toLowerCase(),anchor=corpus.find(item=>item.id.trim().toLowerCase()===target);if(!anchor)return{ids:new Set,found:!1};const childrenByParent=buildChildrenByParent(corpus),descendants=collectDescendants(anchor.id,childrenByParent);return{ids:new Set([anchor.id,...descendants.map(item=>item.id)].map(id=>id.trim().toLowerCase())),found:!0}}function parseContextParent(raw){if(raw===void 0)return;const trimmed=raw.trim();if(trimmed.length===0)throw new PmCliError("Context --parent requires an item id",EXIT_CODE.USAGE);return trimmed}function compareOptionalOrder(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:leftValue-rightValue}function compareOptionalDeadline(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:compareTimestampStrings(leftValue,rightValue)}function daysInUtcMonth(year,monthIndex){return new Date(Date.UTC(year,monthIndex+1,0)).getUTCDate()}function hasNoInvalidDatePrefix(value){const match=LEADING_HYPHEN_DATE.exec(value)??LEADING_COMPACT_DATE.exec(value);if(!match)return!0;const year=Number.parseInt(match[1],10),month=Number.parseInt(match[2],10),day=Number.parseInt(match[3],10);return month>=1&&month<=12&&day>=1&&day<=daysInUtcMonth(year,month-1)}function normalizeTimestampCandidate(value){const compactDate=COMPACT_DATE.exec(value);if(compactDate)return`${compactDate[1]}-${compactDate[2]}-${compactDate[3]}`;const compactDateTime=COMPACT_DATETIME.exec(value);if(compactDateTime){const[,year,month,day,hour,minute,secondRaw,offsetRaw]=compactDateTime,second=secondRaw?`:${secondRaw}`:"",offset=offsetRaw&&offsetRaw.length===5&&offsetRaw!=="Z"?`${offsetRaw.slice(0,3)}:${offsetRaw.slice(3)}`:offsetRaw??"";return`${year}-${month}-${day}T${hour}:${minute}${second}${offset}`}return value}function parseContextTimestampMs(value){if(typeof value!="string")return Number.NaN;const trimmed=value.trim();if(trimmed.length===0||!hasNoInvalidDatePrefix(trimmed))return Number.NaN;const parsed=Date.parse(normalizeTimestampCandidate(trimmed));return Number.isFinite(parsed)?parsed:Number.NaN}function sortableTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString():""}function dateTokenForTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString().slice(0,10):"unknown"}function normalizedParentId(value){if(typeof value!="string")return null;const trimmed=value.trim();return trimmed.length>0?trimmed:null}function compareCriticalItems(left,right,statusRegistry){const byStatus=statusRank(left.status,statusRegistry)-statusRank(right.status,statusRegistry);if(byStatus!==0)return byStatus;const byPriority=left.priority-right.priority;if(byPriority!==0)return byPriority;const byOrder=compareOptionalOrder(left.order,right.order);if(byOrder!==0)return byOrder;const byDeadline=compareOptionalDeadline(left.deadline,right.deadline);if(byDeadline!==0)return byDeadline;const byUpdated=compareTimestampStrings(sortableTimestamp(right.updated_at),sortableTimestamp(left.updated_at)),byId=left.id.localeCompare(right.id);return byUpdated!==0?byUpdated:byId}function estimateJsonTokens(value){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(value),"utf8")/4))}function packRankedContextItems(report,tokenBudget,requiredIds=new Set,profile="context"){return packContextCandidates(report.ranked.map(entry=>({id:entry.id,item:entry.item,rank:entry.rank,score:entry.score,required:requiredIds.has(entry.id),cluster:entry.item.parent?.trim()||entry.item.type,token_costs:{identity:estimateJsonTokens({id:entry.id,title:entry.item.title}),summary:estimateJsonTokens({id:entry.id,title:entry.item.title,type:entry.item.type,status:entry.item.status,priority:entry.item.priority,parent:entry.item.parent}),full:estimateJsonTokens(entry.item)}})),{tokenBudget,profile,latencyBudgetMs:25})}function toContextPackingSummary(report){return{...report,included:report.included.map(entry=>({id:entry.id,projection:entry.projection,tokens:entry.tokens}))}}function toContextRankingSummary(report,featureStore,servedItemIds){const ranked=servedItemIds===void 0?report.ranked:report.ranked.filter(entry=>servedItemIds.has(entry.id));return{model:report.model,available_signals:report.available_signals,items:ranked.map(entry=>({id:entry.id,rank:entry.rank,baseline_rank:entry.baseline_rank,score:entry.score,contributions:entry.contributions,...entry.signal_provenance===void 0?{}:{recency:entry.signal_provenance.recency}})),candidate_count:report.ranked.length,omitted_count:report.ranked.length-ranked.length,...featureStore?{feature_store:{source:featureStore.snapshot.source,cache_status:featureStore.cache_status,source_cursor:featureStore.snapshot.source_cursor,generated_at:featureStore.snapshot.generated_at}}:{}}}function completionPct(closed,total){return total>0?Math.round(closed*100/total):0}function buildChildrenByParent(allItems){const childrenByParent=new Map;for(const item of allItems){const parent=normalizedParentId(item.parent);if(!parent)continue;const children=childrenByParent.get(parent)??[];children.push(item),childrenByParent.set(parent,children)}return childrenByParent}function toContextFocusItem(item,statusRegistry,childrenByParent){const focus={id:item.id,title:item.title,type:item.type,status:item.status,priority:item.priority,order:item.order??null,deadline:item.deadline??null,assignee:item.assignee??null,tags:Array.isArray(item.tags)?[...item.tags]:[],updated_at:item.updated_at,parent:normalizedParentId(item.parent)};if(statusRegistry&&childrenByParent){const descendants=collectDescendants(item.id,childrenByParent),total=descendants.length;if(total>0){const closed=descendants.filter(desc=>isClosedStatus(desc.status,statusRegistry)).length;focus.children_total=total,focus.children_closed=closed,focus.completion_pct=completionPct(closed,total)}}return focus}function summarizeAgenda(events){let deadlines=0,reminders=0,scheduled=0;const itemIds=new Set;for(const event of events){if(itemIds.add(event.item_id),event.kind==="deadline"){deadlines+=1;continue}if(event.kind==="reminder"){reminders+=1;continue}scheduled+=1}return{events:events.length,items:itemIds.size,deadlines,reminders,scheduled}}function mergeSortedWarnings(...warningGroups){return[...new Set(warningGroups.flatMap(group=>group??[]))].sort((left,right)=>left.localeCompare(right))}function filterTerminalCalendarEvents(events,statusRegistry){return events.filter(event=>!statusRegistry.terminal_statuses.has(normalizeStatusForRegistry(event.item_status,statusRegistry)))}function buildHierarchy(allItems,activeItems,statusRegistry,limit){const itemMap=new Map;for(const item of allItems)itemMap.set(item.id,item);const childrenByParent=buildChildrenByParent(allItems),activeHighLevelIds=new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)).map(item=>item.id)),nodes=[];for(const parentId of activeHighLevelIds){const parent=itemMap.get(parentId);if(!parent)continue;const allDescendants=collectDescendants(parentId,childrenByParent),childItems=childrenByParent.get(parentId)??[];let closedCount=0,openCount=0,inProgressCount=0,blockedCount=0;for(const desc of allDescendants)isClosedStatus(desc.status,statusRegistry)?closedCount++:isInProgressStatus(desc.status,statusRegistry)?inProgressCount++:isBlockedStatus(desc.status,statusRegistry)?blockedCount++:isOpenStatus(desc.status,statusRegistry)&&openCount++;const children=childItems.sort((a,b)=>compareCriticalItems(a,b,statusRegistry)).slice(0,limit).map(child=>{const grandchildren=collectDescendants(child.id,childrenByParent),gcClosed=grandchildren.filter(gc=>isClosedStatus(gc.status,statusRegistry)).length;return{id:child.id,title:child.title,type:child.type,status:child.status,children_total:grandchildren.length,children_closed:gcClosed}});nodes.push({id:parent.id,title:parent.title,type:parent.type,status:parent.status,children_total:allDescendants.length,children_closed:closedCount,children_open:openCount,children_in_progress:inProgressCount,children_blocked:blockedCount,children})}return nodes.sort((a,b)=>{const aParent=itemMap.get(a.id),bParent=itemMap.get(b.id);return compareCriticalItems(aParent,bParent,statusRegistry)}).slice(0,limit)}function collectDescendants(parentId,childrenByParent){const result=[],stack=[parentId],visited=new Set;for(;stack.length>0;){const current=stack.pop();if(visited.has(current))continue;visited.add(current);const children=childrenByParent.get(current)??[];for(const child of children)result.push(child),stack.push(child.id)}return result}const _testOnly={buildActivity,buildBlockers,buildChildrenByParent,buildHierarchy,buildHotFiles,buildProgress,buildRecentlyCreated,buildStaleness,buildTestHealth,buildUnparented,buildWorkload,collectDescendants,collectSubtreeIds,compareCriticalItems,compareOptionalDeadline,compareOptionalOrder,completionPct,dateTokenForTimestamp,filterTerminalCalendarEvents,formatAgendaLine,isBlockedStatus,isClosedStatus,isInProgressStatus,isOpenStatus,mergeSortedWarnings,normalizedParentId,parseActivityLimit,parseContextLimit,resolveContextLimitAtScale,parseContextParent,parseContextTimestampMs,parseStaleThresholdDays,sortableTimestamp,statusRank,stripListProjectionFlags,summarizeAgenda,toContextFocusItem};async function buildActivity(activityLimit,global2){return(await runActivity({compact:!0,limit:String(activityLimit)},global2)).compact_activity??[]}function buildProgress(allItems,activeItems,blockedIds,statusRegistry,limit){const childrenByParent=new Map;for(const item of allItems){if(!item.parent)continue;const children=childrenByParent.get(item.parent)??[];children.push(item),childrenByParent.set(item.parent,children)}const activeHighLevel=activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)),entries=[];for(const parent of activeHighLevel){const descendants=collectDescendants(parent.id,childrenByParent),total=descendants.length;if(total===0)continue;let closed=0,open=0,inProgress=0,blocked=0;for(const desc of descendants)isClosedStatus(desc.status,statusRegistry)?closed++:blockedIds.has(desc.id.trim().toLowerCase())?blocked++:isInProgressStatus(desc.status,statusRegistry)?inProgress++:isOpenStatus(desc.status,statusRegistry)&&open++;entries.push({id:parent.id,title:parent.title,type:parent.type,total,closed,open,in_progress:inProgress,blocked,completion_pct:completionPct(closed,total)})}return entries.sort((a,b)=>a.completion_pct-b.completion_pct).slice(0,limit)}function buildBlockers(blockedItems,fullCorpus,statusRegistry,limit){const itemsById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item]));return blockedItems.slice(0,limit).map(item=>{const blockers=resolveItemBlockers(item,itemsById,statusRegistry),blockedBy=blockers.find(blocker=>!blocker.resolved)?.id??blockers[0]?.id??null,blockerItem=blockedBy?itemsById.get(blockedBy.trim().toLowerCase()):void 0;return{id:item.id,title:item.title,blocked_by:blockedBy,blocked_by_title:blockerItem?.title??null,blocked_by_status:blockerItem?.status??null,blocked_reason:item.blocked_reason??null,unblock_note:item.unblock_note??null}})}function buildHotFiles(activeItems,limit){const fileMap=new Map;for(const item of activeItems)for(const file of item.files??[]){const existing=fileMap.get(file.path)??new Set;existing.add(item.id),fileMap.set(file.path,existing)}return[...fileMap.entries()].map(([filePath,itemIds])=>({path:filePath,references:itemIds.size,items:[...itemIds].sort()})).sort((a,b)=>b.references-a.references).slice(0,limit)}function buildWorkload(activeItems,statusRegistry,limit){const groups=new Map;for(const item of activeItems){const key=item.assignee??null,existing=groups.get(key)??[];existing.push(item),groups.set(key,existing)}return[...groups.entries()].map(([assignee,items])=>({assignee,active:items.length,in_progress:items.filter(item=>isInProgressStatus(item.status,statusRegistry)).length,items:items.map(item=>item.id).sort()})).sort((a,b)=>b.active-a.active).slice(0,limit)}function buildStaleness(allNonTerminal,staleThresholdDays,now,limit){const cutoffMs=new Date(now).getTime()-staleThresholdDays*24*60*60*1e3;return allNonTerminal.filter(item=>new Date(item.updated_at).getTime()<cutoffMs).map(item=>({id:item.id,title:item.title,status:item.status,updated_at:item.updated_at,stale_days:Math.floor((new Date(now).getTime()-new Date(item.updated_at).getTime())/(1440*60*1e3))})).sort((a,b)=>b.stale_days-a.stale_days).slice(0,limit)}function buildRecentlyCreated(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.map(item=>({item,sortKey:sortableTimestamp(item.created_at)})).sort((left,right)=>{const byCreated=compareTimestampStrings(right.sortKey,left.sortKey);return byCreated!==0?byCreated:left.item.id.localeCompare(right.item.id)}).slice(0,limit).map(({item})=>({...toContextFocusItem(item,statusRegistry,childrenByParent),created_at:item.created_at}))}function buildUnparented(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.filter(item=>!normalizedParentId(item.parent)&&!HIGH_LEVEL_TYPES.has(item.type)).sort((left,right)=>compareCriticalItems(left,right,statusRegistry)).slice(0,limit).map(item=>toContextFocusItem(item,statusRegistry,childrenByParent))}function buildTestHealth(activeItems){let itemsWithTests=0,itemsWithRecentRuns=0,passed=0,failed=0,skipped=0;const itemsFailing=[];for(const item of activeItems){(item.tests??[]).length>0&&itemsWithTests++;const runs=item.test_runs??[];if(runs.length>0){itemsWithRecentRuns++;let itemHasFailure=!1;for(const run of runs)passed+=run.passed??0,failed+=run.failed??0,skipped+=run.skipped??0,(run.failed??0)>0&&(itemHasFailure=!0);itemHasFailure&&itemsFailing.push(item.id)}}return{scope:"matching_active_items",total_items:activeItems.length,items_with_tests:itemsWithTests,items_with_recent_runs:itemsWithRecentRuns,recent_runs:{passed,failed,skipped},items_failing:itemsFailing.sort()}}function formatClock(timestamp){return`${new Date(timestamp).toISOString().slice(11,16)}Z`}function formatFocusLine(item){const orderToken=item.order===null?"-":String(item.order),deadlineToken=item.deadline??"-",parentToken=item.parent?` parent:${item.parent}`:"",progressToken=item.children_total!==void 0&&item.children_closed!==void 0&&item.completion_pct!==void 0?` children:${item.children_closed}/${item.children_total} done:${item.completion_pct}%`:"",blockedToken=item.blocked===!0?` blocked:${item.blocker_ids?.join(",")||"lifecycle"}`:"";return`${item.id} p${item.priority} ${item.status} ${item.type} order:${orderToken} deadline:${deadlineToken}${parentToken}${progressToken}${blockedToken} ${item.title}`}function formatProjectedFocusLine(item,fields){const source=item;return fields.map(field=>{const value=source[field];return Array.isArray(value)?`${field}:${value.join(",")}`:`${field}:${value??"-"}`}).join(" ")}function formatAgendaLine(event){if("reference_only"in event){const suffix=event.kind==="reminder"?` \u2014 ${event.reminder_text??"reminder"}`:event.kind==="event"?` \u2014 ${event.event_title??"event"}${event.event_recurring?" (recurring)":""}`:"";return`${formatClock(event.at)} [${event.kind}] ${event.item_id} (see focus item)${suffix}`}const base=`${formatClock(event.at)} [${event.kind}] ${event.item_id} p${event.item_priority} ${event.item_status} ${event.item_title}`;if(event.kind==="reminder")return`${base} \u2014 ${event.reminder_text}`;if(event.kind==="event"){const recurringSuffix=event.event_recurring?" (recurring)":"",title=event.event_title??event.item_title;return`${base} \u2014 ${title}${recurringSuffix}`}return base}function pushContextFocusSection(lines,title,rows,emptyText,renderFocus){if(lines.push(`## ${title}`),rows.length===0)lines.push(emptyText);else for(const item of rows)lines.push(`- ${renderFocus(item)}`);lines.push("")}function pushBlockedFallbackSection(lines,result,renderFocus){if(result.blocked_fallback.length!==0){lines.push("## Blocked fallback");for(const item of result.blocked_fallback)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushAgendaSection(lines,result){if(lines.push("## Agenda"),lines.push(`- events: ${result.agenda.summary.events} (deadlines: ${result.agenda.summary.deadlines}, reminders: ${result.agenda.summary.reminders}, scheduled: ${result.agenda.summary.scheduled})`),result.agenda.events.length===0)lines.push("No agenda events matched the selected filters.");else for(const event of result.agenda.events)lines.push(`- ${formatAgendaLine(event)}`);lines.push("")}function pushHierarchySection(lines,result){if(!(!result.hierarchy||result.hierarchy.length===0)){lines.push("## Hierarchy");for(const node of result.hierarchy){const pct=completionPct(node.children_closed,node.children_total);lines.push(`- ${node.id} ${node.type} ${node.status} "${node.title}" [${node.children_closed}/${node.children_total} done ${pct}%]`);for(const child of node.children){const cpct=completionPct(child.children_closed,child.children_total);lines.push(` - ${child.id} ${child.type} ${child.status} "${child.title}" [${child.children_closed}/${child.children_total} done ${cpct}%]`)}}lines.push("")}}function pushProgressSection(lines,result){if(!(!result.progress||result.progress.length===0)){lines.push("## Progress");for(const entry of result.progress)lines.push(`- ${entry.id} "${entry.title}" ${entry.completion_pct}% (${entry.closed}/${entry.total} closed, ${entry.in_progress} wip, ${entry.open} open, ${entry.blocked} blocked)`);lines.push("")}}function pushRecentlyCreatedSection(lines,result,focusFields,renderFocus){if(!(!result.recently_created||result.recently_created.length===0)){lines.push("## Recently created");for(const item of result.recently_created)lines.push(focusFields?`- ${renderFocus(item)}`:`- ${dateTokenForTimestamp(item.created_at)} ${formatFocusLine(item)}`);lines.push("")}}function pushUnparentedSection(lines,result,renderFocus){if(!(!result.unparented||result.unparented.length===0)){lines.push("## Unparented");for(const item of result.unparented)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushActivitySection(lines,result){if(!(!result.activity||result.activity.length===0)){lines.push("## Recent activity");for(const entry of result.activity){const msg=entry.msg?` ${entry.msg}`:"";lines.push(`- ${entry.ts.slice(0,16)}Z ${entry.id} ${entry.op} by:${entry.author}${msg}`)}lines.push("")}}function pushBlockersSection(lines,result){if(!(!result.blockers||result.blockers.length===0)){lines.push("## Blockers");for(const entry of result.blockers){const by=entry.blocked_by?`blocked_by:${entry.blocked_by}(${entry.blocked_by_status??"?"})`:"blocked_by:-",reason=entry.blocked_reason?` reason:"${entry.blocked_reason}"`:"",note=entry.unblock_note?` unblock:"${entry.unblock_note}"`:"";lines.push(`- ${entry.id} "${entry.title}" ${by}${reason}${note}`)}lines.push("")}}function pushFilesSection(lines,result){if(!(!result.files||result.files.length===0)){lines.push("## Hot files");for(const file of result.files)lines.push(`- ${file.path} refs:${file.references} items:[${file.items.join(",")}]`);lines.push("")}}function pushWorkloadSection(lines,result){if(!(!result.workload||result.workload.length===0)){lines.push("## Workload");for(const entry of result.workload){const who=entry.assignee??"(unassigned)";lines.push(`- ${who} active:${entry.active} wip:${entry.in_progress} items:[${entry.items.join(",")}]`)}lines.push("")}}function pushStalenessSection(lines,result){if(!(!result.staleness||result.staleness.length===0)){lines.push("## Stale items");for(const entry of result.staleness)lines.push(`- ${entry.id} ${entry.status} stale:${entry.stale_days}d last:${entry.updated_at.slice(0,10)} "${entry.title}"`);lines.push("")}}function boundedTestHealthFailures(tests,limit,tokenBudget){const included=[];let usedTokens=0;for(const id of tests.items_failing){if(included.length>=limit)break;const tokens=estimateJsonTokens(id);if(usedTokens+tokens>tokenBudget)break;included.push(id),usedTokens+=tokens}return included}function pushTestHealthSection(lines,result){if(!result.tests)return;lines.push("## Test health"),lines.push(`- ${result.tests.scope}: ${result.tests.total_items}`),lines.push(`- items_with_tests: ${result.tests.items_with_tests}`),lines.push(`- items_with_recent_runs: ${result.tests.items_with_recent_runs}`),lines.push(`- passed: ${result.tests.recent_runs.passed}, failed: ${result.tests.recent_runs.failed}, skipped: ${result.tests.recent_runs.skipped}`);const failures=boundedTestHealthFailures(result.tests,result.applied_limit??DEFAULT_CONTEXT_LIMIT,result.filters.token_budget);failures.length>0&&lines.push(`- items_failing: [${failures.join(",")}]`);const omitted=result.tests.items_failing.length-failures.length;omitted>0&&lines.push(`- items_failing_omitted: ${omitted}`),lines.push("")}function pushEmptyContextSuggestions(lines,result){result.summary.active_items===0&&result.summary.blocked===0&&result.agenda.summary.events===0&&(lines.push("## Suggestions"),lines.push("No active work items or upcoming events. Consider:"),lines.push('- `pm create --type Task --title "..."` to add a new work item'),lines.push("- `pm list --status closed --limit 5` to review recent completions"),lines.push("- `pm search <keywords>` to find related past work"),lines.push("- `pm aggregate` for a full project status overview"))}function renderContextMarkdown(result){const lines=[],focusFields=result.focus_fields,renderFocus=item=>focusFields?formatProjectedFocusLine(item,focusFields):formatFocusLine(item);if(lines.push("# pm context"),lines.push(""),lines.push(`- now: ${result.now}`),lines.push(`- depth: ${result.depth}`),result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(`- active_items: ${result.summary.active_items} (in_progress: ${result.summary.in_progress}, open: ${result.summary.open})`),result.summary.total_items!==void 0&&lines.push(`- total_items: ${result.summary.total_items} (closed: ${result.summary.closed??0}, canceled: ${result.summary.canceled??0})`),lines.push(`- agenda_events: ${result.summary.agenda_events}`),lines.push(`- blocked_fallback_used: ${result.summary.blocked_fallback_used}`),result.extension_health){const degradedNames=result.extension_health.packages.filter(entry=>entry.status==="degraded").map(entry=>entry.name);lines.push(`- extensions: ${result.extension_health.ok} ok, ${result.extension_health.degraded} degraded${degradedNames.length>0?` (${degradedNames.join(", ")})`:""}`)}const renderedSections=result.sections_included.filter(section=>section!=="blockers"||(result.blockers?.length??0)>0);if(renderedSections.length>0&&lines.push(`- sections: ${renderedSections.join(", ")}`),lines.push(""),pushContextFocusSection(lines,"High-level focus",result.high_level,"No high-level active items.",renderFocus),pushContextFocusSection(lines,"Low-level focus",result.low_level,"No low-level active items.",renderFocus),pushBlockedFallbackSection(lines,result,renderFocus),pushAgendaSection(lines,result),result.workspace_memory){lines.push("## Workspace memory");for(const rollup of result.workspace_memory.rollups)lines.push(`- ${rollup.kind}:${rollup.key} \u2014 ${rollup.label} (${rollup.item_count} completed, latest ${rollup.last_closed_at})`);lines.push("")}return pushHierarchySection(lines,result),pushProgressSection(lines,result),pushRecentlyCreatedSection(lines,result,focusFields,renderFocus),pushUnparentedSection(lines,result,renderFocus),pushActivitySection(lines,result),pushBlockersSection(lines,result),pushFilesSection(lines,result),pushWorkloadSection(lines,result),pushStalenessSection(lines,result),pushTestHealthSection(lines,result),pushEmptyContextSuggestions(lines,result),lines.join(`
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e25fa213-1da3-576c-a2a5-2828a70d262d")}catch{}})();import{SETTINGS_DEFAULTS,EXIT_CODE,PmCliError,compareTimestampStrings,nowIso,isTerminalStatus,normalizeStatusForRegistry,normalizeStatusInput,resolveRuntimeStatusRegistry,resolvePmRoot,readSettings,resolveAuthor,discoverExtensions,resolveItemTypeRegistry}from"../runtime-primitives.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{collectDependencyBlockedIds,resolveItemBlockers,resolveItemExecutionRole,computeActionabilityReport}from"../actionability.js";import{CONTEXT_DEPTH_VALUES,CONTEXT_SECTION_VALUES}from"../../types/index.js";import{parseIntegerLimit}from"./parsers.js";import{runCalendar}from"./calendar.js";import{runList}from"./list.js";import{runActivity}from"./activity.js";import{scoreContextCandidatesWithActiveExtensions}from"../context-relevance.js";import{buildItemContextRelevanceCandidates}from"../context-relevance.js";import{createQueryFingerprint,encodeQueryCursor,resolveQueryCursorStart,selectCursorSemanticOptions}from"../pagination.js";import{rememberReadOutputFocusRows,refreshReadOutputDeliveredCounts}from"../read-output-rows.js";import{CONTEXT_FLAG_CONTRACTS}from"../cli-contracts/flag-contracts.js";import{packContextCandidates}from"../context-packing.js";import{attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,readContextUsageAffinity,recordContextUsageServing}from"../context-usage.js";import{readWorkspaceContextSignals}from"../context-signal-store.js";import{readWorkspaceMemory,selectWorkspaceMemory}from"../workspace-memory.js";import{detectAgentIdentity}from"../../core/shared/author.js";import{readSessionState,semanticAttributionKey}from"../../core/session/session-state.js";import{semanticAttributionAffinity}from"../context/semantic-session-attribution.js";const CONTEXT_OUTPUT_VALUES=["markdown","toon","json","ndjson"],HIGH_LEVEL_TYPES=new Set(["Epic","Feature"]),DEFAULT_CONTEXT_LIMIT=10,CONTEXT_SCALE_THRESHOLD=1e4,STANDARD_SECTIONS=["hierarchy","activity","progress","recently_created","unparented","workload"],DEEP_SECTIONS=[...STANDARD_SECTIONS,"blockers","files","staleness","tests"],LEADING_HYPHEN_DATE=/^(\d{4})-(\d{2})-(\d{2})/,LEADING_COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})$/,COMPACT_DATETIME=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function parseOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!CONTEXT_OUTPUT_VALUES.includes(normalized))throw new PmCliError("Context format must be one of markdown|toon|json|ndjson",EXIT_CODE.USAGE);return normalized}const FOCUS_PROJECTION_FIELDS=new Set(["id","title","type","status","priority","order","deadline","assignee","tags","tags_inherited","updated_at","parent","children_total","children_closed","completion_pct","blocked","blocker_ids","created_at"]);function parseContextFocusFields(raw){if(raw===void 0)return;const fields=[];for(const token of raw.split(",")){const normalized=token.trim().toLowerCase();if(normalized.length!==0){if(!FOCUS_PROJECTION_FIELDS.has(normalized))throw new PmCliError(`Context --fields value not projectable: ${normalized} (valid: ${[...FOCUS_PROJECTION_FIELDS].join(", ")})`,EXIT_CODE.USAGE);fields.includes(normalized)||fields.push(normalized)}}if(fields.length===0)throw new PmCliError("Context --fields requires at least one field name",EXIT_CODE.USAGE);return fields}function projectContextFocusRows(rows,fields){return rows.map(row=>{const projected={},source=row;for(const field of fields)projected[field]=source[field]??null;return projected})}function resolveContextOutputFormat(options,global2){const commandFormat=parseOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json"&&commandFormat!=="ndjson")throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE);return global2.json?commandFormat==="ndjson"?"ndjson":"json":commandFormat??"toon"}function parseContextLimit(raw,depth){return parseIntegerLimit(raw,"--limit")??(depth==="full"?Number.MAX_SAFE_INTEGER:DEFAULT_CONTEXT_LIMIT)}function resolveContextTokenBudget(raw,fallback){if(raw===void 0)return fallback;const parsed=typeof raw=="number"?raw:Number(raw);if(!Number.isInteger(parsed)||parsed<1)throw new PmCliError("--token-budget must be a positive integer",EXIT_CODE.USAGE);return parsed}function resolveContextLimitAtScale(limit,itemCount){return itemCount>=CONTEXT_SCALE_THRESHOLD&&limit===Number.MAX_SAFE_INTEGER?DEFAULT_CONTEXT_LIMIT:limit}function parseContextDepth(raw,settings){if(!raw)return settings.default_depth;const normalized=raw.trim().toLowerCase();if(!CONTEXT_DEPTH_VALUES.includes(normalized))throw new PmCliError(`Context --depth must be one of ${CONTEXT_DEPTH_VALUES.join("|")}`,EXIT_CODE.USAGE);return normalized}function parseContextSections(raw,depth,settings){if(raw&&raw.length>0){const sections=[];for(const value of raw){const normalized=value.trim().toLowerCase();if(!CONTEXT_SECTION_VALUES.includes(normalized))throw new PmCliError(`Context --section must be one of ${CONTEXT_SECTION_VALUES.join("|")}`,EXIT_CODE.USAGE);sections.includes(normalized)||sections.push(normalized)}return sections}return depth==="brief"?[]:depth==="full"?[...CONTEXT_SECTION_VALUES]:(depth==="deep"?DEEP_SECTIONS:STANDARD_SECTIONS).filter(section=>settings.sections[section])}function parseActivityLimit(raw,settings){return raw?parseIntegerLimit(raw,"--activity-limit")??settings.activity_limit:settings.activity_limit}function parseStaleThresholdDays(raw,settings){if(!raw)return settings.stale_threshold_days;const trimmed=raw.trim().toLowerCase(),match=/^(\d+)d?$/.exec(trimmed);if(!match)throw new PmCliError("--stale-threshold must be a number of days (e.g. 7 or 7d)",EXIT_CODE.USAGE);const days=parseInt(match[1],10);if(days<=0)throw new PmCliError("--stale-threshold must be positive",EXIT_CODE.USAGE);return days}function statusRank(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry),blockedStatus=normalizeStatusInput("blocked",statusRegistry),draftStatus=normalizeStatusInput("draft",statusRegistry);return normalizedStatus===statusRegistry.in_progress_status?0:statusRegistry.active_statuses.has(normalizedStatus)?1:blockedStatus&&normalizedStatus===blockedStatus?2:draftStatus&&normalizedStatus===draftStatus?3:statusRegistry.blocked_statuses.has(normalizedStatus)?5:statusRegistry.terminal_statuses.has(normalizedStatus)?7:6}function isClosedStatus(status,statusRegistry){const closeStatus=normalizeStatusInput("closed",statusRegistry);return normalizeStatusForRegistry(status,statusRegistry)===closeStatus}function isInProgressStatus(status,statusRegistry){return normalizeStatusForRegistry(status,statusRegistry)===statusRegistry.in_progress_status}function isOpenStatus(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry);return normalizedStatus!==statusRegistry.in_progress_status&&statusRegistry.active_statuses.has(normalizedStatus)}function isBlockedStatus(status,statusRegistry){return statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(status,statusRegistry))}const LIST_PROJECTION_FLAGS=["compact","brief","fields","includeBody","include_body","parent"];function stripListProjectionFlags(options){const copy={...options};for(const key of LIST_PROJECTION_FLAGS)delete copy[key];return copy}function collectSubtreeIds(corpus,parentId){const target=parentId.trim().toLowerCase(),anchor=corpus.find(item=>item.id.trim().toLowerCase()===target);if(!anchor)return{ids:new Set,found:!1};const childrenByParent=buildChildrenByParent(corpus),descendants=collectDescendants(anchor.id,childrenByParent);return{ids:new Set([anchor.id,...descendants.map(item=>item.id)].map(id=>id.trim().toLowerCase())),found:!0}}function parseContextParent(raw){if(raw===void 0)return;const trimmed=raw.trim();if(trimmed.length===0)throw new PmCliError("Context --parent requires an item id",EXIT_CODE.USAGE);return trimmed}function compareOptionalOrder(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:leftValue-rightValue}function compareOptionalDeadline(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:compareTimestampStrings(leftValue,rightValue)}function daysInUtcMonth(year,monthIndex){return new Date(Date.UTC(year,monthIndex+1,0)).getUTCDate()}function hasNoInvalidDatePrefix(value){const match=LEADING_HYPHEN_DATE.exec(value)??LEADING_COMPACT_DATE.exec(value);if(!match)return!0;const year=Number.parseInt(match[1],10),month=Number.parseInt(match[2],10),day=Number.parseInt(match[3],10);return month>=1&&month<=12&&day>=1&&day<=daysInUtcMonth(year,month-1)}function normalizeTimestampCandidate(value){const compactDate=COMPACT_DATE.exec(value);if(compactDate)return`${compactDate[1]}-${compactDate[2]}-${compactDate[3]}`;const compactDateTime=COMPACT_DATETIME.exec(value);if(compactDateTime){const[,year,month,day,hour,minute,secondRaw,offsetRaw]=compactDateTime,second=secondRaw?`:${secondRaw}`:"",offset=offsetRaw&&offsetRaw.length===5&&offsetRaw!=="Z"?`${offsetRaw.slice(0,3)}:${offsetRaw.slice(3)}`:offsetRaw??"";return`${year}-${month}-${day}T${hour}:${minute}${second}${offset}`}return value}function parseContextTimestampMs(value){if(typeof value!="string")return Number.NaN;const trimmed=value.trim();if(trimmed.length===0||!hasNoInvalidDatePrefix(trimmed))return Number.NaN;const parsed=Date.parse(normalizeTimestampCandidate(trimmed));return Number.isFinite(parsed)?parsed:Number.NaN}function sortableTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString():""}function dateTokenForTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString().slice(0,10):"unknown"}function normalizedParentId(value){if(typeof value!="string")return null;const trimmed=value.trim();return trimmed.length>0?trimmed:null}function compareCriticalItems(left,right,statusRegistry){const byStatus=statusRank(left.status,statusRegistry)-statusRank(right.status,statusRegistry);if(byStatus!==0)return byStatus;const byPriority=left.priority-right.priority;if(byPriority!==0)return byPriority;const byOrder=compareOptionalOrder(left.order,right.order);if(byOrder!==0)return byOrder;const byDeadline=compareOptionalDeadline(left.deadline,right.deadline);if(byDeadline!==0)return byDeadline;const byUpdated=compareTimestampStrings(sortableTimestamp(right.updated_at),sortableTimestamp(left.updated_at)),byId=left.id.localeCompare(right.id);return byUpdated!==0?byUpdated:byId}function estimateJsonTokens(value){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(value),"utf8")/4))}function packRankedContextItems(report,tokenBudget,requiredIds=new Set,profile="context"){return packContextCandidates(report.ranked.map(entry=>({id:entry.id,item:entry.item,rank:entry.rank,score:entry.score,required:requiredIds.has(entry.id),cluster:entry.item.parent?.trim()||entry.item.type,token_costs:{identity:estimateJsonTokens({id:entry.id,title:entry.item.title}),summary:estimateJsonTokens({id:entry.id,title:entry.item.title,type:entry.item.type,status:entry.item.status,priority:entry.item.priority,parent:entry.item.parent}),full:estimateJsonTokens(entry.item)}})),{tokenBudget,profile,latencyBudgetMs:25})}function toContextPackingSummary(report){return{...report,included:report.included.map(entry=>({id:entry.id,projection:entry.projection,tokens:entry.tokens}))}}function toContextRankingSummary(report,featureStore,servedItemIds){const ranked=servedItemIds===void 0?report.ranked:report.ranked.filter(entry=>servedItemIds.has(entry.id));return{model:report.model,available_signals:report.available_signals,items:ranked.map(entry=>({id:entry.id,rank:entry.rank,baseline_rank:entry.baseline_rank,score:entry.score,contributions:entry.contributions,...entry.signal_provenance===void 0?{}:{recency:entry.signal_provenance.recency}})),candidate_count:report.ranked.length,omitted_count:report.ranked.length-ranked.length,...featureStore?{feature_store:{source:featureStore.snapshot.source,cache_status:featureStore.cache_status,source_cursor:featureStore.snapshot.source_cursor,generated_at:featureStore.snapshot.generated_at}}:{}}}function completionPct(closed,total){return total>0?Math.round(closed*100/total):0}function buildChildrenByParent(allItems){const childrenByParent=new Map;for(const item of allItems){const parent=normalizedParentId(item.parent);if(!parent)continue;const children=childrenByParent.get(parent)??[];children.push(item),childrenByParent.set(parent,children)}return childrenByParent}function toContextFocusItem(item,statusRegistry,childrenByParent){const focus={id:item.id,title:item.title,type:item.type,status:item.status,priority:item.priority,order:item.order??null,deadline:item.deadline??null,assignee:item.assignee??null,tags:Array.isArray(item.tags)?[...item.tags]:[],updated_at:item.updated_at,parent:normalizedParentId(item.parent)};if(statusRegistry&&childrenByParent){const descendants=collectDescendants(item.id,childrenByParent),total=descendants.length;if(total>0){const closed=descendants.filter(desc=>isClosedStatus(desc.status,statusRegistry)).length;focus.children_total=total,focus.children_closed=closed,focus.completion_pct=completionPct(closed,total)}}return focus}function summarizeAgenda(events){let deadlines=0,reminders=0,scheduled=0;const itemIds=new Set;for(const event of events){if(itemIds.add(event.item_id),event.kind==="deadline"){deadlines+=1;continue}if(event.kind==="reminder"){reminders+=1;continue}scheduled+=1}return{events:events.length,items:itemIds.size,deadlines,reminders,scheduled}}function mergeSortedWarnings(...warningGroups){return[...new Set(warningGroups.flatMap(group=>group??[]))].sort((left,right)=>left.localeCompare(right))}function filterTerminalCalendarEvents(events,statusRegistry){return events.filter(event=>!statusRegistry.terminal_statuses.has(normalizeStatusForRegistry(event.item_status,statusRegistry)))}function buildHierarchy(allItems,activeItems,statusRegistry,limit){const itemMap=new Map;for(const item of allItems)itemMap.set(item.id,item);const childrenByParent=buildChildrenByParent(allItems),activeHighLevelIds=new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)).map(item=>item.id)),nodes=[];for(const parentId of activeHighLevelIds){const parent=itemMap.get(parentId);if(!parent)continue;const allDescendants=collectDescendants(parentId,childrenByParent),childItems=childrenByParent.get(parentId)??[];let closedCount=0,openCount=0,inProgressCount=0,blockedCount=0;for(const desc of allDescendants)isClosedStatus(desc.status,statusRegistry)?closedCount++:isInProgressStatus(desc.status,statusRegistry)?inProgressCount++:isBlockedStatus(desc.status,statusRegistry)?blockedCount++:isOpenStatus(desc.status,statusRegistry)&&openCount++;const children=childItems.sort((a,b)=>compareCriticalItems(a,b,statusRegistry)).slice(0,limit).map(child=>{const grandchildren=collectDescendants(child.id,childrenByParent),gcClosed=grandchildren.filter(gc=>isClosedStatus(gc.status,statusRegistry)).length;return{id:child.id,title:child.title,type:child.type,status:child.status,children_total:grandchildren.length,children_closed:gcClosed}});nodes.push({id:parent.id,title:parent.title,type:parent.type,status:parent.status,children_total:allDescendants.length,children_closed:closedCount,children_open:openCount,children_in_progress:inProgressCount,children_blocked:blockedCount,children})}return nodes.sort((a,b)=>{const aParent=itemMap.get(a.id),bParent=itemMap.get(b.id);return compareCriticalItems(aParent,bParent,statusRegistry)}).slice(0,limit)}function collectDescendants(parentId,childrenByParent){const result=[],stack=[parentId],visited=new Set;for(;stack.length>0;){const current=stack.pop();if(visited.has(current))continue;visited.add(current);const children=childrenByParent.get(current)??[];for(const child of children)result.push(child),stack.push(child.id)}return result}const _testOnly={buildActivity,buildBlockers,buildChildrenByParent,buildHierarchy,buildHotFiles,buildProgress,buildRecentlyCreated,buildStaleness,buildTestHealth,buildUnparented,buildWorkload,collectDescendants,collectSubtreeIds,compareCriticalItems,compareOptionalDeadline,compareOptionalOrder,completionPct,dateTokenForTimestamp,filterTerminalCalendarEvents,formatAgendaLine,isBlockedStatus,isClosedStatus,isInProgressStatus,isOpenStatus,mergeSortedWarnings,normalizedParentId,parseActivityLimit,parseContextLimit,resolveContextLimitAtScale,parseContextParent,parseContextTimestampMs,parseStaleThresholdDays,sortableTimestamp,statusRank,stripListProjectionFlags,summarizeAgenda,toContextFocusItem};async function buildActivity(activityLimit,global2){return(await runActivity({compact:!0,limit:String(activityLimit)},global2)).compact_activity??[]}function buildProgress(allItems,activeItems,blockedIds,statusRegistry,limit){const childrenByParent=new Map;for(const item of allItems){if(!item.parent)continue;const children=childrenByParent.get(item.parent)??[];children.push(item),childrenByParent.set(item.parent,children)}const activeHighLevel=activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)),entries=[];for(const parent of activeHighLevel){const descendants=collectDescendants(parent.id,childrenByParent),total=descendants.length;if(total===0)continue;let closed=0,open=0,inProgress=0,blocked=0;for(const desc of descendants)isClosedStatus(desc.status,statusRegistry)?closed++:blockedIds.has(desc.id.trim().toLowerCase())?blocked++:isInProgressStatus(desc.status,statusRegistry)?inProgress++:isOpenStatus(desc.status,statusRegistry)&&open++;entries.push({id:parent.id,title:parent.title,type:parent.type,total,closed,open,in_progress:inProgress,blocked,completion_pct:completionPct(closed,total)})}return entries.sort((a,b)=>a.completion_pct-b.completion_pct).slice(0,limit)}function buildBlockers(blockedItems,fullCorpus,statusRegistry,limit){const itemsById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item]));return blockedItems.slice(0,limit).map(item=>{const blockers=resolveItemBlockers(item,itemsById,statusRegistry),blockedBy=blockers.find(blocker=>!blocker.resolved)?.id??blockers[0]?.id??null,blockerItem=blockedBy?itemsById.get(blockedBy.trim().toLowerCase()):void 0;return{id:item.id,title:item.title,blocked_by:blockedBy,blocked_by_title:blockerItem?.title??null,blocked_by_status:blockerItem?.status??null,blocked_reason:item.blocked_reason??null,unblock_note:item.unblock_note??null}})}function buildHotFiles(activeItems,limit){const fileMap=new Map;for(const item of activeItems)for(const file of item.files??[]){const existing=fileMap.get(file.path)??new Set;existing.add(item.id),fileMap.set(file.path,existing)}return[...fileMap.entries()].map(([filePath,itemIds])=>({path:filePath,references:itemIds.size,items:[...itemIds].sort()})).sort((a,b)=>b.references-a.references).slice(0,limit)}function buildWorkload(activeItems,statusRegistry,limit){const groups=new Map;for(const item of activeItems){const key=item.assignee??null,existing=groups.get(key)??[];existing.push(item),groups.set(key,existing)}return[...groups.entries()].map(([assignee,items])=>({assignee,active:items.length,in_progress:items.filter(item=>isInProgressStatus(item.status,statusRegistry)).length,items:items.map(item=>item.id).sort()})).sort((a,b)=>b.active-a.active).slice(0,limit)}function buildStaleness(allNonTerminal,staleThresholdDays,now,limit){const cutoffMs=new Date(now).getTime()-staleThresholdDays*24*60*60*1e3;return allNonTerminal.filter(item=>new Date(item.updated_at).getTime()<cutoffMs).map(item=>({id:item.id,title:item.title,status:item.status,updated_at:item.updated_at,stale_days:Math.floor((new Date(now).getTime()-new Date(item.updated_at).getTime())/(1440*60*1e3))})).sort((a,b)=>b.stale_days-a.stale_days).slice(0,limit)}function buildRecentlyCreated(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.map(item=>({item,sortKey:sortableTimestamp(item.created_at)})).sort((left,right)=>{const byCreated=compareTimestampStrings(right.sortKey,left.sortKey);return byCreated!==0?byCreated:left.item.id.localeCompare(right.item.id)}).slice(0,limit).map(({item})=>({...toContextFocusItem(item,statusRegistry,childrenByParent),created_at:item.created_at}))}function buildUnparented(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.filter(item=>!normalizedParentId(item.parent)&&!HIGH_LEVEL_TYPES.has(item.type)).sort((left,right)=>compareCriticalItems(left,right,statusRegistry)).slice(0,limit).map(item=>toContextFocusItem(item,statusRegistry,childrenByParent))}function buildTestHealth(activeItems){let itemsWithTests=0,itemsWithRecentRuns=0,passed=0,failed=0,skipped=0;const itemsFailing=[];for(const item of activeItems){(item.tests??[]).length>0&&itemsWithTests++;const runs=item.test_runs??[];if(runs.length>0){itemsWithRecentRuns++;let itemHasFailure=!1;for(const run of runs)passed+=run.passed??0,failed+=run.failed??0,skipped+=run.skipped??0,(run.failed??0)>0&&(itemHasFailure=!0);itemHasFailure&&itemsFailing.push(item.id)}}return{scope:"matching_active_items",total_items:activeItems.length,items_with_tests:itemsWithTests,items_with_recent_runs:itemsWithRecentRuns,recent_runs:{passed,failed,skipped},items_failing:itemsFailing.sort()}}function formatClock(timestamp){return`${new Date(timestamp).toISOString().slice(11,16)}Z`}function formatFocusLine(item){const orderToken=item.order===null?"-":String(item.order),deadlineToken=item.deadline??"-",parentToken=item.parent?` parent:${item.parent}`:"",progressToken=item.children_total!==void 0&&item.children_closed!==void 0&&item.completion_pct!==void 0?` children:${item.children_closed}/${item.children_total} done:${item.completion_pct}%`:"",blockedToken=item.blocked===!0?` blocked:${item.blocker_ids?.join(",")||"lifecycle"}`:"";return`${item.id} p${item.priority} ${item.status} ${item.type} order:${orderToken} deadline:${deadlineToken}${parentToken}${progressToken}${blockedToken} ${item.title}`}function formatProjectedFocusLine(item,fields){const source=item;return fields.map(field=>{const value=source[field];return Array.isArray(value)?`${field}:${value.join(",")}`:`${field}:${value??"-"}`}).join(" ")}function formatAgendaLine(event){if("reference_only"in event){const suffix=event.kind==="reminder"?` \u2014 ${event.reminder_text??"reminder"}`:event.kind==="event"?` \u2014 ${event.event_title??"event"}${event.event_recurring?" (recurring)":""}`:"";return`${formatClock(event.at)} [${event.kind}] ${event.item_id} (see focus item)${suffix}`}const base=`${formatClock(event.at)} [${event.kind}] ${event.item_id} p${event.item_priority} ${event.item_status} ${event.item_title}`;if(event.kind==="reminder")return`${base} \u2014 ${event.reminder_text}`;if(event.kind==="event"){const recurringSuffix=event.event_recurring?" (recurring)":"",title=event.event_title??event.item_title;return`${base} \u2014 ${title}${recurringSuffix}`}return base}function pushContextFocusSection(lines,title,rows,emptyText,renderFocus){if(lines.push(`## ${title}`),rows.length===0)lines.push(emptyText);else for(const item of rows)lines.push(`- ${renderFocus(item)}`);lines.push("")}function pushBlockedFallbackSection(lines,result,renderFocus){if(result.blocked_fallback.length!==0){lines.push("## Blocked fallback");for(const item of result.blocked_fallback)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushAgendaSection(lines,result){if(lines.push("## Agenda"),lines.push(`- events: ${result.agenda.summary.events} (deadlines: ${result.agenda.summary.deadlines}, reminders: ${result.agenda.summary.reminders}, scheduled: ${result.agenda.summary.scheduled})`),result.agenda.events.length===0)lines.push("No agenda events matched the selected filters.");else for(const event of result.agenda.events)lines.push(`- ${formatAgendaLine(event)}`);lines.push("")}function pushHierarchySection(lines,result){if(!(!result.hierarchy||result.hierarchy.length===0)){lines.push("## Hierarchy");for(const node of result.hierarchy){const pct=completionPct(node.children_closed,node.children_total);lines.push(`- ${node.id} ${node.type} ${node.status} "${node.title}" [${node.children_closed}/${node.children_total} done ${pct}%]`);for(const child of node.children){const cpct=completionPct(child.children_closed,child.children_total);lines.push(` - ${child.id} ${child.type} ${child.status} "${child.title}" [${child.children_closed}/${child.children_total} done ${cpct}%]`)}}lines.push("")}}function pushProgressSection(lines,result){if(!(!result.progress||result.progress.length===0)){lines.push("## Progress");for(const entry of result.progress)lines.push(`- ${entry.id} "${entry.title}" ${entry.completion_pct}% (${entry.closed}/${entry.total} closed, ${entry.in_progress} wip, ${entry.open} open, ${entry.blocked} blocked)`);lines.push("")}}function pushRecentlyCreatedSection(lines,result,focusFields,renderFocus){if(!(!result.recently_created||result.recently_created.length===0)){lines.push("## Recently created");for(const item of result.recently_created)lines.push(focusFields?`- ${renderFocus(item)}`:`- ${dateTokenForTimestamp(item.created_at)} ${formatFocusLine(item)}`);lines.push("")}}function pushUnparentedSection(lines,result,renderFocus){if(!(!result.unparented||result.unparented.length===0)){lines.push("## Unparented");for(const item of result.unparented)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushActivitySection(lines,result){if(!(!result.activity||result.activity.length===0)){lines.push("## Recent activity");for(const entry of result.activity){const msg=entry.msg?` ${entry.msg}`:"";lines.push(`- ${entry.ts.slice(0,16)}Z ${entry.id} ${entry.op} by:${entry.author}${msg}`)}lines.push("")}}function pushBlockersSection(lines,result){if(!(!result.blockers||result.blockers.length===0)){lines.push("## Blockers");for(const entry of result.blockers){const by=entry.blocked_by?`blocked_by:${entry.blocked_by}(${entry.blocked_by_status??"?"})`:"blocked_by:-",reason=entry.blocked_reason?` reason:"${entry.blocked_reason}"`:"",note=entry.unblock_note?` unblock:"${entry.unblock_note}"`:"";lines.push(`- ${entry.id} "${entry.title}" ${by}${reason}${note}`)}lines.push("")}}function pushFilesSection(lines,result){if(!(!result.files||result.files.length===0)){lines.push("## Hot files");for(const file of result.files)lines.push(`- ${file.path} refs:${file.references} items:[${file.items.join(",")}]`);lines.push("")}}function pushWorkloadSection(lines,result){if(!(!result.workload||result.workload.length===0)){lines.push("## Workload");for(const entry of result.workload){const who=entry.assignee??"(unassigned)";lines.push(`- ${who} active:${entry.active} wip:${entry.in_progress} items:[${entry.items.join(",")}]`)}lines.push("")}}function pushStalenessSection(lines,result){if(!(!result.staleness||result.staleness.length===0)){lines.push("## Stale items");for(const entry of result.staleness)lines.push(`- ${entry.id} ${entry.status} stale:${entry.stale_days}d last:${entry.updated_at.slice(0,10)} "${entry.title}"`);lines.push("")}}function boundedTestHealthFailures(tests,limit,tokenBudget){const included=[];let usedTokens=0;for(const id of tests.items_failing){if(included.length>=limit)break;const tokens=estimateJsonTokens(id);if(usedTokens+tokens>tokenBudget)break;included.push(id),usedTokens+=tokens}return included}function pushTestHealthSection(lines,result){if(!result.tests)return;lines.push("## Test health"),lines.push(`- ${result.tests.scope}: ${result.tests.total_items}`),lines.push(`- items_with_tests: ${result.tests.items_with_tests}`),lines.push(`- items_with_recent_runs: ${result.tests.items_with_recent_runs}`),lines.push(`- passed: ${result.tests.recent_runs.passed}, failed: ${result.tests.recent_runs.failed}, skipped: ${result.tests.recent_runs.skipped}`);const failures=boundedTestHealthFailures(result.tests,result.applied_limit??DEFAULT_CONTEXT_LIMIT,result.filters.token_budget);failures.length>0&&lines.push(`- items_failing: [${failures.join(",")}]`);const omitted=result.tests.items_failing.length-failures.length;omitted>0&&lines.push(`- items_failing_omitted: ${omitted}`),lines.push("")}function pushEmptyContextSuggestions(lines,result){result.summary.active_items===0&&result.summary.blocked===0&&result.agenda.summary.events===0&&(lines.push("## Suggestions"),lines.push("No active work items or upcoming events. Consider:"),lines.push('- `pm create --type Task --title "..."` to add a new work item'),lines.push("- `pm list --status closed --limit 5` to review recent completions"),lines.push("- `pm search <keywords>` to find related past work"),lines.push("- `pm aggregate` for a full project status overview"))}function renderContextMarkdown(result){const lines=[],focusFields=result.focus_fields,renderFocus=item=>focusFields?formatProjectedFocusLine(item,focusFields):formatFocusLine(item);if(lines.push("# pm context"),lines.push(""),lines.push(`- now: ${result.now}`),lines.push(`- depth: ${result.depth}`),result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(`- active_items: ${result.summary.active_items} (in_progress: ${result.summary.in_progress}, open: ${result.summary.open})`),result.summary.total_items!==void 0&&lines.push(`- total_items: ${result.summary.total_items} (closed: ${result.summary.closed??0}, canceled: ${result.summary.canceled??0})`),lines.push(`- agenda_events: ${result.summary.agenda_events}`),lines.push(`- blocked_fallback_used: ${result.summary.blocked_fallback_used}`),result.extension_health){const degradedNames=result.extension_health.packages.filter(entry=>entry.status==="degraded").map(entry=>entry.name);lines.push(`- extensions: ${result.extension_health.ok} ok, ${result.extension_health.degraded} degraded${degradedNames.length>0?` (${degradedNames.join(", ")})`:""}`)}const renderedSections=result.sections_included.filter(section=>section!=="blockers"||(result.blockers?.length??0)>0);if(renderedSections.length>0&&lines.push(`- sections: ${renderedSections.join(", ")}`),lines.push(""),pushContextFocusSection(lines,"High-level focus",result.high_level,"No high-level active items.",renderFocus),pushContextFocusSection(lines,"Low-level focus",result.low_level,"No low-level active items.",renderFocus),pushBlockedFallbackSection(lines,result,renderFocus),pushAgendaSection(lines,result),result.workspace_memory){lines.push("## Workspace memory");for(const rollup of result.workspace_memory.rollups)lines.push(`- ${rollup.kind}:${rollup.key} \u2014 ${rollup.label} (${rollup.item_count} completed, latest ${rollup.last_closed_at})`);lines.push("")}return pushHierarchySection(lines,result),pushProgressSection(lines,result),pushRecentlyCreatedSection(lines,result,focusFields,renderFocus),pushUnparentedSection(lines,result,renderFocus),pushActivitySection(lines,result),pushBlockersSection(lines,result),pushFilesSection(lines,result),pushWorkloadSection(lines,result),pushStalenessSection(lines,result),pushTestHealthSection(lines,result),pushEmptyContextSuggestions(lines,result),lines.join(`
2
2
  `)}async function resolveContextRuntime(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),settings=await readSettings(pmRoot),contextSettings=settings.context??SETTINGS_DEFAULTS.context,statusRegistry=resolveRuntimeStatusRegistry(settings.schema),depth=parseContextDepth(options.depth,contextSettings),limit=parseContextLimit(options.limit??options.maxItems,depth);return{settings,contextSettings,statusRegistry,depth,limit,sectionsIncluded:parseContextSections(options.section,depth,contextSettings),activityLimit:parseActivityLimit(options.activityLimit,contextSettings),staleThresholdDays:parseStaleThresholdDays(options.staleThreshold,contextSettings),parentScope:parseContextParent(options.parent),focusFields:parseContextFocusFields(options.fields),baseListOptions:stripListProjectionFlags(options)}}function contextNeedsAllItems(sectionsIncluded){return sectionsIncluded.some(section=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(section))}function buildUnpaginatedContextListOptions(baseListOptions,extra){return{...baseListOptions,...extra,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function loadContextCorpus(global2,runtime){const listed=await runList(void 0,buildUnpaginatedContextListOptions(runtime.baseListOptions,{excludeTerminal:!1}),global2),fullCorpus=listed.items;let listedItemMetadata=fullCorpus.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),allItems=fullCorpus;const subtreeIds=resolveContextSubtreeIds(runtime.parentScope,fullCorpus);return subtreeIds&&(listedItemMetadata=listedItemMetadata.filter(item=>subtreeIds.has(item.id.trim().toLowerCase())),allItems=allItems.filter(item=>subtreeIds.has(item.id.trim().toLowerCase()))),{listed,listedItemMetadata,allItems,fullCorpus,subtreeIds}}function resolveContextSubtreeIds(parentScope,fullCorpus){if(parentScope===void 0)return;const subtree=collectSubtreeIds(fullCorpus,parentScope);if(!subtree.found)throw new PmCliError(`Context --parent item not found: ${parentScope}`,EXIT_CODE.NOT_FOUND);return subtree.ids}function collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry){const containers=new Set(computeActionabilityReport(activeItems,fullCorpus,statusRegistry,typeRegistry).containers.map(entry=>entry.item.id));return new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)||containers.has(item.id)||resolveItemExecutionRole(item.type,typeRegistry)!=="agent").map(item=>item.id))}async function resolveContextFocusGroups(listedItemMetadata,allItems,fullCorpus,blockedIds,statusRegistry,sectionsIncluded,limit,now,author,cursor,cursorFingerprint,useBoundedPage,pmRoot,tokenBudget,claimFocus,typeRegistry){const structural=[...listedItemMetadata].sort((left,right)=>compareCriticalItems(left,right,statusRegistry)),usage=await readContextUsageAffinity({pmRoot,author,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),featureStore=await readWorkspaceContextSignals(structural,{pmRoot,storeKey:"context",statusRegistry,now,author,usageAffinity:usage.affinity,claimFocus}),ranking=await scoreContextCandidatesWithActiveExtensions("context",featureStore.candidates),ranked=ranking.ranked.map(entry=>entry.item),activeStatuses=statusRegistry.active_statuses,rankedActiveItems=ranked.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),pageStart=useBoundedPage?resolveQueryCursorStart(rankedActiveItems,cursor,cursorFingerprint,item=>item.id):0,focusPage=useBoundedPage?rankedActiveItems.slice(pageStart,pageStart+limit):rankedActiveItems,hasMore=useBoundedPage&&focusPage.length>0&&pageStart+focusPage.length<rankedActiveItems.length,nextCursor=hasMore&&focusPage.length>0?encodeQueryCursor(cursorFingerprint,focusPage[focusPage.length-1].id,pageStart+focusPage.length-1):void 0,rankedBlockedItems=ranked.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),packingIds=new Set([...focusPage.map(item=>item.id),...rankedBlockedItems.filter(item=>!activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))).slice(0,limit).map(item=>item.id)]),packing=packRankedContextItems({...ranking,ranked:ranking.ranked.filter(entry=>packingIds.has(entry.id))},tokenBudget,new Set(Object.entries(claimFocus??{}).filter(([,affinity])=>affinity>=1).map(([id])=>id))),packedItems=packing.included.map(entry=>entry.item),activeItems=packedItems.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),blockedItems=packedItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),childrenByParent=buildChildrenByParent(allItems),focusChildrenByParent=contextNeedsAllItems(sectionsIncluded)?childrenByParent:void 0,fullCorpusById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item])),projectFocusItem=item=>{const focus=toContextFocusItem(item,statusRegistry,focusChildrenByParent);return blockedIds.has(item.id.trim().toLowerCase())&&(focus.blocked=!0,focus.blocker_ids=resolveItemBlockers(item,fullCorpusById,statusRegistry).filter(blocker=>!blocker.resolved).map(blocker=>blocker.id)),focus},highLevelIds=collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry),highLevel=activeItems.filter(item=>highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),lowLevel=activeItems.filter(item=>!highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),blockedFallbackUsed=rankedActiveItems.length===0;return{activeItems,blockedItems,highLevel,lowLevel,blockedFallback:blockedFallbackUsed?blockedItems.slice(0,limit).map(projectFocusItem):[],blockedFallbackUsed,ranking,packing,featureStore,pageExtras:{...useBoundedPage?{applied_limit:limit}:{},...hasMore?{has_more:!0,truncated:!0}:{},...nextCursor?{next_cursor:nextCursor}:{}}}}function buildContextCursorFingerprint(options,pmRoot){return createQueryFingerprint("context",{pmRoot,options:selectCursorSemanticOptions(options,CONTEXT_FLAG_CONTRACTS)})}function shouldPageContextFocus(options,corpusItemCount){return options.limit!==void 0||options.maxItems!==void 0||options.after!==void 0||corpusItemCount>=CONTEXT_SCALE_THRESHOLD}async function buildContextAgenda(global2,runtime,subtreeIds,listedFocusIds){const calendarOptions={...runtime.baseListOptions,view:"agenda",include:"all",limit:runtime.parentScope===void 0?String(runtime.limit):void 0},agenda=await runCalendar(calendarOptions,global2),scopedAgenda=subtreeIds===void 0?agenda.events:agenda.events.filter(event=>subtreeIds.has(event.item_id.trim().toLowerCase())),fullAgendaEvents=filterTerminalCalendarEvents(scopedAgenda,runtime.statusRegistry).slice(0,runtime.limit),agendaEvents=fullAgendaEvents.map(event=>listedFocusIds.has(event.item_id)?{at:event.at,date:event.date,kind:event.kind,item_id:event.item_id,reference_only:!0,...event.kind==="reminder"?{reminder_text:event.reminder_text}:{},...event.kind==="event"?{event_title:event.event_title,event_recurring:event.event_recurring}:{}}:event);return{agenda,agendaEvents,agendaSummary:summarizeAgenda(fullAgendaEvents)}}function countContextStatus(items,status,statusRegistry){const targetStatus=String(status);return items.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===targetStatus).length}async function buildOptionalContextSections(params){const{runtime,allItems,fullCorpus,blockedIds,focusGroups,now,global:global2}=params,childrenByParent=buildChildrenByParent(allItems),allNonTerminal=allItems.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),has=section=>runtime.sectionsIncluded.includes(section);return{hierarchy:has("hierarchy")?buildHierarchy(allItems,focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,activity:has("activity")?await buildActivity(runtime.activityLimit,global2):void 0,progress:has("progress")?buildProgress(allItems,focusGroups.activeItems,blockedIds,runtime.statusRegistry,runtime.limit):void 0,blockersSection:has("blockers")?buildBlockers(focusGroups.blockedItems,fullCorpus,runtime.statusRegistry,runtime.limit):void 0,recentlyCreated:has("recently_created")?buildRecentlyCreated(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,unparented:has("unparented")?buildUnparented(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,filesSection:has("files")?buildHotFiles(focusGroups.activeItems,runtime.limit):void 0,workload:has("workload")?buildWorkload(focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,staleness:has("staleness")?buildStaleness(allNonTerminal,runtime.staleThresholdDays,now,runtime.limit):void 0,tests:has("tests")?buildTestHealth(allItems.filter(item=>runtime.statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,runtime.statusRegistry)))):void 0}}function buildContextSummaryExtras(allItems,statusRegistry,blockedIds){const canceledStatus=normalizeStatusInput("canceled",statusRegistry),activeItems=allItems.filter(item=>statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),inProgress=countContextStatus(activeItems,statusRegistry.in_progress_status,statusRegistry);return{scope:"matching_items",active_items:activeItems.length,open:activeItems.length-inProgress,in_progress:inProgress,blocked:allItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())).length,total_items:allItems.length,closed:allItems.filter(item=>isClosedStatus(item.status,statusRegistry)).length,canceled:allItems.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===canceledStatus).length}}function attachOptionalContextSections(result,sections,warningDetails){sections.hierarchy&&(result.hierarchy=sections.hierarchy),sections.activity&&(result.activity=sections.activity),sections.progress&&(result.progress=sections.progress),sections.blockersSection&&(result.blockers=sections.blockersSection),sections.recentlyCreated&&(result.recently_created=sections.recentlyCreated),sections.unparented&&(result.unparented=sections.unparented),sections.filesSection&&(result.files=sections.filesSection),sections.workload&&(result.workload=sections.workload),sections.staleness&&(result.staleness=sections.staleness),sections.tests&&(result.tests=sections.tests),warningDetails!==void 0&&warningDetails.length>0&&(result.warning_details=warningDetails)}function applyContextFocusProjection(result,focusFields){focusFields&&(result.focus_fields=focusFields,result.high_level=projectContextFocusRows(result.high_level,focusFields),result.low_level=projectContextFocusRows(result.low_level,focusFields),result.blocked_fallback=projectContextFocusRows(result.blocked_fallback,focusFields),result.recently_created&&(result.recently_created=projectContextFocusRows(result.recently_created,focusFields)),result.unparented&&(result.unparented=projectContextFocusRows(result.unparented,focusFields)))}function applyContextTagProjection(result,noTags){const rows=[result.high_level,result.low_level,result.blocked_fallback,result.recently_created??[],result.unparented??[]].flat();if(noTags){for(const row of rows)delete row.tags,delete row.tags_inherited;return}const rowsById=new Map(rows.map(row=>[row.id,row])),originalTagSignatures=new Map(rows.map(row=>[row.id,row.tags?[...row.tags].sort().join("\0"):void 0]));for(const row of rows){if(!row.parent||!row.tags)continue;const parent=rowsById.get(row.parent);parent&&originalTagSignatures.get(row.id)===originalTagSignatures.get(parent.id)&&(delete row.tags,row.tags_inherited=parent.id)}}function maybeAttachEmptyContextSuggestions(result,activeItems,blockedItems){activeItems.length>0||blockedItems.length>0||result.agenda.events.length>0||(result.suggestions=['pm create --type Task --title "..." to add a new work item',"pm list --status closed --limit 5 to review recent completions","pm search <keywords> to find related past work","pm aggregate for a full project status overview"])}async function attachContextUsageFeedback(result,focusGroups,pmRoot,author){try{const included=new Set(focusGroups.packing.included.map(entry=>entry.id)),rows=focusGroups.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)})),rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(result,"context"))rankedIds.has(id)||(rows.push({id,rank:rows.length+1,included:!1}),rankedIds.add(id));const receipt=await recordContextUsageServing({pmRoot,author,surface:"context",profile:focusGroups.packing.profile,rows,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});attachContextUsageServingReceipt(result,receipt)}catch{result.warnings=mergeSortedWarnings(result.warnings,["context_usage_feedback_write_failed"])}}async function resolveContextExtensionHealthProjection(omitted,pmRoot,settings){if(omitted)return{};const packages=(await discoverExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:!1})).discovered.map(diagnostic=>({name:diagnostic.name??diagnostic.directory,status:diagnostic.status==="ok"?"ok":"degraded"})).sort((left,right)=>left.name.localeCompare(right.name)),degraded=packages.filter(entry=>entry.status==="degraded").length;return packages.length===0?{}:{extension_health:{total:packages.length,ok:packages.length-degraded,degraded,packages:packages.slice(0,20),...packages.length>20?{truncated:!0}:{}}}}async function resolveContextSemanticAffinity(pmRoot,author){const identity=detectAgentIdentity(),semanticState=await readSessionState(pmRoot),attributionKey=identity.instance||semanticAttributionKey(author);return semanticAttributionAffinity(semanticState.semantic_attribution?.[attributionKey])}async function runContext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),resolvedRuntime=await resolveContextRuntime(options,global2),corpus=await loadContextCorpus(global2,resolvedRuntime),scaledLimit=resolveContextLimitAtScale(resolvedRuntime.limit,corpus.fullCorpus.length),runtime={...resolvedRuntime,limit:scaledLimit,tokenBudget:resolveContextTokenBudget(options.tokenBudget,Math.max(256,scaledLimit*160))},author=resolveAuthor(void 0,runtime.settings.author_default),claimFocus=await resolveContextSemanticAffinity(pmRoot,author),extensionHealthPromise=resolveContextExtensionHealthProjection(options.noExtensionHealth===!0,pmRoot,runtime.settings),blockedIds=collectDependencyBlockedIds(corpus.fullCorpus,runtime.statusRegistry),focusGroups=await resolveContextFocusGroups(corpus.listedItemMetadata,corpus.allItems,corpus.fullCorpus,blockedIds,runtime.statusRegistry,runtime.sectionsIncluded,runtime.limit,nowIso(),author,options.after,buildContextCursorFingerprint(options,pmRoot),shouldPageContextFocus(options,corpus.fullCorpus.length),pmRoot,runtime.tokenBudget,claimFocus,resolveItemTypeRegistry(runtime.settings,getActiveExtensionRegistrations())),agendaContext=await buildContextAgenda(global2,runtime,corpus.subtreeIds,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(item=>item.id))),workspaceMemory=await readWorkspaceMemory(corpus.fullCorpus,{pmRoot,statusRegistry:runtime.statusRegistry,now:agendaContext.agenda.now}),warnings=mergeSortedWarnings(corpus.listed.warnings,agendaContext.agenda.warnings,focusGroups.ranking.warnings,[...focusGroups.featureStore.warnings],workspaceMemory.warnings),inProgressCount=countContextStatus(focusGroups.activeItems,runtime.statusRegistry.in_progress_status,runtime.statusRegistry),openCount=focusGroups.activeItems.length-inProgressCount,sections=await buildOptionalContextSections({runtime,allItems:corpus.allItems,fullCorpus:corpus.fullCorpus,blockedIds,focusGroups,now:agendaContext.agenda.now,global:global2}),summaryExtras=buildContextSummaryExtras(corpus.allItems,runtime.statusRegistry,blockedIds),result={output_default:"toon",now:agendaContext.agenda.now,depth:runtime.depth,sections_included:runtime.sectionsIncluded,window:{anchor:agendaContext.agenda.anchor,start:agendaContext.agenda.range.start,end:agendaContext.agenda.range.end,past:agendaContext.agenda.range.past,from:agendaContext.agenda.range.from,to:agendaContext.agenda.range.to},filters:{type:options.type??null,tag:options.tag??null,priority:options.priority??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,limit:options.limit??options.maxItems??null,parent:runtime.parentScope??null,token_budget:runtime.tokenBudget,runtime_filters:corpus.listed.filters.runtime_filters??agendaContext.agenda.filters.runtime_filters??{}},summary:{returned_focus:{active_items:focusGroups.activeItems.length,in_progress:inProgressCount,open:openCount,blocked:focusGroups.blockedItems.length},blocked_fallback_used:focusGroups.blockedFallbackUsed,high_level:focusGroups.highLevel.length,low_level:focusGroups.lowLevel.length,agenda_events:agendaContext.agendaSummary.events,...summaryExtras},high_level:focusGroups.highLevel,low_level:focusGroups.lowLevel,blocked_fallback:focusGroups.blockedFallback,agenda:{summary:agendaContext.agendaSummary,events:agendaContext.agendaEvents},...focusGroups.pageExtras};return result.workspace_memory=selectWorkspaceMemory(workspaceMemory,Math.min(800,Math.floor(runtime.tokenBudget*.2))),Object.assign(result,await extensionHealthPromise),attachOptionalContextSections(result,sections,focusGroups.featureStore.warning_details),applyContextTagProjection(result,options.noTags===!0),options.explainRanking===!0&&(result.ranking=toContextRankingSummary(focusGroups.ranking,focusGroups.featureStore,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(entry=>entry.id))),result.packing=toContextPackingSummary(focusGroups.packing)),rememberReadOutputFocusRows(result,[...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(row=>({id:row.id,status:normalizeStatusForRegistry(row.status,runtime.statusRegistry)===runtime.statusRegistry.in_progress_status?"in_progress":"open",blocked:row.blocked}))),applyContextFocusProjection(result,runtime.focusFields),refreshReadOutputDeliveredCounts(result),warnings.length>0&&(result.warnings=warnings),maybeAttachEmptyContextSuggestions(result,focusGroups.activeItems,focusGroups.blockedItems),await attachContextUsageFeedback(result,focusGroups,pmRoot,author),result}export{CONTEXT_OUTPUT_VALUES,_testOnly,applyContextTagProjection,buildChildrenByParent,buildItemContextRelevanceCandidates,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,projectContextFocusRows,renderContextMarkdown,resolveContextExtensionHealthProjection,resolveContextOutputFormat,resolveContextTokenBudget,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary};
3
3
  //# sourceMappingURL=context.js.map
@@ -1,3 +1,4 @@
1
+ import type { PmReadOutputMetadata } from "../read-output-contracts.js";
1
2
  import { type GlobalOptions } from "../runtime-primitives.js";
2
3
  import { type ResolvedBlocker } from "../actionability.js";
3
4
  import { type ChildRollupContext } from "../item-children.js";
@@ -42,7 +43,7 @@ events:number;
42
43
  }>;
43
44
  };
44
45
  /** Single-item read with optional derived facets; omission materiality is carried separately from its JSON representation. */
45
- export interface GetResult {
46
+ export interface GetResult extends Partial<PmReadOutputMetadata> {
46
47
  /** Selected metadata and body; requested empty collections are represented explicitly. */
47
48
  item:GetItemProjection;
48
49
  /** Requested artifact groups; narrower selectors leave unrequested groups empty. */
@@ -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]="e2c03bb3-e603-579b-bb44-0b3757a00ea8")}catch{}})();import{readdir}from"node:fs/promises";import path from"node:path";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,toItemRecord,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,TYPE_TO_FOLDER,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,getHistoryPath,resolvePmRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{renderPmCommand}from"../command-line.js";import{recordContextUsageTouches}from"../context-usage.js";import{createPmCliExpectedError}from"../errors.js";import{collectBlockedByIds,resolveItemBlockers}from"../actionability.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"../../core/item/dependency-reference.js";import{buildItemChildrenRollup}from"../item-children.js";import{buildItemSchedule}from"../item-schedule.js";import{getItemAt}from"../history-read.js";import{parseIntegerLimit}from"./parsers.js";import{runList}from"./list.js";import{registerOutputMaterialFieldGroups}from"../output-projection.js";import{GET_DEPTH_VALUES,listGetProjectionFields}from"./projection-contracts.js";import{GET_DEPTH_VALUES as GET_DEPTH_VALUES2,listGetProjectionFields as listGetProjectionFields2}from"./projection-contracts.js";const AUTOMATIC_CHILD_ROLLUP_TYPES=new Set(["epic","feature","milestone","plan"]),BUILTIN_ITEM_TYPES=new Set(Object.keys(TYPE_TO_FOLDER).map(type=>type.toLowerCase()));function itemCollectionCounts(item){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(key=>[key,item[key]?.length??0]))}function itemMaterialFieldGroups(item,body,children,currentSnapshot,projection){const collectionCounts=itemCollectionCounts(item);return[...body.length>0?["body"]:[],...Object.entries(collectionCounts).flatMap(([name,count])=>count>0?[name]:[]),...collectionCounts.files+collectionCounts.tests+collectionCounts.docs>0?["linked"]:[],...children===void 0?["children"]:children.count>0?["children"]:[],...typeof item.assignee=="string"&&item.assignee.trim().length>0?["claim_state"]:[],...buildItemSchedule(item)?["schedule"]:[],...currentSnapshot&&collectBlockedByIds(item).length>0?["blockers"]:[],...!projection.full&&item.dependencies?.some(({id:_id,kind:_kind,...provenance})=>Object.values(provenance).some(value=>value!==void 0))?["dependency_provenance"]:[]]}function shouldAutoIncludeGetChildren(itemType){const normalizedType=itemType.trim().toLowerCase();return normalizedType.length>0&&(AUTOMATIC_CHILD_ROLLUP_TYPES.has(normalizedType)||!BUILTIN_ITEM_TYPES.has(normalizedType))}function toClaimHistoryContext(entry){return{ts:entry.ts,author:entry.author,message:entry.message??null}}function resolveClaimStateContext(assigneeValue,history){const assignee=assigneeValue?.trim(),normalizedAssignee=assignee&&assignee.length>0?assignee:null,lastClaim=[...history].reverse().find(entry=>entry.op==="claim"),lastRelease=[...history].reverse().find(entry=>entry.op==="release");return{claimed:normalizedAssignee!==null,assignee:normalizedAssignee,last_claim:lastClaim?toClaimHistoryContext(lastClaim):null,last_release:lastRelease?toClaimHistoryContext(lastRelease):null}}function parseGetDepth(raw){if(raw===void 0||raw.trim().length===0)return"standard";const normalized=raw.trim().toLowerCase();if(normalized==="full")return"deep";if(GET_DEPTH_VALUES.includes(normalized))return normalized;throw new PmCliError("Get --depth must be one of brief|standard|deep|full",EXIT_CODE.USAGE,{field:"depth",value:raw,recovery:{allowed_values:[...GET_DEPTH_VALUES,"full"]}})}function projectItemForDepth(item,depth,full){const collectionCounts=itemCollectionCounts(item),projectedItem={...item};if(!full&&item.dependencies!==void 0&&(projectedItem.dependencies=item.dependencies.map(({id,kind})=>({id,kind}))),depth==="deep")return{...projectedItem,comments:item.comments??[],notes:item.notes??[],learnings:item.learnings??[],files:item.files??[],tests:item.tests??[],docs:item.docs??[],reminders:item.reminders??[],events:item.events??[],notes_count:collectionCounts.notes,tests_count:collectionCounts.tests,collection_counts:collectionCounts};const{comments:_comments,notes:_notes,learnings:_learnings,files:_files,tests:_tests,docs:_docs,reminders:_reminders,events:_events,...projected}=projectedItem;return{...projected,notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:collectionCounts}}function parseGetFields(raw){if(raw===void 0)return null;const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0)throw new PmCliError("Get --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);return fields}function normalizeGetField(field){return field.startsWith("item.")?field.slice(5):field}function validateGetFields(fields,runtimeMetadataKeys,id){if(fields===null)return;const allowedValues=listGetProjectionFields(runtimeMetadataKeys),allowed=new Set(allowedValues),unknown=fields.filter(field=>{const normalized=normalizeGetField(field);return!allowed.has(field)&&!allowed.has(normalized)});if(unknown.length>0){const suggestedRetryArguments=["get",id,"--fields",fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown get --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const EMPTY_PROJECTED_COLLECTION_FIELDS=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function projectedMetadataValue(source,counts,field){return Object.hasOwn(counts,field)?counts[field]:source[field]!==void 0?source[field]:EMPTY_PROJECTED_COLLECTION_FIELDS.has(field)?[]:void 0}function projectItemForFields(item,fields){const source=toItemRecord(item),omittedCounts={notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:itemCollectionCounts(item)},projected={id:item.id};for(const field of fields){const normalized=normalizeGetField(field);normalized==="body"||normalized==="linked"||normalized.startsWith("linked.")||normalized==="claim_state"||normalized.startsWith("claim_state.")||normalized==="children"||normalized.startsWith("children.")||normalized==="schedule"||normalized.startsWith("schedule.")||normalized==="blockers"||(projected[normalized]=projectedMetadataValue(source,omittedCounts,normalized))}return projected}function fieldsInclude(fields,name){return fields?.some(field=>field===name||field===`item.${name}`)??!1}function fieldsIncludeRoot(fields,name){return fields.some(field=>{const normalized=normalizeGetField(field);return normalized===name||normalized.startsWith(`${name}.`)})}function resolveGetProjection(options,id){if(options.full&&(options.fields!==void 0||options.depth!==void 0))throw new PmCliError("Get projection options are mutually exclusive; remove the extra projection flag and retry.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:renderPmCommand(["get",id,"--full"]),suggested_retry_args:["get",id,"--full"]}});if(options.tree!==!0&&options.treeDepth!==void 0)throw new PmCliError("Get --tree-depth requires --tree",EXIT_CODE.USAGE);if(options.at!==void 0&&options.tree===!0)throw new PmCliError("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",EXIT_CODE.USAGE);return{depth:options.full?"deep":parseGetDepth(options.depth),full:options.full===!0||options.depth?.trim().toLowerCase()==="full",treeDepth:options.tree===!0?parseIntegerLimit(options.treeDepth,"--tree-depth"):void 0,fields:parseGetFields(options.fields),fieldProjection:options.fields!==void 0}}async function loadGetItemContext(id,global2,at){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());if(at!==void 0){const historical=await getItemAt(id,at,{pmRoot:global2.path});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:historical.document.metadata.id,metadata:historical.document.metadata,body:historical.document.body,historical}}const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeRegistry.type_to_folder);const loaded=await readLocatedItem(located,{schema:settings.schema});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:located.id,metadata:loaded.document.metadata,body:loaded.document.body}}function validateGetProjectionFields(fields,settings,historical,id){const runtimeMetadataKeys=resolveRuntimeFieldRegistry(settings.schema).definitions.map(field=>field.metadata_key);if(validateGetFields(fields,runtimeMetadataKeys,id),historical&&fieldsIncludeRoot(fields??[],"children"))throw new PmCliError("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",EXIT_CODE.USAGE);if(historical&&fieldsIncludeRoot(fields??[],"blockers"))throw new PmCliError("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",EXIT_CODE.USAGE)}function shouldIncludeGetField(params){const{fieldProjection,depth,fields,field}=params;return fieldProjection?field==="body"||field==="linked"?fieldsInclude(fields,field):fieldsIncludeRoot(fields,field):depth!=="brief"}async function resolveGetClaimState(context,includeClaimState){if(!includeClaimState)return;const historyPath=getHistoryPath(context.pmRoot,context.locatedId),history=await readHistoryEntries(historyPath,context.locatedId);return resolveClaimStateContext(context.metadata.assignee,context.historical?history.slice(0,context.historical.target.historyIndex+1):history)}function attachGetLinked(result,context,fields,includeLinked){const includeLinkedFiles=includeLinked||fieldsInclude(fields,"linked.files"),includeLinkedTests=includeLinked||fieldsInclude(fields,"linked.tests"),includeLinkedDocs=includeLinked||fieldsInclude(fields,"linked.docs");!includeLinked&&!includeLinkedFiles&&!includeLinkedTests&&!includeLinkedDocs||(result.linked={files:includeLinkedFiles?context.metadata.files??[]:[],tests:includeLinkedTests?context.metadata.tests??[]:[],docs:includeLinkedDocs?context.metadata.docs??[]:[]})}async function buildGetChildrenRollup(context,includeChildren){if(!includeChildren)return;const statusRegistry=resolveRuntimeStatusRegistry(context.settings.schema),corpus=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,context.typeToFolder,void 0,context.settings.schema);return buildItemChildrenRollup(context.locatedId,corpus,statusRegistry)}function canonicalizeDeclaredBlockers(blockers,targets){const canonical=new Map;for(const blocker of blockers){const id=blocker.external?blocker.id:targets.get(blocker.id.toLowerCase())?.id??blocker.id;canonical.set(blocker.external?`external:${id}`:`local:${id.toLowerCase()}`,{...blocker,id})}return[...canonical.values()]}async function resolvePhysicalBlockerId(itemPath,probedId){const filename=path.basename(itemPath),physicalId=(await readdir(path.dirname(itemPath)).catch(error=>{throw createPmCliExpectedError("Cannot verify the blocker's physical file identity",{exitCode:EXIT_CODE.GENERIC_FAILURE,context:{code:"blocker_identity_read_failed",required:"Restore access to the blocker item directory, then retry the item read."},cause:error})})).filter(name=>name.toLowerCase()===filename.toLowerCase()).sort((left,right)=>+(right===filename)-+(left===filename)||left.localeCompare(right)).map(name=>path.parse(name).name)[0];if(physicalId===void 0)throw new PmCliError(`Blocker canonical file disappeared during identity verification: ${probedId}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker file and validate storage integrity before retrying the item read."});return physicalId}async function attachGetBlockers(result,context,projection){if(context.historical!==void 0||!(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"blockers"):projection.depth!=="brief"))return;const ids=collectBlockedByIds(context.metadata);if(ids.length===0)return;const declaredIds=new Map([context.metadata.blocked_by,...(context.metadata.dependencies??[]).filter(dependency=>dependency.kind==="blocked_by").map(dependency=>dependency.id)].filter(id=>typeof id=="string").map(id=>[id.trim().toLowerCase(),id.trim()])),targets=new Map;for(const id of ids){if(isExternalDependencyReference(id)||!/^(?!\.{1,2}$)[^/\\:\0]+$/u.test(id)||context.metadata.dependencies?.some(dependency=>dependency.id.trim()===id&&dependency.kind==="blocked_by"&&isExternalDependencySourceKind(dependency.source_kind)))continue;const located=await locateItem(context.pmRoot,declaredIds.get(id),context.settings.id_prefix,context.settings.item_format,context.typeToFolder);if(located===null)continue;const loaded=await readLocatedItem(located,{schema:context.settings.schema});if(located.id=await resolvePhysicalBlockerId(located.itemPath,located.id),loaded.document.metadata.id!==located.id)throw new PmCliError(`Blocker identity differs from its canonical file: ${located.id}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker identity and validate storage integrity before retrying the item read."});targets.set(id.toLowerCase(),loaded.document.metadata)}const resolved=canonicalizeDeclaredBlockers(resolveItemBlockers({blocked_by:context.metadata.blocked_by,dependencies:context.metadata.dependencies,updated_at:context.metadata.updated_at},targets,resolveRuntimeStatusRegistry(context.settings.schema)),targets);result.blockers={scope:"declared",open:resolved.filter(blocker=>!blocker.resolved).map(({resolved:_resolved,...blocker})=>blocker),closed_count:resolved.filter(blocker=>blocker.resolved).length},!projection.fieldProjection&&!projection.full&&delete result.item.blocked_by}function attachGetSchedule(result,context,fields,includeSchedule){if(!includeSchedule)return;const schedule=buildItemSchedule(context.metadata);if(schedule){if(fields===null||fieldsInclude(fields,"schedule")){result.schedule=schedule;return}result.schedule=Object.fromEntries(Object.entries(schedule).filter(([key])=>fields.some(field=>normalizeGetField(field)===`schedule.${key}`)))}}async function buildGetTree(context,options,treeDepth,global2){if(options.tree!==!0)return;const subtree=await runList(void 0,{parent:context.locatedId,tree:!0,treeDepth:treeDepth===void 0?void 0:String(treeDepth),full:!0},global2);return{root_id:context.locatedId,root_title:context.metadata.title,depth_limit:treeDepth??null,count:subtree.count,items:subtree.items.map(entry=>toItemRecord(entry))}}async function runGet(id,global2,options={}){const projection=resolveGetProjection(options,id),context=await loadGetItemContext(id,global2,options.at);validateGetProjectionFields(projection.fields,context.settings,context.historical!==void 0,context.locatedId);const includeBody=shouldIncludeGetField({...projection,field:"body"}),includeLinked=shouldIncludeGetField({...projection,field:"linked"}),includeClaimState=shouldIncludeGetField({...projection,field:"claim_state"}),includeChildren=context.historical===void 0&&(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"children"):projection.depth==="deep"&&(projection.full||shouldAutoIncludeGetChildren(context.metadata.type))),includeSchedule=projection.fieldProjection?fieldsIncludeRoot(projection.fields,"schedule"):projection.depth!=="brief",claimState=await resolveGetClaimState(context,includeClaimState),result={item:projection.fieldProjection?projectItemForFields(context.metadata,projection.fields):projectItemForDepth(context.metadata,projection.depth,projection.full)};includeBody&&(result.item.body=context.body),attachGetLinked(result,context,projection.fields,includeLinked),claimState&&(result.claim_state=claimState),attachGetSchedule(result,context,projection.fields,includeSchedule),await attachGetBlockers(result,context,projection);const children=await buildGetChildrenRollup(context,includeChildren);children!==void 0&&(result.children=children);const tree=await buildGetTree(context,options,projection.treeDepth,global2);if(tree!==void 0&&(result.tree=tree),context.historical&&(result.reconstructed=!0,result.as_of_version=context.historical.as_of_version,result.as_of_timestamp=context.historical.as_of_timestamp),context.historical===void 0)try{await recordContextUsageTouches({pmRoot:context.pmRoot,author:resolveAuthor(void 0,context.settings.author_default),itemIds:[context.locatedId],intent:"get"})}catch{}return registerOutputMaterialFieldGroups(result,projection.fieldProjection?[]:itemMaterialFieldGroups(context.metadata,context.body,children,context.historical===void 0,projection)),result}const _testOnlyGetCommand={shouldAutoIncludeGetChildren};export{GET_DEPTH_VALUES2 as GET_DEPTH_VALUES,_testOnlyGetCommand,listGetProjectionFields2 as listGetProjectionFields,runGet};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="623eaead-53e7-57f5-8d05-2cfd1fe062db")}catch{}})();import{readdir}from"node:fs/promises";import path from"node:path";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,toItemRecord,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,TYPE_TO_FOLDER,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,getHistoryPath,resolvePmRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{renderPmCommand}from"../command-line.js";import{recordContextUsageTouches}from"../context-usage.js";import{createPmCliExpectedError}from"../errors.js";import{collectBlockedByIds,resolveItemBlockers}from"../actionability.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"../../core/item/dependency-reference.js";import{buildItemChildrenRollup}from"../item-children.js";import{buildItemSchedule}from"../item-schedule.js";import{getItemAt}from"../history-read.js";import{parseIntegerLimit}from"./parsers.js";import{runList}from"./list.js";import{registerOutputMaterialFieldGroups}from"../output-projection.js";import{GET_DEPTH_VALUES,listGetProjectionFields}from"./projection-contracts.js";import{GET_DEPTH_VALUES as GET_DEPTH_VALUES2,listGetProjectionFields as listGetProjectionFields2}from"./projection-contracts.js";const AUTOMATIC_CHILD_ROLLUP_TYPES=new Set(["epic","feature","milestone","plan"]),BUILTIN_ITEM_TYPES=new Set(Object.keys(TYPE_TO_FOLDER).map(type=>type.toLowerCase()));function itemCollectionCounts(item){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(key=>[key,item[key]?.length??0]))}function itemMaterialFieldGroups(item,body,children,currentSnapshot,projection){const collectionCounts=itemCollectionCounts(item);return[...body.length>0?["body"]:[],...Object.entries(collectionCounts).flatMap(([name,count])=>count>0?[name]:[]),...collectionCounts.files+collectionCounts.tests+collectionCounts.docs>0?["linked"]:[],...children===void 0?["children"]:children.count>0?["children"]:[],...typeof item.assignee=="string"&&item.assignee.trim().length>0?["claim_state"]:[],...buildItemSchedule(item)?["schedule"]:[],...currentSnapshot&&collectBlockedByIds(item).length>0?["blockers"]:[],...!projection.full&&item.dependencies?.some(({id:_id,kind:_kind,...provenance})=>Object.values(provenance).some(value=>value!==void 0))?["dependency_provenance"]:[]]}function shouldAutoIncludeGetChildren(itemType){const normalizedType=itemType.trim().toLowerCase();return normalizedType.length>0&&(AUTOMATIC_CHILD_ROLLUP_TYPES.has(normalizedType)||!BUILTIN_ITEM_TYPES.has(normalizedType))}function toClaimHistoryContext(entry){return{ts:entry.ts,author:entry.author,message:entry.message??null}}function resolveClaimStateContext(assigneeValue,history){const assignee=assigneeValue?.trim(),normalizedAssignee=assignee&&assignee.length>0?assignee:null,lastClaim=[...history].reverse().find(entry=>entry.op==="claim"),lastRelease=[...history].reverse().find(entry=>entry.op==="release");return{claimed:normalizedAssignee!==null,assignee:normalizedAssignee,last_claim:lastClaim?toClaimHistoryContext(lastClaim):null,last_release:lastRelease?toClaimHistoryContext(lastRelease):null}}function parseGetDepth(raw){if(raw===void 0||raw.trim().length===0)return"standard";const normalized=raw.trim().toLowerCase();if(normalized==="full")return"deep";if(GET_DEPTH_VALUES.includes(normalized))return normalized;throw new PmCliError("Get --depth must be one of brief|standard|deep|full",EXIT_CODE.USAGE,{field:"depth",value:raw,recovery:{allowed_values:[...GET_DEPTH_VALUES,"full"]}})}function projectItemForDepth(item,depth,full){const collectionCounts=itemCollectionCounts(item),projectedItem={...item};if(!full&&item.dependencies!==void 0&&(projectedItem.dependencies=item.dependencies.map(({id,kind})=>({id,kind}))),depth==="deep")return{...projectedItem,comments:item.comments??[],notes:item.notes??[],learnings:item.learnings??[],files:item.files??[],tests:item.tests??[],docs:item.docs??[],reminders:item.reminders??[],events:item.events??[],notes_count:collectionCounts.notes,tests_count:collectionCounts.tests,collection_counts:collectionCounts};const{comments:_comments,notes:_notes,learnings:_learnings,files:_files,tests:_tests,docs:_docs,reminders:_reminders,events:_events,...projected}=projectedItem;return{...projected,notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:collectionCounts}}function parseGetFields(raw){if(raw===void 0)return null;const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0)throw new PmCliError("Get --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);return fields}function normalizeGetField(field){return field.startsWith("item.")?field.slice(5):field}function validateGetFields(fields,runtimeMetadataKeys,id){if(fields===null)return;const allowedValues=listGetProjectionFields(runtimeMetadataKeys),allowed=new Set(allowedValues),unknown=fields.filter(field=>{const normalized=normalizeGetField(field);return!allowed.has(field)&&!allowed.has(normalized)});if(unknown.length>0){const suggestedRetryArguments=["get",id,"--fields",fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown get --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const EMPTY_PROJECTED_COLLECTION_FIELDS=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function projectedMetadataValue(source,counts,field){return Object.hasOwn(counts,field)?counts[field]:source[field]!==void 0?source[field]:EMPTY_PROJECTED_COLLECTION_FIELDS.has(field)?[]:void 0}function projectItemForFields(item,fields){const source=toItemRecord(item),omittedCounts={notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:itemCollectionCounts(item)},projected={id:item.id};for(const field of fields){const normalized=normalizeGetField(field);normalized==="body"||normalized==="linked"||normalized.startsWith("linked.")||normalized==="claim_state"||normalized.startsWith("claim_state.")||normalized==="children"||normalized.startsWith("children.")||normalized==="schedule"||normalized.startsWith("schedule.")||normalized==="blockers"||(projected[normalized]=projectedMetadataValue(source,omittedCounts,normalized))}return projected}function fieldsInclude(fields,name){return fields?.some(field=>field===name||field===`item.${name}`)??!1}function fieldsIncludeRoot(fields,name){return fields.some(field=>{const normalized=normalizeGetField(field);return normalized===name||normalized.startsWith(`${name}.`)})}function resolveGetProjection(options,id){if(options.full&&(options.fields!==void 0||options.depth!==void 0))throw new PmCliError("Get projection options are mutually exclusive; remove the extra projection flag and retry.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:renderPmCommand(["get",id,"--full"]),suggested_retry_args:["get",id,"--full"]}});if(options.tree!==!0&&options.treeDepth!==void 0)throw new PmCliError("Get --tree-depth requires --tree",EXIT_CODE.USAGE);if(options.at!==void 0&&options.tree===!0)throw new PmCliError("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",EXIT_CODE.USAGE);return{depth:options.full?"deep":parseGetDepth(options.depth),full:options.full===!0||options.depth?.trim().toLowerCase()==="full",treeDepth:options.tree===!0?parseIntegerLimit(options.treeDepth,"--tree-depth"):void 0,fields:parseGetFields(options.fields),fieldProjection:options.fields!==void 0}}async function loadGetItemContext(id,global2,at){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());if(at!==void 0){const historical=await getItemAt(id,at,{pmRoot:global2.path});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:historical.document.metadata.id,metadata:historical.document.metadata,body:historical.document.body,historical}}const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeRegistry.type_to_folder);const loaded=await readLocatedItem(located,{schema:settings.schema});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:located.id,metadata:loaded.document.metadata,body:loaded.document.body}}function validateGetProjectionFields(fields,settings,historical,id){const runtimeMetadataKeys=resolveRuntimeFieldRegistry(settings.schema).definitions.map(field=>field.metadata_key);if(validateGetFields(fields,runtimeMetadataKeys,id),historical&&fieldsIncludeRoot(fields??[],"children"))throw new PmCliError("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",EXIT_CODE.USAGE);if(historical&&fieldsIncludeRoot(fields??[],"blockers"))throw new PmCliError("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",EXIT_CODE.USAGE)}function shouldIncludeGetField(params){const{fieldProjection,depth,fields,field}=params;return fieldProjection?field==="body"||field==="linked"?fieldsInclude(fields,field):fieldsIncludeRoot(fields,field):depth!=="brief"}async function resolveGetClaimState(context,includeClaimState){if(!includeClaimState)return;const historyPath=getHistoryPath(context.pmRoot,context.locatedId),history=await readHistoryEntries(historyPath,context.locatedId);return resolveClaimStateContext(context.metadata.assignee,context.historical?history.slice(0,context.historical.target.historyIndex+1):history)}function attachGetLinked(result,context,fields,includeLinked){const includeLinkedFiles=includeLinked||fieldsInclude(fields,"linked.files"),includeLinkedTests=includeLinked||fieldsInclude(fields,"linked.tests"),includeLinkedDocs=includeLinked||fieldsInclude(fields,"linked.docs");!includeLinked&&!includeLinkedFiles&&!includeLinkedTests&&!includeLinkedDocs||(result.linked={files:includeLinkedFiles?context.metadata.files??[]:[],tests:includeLinkedTests?context.metadata.tests??[]:[],docs:includeLinkedDocs?context.metadata.docs??[]:[]})}async function buildGetChildrenRollup(context,includeChildren){if(!includeChildren)return;const statusRegistry=resolveRuntimeStatusRegistry(context.settings.schema),corpus=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,context.typeToFolder,void 0,context.settings.schema);return buildItemChildrenRollup(context.locatedId,corpus,statusRegistry)}function canonicalizeDeclaredBlockers(blockers,targets){const canonical=new Map;for(const blocker of blockers){const id=blocker.external?blocker.id:targets.get(blocker.id.toLowerCase())?.id??blocker.id;canonical.set(blocker.external?`external:${id}`:`local:${id.toLowerCase()}`,{...blocker,id})}return[...canonical.values()]}async function resolvePhysicalBlockerId(itemPath,probedId){const filename=path.basename(itemPath),physicalId=(await readdir(path.dirname(itemPath)).catch(error=>{throw createPmCliExpectedError("Cannot verify the blocker's physical file identity",{exitCode:EXIT_CODE.GENERIC_FAILURE,context:{code:"blocker_identity_read_failed",required:"Restore access to the blocker item directory, then retry the item read."},cause:error})})).filter(name=>name.toLowerCase()===filename.toLowerCase()).sort((left,right)=>+(right===filename)-+(left===filename)||left.localeCompare(right)).map(name=>path.parse(name).name)[0];if(physicalId===void 0)throw new PmCliError(`Blocker canonical file disappeared during identity verification: ${probedId}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker file and validate storage integrity before retrying the item read."});return physicalId}async function attachGetBlockers(result,context,projection){if(context.historical!==void 0||!(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"blockers"):projection.depth!=="brief"))return;const ids=collectBlockedByIds(context.metadata);if(ids.length===0)return;const declaredIds=new Map([context.metadata.blocked_by,...(context.metadata.dependencies??[]).filter(dependency=>dependency.kind==="blocked_by").map(dependency=>dependency.id)].filter(id=>typeof id=="string").map(id=>[id.trim().toLowerCase(),id.trim()])),targets=new Map;for(const id of ids){if(isExternalDependencyReference(id)||!/^(?!\.{1,2}$)[^/\\:\0]+$/u.test(id)||context.metadata.dependencies?.some(dependency=>dependency.id.trim()===id&&dependency.kind==="blocked_by"&&isExternalDependencySourceKind(dependency.source_kind)))continue;const located=await locateItem(context.pmRoot,declaredIds.get(id),context.settings.id_prefix,context.settings.item_format,context.typeToFolder);if(located===null)continue;const loaded=await readLocatedItem(located,{schema:context.settings.schema});if(located.id=await resolvePhysicalBlockerId(located.itemPath,located.id),loaded.document.metadata.id!==located.id)throw new PmCliError(`Blocker identity differs from its canonical file: ${located.id}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker identity and validate storage integrity before retrying the item read."});targets.set(id.toLowerCase(),loaded.document.metadata)}const resolved=canonicalizeDeclaredBlockers(resolveItemBlockers({blocked_by:context.metadata.blocked_by,dependencies:context.metadata.dependencies,updated_at:context.metadata.updated_at},targets,resolveRuntimeStatusRegistry(context.settings.schema)),targets);result.blockers={scope:"declared",open:resolved.filter(blocker=>!blocker.resolved).map(({resolved:_resolved,...blocker})=>blocker),closed_count:resolved.filter(blocker=>blocker.resolved).length},!projection.fieldProjection&&!projection.full&&delete result.item.blocked_by}function attachGetSchedule(result,context,fields,includeSchedule){if(!includeSchedule)return;const schedule=buildItemSchedule(context.metadata);if(schedule){if(fields===null||fieldsInclude(fields,"schedule")){result.schedule=schedule;return}result.schedule=Object.fromEntries(Object.entries(schedule).filter(([key])=>fields.some(field=>normalizeGetField(field)===`schedule.${key}`)))}}async function buildGetTree(context,options,treeDepth,global2){if(options.tree!==!0)return;const subtree=await runList(void 0,{parent:context.locatedId,tree:!0,treeDepth:treeDepth===void 0?void 0:String(treeDepth),full:!0},global2);return{root_id:context.locatedId,root_title:context.metadata.title,depth_limit:treeDepth??null,count:subtree.count,items:subtree.items.map(entry=>toItemRecord(entry))}}async function runGet(id,global2,options={}){const projection=resolveGetProjection(options,id),context=await loadGetItemContext(id,global2,options.at);validateGetProjectionFields(projection.fields,context.settings,context.historical!==void 0,context.locatedId);const includeBody=shouldIncludeGetField({...projection,field:"body"}),includeLinked=shouldIncludeGetField({...projection,field:"linked"}),includeClaimState=shouldIncludeGetField({...projection,field:"claim_state"}),includeChildren=context.historical===void 0&&(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"children"):projection.depth==="deep"&&(projection.full||shouldAutoIncludeGetChildren(context.metadata.type))),includeSchedule=projection.fieldProjection?fieldsIncludeRoot(projection.fields,"schedule"):projection.depth!=="brief",claimState=await resolveGetClaimState(context,includeClaimState),result={item:projection.fieldProjection?projectItemForFields(context.metadata,projection.fields):projectItemForDepth(context.metadata,projection.depth,projection.full)};includeBody&&(result.item.body=context.body),attachGetLinked(result,context,projection.fields,includeLinked),claimState&&(result.claim_state=claimState),attachGetSchedule(result,context,projection.fields,includeSchedule),await attachGetBlockers(result,context,projection);const children=await buildGetChildrenRollup(context,includeChildren);children!==void 0&&(result.children=children);const tree=await buildGetTree(context,options,projection.treeDepth,global2);if(tree!==void 0&&(result.tree=tree),context.historical&&(result.reconstructed=!0,result.as_of_version=context.historical.as_of_version,result.as_of_timestamp=context.historical.as_of_timestamp),context.historical===void 0)try{await recordContextUsageTouches({pmRoot:context.pmRoot,author:resolveAuthor(void 0,context.settings.author_default),itemIds:[context.locatedId],intent:"get"})}catch{}return registerOutputMaterialFieldGroups(result,projection.fieldProjection?[]:itemMaterialFieldGroups(context.metadata,context.body,children,context.historical===void 0,projection)),result}const _testOnlyGetCommand={shouldAutoIncludeGetChildren};export{GET_DEPTH_VALUES2 as GET_DEPTH_VALUES,_testOnlyGetCommand,listGetProjectionFields2 as listGetProjectionFields,runGet};
2
2
  //# sourceMappingURL=get.js.map
@@ -1,3 +1,4 @@
1
+ import type { PmReadOutputMetadata } from "../read-output-contracts.js";
1
2
  import { type ItemTypeRegistry } from "../../core/item/type-registry.js";
2
3
  import { type MissingMetadataFilters } from "../../core/governance/metadata-coverage.js";
3
4
  import { type ContentFieldFilters } from "../../core/governance/content-fields.js";
@@ -135,7 +136,7 @@ export type ListSortField = (typeof LIST_SORT_FIELDS)[number];
135
136
  export declare const LIST_SORT_ORDER_VALUES:readonly ["asc","desc"];
136
137
  /** Restricts list sort order values accepted by command, SDK, and storage contracts. */
137
138
  export type ListSortOrder = (typeof LIST_SORT_ORDER_VALUES)[number];
138
- interface ListResultBase {
139
+ interface ListResultBase extends Partial<PmReadOutputMetadata> {
139
140
  items:ListResultItem[];
140
141
  count:number;
141
142
  /** Total rows matched before pagination. Stable on every list envelope. */
@@ -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]="18a4b856-e3fb-5ac0-a2f1-1c041d88795d")}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??"priority"])]}}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",...ordering.sortField===void 0&&!ordering.treeEnabled?{effective_keys:[["status_registry:nonterminal_before_terminal","asc"],["priority","asc"],["updated_at","desc"],["id","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]="0479845d-dd41-5604-a026-6733bb595236")}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??"priority"])]}}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",...ordering.sortField===void 0&&!ordering.treeEnabled?{effective_keys:[["status_registry:nonterminal_before_terminal","asc"],["priority","asc"],["updated_at","desc"],["id","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
@@ -2,6 +2,7 @@
2
2
  * @module sdk/query/search/types
3
3
  * Shared search result and pipeline state contracts; no runtime dependencies.
4
4
  */
5
+ import type { PmReadOutputMetadata } from "../../read-output-contracts.js";
5
6
  import { type QueryExpansionConfig,type RerankConfig } from "../../../core/search/relevance.js";
6
7
  import type { ItemMetadata } from "../../../types/index.js";
7
8
  import { type WorkspaceMemoryRollup } from "../../workspace-memory.js";
@@ -35,7 +36,7 @@ snippet:string;
35
36
  }
36
37
  /** Restricts search result item values accepted by command, SDK, and storage contracts. */
37
38
  export type SearchResultItem = SearchHit | Record<string,unknown>;
38
- interface SearchResultBase {
39
+ interface SearchResultBase extends Partial<PmReadOutputMetadata> {
39
40
  query:string;
40
41
  mode:SearchMode;
41
42
  /** Which layer chose `mode` before any runtime fallback: the caller, `search.default_mode`, or the workspace-state default. */
@@ -4,6 +4,7 @@
4
4
  * Provides focused read, search, pagination, and context-ranking primitives.
5
5
  */
6
6
  export * from "./query/list.js";
7
+ export type { PmReadOutputMetadata } from "./read-output-contracts.js";
7
8
  export * from "./query/complete-list.js";
8
9
  export * from "./query/search.js";
9
10
  export { runActivity,type ActivityCommandOptions,type ActivityEntry,type ActivityResult,type CompactActivityEntry,} from "./query/activity.js";