@unbrained/pm-cli 2026.10.20 → 2026.10.21
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.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +25 -0
- package/dist/cli/error-guidance.d.ts +8 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/main.js +1 -1
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-QMZ73FCW.js → chunk-2B5HAZFK.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-4D25HF3V.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-QETMESEB.js → chunk-4OYU5OXQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YTHI5DTH.js → chunk-5PZ7JNMI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TZU6U5ZE.js → chunk-C6SAXKBO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-DIKQ2AL5.js +2 -0
- package/dist/cli-bundle/chunks/chunk-DIR3YEFD.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-KU4Q3MSI.js → chunk-DJQVNDXO.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-DR6DUBTU.js +30 -0
- package/dist/cli-bundle/chunks/{chunk-YT2Z3JPC.js → chunk-EMGMLKRV.js} +47 -47
- package/dist/cli-bundle/chunks/{chunk-YECCKB4E.js → chunk-GWIGZDRS.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-PNPE2OVJ.js → chunk-KBSVPUFD.js} +46 -45
- package/dist/cli-bundle/chunks/{chunk-7ZOIZ2AZ.js → chunk-MOC5BJHW.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-MZZIAC6S.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-LS55VKRK.js → chunk-NNB65OOO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YW6SIKYP.js → chunk-QPV6UD55.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GHJOMRSF.js → chunk-TMXWWOPJ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-VLJLWZBO.js → chunk-V3XONSVC.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-V5GJTXYW.js +126 -0
- package/dist/cli-bundle/chunks/{chunk-ZA3XXHEE.js → chunk-ZNKFMIVA.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-U7VGKIYC.js → indexed-receipt-blobs-65XXSPPR.js} +2 -2
- package/dist/cli-bundle/chunks/mutation-admission-FNWOVJLN.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-NNDV6F6I.js → register-list-query-6PT5Y2EZ.js} +5 -5
- package/dist/cli-bundle/chunks/{register-mutation-3GCBSNQS.js → register-mutation-TAIQV46L.js} +4 -4
- package/dist/cli-bundle/chunks/register-operations-ONIRO22G.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-OQMUZBJV.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-CLRGA6O7.js → settlement-hook-UVFYSBMU.js} +2 -2
- package/dist/cli-bundle/chunks/stage-FCPVFO3B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-32ZKLRWM.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HUZAXSIJ.js → chunk-3LWH2RJC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZGEK57KD.js → chunk-44353U27.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4HJVAUFX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VLSER3XW.js → chunk-5IMM7GOF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-J6EYUGAR.js → chunk-6QSZHRM7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-F7FD25TG.js → chunk-7UD7XTOE.js} +10 -10
- package/dist/cli-bundle/focused-chunks/{chunk-KKRFSI2N.js → chunk-CUWNNU4N.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-E2S42XCT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-GRSQGMRR.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NI6NS44Q.js → chunk-HNCMYF2W.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-37SU7BZI.js → chunk-IAGFXKMZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JI3RXXRN.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-JMZPZQHR.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-E4II2D2B.js → chunk-KVYUQS6Y.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-O3M6YWVL.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-P5D7MHDS.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-PDOWLRHC.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-T27TLSEU.js +65 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LJPUJ2KK.js → chunk-VD64TPXI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GYHZ7W6O.js → chunk-VE6MTRH5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XE7P7N5X.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-YIWDX6KO.js +91 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-H2G6CCGO.js → indexed-receipt-blobs-CRP6HAZY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-KM57KDDF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-5SNBBT7C.js → settlement-hook-MNCHFCAX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/stage-UJYGWNZ7.js +2 -0
- package/dist/cli-bundle/main.js +21 -21
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +23 -23
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +58 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +2 -2
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/lock/lock-gc.d.ts +12 -5
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.d.ts +33 -0
- package/dist/core/lock/lock-owner.js +2 -0
- package/dist/core/lock/lock.d.ts +11 -22
- package/dist/core/lock/lock.js +4 -3
- package/dist/core/output/output.js +3 -3
- package/dist/core/shared/errors.d.ts +2 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/pagination.d.ts +3 -3
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/list.d.ts +2 -0
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/projection-contracts.d.ts +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/runtime/mutation-admission.d.ts +2 -0
- package/dist/sdk/runtime/mutation-admission.js +2 -0
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/execution.d.ts +1 -0
- package/dist/sdk/test/execution.js +2 -2
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +9 -0
- package/docs/ASSURANCE.md +17 -2
- package/docs/COMMANDS.md +17 -3
- package/docs/CONFIGURATION.md +29 -0
- package/docs/CONTEXT_RELEVANCE.md +15 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +26 -3
- package/docs/SDK.md +67 -0
- package/docs/TESTING.md +18 -0
- package/docs/agent-task-token-baseline.json +1 -1
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2GGGOD7P.js +0 -30
- package/dist/cli-bundle/chunks/chunk-7NHA5K77.js +0 -126
- package/dist/cli-bundle/chunks/chunk-PTL3TBT6.js +0 -20
- package/dist/cli-bundle/chunks/chunk-QQYCB2LO.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-YKDGNKUL.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-AOUZQQWB.js +0 -2
- package/dist/cli-bundle/chunks/stage-6QXYRMSU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-6IU7BESB.js +0 -65
- package/dist/cli-bundle/focused-chunks/chunk-AS3MOBO3.js +0 -25
- package/dist/cli-bundle/focused-chunks/chunk-AW35RDKA.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-H5Q2HUU6.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-JEXZEIAX.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-KDGUIIRU.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-MQ42BFGX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VAYS754X.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VS6VTWTZ.js +0 -8
- package/dist/cli-bundle/focused-chunks/stage-EMTISXR7.js +0 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="599ebac9-d3e8-561d-a971-8164179f1adf")}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/total*100):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{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=node.children_total>0?Math.round(node.children_closed/node.children_total*100):0;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=child.children_total>0?Math.round(child.children_closed/child.children_total*100):0;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 pushTestHealthSection(lines,result){result.tests&&(lines.push("## Test health"),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}`),result.tests.items_failing.length>0&&lines.push(`- items_failing: [${result.tests.items_failing.join(",")}]`),lines.push(""))}function pushEmptyContextSuggestions(lines,result){result.summary.active_items===0&&result.summary.blocked===0&&result.agenda.summary.events===0&&(lines.push("## Suggestions"),lines.push("No active work items or upcoming events. Consider:"),lines.push('- `pm create --type Task --title "..."` to add a new work item'),lines.push("- `pm list --status closed --limit 5` to review recent completions"),lines.push("- `pm search <keywords>` to find related past work"),lines.push("- `pm aggregate` for a full project status overview"))}function renderContextMarkdown(result){const lines=[],focusFields=result.focus_fields,renderFocus=item=>focusFields?formatProjectedFocusLine(item,focusFields):formatFocusLine(item);if(lines.push("# pm context"),lines.push(""),lines.push(`- now: ${result.now}`),lines.push(`- depth: ${result.depth}`),result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(`- active_items: ${result.summary.active_items} (in_progress: ${result.summary.in_progress}, open: ${result.summary.open})`),result.summary.total_items!==void 0&&lines.push(`- total_items: ${result.summary.total_items} (closed: ${result.summary.closed??0}, canceled: ${result.summary.canceled??0})`),lines.push(`- agenda_events: ${result.summary.agenda_events}`),lines.push(`- blocked_fallback_used: ${result.summary.blocked_fallback_used}`),result.extension_health){const degradedNames=result.extension_health.packages.filter(entry=>entry.status==="degraded").map(entry=>entry.name);lines.push(`- extensions: ${result.extension_health.ok} ok, ${result.extension_health.degraded} degraded${degradedNames.length>0?` (${degradedNames.join(", ")})`:""}`)}const renderedSections=result.sections_included.filter(section=>section!=="blockers"||(result.blockers?.length??0)>0);if(renderedSections.length>0&&lines.push(`- sections: ${renderedSections.join(", ")}`),lines.push(""),pushContextFocusSection(lines,"High-level focus",result.high_level,"No high-level active items.",renderFocus),pushContextFocusSection(lines,"Low-level focus",result.low_level,"No low-level active items.",renderFocus),pushBlockedFallbackSection(lines,result,renderFocus),pushAgendaSection(lines,result),result.workspace_memory){lines.push("## Workspace memory");for(const rollup of result.workspace_memory.rollups)lines.push(`- ${rollup.kind}:${rollup.key} \u2014 ${rollup.label} (${rollup.item_count} completed, latest ${rollup.last_closed_at})`);lines.push("")}return pushHierarchySection(lines,result),pushProgressSection(lines,result),pushRecentlyCreatedSection(lines,result,focusFields,renderFocus),pushUnparentedSection(lines,result,renderFocus),pushActivitySection(lines,result),pushBlockersSection(lines,result),pushFilesSection(lines,result),pushWorkloadSection(lines,result),pushStalenessSection(lines,result),pushTestHealthSection(lines,result),pushEmptyContextSuggestions(lines,result),lines.join(`
|
|
2
|
-
`)}async function resolveContextRuntime(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),settings=await readSettings(pmRoot),contextSettings=settings.context??SETTINGS_DEFAULTS.context,statusRegistry=resolveRuntimeStatusRegistry(settings.schema),depth=parseContextDepth(options.depth,contextSettings),limit=parseContextLimit(options.limit??options.maxItems,depth);return{settings,contextSettings,statusRegistry,depth,limit,sectionsIncluded:parseContextSections(options.section,depth,contextSettings),activityLimit:parseActivityLimit(options.activityLimit,contextSettings),staleThresholdDays:parseStaleThresholdDays(options.staleThreshold,contextSettings),parentScope:parseContextParent(options.parent),focusFields:parseContextFocusFields(options.fields),baseListOptions:stripListProjectionFlags(options)}}function contextNeedsAllItems(sectionsIncluded){return sectionsIncluded.some(section=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(section))}function buildUnpaginatedContextListOptions(baseListOptions,extra){return{...baseListOptions,...extra,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function loadContextCorpus(global2,runtime){const listed=await runList(void 0,buildUnpaginatedContextListOptions(runtime.baseListOptions,{excludeTerminal:!1}),global2),fullCorpus=listed.items;let listedItemMetadata=fullCorpus.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),allItems=fullCorpus;const subtreeIds=resolveContextSubtreeIds(runtime.parentScope,fullCorpus);return subtreeIds&&(listedItemMetadata=listedItemMetadata.filter(item=>subtreeIds.has(item.id.trim().toLowerCase())),allItems=allItems.filter(item=>subtreeIds.has(item.id.trim().toLowerCase()))),{listed,listedItemMetadata,allItems,fullCorpus,subtreeIds}}function resolveContextSubtreeIds(parentScope,fullCorpus){if(parentScope===void 0)return;const subtree=collectSubtreeIds(fullCorpus,parentScope);if(!subtree.found)throw new PmCliError(`Context --parent item not found: ${parentScope}`,EXIT_CODE.NOT_FOUND);return subtree.ids}function collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry){const containers=new Set(computeActionabilityReport(activeItems,fullCorpus,statusRegistry,typeRegistry).containers.map(entry=>entry.item.id));return new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)||containers.has(item.id)||resolveItemExecutionRole(item.type,typeRegistry)!=="agent").map(item=>item.id))}async function resolveContextFocusGroups(listedItemMetadata,allItems,fullCorpus,blockedIds,statusRegistry,sectionsIncluded,limit,now,author,cursor,cursorFingerprint,useBoundedPage,pmRoot,tokenBudget,claimFocus,typeRegistry){const structural=[...listedItemMetadata].sort((left,right)=>compareCriticalItems(left,right,statusRegistry)),usage=await readContextUsageAffinity({pmRoot,author,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),featureStore=await readWorkspaceContextSignals(structural,{pmRoot,storeKey:"context",statusRegistry,now,author,usageAffinity:usage.affinity,claimFocus}),ranking=await scoreContextCandidatesWithActiveExtensions("context",featureStore.candidates),ranked=ranking.ranked.map(entry=>entry.item),activeStatuses=statusRegistry.active_statuses,rankedActiveItems=ranked.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),pageStart=useBoundedPage?resolveQueryCursorStart(rankedActiveItems,cursor,cursorFingerprint,item=>item.id):0,focusPage=useBoundedPage?rankedActiveItems.slice(pageStart,pageStart+limit):rankedActiveItems,hasMore=useBoundedPage&&focusPage.length>0&&pageStart+focusPage.length<rankedActiveItems.length,nextCursor=hasMore&&focusPage.length>0?encodeQueryCursor(cursorFingerprint,focusPage[focusPage.length-1].id,pageStart+focusPage.length-1):void 0,rankedBlockedItems=ranked.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),packingIds=new Set([...focusPage.map(item=>item.id),...rankedBlockedItems.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(focusGroups.activeItems):void 0}}function buildContextSummaryExtras(allItems,statusRegistry,blockedIds){const canceledStatus=normalizeStatusInput("canceled",statusRegistry),activeItems=allItems.filter(item=>statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),inProgress=countContextStatus(activeItems,statusRegistry.in_progress_status,statusRegistry);return{scope:"matching_items",active_items:activeItems.length,open:activeItems.length-inProgress,in_progress:inProgress,blocked:allItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())).length,total_items:allItems.length,closed:allItems.filter(item=>isClosedStatus(item.status,statusRegistry)).length,canceled:allItems.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===canceledStatus).length}}function attachOptionalContextSections(result,sections,warningDetails){sections.hierarchy&&(result.hierarchy=sections.hierarchy),sections.activity&&(result.activity=sections.activity),sections.progress&&(result.progress=sections.progress),sections.blockersSection&&(result.blockers=sections.blockersSection),sections.recentlyCreated&&(result.recently_created=sections.recentlyCreated),sections.unparented&&(result.unparented=sections.unparented),sections.filesSection&&(result.files=sections.filesSection),sections.workload&&(result.workload=sections.workload),sections.staleness&&(result.staleness=sections.staleness),sections.tests&&(result.tests=sections.tests),warningDetails!==void 0&&warningDetails.length>0&&(result.warning_details=warningDetails)}function applyContextFocusProjection(result,focusFields){focusFields&&(result.focus_fields=focusFields,result.high_level=projectContextFocusRows(result.high_level,focusFields),result.low_level=projectContextFocusRows(result.low_level,focusFields),result.blocked_fallback=projectContextFocusRows(result.blocked_fallback,focusFields),result.recently_created&&(result.recently_created=projectContextFocusRows(result.recently_created,focusFields)),result.unparented&&(result.unparented=projectContextFocusRows(result.unparented,focusFields)))}function applyContextTagProjection(result,noTags){const rows=[result.high_level,result.low_level,result.blocked_fallback,result.recently_created??[],result.unparented??[]].flat();if(noTags){for(const row of rows)delete row.tags,delete row.tags_inherited;return}const rowsById=new Map(rows.map(row=>[row.id,row])),originalTagSignatures=new Map(rows.map(row=>[row.id,row.tags?[...row.tags].sort().join("\0"):void 0]));for(const row of rows){if(!row.parent||!row.tags)continue;const parent=rowsById.get(row.parent);parent&&originalTagSignatures.get(row.id)===originalTagSignatures.get(parent.id)&&(delete row.tags,row.tags_inherited=parent.id)}}function maybeAttachEmptyContextSuggestions(result,activeItems,blockedItems){activeItems.length>0||blockedItems.length>0||result.agenda.events.length>0||(result.suggestions=['pm create --type Task --title "..." to add a new work item',"pm list --status closed --limit 5 to review recent completions","pm search <keywords> to find related past work","pm aggregate for a full project status overview"])}async function attachContextUsageFeedback(result,focusGroups,pmRoot,author){try{const included=new Set(focusGroups.packing.included.map(entry=>entry.id)),rows=focusGroups.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)})),rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(result,"context"))rankedIds.has(id)||(rows.push({id,rank:rows.length+1,included:!1}),rankedIds.add(id));const receipt=await recordContextUsageServing({pmRoot,author,surface:"context",profile:focusGroups.packing.profile,rows,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});attachContextUsageServingReceipt(result,receipt)}catch{result.warnings=mergeSortedWarnings(result.warnings,["context_usage_feedback_write_failed"])}}async function resolveContextExtensionHealthProjection(omitted,pmRoot,settings){if(omitted)return{};const packages=(await discoverExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:!1})).discovered.map(diagnostic=>({name:diagnostic.name??diagnostic.directory,status:diagnostic.status==="ok"?"ok":"degraded"})).sort((left,right)=>left.name.localeCompare(right.name)),degraded=packages.filter(entry=>entry.status==="degraded").length;return packages.length===0?{}:{extension_health:{total:packages.length,ok:packages.length-degraded,degraded,packages:packages.slice(0,20),...packages.length>20?{truncated:!0}:{}}}}async function resolveContextSemanticAffinity(pmRoot,author){const identity=detectAgentIdentity(),semanticState=await readSessionState(pmRoot),attributionKey=identity.instance||semanticAttributionKey(author);return semanticAttributionAffinity(semanticState.semantic_attribution?.[attributionKey])}async function runContext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),resolvedRuntime=await resolveContextRuntime(options,global2),corpus=await loadContextCorpus(global2,resolvedRuntime),scaledLimit=resolveContextLimitAtScale(resolvedRuntime.limit,corpus.fullCorpus.length),runtime={...resolvedRuntime,limit:scaledLimit,tokenBudget:resolveContextTokenBudget(options.tokenBudget,Math.max(256,scaledLimit*160))},author=resolveAuthor(void 0,runtime.settings.author_default),claimFocus=await resolveContextSemanticAffinity(pmRoot,author),extensionHealthPromise=resolveContextExtensionHealthProjection(options.noExtensionHealth===!0,pmRoot,runtime.settings),blockedIds=collectDependencyBlockedIds(corpus.fullCorpus,runtime.statusRegistry),focusGroups=await resolveContextFocusGroups(corpus.listedItemMetadata,corpus.allItems,corpus.fullCorpus,blockedIds,runtime.statusRegistry,runtime.sectionsIncluded,runtime.limit,nowIso(),author,options.after,buildContextCursorFingerprint(options,pmRoot),shouldPageContextFocus(options,corpus.fullCorpus.length),pmRoot,runtime.tokenBudget,claimFocus,resolveItemTypeRegistry(runtime.settings,getActiveExtensionRegistrations())),agendaContext=await buildContextAgenda(global2,runtime,corpus.subtreeIds,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(item=>item.id))),workspaceMemory=await readWorkspaceMemory(corpus.fullCorpus,{pmRoot,statusRegistry:runtime.statusRegistry,now:agendaContext.agenda.now}),warnings=mergeSortedWarnings(corpus.listed.warnings,agendaContext.agenda.warnings,focusGroups.ranking.warnings,[...focusGroups.featureStore.warnings],workspaceMemory.warnings),inProgressCount=countContextStatus(focusGroups.activeItems,runtime.statusRegistry.in_progress_status,runtime.statusRegistry),openCount=focusGroups.activeItems.length-inProgressCount,sections=await buildOptionalContextSections({runtime,allItems:corpus.allItems,fullCorpus:corpus.fullCorpus,blockedIds,focusGroups,now:agendaContext.agenda.now,global:global2}),summaryExtras=buildContextSummaryExtras(corpus.allItems,runtime.statusRegistry,blockedIds),result={output_default:"toon",now:agendaContext.agenda.now,depth:runtime.depth,sections_included:runtime.sectionsIncluded,window:{anchor:agendaContext.agenda.anchor,start:agendaContext.agenda.range.start,end:agendaContext.agenda.range.end,past:agendaContext.agenda.range.past,from:agendaContext.agenda.range.from,to:agendaContext.agenda.range.to},filters:{type:options.type??null,tag:options.tag??null,priority:options.priority??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,limit:options.limit??options.maxItems??null,parent:runtime.parentScope??null,token_budget:runtime.tokenBudget,runtime_filters:corpus.listed.filters.runtime_filters??agendaContext.agenda.filters.runtime_filters??{}},summary:{returned_focus:{active_items:focusGroups.activeItems.length,in_progress:inProgressCount,open:openCount,blocked:focusGroups.blockedItems.length},blocked_fallback_used:focusGroups.blockedFallbackUsed,high_level:focusGroups.highLevel.length,low_level:focusGroups.lowLevel.length,agenda_events:agendaContext.agendaSummary.events,...summaryExtras},high_level:focusGroups.highLevel,low_level:focusGroups.lowLevel,blocked_fallback:focusGroups.blockedFallback,agenda:{summary:agendaContext.agendaSummary,events:agendaContext.agendaEvents},...focusGroups.pageExtras};return result.workspace_memory=selectWorkspaceMemory(workspaceMemory,Math.min(800,Math.floor(runtime.tokenBudget*.2))),Object.assign(result,await extensionHealthPromise),attachOptionalContextSections(result,sections,focusGroups.featureStore.warning_details),applyContextTagProjection(result,options.noTags===!0),options.explainRanking===!0&&(result.ranking=toContextRankingSummary(focusGroups.ranking,focusGroups.featureStore,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(entry=>entry.id))),result.packing=toContextPackingSummary(focusGroups.packing)),rememberReadOutputFocusRows(result,[...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(row=>({id:row.id,status:normalizeStatusForRegistry(row.status,runtime.statusRegistry)===runtime.statusRegistry.in_progress_status?"in_progress":"open",blocked:row.blocked}))),applyContextFocusProjection(result,runtime.focusFields),refreshReadOutputDeliveredCounts(result),warnings.length>0&&(result.warnings=warnings),maybeAttachEmptyContextSuggestions(result,focusGroups.activeItems,focusGroups.blockedItems),await attachContextUsageFeedback(result,focusGroups,pmRoot,author),result}export{CONTEXT_OUTPUT_VALUES,_testOnly,applyContextTagProjection,buildChildrenByParent,buildItemContextRelevanceCandidates,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,projectContextFocusRows,renderContextMarkdown,resolveContextExtensionHealthProjection,resolveContextOutputFormat,resolveContextTokenBudget,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f3fdd154-b363-5447-aee5-69fc833a8c03")}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{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 pushTestHealthSection(lines,result){result.tests&&(lines.push("## Test health"),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}`),result.tests.items_failing.length>0&&lines.push(`- items_failing: [${result.tests.items_failing.join(",")}]`),lines.push(""))}function pushEmptyContextSuggestions(lines,result){result.summary.active_items===0&&result.summary.blocked===0&&result.agenda.summary.events===0&&(lines.push("## Suggestions"),lines.push("No active work items or upcoming events. Consider:"),lines.push('- `pm create --type Task --title "..."` to add a new work item'),lines.push("- `pm list --status closed --limit 5` to review recent completions"),lines.push("- `pm search <keywords>` to find related past work"),lines.push("- `pm aggregate` for a full project status overview"))}function renderContextMarkdown(result){const lines=[],focusFields=result.focus_fields,renderFocus=item=>focusFields?formatProjectedFocusLine(item,focusFields):formatFocusLine(item);if(lines.push("# pm context"),lines.push(""),lines.push(`- now: ${result.now}`),lines.push(`- depth: ${result.depth}`),result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(`- active_items: ${result.summary.active_items} (in_progress: ${result.summary.in_progress}, open: ${result.summary.open})`),result.summary.total_items!==void 0&&lines.push(`- total_items: ${result.summary.total_items} (closed: ${result.summary.closed??0}, canceled: ${result.summary.canceled??0})`),lines.push(`- agenda_events: ${result.summary.agenda_events}`),lines.push(`- blocked_fallback_used: ${result.summary.blocked_fallback_used}`),result.extension_health){const degradedNames=result.extension_health.packages.filter(entry=>entry.status==="degraded").map(entry=>entry.name);lines.push(`- extensions: ${result.extension_health.ok} ok, ${result.extension_health.degraded} degraded${degradedNames.length>0?` (${degradedNames.join(", ")})`:""}`)}const renderedSections=result.sections_included.filter(section=>section!=="blockers"||(result.blockers?.length??0)>0);if(renderedSections.length>0&&lines.push(`- sections: ${renderedSections.join(", ")}`),lines.push(""),pushContextFocusSection(lines,"High-level focus",result.high_level,"No high-level active items.",renderFocus),pushContextFocusSection(lines,"Low-level focus",result.low_level,"No low-level active items.",renderFocus),pushBlockedFallbackSection(lines,result,renderFocus),pushAgendaSection(lines,result),result.workspace_memory){lines.push("## Workspace memory");for(const rollup of result.workspace_memory.rollups)lines.push(`- ${rollup.kind}:${rollup.key} \u2014 ${rollup.label} (${rollup.item_count} completed, latest ${rollup.last_closed_at})`);lines.push("")}return pushHierarchySection(lines,result),pushProgressSection(lines,result),pushRecentlyCreatedSection(lines,result,focusFields,renderFocus),pushUnparentedSection(lines,result,renderFocus),pushActivitySection(lines,result),pushBlockersSection(lines,result),pushFilesSection(lines,result),pushWorkloadSection(lines,result),pushStalenessSection(lines,result),pushTestHealthSection(lines,result),pushEmptyContextSuggestions(lines,result),lines.join(`
|
|
2
|
+
`)}async function resolveContextRuntime(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),settings=await readSettings(pmRoot),contextSettings=settings.context??SETTINGS_DEFAULTS.context,statusRegistry=resolveRuntimeStatusRegistry(settings.schema),depth=parseContextDepth(options.depth,contextSettings),limit=parseContextLimit(options.limit??options.maxItems,depth);return{settings,contextSettings,statusRegistry,depth,limit,sectionsIncluded:parseContextSections(options.section,depth,contextSettings),activityLimit:parseActivityLimit(options.activityLimit,contextSettings),staleThresholdDays:parseStaleThresholdDays(options.staleThreshold,contextSettings),parentScope:parseContextParent(options.parent),focusFields:parseContextFocusFields(options.fields),baseListOptions:stripListProjectionFlags(options)}}function contextNeedsAllItems(sectionsIncluded){return sectionsIncluded.some(section=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(section))}function buildUnpaginatedContextListOptions(baseListOptions,extra){return{...baseListOptions,...extra,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function loadContextCorpus(global2,runtime){const listed=await runList(void 0,buildUnpaginatedContextListOptions(runtime.baseListOptions,{excludeTerminal:!1}),global2),fullCorpus=listed.items;let listedItemMetadata=fullCorpus.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),allItems=fullCorpus;const subtreeIds=resolveContextSubtreeIds(runtime.parentScope,fullCorpus);return subtreeIds&&(listedItemMetadata=listedItemMetadata.filter(item=>subtreeIds.has(item.id.trim().toLowerCase())),allItems=allItems.filter(item=>subtreeIds.has(item.id.trim().toLowerCase()))),{listed,listedItemMetadata,allItems,fullCorpus,subtreeIds}}function resolveContextSubtreeIds(parentScope,fullCorpus){if(parentScope===void 0)return;const subtree=collectSubtreeIds(fullCorpus,parentScope);if(!subtree.found)throw new PmCliError(`Context --parent item not found: ${parentScope}`,EXIT_CODE.NOT_FOUND);return subtree.ids}function collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry){const containers=new Set(computeActionabilityReport(activeItems,fullCorpus,statusRegistry,typeRegistry).containers.map(entry=>entry.item.id));return new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)||containers.has(item.id)||resolveItemExecutionRole(item.type,typeRegistry)!=="agent").map(item=>item.id))}async function resolveContextFocusGroups(listedItemMetadata,allItems,fullCorpus,blockedIds,statusRegistry,sectionsIncluded,limit,now,author,cursor,cursorFingerprint,useBoundedPage,pmRoot,tokenBudget,claimFocus,typeRegistry){const structural=[...listedItemMetadata].sort((left,right)=>compareCriticalItems(left,right,statusRegistry)),usage=await readContextUsageAffinity({pmRoot,author,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),featureStore=await readWorkspaceContextSignals(structural,{pmRoot,storeKey:"context",statusRegistry,now,author,usageAffinity:usage.affinity,claimFocus}),ranking=await scoreContextCandidatesWithActiveExtensions("context",featureStore.candidates),ranked=ranking.ranked.map(entry=>entry.item),activeStatuses=statusRegistry.active_statuses,rankedActiveItems=ranked.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),pageStart=useBoundedPage?resolveQueryCursorStart(rankedActiveItems,cursor,cursorFingerprint,item=>item.id):0,focusPage=useBoundedPage?rankedActiveItems.slice(pageStart,pageStart+limit):rankedActiveItems,hasMore=useBoundedPage&&focusPage.length>0&&pageStart+focusPage.length<rankedActiveItems.length,nextCursor=hasMore&&focusPage.length>0?encodeQueryCursor(cursorFingerprint,focusPage[focusPage.length-1].id,pageStart+focusPage.length-1):void 0,rankedBlockedItems=ranked.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),packingIds=new Set([...focusPage.map(item=>item.id),...rankedBlockedItems.filter(item=>!activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))).slice(0,limit).map(item=>item.id)]),packing=packRankedContextItems({...ranking,ranked:ranking.ranked.filter(entry=>packingIds.has(entry.id))},tokenBudget,new Set(Object.entries(claimFocus??{}).filter(([,affinity])=>affinity>=1).map(([id])=>id))),packedItems=packing.included.map(entry=>entry.item),activeItems=packedItems.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),blockedItems=packedItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),childrenByParent=buildChildrenByParent(allItems),focusChildrenByParent=contextNeedsAllItems(sectionsIncluded)?childrenByParent:void 0,fullCorpusById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item])),projectFocusItem=item=>{const focus=toContextFocusItem(item,statusRegistry,focusChildrenByParent);return blockedIds.has(item.id.trim().toLowerCase())&&(focus.blocked=!0,focus.blocker_ids=resolveItemBlockers(item,fullCorpusById,statusRegistry).filter(blocker=>!blocker.resolved).map(blocker=>blocker.id)),focus},highLevelIds=collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry),highLevel=activeItems.filter(item=>highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),lowLevel=activeItems.filter(item=>!highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),blockedFallbackUsed=rankedActiveItems.length===0;return{activeItems,blockedItems,highLevel,lowLevel,blockedFallback:blockedFallbackUsed?blockedItems.slice(0,limit).map(projectFocusItem):[],blockedFallbackUsed,ranking,packing,featureStore,pageExtras:{...useBoundedPage?{applied_limit:limit}:{},...hasMore?{has_more:!0,truncated:!0}:{},...nextCursor?{next_cursor:nextCursor}:{}}}}function buildContextCursorFingerprint(options,pmRoot){return createQueryFingerprint("context",{pmRoot,options:selectCursorSemanticOptions(options,CONTEXT_FLAG_CONTRACTS)})}function shouldPageContextFocus(options,corpusItemCount){return options.limit!==void 0||options.maxItems!==void 0||options.after!==void 0||corpusItemCount>=CONTEXT_SCALE_THRESHOLD}async function buildContextAgenda(global2,runtime,subtreeIds,listedFocusIds){const calendarOptions={...runtime.baseListOptions,view:"agenda",include:"all",limit:runtime.parentScope===void 0?String(runtime.limit):void 0},agenda=await runCalendar(calendarOptions,global2),scopedAgenda=subtreeIds===void 0?agenda.events:agenda.events.filter(event=>subtreeIds.has(event.item_id.trim().toLowerCase())),fullAgendaEvents=filterTerminalCalendarEvents(scopedAgenda,runtime.statusRegistry).slice(0,runtime.limit),agendaEvents=fullAgendaEvents.map(event=>listedFocusIds.has(event.item_id)?{at:event.at,date:event.date,kind:event.kind,item_id:event.item_id,reference_only:!0,...event.kind==="reminder"?{reminder_text:event.reminder_text}:{},...event.kind==="event"?{event_title:event.event_title,event_recurring:event.event_recurring}:{}}:event);return{agenda,agendaEvents,agendaSummary:summarizeAgenda(fullAgendaEvents)}}function countContextStatus(items,status,statusRegistry){const targetStatus=String(status);return items.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===targetStatus).length}async function buildOptionalContextSections(params){const{runtime,allItems,fullCorpus,blockedIds,focusGroups,now,global:global2}=params,childrenByParent=buildChildrenByParent(allItems),allNonTerminal=allItems.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),has=section=>runtime.sectionsIncluded.includes(section);return{hierarchy:has("hierarchy")?buildHierarchy(allItems,focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,activity:has("activity")?await buildActivity(runtime.activityLimit,global2):void 0,progress:has("progress")?buildProgress(allItems,focusGroups.activeItems,blockedIds,runtime.statusRegistry,runtime.limit):void 0,blockersSection:has("blockers")?buildBlockers(focusGroups.blockedItems,fullCorpus,runtime.statusRegistry,runtime.limit):void 0,recentlyCreated:has("recently_created")?buildRecentlyCreated(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,unparented:has("unparented")?buildUnparented(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,filesSection:has("files")?buildHotFiles(focusGroups.activeItems,runtime.limit):void 0,workload:has("workload")?buildWorkload(focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,staleness:has("staleness")?buildStaleness(allNonTerminal,runtime.staleThresholdDays,now,runtime.limit):void 0,tests:has("tests")?buildTestHealth(focusGroups.activeItems):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
|
package/dist/sdk/query/list.d.ts
CHANGED
|
@@ -186,6 +186,8 @@ fields:string[] | null;
|
|
|
186
186
|
sorting:{
|
|
187
187
|
sort:ListSortField | "default";
|
|
188
188
|
order:ListSortOrder;
|
|
189
|
+
/** Ordered [field, direction] stages; status_registry:nonterminal_before_terminal is a synthetic grouping from the active status registry. */
|
|
190
|
+
effective_keys?:Array<[field:string,order:ListSortOrder]>;
|
|
189
191
|
};
|
|
190
192
|
/** Value that configures or reports now for this contract. */
|
|
191
193
|
now:string;
|
package/dist/sdk/query/list.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8c315632-500b-53c4-a8ed-99865c8c0246")}catch{}})();import{renderPmCommand}from"../command-line.js";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,hasActiveOnReadHooks}from"../../core/extensions/index.js";import{toItemRecord}from"../../core/item/item-record.js";import{isTerminalStatus}from"../../core/item/status.js";import{collectDependencyBlockedIds}from"../actionability.js";import{isStatusAllFilterInput,parseStatusFilterCsv}from"../../core/item/status-filter.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{parseIntegerLimit}from"./parsers.js";import{parsePriorityFilterSet,parseStringFilterSet,parseTypeFilterSet}from"./multi-value-filters.js";import{collectRuntimeFilterValues,matchesRuntimeFilters}from"../../core/schema/runtime-field-filters.js";import{hasMissingMetadataFilter,itemMatchesMissingMetadata,lifecycleClassifierFromStatusRegistry}from"../../core/governance/metadata-coverage.js";import{contentFiltersNeedBody,contentFiltersNeedCollections,hasContentFieldFilter,itemMatchesContentFilters}from"../../core/governance/content-fields.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../../core/schema/runtime-schema.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{compareTimestampStrings,matchesTimestampFilters,nowIso,resolveIsoOrRelative}from"../../core/shared/time.js";import{listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody}from"../../core/store/item-store.js";import{HEAVY_METADATA_KEYS,readItemMetadataDerivedIndexState}from"../../core/store/item-metadata-cache.js";import{queryItemMetadataIndex}from"../../core/store/item-metadata-query-index.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{LIST_FILTER_FLAG_CONTRACTS}from"../cli-contracts/flag-contracts.js";import{resolveWorkspaceRelationshipKindRegistry}from"../graph/assembly.js";import{collectHierarchyRelations,indexHierarchyRelations}from"../graph/hierarchy-integrity.js";import{createQueryFingerprint,encodeQueryCursor,resolveQueryCursorStart,selectCursorSemanticOptions}from"../pagination.js";import{BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS,listListProjectionFields}from"./projection-contracts.js";import{BRIEF_LIST_FIELDS as BRIEF_LIST_FIELDS2,DEFAULT_COMPACT_LIST_FIELDS as DEFAULT_COMPACT_LIST_FIELDS2,LIST_COMMAND_DEFAULT_PROJECTIONS,listListProjectionFields as listListProjectionFields2}from"./projection-contracts.js";const resolveMissingMetadataFilters=options=>({acMissing:options.filterAcMissing===!0,estimatesMissing:options.filterEstimatesMissing===!0,resolutionMissing:options.filterResolutionMissing===!0,metadataMissing:options.filterMetadataMissing===!0,reviewerMissing:options.filterReviewerMissing===!0,riskMissing:options.filterRiskMissing===!0,confidenceMissing:options.filterConfidenceMissing===!0,sprintMissing:options.filterSprintMissing===!0,releaseMissing:options.filterReleaseMissing===!0}),CONTENT_FIELD_FLAG_MAPPINGS=[{field:"notes",presentKey:"hasNotes",absentKey:"noNotes",presentFlag:"--has-notes",absentFlag:"--no-notes"},{field:"learnings",presentKey:"hasLearnings",absentKey:"noLearnings",presentFlag:"--has-learnings",absentFlag:"--no-learnings"},{field:"files",presentKey:"hasFiles",absentKey:"noFiles",presentFlag:"--has-files",absentFlag:"--no-files"},{field:"docs",presentKey:"hasDocs",absentKey:"noDocs",presentFlag:"--has-docs",absentFlag:"--no-docs"},{field:"tests",presentKey:"hasTests",absentKey:"noTests",presentFlag:"--has-tests",absentFlag:"--no-tests"},{field:"comments",presentKey:"hasComments",absentKey:"noComments",presentFlag:"--has-comments",absentFlag:"--no-comments"},{field:"deps",presentKey:"hasDeps",absentKey:"noDeps",presentFlag:"--has-deps",absentFlag:"--no-deps"},{field:"body",presentKey:"hasBody",absentKey:"emptyBody",presentFlag:"--has-body",absentFlag:"--empty-body"},{field:"linked_command",presentKey:"hasLinkedCommand",absentKey:"noLinkedCommand",presentFlag:"--has-linked-command",absentFlag:"--no-linked-command"}],resolveContentFieldFilters=options=>{const conflict=CONTENT_FIELD_FLAG_MAPPINGS.find(mapping=>options[mapping.presentKey]===!0&&options[mapping.absentKey]===!0);if(conflict)throw new PmCliError(`Cannot combine ${conflict.presentFlag} with ${conflict.absentFlag} for the same field.`,EXIT_CODE.USAGE);return Object.fromEntries(CONTENT_FIELD_FLAG_MAPPINGS.flatMap(mapping=>options[mapping.presentKey]===!0?[[mapping.field,"present"]]:options[mapping.absentKey]===!0?[[mapping.field,"absent"]]:[]))},LIST_SORT_FIELDS=["priority","deadline","updated_at","created_at","title","parent"],LIST_SORT_ORDER_VALUES=["asc","desc"],HEAVY_PROJECTION_FIELDS=new Set(HEAVY_METADATA_KEYS);function resolveListCompleteness(warnings,indexed,strict){const unreadableItemCount=warnings.filter(warning=>warning.startsWith("item_list_item_read_failed:")).length,unreadableDirectoryCount=warnings.filter(warning=>warning.startsWith("item_list_directory_read_failed:")).length,completeness={status:indexed?"unchecked":unreadableItemCount+unreadableDirectoryCount>0?"partial":"complete",unreadable_item_count:unreadableItemCount,unreadable_directory_count:unreadableDirectoryCount};if(strict&&completeness.status==="partial")throw new PmCliError(`List source is incomplete: ${unreadableItemCount} item document(s) and ${unreadableDirectoryCount} item directory/directories could not be read.`,EXIT_CODE.GENERIC_FAILURE,{code:"list_source_incomplete",why:"Strict list reads fail closed so agents and SDK consumers never treat an omitted item as a complete workspace.",nextSteps:["Run pm validate --check-storage-integrity to locate unreadable tracker artifacts.","Repair the reported files or align the installed decoder version, then retry."]});return completeness}function isNonEmptyRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length>0}const CONTENT_FILTER_ECHO_ENTRIES=[{key:"hasNotes",summaryKey:"has_notes"},{key:"hasLearnings",summaryKey:"has_learnings"},{key:"hasFiles",summaryKey:"has_files"},{key:"hasDocs",summaryKey:"has_docs"},{key:"hasTests",summaryKey:"has_tests"},{key:"hasComments",summaryKey:"has_comments"},{key:"hasDeps",summaryKey:"has_deps"},{key:"hasBody",summaryKey:"has_body"},{key:"hasLinkedCommand",summaryKey:"has_linked_command"},{key:"noNotes",summaryKey:"no_notes"},{key:"noLearnings",summaryKey:"no_learnings"},{key:"noFiles",summaryKey:"no_files"},{key:"noDocs",summaryKey:"no_docs"},{key:"noTests",summaryKey:"no_tests"},{key:"noComments",summaryKey:"no_comments"},{key:"noDeps",summaryKey:"no_deps"},{key:"emptyBody",summaryKey:"empty_body"},{key:"noLinkedCommand",summaryKey:"no_linked_command"}],GOVERNANCE_MISSING_ECHO_ENTRIES=[{key:"filterReviewerMissing",summaryKey:"filter_reviewer_missing"},{key:"filterRiskMissing",summaryKey:"filter_risk_missing"},{key:"filterConfidenceMissing",summaryKey:"filter_confidence_missing"},{key:"filterSprintMissing",summaryKey:"filter_sprint_missing"},{key:"filterReleaseMissing",summaryKey:"filter_release_missing"}];function applyContentFilterEcho(filters,options){for(const entry of CONTENT_FILTER_ECHO_ENTRIES)options[entry.key]===!0&&(filters[entry.summaryKey]=!0)}function applyGovernanceMissingFilterEcho(filters,options){for(const entry of GOVERNANCE_MISSING_ECHO_ENTRIES)options[entry.key]===!0&&(filters[entry.summaryKey]=!0)}function applyFilterValueEcho(filters,options,entries){for(const entry of entries){const value=options[entry.optionKey];value!==void 0&&(filters[entry.summaryKey]=entry.normalize?entry.normalize(value):value)}}function buildContentFilterEcho(options){const echo={};return applyContentFilterEcho(echo,options),echo}function buildGovernanceMissingFilterEcho(options){const echo={};return applyGovernanceMissingFilterEcho(echo,options),echo}const COMPACT_LIST_VALUE_FILTER_ECHO_ENTRIES=[{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"ids",summaryKey:"ids"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"assigneeFilter",summaryKey:"assignee_filter"},{optionKey:"parent",summaryKey:"parent"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"}],VERBOSE_LIST_VALUE_FILTER_ECHO_ENTRIES=[{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"ids",summaryKey:"ids"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"assigneeFilter",summaryKey:"assignee_filter"},{optionKey:"parent",summaryKey:"parent"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"},{optionKey:"limit",summaryKey:"limit"},{optionKey:"offset",summaryKey:"offset"},{optionKey:"includeBody",summaryKey:"include_body"},{optionKey:"compact",summaryKey:"compact"},{optionKey:"fields",summaryKey:"fields"}],VERBOSE_LIST_BOOLEAN_FILTER_ECHO_ENTRIES=[{key:"filterAcMissing",summaryKey:"filter_ac_missing"},{key:"filterEstimatesMissing",summaryKey:"filter_estimates_missing"},{key:"filterResolutionMissing",summaryKey:"filter_resolution_missing"},{key:"filterMetadataMissing",summaryKey:"filter_metadata_missing"}],LIST_RECENT_WINDOW="-7d";function buildCompactListFilterSummary(params){const{filtersStatus,options,treeEnabled,treeDepth,sortField,sortOrder,runtimeFieldFilters}=params,filters={};return filtersStatus!==null&&(filters.status=filtersStatus),options.dependencyBlocked===!0&&(filters.blocked_semantics="status_or_dependency"),applyFilterValueEcho(filters,options,COMPACT_LIST_VALUE_FILTER_ECHO_ENTRIES),applyListWindowFilterEcho(filters,options),options.filterAcMissing===!0&&(filters.filter_ac_missing=!0),options.filterEstimatesMissing===!0&&(filters.filter_estimates_missing=!0),options.filterResolutionMissing===!0&&(filters.filter_resolution_missing=!0),options.filterMetadataMissing===!0&&(filters.filter_metadata_missing=!0),applyGovernanceMissingFilterEcho(filters,options),applyContentFilterEcho(filters,options),options.limit!==void 0&&(filters.limit=options.limit),options.offset!==void 0&&(filters.offset=options.offset),options.includeBody===!0&&(filters.include_body=!0),options.fields!==void 0&&(filters.fields=options.fields),treeEnabled&&(filters.tree=!0,treeDepth!==void 0&&(filters.tree_depth=treeDepth)),sortField!==void 0&&(filters.sort=sortField,filters.order=sortOrder),isNonEmptyRecord(runtimeFieldFilters)&&(filters.runtime_filters=runtimeFieldFilters),filters}function compareDefaultSort(left,right,statusRegistry){const leftTerminal=isTerminalStatus(left.status,statusRegistry),rightTerminal=isTerminalStatus(right.status,statusRegistry);if(leftTerminal!==rightTerminal)return leftTerminal?1:-1;const byPriority=left.priority-right.priority;if(byPriority!==0)return byPriority;const byUpdated=compareTimestampStrings(right.updated_at,left.updated_at);return byUpdated!==0?byUpdated:(left.id??"").localeCompare(right.id??"")}function sortItemsDefault(items,statusRegistry){return[...items].sort((left,right)=>compareDefaultSort(left,right,statusRegistry))}function parseDeadline(raw,fieldLabel){if(raw!==void 0)return resolveIsoOrRelative(raw,new Date,fieldLabel)}function parseTimestampWindow(raw,fieldLabel){if(raw==null)return;const value=String(raw).trim();if(value.length!==0)return resolveIsoOrRelative(value,new Date,fieldLabel)}function resolveListUpdatedAfter(options){const hasUpdatedAfter=options.updatedAfter!=null&&String(options.updatedAfter).trim().length>0;if([options.today===!0,options.recent===!0,hasUpdatedAfter].filter(selected=>selected).length>1)throw new PmCliError("Choose only one updated_at window: --today, --recent, or --updated-after.",EXIT_CODE.USAGE);if(options.today===!0){const today=new Date;return today.setHours(0,0,0,0),today.toISOString()}return options.recent===!0?parseTimestampWindow(LIST_RECENT_WINDOW,"recent"):parseTimestampWindow(options.updatedAfter,"updated-after")}function applyListWindowFilterEcho(filters,options){options.today===!0&&(filters.today=!0),options.recent===!0&&(filters.recent=!0)}function parseIdsFilter(raw){if(raw==null)return;const value=String(raw).trim();if(value.length===0)throw new PmCliError("--ids requires at least one non-empty item ID",EXIT_CODE.USAGE);const ids=value.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(ids.length===0)throw new PmCliError("--ids requires at least one non-empty item ID",EXIT_CODE.USAGE);return new Set(ids)}function parseOffset(raw){if(raw===void 0)return;const normalized=String(raw).trim(),parsed=normalized.length===0?Number.NaN:Number(normalized);if(!Number.isInteger(parsed)||parsed<0)throw new PmCliError("Offset filter must be a non-negative integer",EXIT_CODE.USAGE);return parsed}function parseFieldSelectors(raw){if(raw===void 0)return;const selectors=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(selectors.length===0)throw new PmCliError("List --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);return[...new Set(selectors)]}function parseProjectionConfig(options,invokedCommand=options.projectionCommand??"list"){const compactRequested=options.compact===!0,briefRequested=options.brief===!0,fullRequested=options.full===!0,fieldSelectors=parseFieldSelectors(options.fields);if(Number(compactRequested)+Number(briefRequested)+Number(fullRequested)+ +(fieldSelectors!==void 0)>1)throw new PmCliError("List projection options are mutually exclusive. Use one of --compact, --brief, --full, or --fields.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:`pm ${invokedCommand} --brief`,suggested_retry_args:[invokedCommand,"--brief"]}});if(fullRequested)return{mode:"full",fields:[]};if(briefRequested){const sortField=parseSortField(options.sort);return{mode:"brief",fields:[...new Set([...BRIEF_LIST_FIELDS,...sortField?[sortField]:[]])]}}return compactRequested?{mode:"compact",fields:[...DEFAULT_COMPACT_LIST_FIELDS]}:fieldSelectors?{mode:"fields",fields:[...new Set(fieldSelectors.map(field=>normalizeProjectionField(field)))]}:{mode:"full",fields:[]}}function normalizeProjectionField(field){return field.startsWith("item.")?field.slice(5):field}function validateListProjectionFields(projection,runtimeMetadataKeys,invokedCommand){if(projection.mode!=="fields")return;const allowedValues=listListProjectionFields(runtimeMetadataKeys),allowed=new Set(allowedValues.map(field=>normalizeProjectionField(field))),unknown=projection.fields.filter(field=>!allowed.has(normalizeProjectionField(field)));if(unknown.length>0){const suggestedRetryArguments=[invokedCommand,"--fields",projection.fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown list --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm list --status open --fields id,title,status","pm list --fields id,title,parent,priority --limit 10","pm list --all --fields id,title,body --limit 5"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const LIST_SORT_FIELD_ALIASES=new Map([["updated","updated_at"],["update","updated_at"],["modified","updated_at"],["created","created_at"],["create","created_at"]]);function parseSortField(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase(),aliased=LIST_SORT_FIELD_ALIASES.get(normalized);if(aliased)return aliased;if(!LIST_SORT_FIELDS.includes(normalized))throw new PmCliError(`Sort field must be one of ${LIST_SORT_FIELDS.join("|")} (aliases: updated->updated_at, created->created_at)`,EXIT_CODE.USAGE);return normalized}function parseSortOrder(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(!LIST_SORT_ORDER_VALUES.includes(normalized))throw new PmCliError(`Sort order must be one of ${LIST_SORT_ORDER_VALUES.join("|")}`,EXIT_CODE.USAGE);return normalized}function parseTreeDepth(raw){return parseIntegerLimit(raw,"--tree-depth")}function parseAssigneeFilter(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(!normalized)throw new PmCliError("Assignee filter must be one of assigned|unassigned",EXIT_CODE.USAGE);if(normalized!=="assigned"&&normalized!=="unassigned")throw new PmCliError(`Invalid assignee filter "${raw}". Allowed: assigned|unassigned`,EXIT_CODE.USAGE);return normalized}function resolveStatusFilter(status,statusRegistry){return parseStatusFilterCsv(status,statusRegistry,{strict:!0})}function parseListTagFilters(raw){return parseStringFilterSet(raw,{label:"--tag",normalize:tag=>tag.toLowerCase()})}function appendUnknownTagWarning(items,rawTags,warnings){const requestedTags=parseListTagFilters(rawTags);if(requestedTags===void 0)return;const knownTags=new Set(items.flatMap(item=>item.tags.map(tag=>tag.trim().toLowerCase()))),unknownTags=[...requestedTags].filter(tag=>!knownTags.has(tag));unknownTags.length>0&&warnings.push(`unknown_tags:${unknownTags.join(",")}`)}function assertListAssigneeFilters(assigneeFilter,assigneeModeFilter){if(assigneeFilter&&[...assigneeFilter].some(value=>value.toLowerCase()==="none"||value.toLowerCase()==="null"))throw new PmCliError('--assignee no longer accepts "none" or "null". Use --assignee-filter unassigned.',EXIT_CODE.USAGE);if(assigneeFilter!==void 0&&assigneeModeFilter==="unassigned")throw new PmCliError("Cannot combine --assignee with --assignee-filter unassigned",EXIT_CODE.USAGE)}function resolveListFilterSet(status,options,typeRegistry,statusRegistry){const assigneeFilter=parseStringFilterSet(options.assignee,{label:"--assignee"}),assigneeModeFilter=parseAssigneeFilter(options.assigneeFilter);assertListAssigneeFilters(assigneeFilter,assigneeModeFilter);const missingMetadataFilters=resolveMissingMetadataFilters(options),contentFieldFilters=resolveContentFieldFilters(options);return{idsFilter:parseIdsFilter(options.ids),statusSet:status&&status.length>0?new Set(status):void 0,excludeTerminal:options.excludeTerminal===!0,typeFilter:parseTypeFilterSet(options.type,typeRegistry),tagFilters:parseListTagFilters(options.tag),priorityFilter:parsePriorityFilterSet(options.priority),deadlineBefore:parseDeadline(options.deadlineBefore,"deadline-before"),deadlineAfter:parseDeadline(options.deadlineAfter,"deadline-after"),updatedAfter:resolveListUpdatedAfter(options),updatedBefore:parseTimestampWindow(options.updatedBefore,"updated-before"),createdAfter:parseTimestampWindow(options.createdAfter,"created-after"),createdBefore:parseTimestampWindow(options.createdBefore,"created-before"),assigneeFilter,assigneeModeFilter,parentFilter:options.parent?.trim(),treeEnabled:options.tree===!0,sprintFilter:parseStringFilterSet(options.sprint,{label:"--sprint"}),releaseFilter:parseStringFilterSet(options.release,{label:"--release"}),missingMetadataFilters,missingMetadataActive:hasMissingMetadataFilter(missingMetadataFilters),lifecycleClassifier:lifecycleClassifierFromStatusRegistry(statusRegistry),contentFieldFilters,contentFiltersActive:hasContentFieldFilter(contentFieldFilters)}}function matchesListIdentityFilters(item,filters,statusRegistry){return filters.idsFilter&&!filters.idsFilter.has(item.id)||filters.statusSet&&!filters.statusSet.has(item.status)||filters.excludeTerminal&&isTerminalStatus(item.status,statusRegistry)||filters.typeFilter&&!filters.typeFilter.has(item.type)||filters.tagFilters&&![...filters.tagFilters].some(tag=>(item.tags??[]).some(candidate=>candidate.trim().toLowerCase()===tag))?!1:filters.priorityFilter===void 0||filters.priorityFilter.has(item.priority)}function matchesListDateFilters(item,filters){return matchesTimestampFilters(item,filters)}function matchesListAssigneeFilterSet(item,filters){return filters.assigneeModeFilter==="assigned"&&!item.assignee||filters.assigneeModeFilter==="unassigned"&&item.assignee?!1:filters.assigneeFilter===void 0||item.assignee!==void 0&&filters.assigneeFilter.has(item.assignee)}function matchesListScopeFilters(item,filters,parentsByChild){const scalarParent=item.parent?.trim().toLowerCase(),logicalParentIds=[...new Set([...parentsByChild?.get(item.id.trim().toLowerCase())??[],...scalarParent?[scalarParent]:[]])];return filters.parentFilter!==void 0&&!filters.treeEnabled&&!logicalParentIds.includes(filters.parentFilter.trim().toLowerCase())||filters.sprintFilter!==void 0&&(item.sprint===void 0||!filters.sprintFilter.has(item.sprint))?!1:filters.releaseFilter===void 0||item.release!==void 0&&filters.releaseFilter.has(item.release)}function matchesListFilterSet(item,filters,statusRegistry,runtimeFieldFilters,parentsByChild){return!(!matchesListIdentityFilters(item,filters,statusRegistry)||!matchesListDateFilters(item,filters)||!matchesListAssigneeFilterSet(item,filters)||!matchesListScopeFilters(item,filters,parentsByChild)||filters.missingMetadataActive&&!itemMatchesMissingMetadata(item,filters.missingMetadataFilters,filters.lifecycleClassifier)||filters.contentFiltersActive&&!itemMatchesContentFilters(item,filters.contentFieldFilters)||!matchesRuntimeFilters(item,runtimeFieldFilters))}function applyFilters(items,status,options,typeRegistry,statusRegistry,runtimeFieldFilters,parentsByChild){const filters=resolveListFilterSet(status,options,typeRegistry,statusRegistry);return items.filter(item=>matchesListFilterSet(item,filters,statusRegistry,runtimeFieldFilters,parentsByChild))}function trimNonEmpty(value){if(typeof value!="string")return;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function withTreeMetadata(item,depth,childCount,parentId){const itemRecord=toItemRecord(item),title=typeof itemRecord.title=="string"?itemRecord.title:"",parent=parentId??trimNonEmpty(typeof itemRecord.parent=="string"?itemRecord.parent:void 0)??null;return{...item,tree_depth:depth,tree_parent:parent,tree_children:childCount,tree_title:`${" ".repeat(depth)}${title}`}}function buildListTreeIndexes(sortedItems,hierarchyIndexes){const byId=new Map,childrenByParent=new Map;for(const item of sortedItems){const itemId=item.id.trim().toLowerCase();byId.set(itemId,item);const parentIds=hierarchyIndexes?hierarchyIndexes.parents_by_child.get(itemId)??[]:[trimNonEmpty(item.parent)?.toLowerCase()].filter(value=>value!==void 0);for(const parentId of parentIds){const children=childrenByParent.get(parentId)??[];children.push(item),childrenByParent.set(parentId,children)}}return{byId,childrenByParent}}function resolveListTreeRoots(sortedItems,parentRoot,byId,childrenByParent,hierarchyIndexes){return parentRoot?[...childrenByParent.get(parentRoot.toLowerCase())??[]]:sortedItems.filter(item=>(hierarchyIndexes?hierarchyIndexes.parents_by_child.get(item.id.trim().toLowerCase())??[]:[trimNonEmpty(item.parent)?.toLowerCase()].filter(value=>value!==void 0)).every(parentId=>!byId.has(parentId)))}function orderItemsAsTree(sortedItems,parentRoot,maxDepth,hierarchyIndexes,completeItems=sortedItems){const{byId,childrenByParent}=buildListTreeIndexes(sortedItems,hierarchyIndexes),roots=resolveListTreeRoots(sortedItems,parentRoot,byId,childrenByParent,hierarchyIndexes),ordered=[],visited=new Set,canonicalIdByLowercase=new Map(completeItems.map(item=>[item.id.trim().toLowerCase(),item.id.trim()])),pending=[...roots].reverse().map(node=>({node,depth:0,parentId:parentRoot===void 0?void 0:canonicalIdByLowercase.get(parentRoot.trim().toLowerCase())??parentRoot.trim()}));for(;pending.length>0;){const{node,depth,parentId}=pending.pop(),nodeId=node.id.trim().toLowerCase();if(visited.has(nodeId))continue;visited.add(nodeId);const children=childrenByParent.get(nodeId)??[];if(ordered.push(withTreeMetadata(node,depth,children.length,parentId)),!(maxDepth!==void 0&&depth>=maxDepth))for(const child of[...children].reverse())pending.push({node:child,depth:depth+1,parentId:canonicalIdByLowercase.get(nodeId)})}if(parentRoot===void 0&&maxDepth===void 0)for(const item of sortedItems){const itemId=item.id.trim().toLowerCase();visited.has(itemId)||(visited.add(itemId),ordered.push(withTreeMetadata(item,0,childrenByParent.get(itemId)?.length??0)))}return ordered}function compareNullableString(left,right){return left===right?0:left===null?1:right===null?-1:left.localeCompare(right)}function compareNullableTimestamp(left,right){return left===right?0:left===null?1:right===null?-1:compareTimestampStrings(left,right)}function compareBySortField(left,right,field){switch(field){case"priority":return left.priority-right.priority;case"deadline":return compareNullableTimestamp(left.deadline??null,right.deadline??null);case"updated_at":return compareTimestampStrings(left.updated_at,right.updated_at);case"created_at":return compareTimestampStrings(left.created_at,right.created_at);case"title":return(left.title??"").localeCompare(right.title??"");case"parent":return compareNullableString(left.parent??null,right.parent??null);default:return 0}}function sortItems(items,sortField,sortOrder,statusRegistry){return sortField?[...items].sort((left,right)=>{const byField=compareBySortField(left,right,sortField);if(byField!==0)return sortOrder==="desc"?-byField:byField;const fallback=compareDefaultSort(left,right,statusRegistry);return sortOrder==="desc"?-fallback:fallback}):sortItemsDefault(items,statusRegistry)}function readListFieldValue(item,field,treeMode=!1){const normalized=normalizeProjectionField(field.trim());if(normalized.length===0)return null;const itemRecord=toItemRecord(item);return treeMode&&normalized==="title"&&typeof itemRecord.tree_title=="string"?itemRecord.tree_title:Object.prototype.hasOwnProperty.call(itemRecord,normalized)?itemRecord[normalized]??null:null}function projectListItems(items,projection,treeMode=!1){return projection.mode==="full"?items:items.map(item=>{const projected={};for(const field of projection.fields)projected[field]=readListFieldValue(item,field,treeMode);return projected})}function runtimeMetadataKeysForProjection(definitions){const keys=[];for(const field of definitions)keys.push(field.metadata_key);return keys}function resolveListPageLimit(options,totalRows){const explicitLimit=parseIntegerLimit(options.limit);if(explicitLimit!==void 0)return explicitLimit;if(options.noTruncate!==!0)return totalRows>=1e4?20:void 0}function resolveListPageStart(ordered,options,cursorFingerprint){return options.after===void 0?parseOffset(options.offset)??0:resolveQueryCursorStart(ordered,options.after,cursorFingerprint,item=>item.id)}function buildListPageExtras(limit,hasMore,nextCursor){return{...limit!==void 0?{applied_limit:limit}:{},has_more:hasMore,truncated:hasMore,next_cursor:nextCursor??null}}async function resolveListRuntimeContext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),runtimeFieldRegistry=resolveRuntimeFieldRegistry(settings.schema),invokedCommand=options.projectionCommand??"list",projection=parseProjectionConfig(options,invokedCommand);return validateListProjectionFields(projection,runtimeMetadataKeysForProjection(runtimeFieldRegistry.definitions),invokedCommand),{pmRoot,settings,statusRegistry,runtimeFieldFilters:collectRuntimeFilterValues(options,runtimeFieldRegistry,"list"),typeRegistry:resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),projection}}async function loadListItems(options,runtime,listWarnings){const projectionNeedsBody=runtime.projection.fields.some(field=>normalizeProjectionField(field)==="body"),projectionNeedsCollections=runtime.projection.mode==="full"||runtime.projection.fields.some(field=>HEAVY_PROJECTION_FIELDS.has(normalizeProjectionField(field))),contentFieldFilters=resolveContentFieldFilters(options),contentNeedsCollections=contentFiltersNeedCollections(contentFieldFilters),contentNeedsBody=contentFiltersNeedBody(contentFieldFilters);return options.includeBody||projectionNeedsBody||contentNeedsBody?await listAllItemMetadataWithBody(runtime.pmRoot,runtime.settings.item_format,runtime.typeRegistry.type_to_folder,listWarnings,runtime.settings.schema):projectionNeedsCollections||contentNeedsCollections?await listAllItemMetadata(runtime.pmRoot,runtime.settings.item_format,runtime.typeRegistry.type_to_folder,listWarnings,runtime.settings.schema):await listAllItemMetadataLight(runtime.pmRoot,runtime.settings.item_format,runtime.typeRegistry.type_to_folder,listWarnings,runtime.settings.schema)}function resolveListOrderingOptions(options){const sortField=parseSortField(options.sort),sortOrder=parseSortOrder(options.order)??"asc",treeEnabled=options.tree===!0;if(!treeEnabled&&options.treeDepth!==void 0)throw new PmCliError("List --tree-depth requires --tree",EXIT_CODE.USAGE);if(!sortField&&options.order!==void 0)throw new PmCliError("List --order requires --sort",EXIT_CODE.USAGE);return{sortField,sortOrder,treeEnabled,treeDepth:treeEnabled?parseTreeDepth(options.treeDepth):void 0,parentRoot:treeEnabled?trimNonEmpty(options.parent):void 0}}function resolveListStatusSelection(status,options,statusRegistry){const explicitStatus=resolveStatusFilter(options.status,statusRegistry);let lifecycleStatus;options.lifecycleBucket==="in_progress"?lifecycleStatus=[statusRegistry.in_progress_status]:options.lifecycleBucket==="open"&&(lifecycleStatus=[...statusRegistry.active_statuses].filter(entry=>entry!==statusRegistry.in_progress_status).sort((left,right)=>left.localeCompare(right)));const resolvedStatus=explicitStatus??lifecycleStatus??resolveStatusFilter(status,statusRegistry),explicitAllStatuses=isStatusAllFilterInput(options.status),effectiveOptions=explicitStatus||explicitAllStatuses?{...options,excludeTerminal:!1}:options;let filtersStatus="all";return explicitAllStatuses?filtersStatus="all":explicitStatus!==void 0?filtersStatus=explicitStatus.length===1?explicitStatus[0]:explicitStatus:options.lifecycleBucket!==void 0?filtersStatus=options.lifecycleBucket:resolvedStatus!==void 0?filtersStatus=resolvedStatus.length===1?resolvedStatus[0]:resolvedStatus:effectiveOptions.excludeTerminal===!0&&(filtersStatus=null),{resolvedStatus,explicitAllStatuses,effectiveOptions,filtersStatus}}function pageAndProjectListItems(ordered,options,projection,treeEnabled,cursorFingerprint){if(options.after!==void 0&&options.offset!==void 0)throw new PmCliError("List --after cannot be combined with --offset.",EXIT_CODE.USAGE);const limit=resolveListPageLimit(options,ordered.length),offset=resolveListPageStart(ordered,options,cursorFingerprint),limited=limit===void 0?ordered.slice(offset):ordered.slice(offset,offset+limit),projected=projectListItems(limited,projection,treeEnabled),totalMatched=ordered.length,hasMore=limited.length>0&&offset+limited.length<totalMatched,nextCursor=hasMore&&limited.length>0?encodeQueryCursor(cursorFingerprint,limited[limited.length-1].id,offset+limited.length-1):void 0;return{projected,totalMatched,pageExtras:buildListPageExtras(limit,hasMore,nextCursor)}}function buildListCursorFingerprint(status,options,ordering,pmRoot){return createQueryFingerprint("list",{pmRoot,status,options:selectCursorSemanticOptions(options,LIST_FILTER_FLAG_CONTRACTS),sort:ordering.sortField??"default",order:ordering.sortOrder,tree:ordering.treeEnabled,tree_depth:ordering.treeDepth??null})}async function tryLoadIndexedListPage(params){const{options,runtime,statusSelection,ordering}=params,supportedOptionKeys=new Set(["status","limit","offset","compact","brief","full","fields","format","stream","includeBody","excludeTerminal","dependencyBlocked","lifecycleBucket","noTruncate","projectionCommand","truncate","notes","learnings","files","docs","tests","comments","deps","linkedCommand"]),projectionNeedsHeavyData=[runtime.projection.mode==="full",runtime.projection.fields.some(field=>{const normalized=normalizeProjectionField(field);return normalized==="body"||HEAVY_PROJECTION_FIELDS.has(normalized)})].includes(!0);if([options.limit===void 0,options.after!==void 0,options.noTruncate===!0,options.includeBody===!0,options.dependencyBlocked===!0,options.strictRead===!0,ordering.treeEnabled,ordering.sortField!==void 0,projectionNeedsHeavyData,hasActiveOnReadHooks(),Object.keys(runtime.runtimeFieldFilters).length>0,Object.entries(options).some(([key,value])=>value!==void 0&&!supportedOptionKeys.has(key))].includes(!0))return null;const indexState=await readItemMetadataDerivedIndexState(runtime.pmRoot,[...new Set(Object.values(runtime.typeRegistry.type_to_folder))]);if(!indexState)return null;const limit=parseIntegerLimit(options.limit),offset=parseOffset(options.offset)??0,indexed=await queryItemMetadataIndex({pmRoot:runtime.pmRoot,expectedSourceCursor:indexState.source_cursor,query:{statuses:statusSelection.resolvedStatus,excludeStatuses:statusSelection.resolvedStatus===void 0&&statusSelection.effectiveOptions.excludeTerminal===!0?[...runtime.statusRegistry.terminal_statuses]:void 0,terminalStatuses:[...runtime.statusRegistry.terminal_statuses],limit,offset}});if(!indexed)return null;const hasMore=indexed.items.length>0&&offset+indexed.items.length<indexed.total,nextCursor=hasMore?encodeQueryCursor(buildListCursorFingerprint(statusSelection.filtersStatus,options,ordering,runtime.pmRoot),indexed.items.at(-1).id,offset+indexed.items.length-1):void 0;return{projected:projectListItems(indexed.items,runtime.projection,!1),totalMatched:indexed.total,pageExtras:buildListPageExtras(limit,hasMore,nextCursor)}}function buildVerboseListFilters(params){const{filtersStatus,options,noTruncate,treeEnabled,treeDepth,sortField,sortOrder,runtimeFieldFilters}=params,filters={};filtersStatus!==null&&(filters.status=filtersStatus),options.dependencyBlocked===!0&&(filters.blocked_semantics="status_or_dependency");const optionRecord=options;for(const entry of VERBOSE_LIST_VALUE_FILTER_ECHO_ENTRIES){const value=optionRecord[entry.optionKey];value!=null&&(filters[entry.summaryKey]=value)}for(const entry of VERBOSE_LIST_BOOLEAN_FILTER_ECHO_ENTRIES)optionRecord[entry.key]===!0&&(filters[entry.summaryKey]=!0);return Object.assign(filters,buildGovernanceMissingFilterEcho(options),buildContentFilterEcho(options)),applyListWindowFilterEcho(filters,options),noTruncate&&(filters.no_truncate=!0),options.strictRead===!0&&(filters.strict_read=!0),treeEnabled&&(filters.tree=!0,treeDepth!==void 0&&(filters.tree_depth=treeDepth)),sortField!==void 0&&(filters.sort=sortField,filters.order=sortOrder),filters.runtime_filters=runtimeFieldFilters,filters}async function runList(status,options,global2){const runtime=await resolveListRuntimeContext(options,global2),listWarnings=[],ordering=resolveListOrderingOptions(options),statusSelection=resolveListStatusSelection(status,options,runtime.statusRegistry),noTruncate=options.noTruncate===!0,indexedPage=await tryLoadIndexedListPage({options,runtime,statusSelection,ordering});let page=indexedPage;if(!page){const items=await loadListItems(options,runtime,listWarnings),hierarchyIndexes=ordering.treeEnabled||trimNonEmpty(options.parent)!==void 0?indexHierarchyRelations(collectHierarchyRelations(items,resolveWorkspaceRelationshipKindRegistry())):void 0;appendUnknownTagWarning(items,options.tag,listWarnings);const filtered=applyFilters(items,statusSelection.resolvedStatus,statusSelection.effectiveOptions,runtime.typeRegistry,runtime.statusRegistry,runtime.runtimeFieldFilters,hierarchyIndexes?.parents_by_child),scoped=options.dependencyBlocked===!0?(()=>{const blockedIds=collectDependencyBlockedIds(items,runtime.statusRegistry);return filtered.filter(item=>blockedIds.has(item.id.trim().toLowerCase()))})():filtered,sorted=sortItems(scoped,ordering.sortField,ordering.sortOrder,runtime.statusRegistry),ordered=ordering.treeEnabled?orderItemsAsTree(sorted,ordering.parentRoot,ordering.treeDepth,hierarchyIndexes,items):sorted;page=pageAndProjectListItems(ordered,options,runtime.projection,ordering.treeEnabled,buildListCursorFingerprint(statusSelection.filtersStatus,options,ordering,runtime.pmRoot))}const now=nowIso(),warnings=[...new Set(listWarnings)].sort((left,right)=>left.localeCompare(right)),completeness=resolveListCompleteness(warnings,indexedPage!==null,options.strictRead===!0),projectionFields=runtime.projection.mode==="full"?null:[...runtime.projection.fields];if(runtime.projection.mode==="compact"&&options.compact===!0){const compactFilters=buildCompactListFilterSummary({filtersStatus:statusSelection.filtersStatus,options,treeEnabled:ordering.treeEnabled,treeDepth:ordering.treeDepth,sortField:ordering.sortField,sortOrder:ordering.sortOrder,runtimeFieldFilters:runtime.runtimeFieldFilters});return{items:page.projected,count:page.projected.length,total:page.totalMatched,...page.pageExtras,completeness,filters:compactFilters,projection:{mode:"compact",fields:projectionFields},...warnings.length>0?{warnings}:{}}}return{items:page.projected,count:page.projected.length,total:page.totalMatched,...page.pageExtras,completeness,filters:buildVerboseListFilters({filtersStatus:statusSelection.filtersStatus,options,noTruncate,treeEnabled:ordering.treeEnabled,treeDepth:ordering.treeDepth,sortField:ordering.sortField,sortOrder:ordering.sortOrder,runtimeFieldFilters:runtime.runtimeFieldFilters}),projection:{mode:runtime.projection.mode,fields:projectionFields},sorting:{sort:ordering.sortField??"default",order:ordering.sortField?ordering.sortOrder:"asc"},now,...warnings.length>0?{warnings}:{}}}const _testOnly={applyFilters,buildCompactListFilterSummary,buildContentFilterEcho,buildGovernanceMissingFilterEcho,resolveContentFieldFilters,resolveMissingMetadataFilters,compareBySortField,compareDefaultSort,compareNullableString,compareNullableTimestamp,normalizeProjectionField,parseAssigneeFilter,parseFieldSelectors,parseIdsFilter,parseOffset,parseProjectionConfig,resolveListUpdatedAfter,resolveListPageLimit,parseSortField,parseSortOrder,orderItemsAsTree,projectListItems,readListFieldValue,runtimeMetadataKeysForProjection,sortItems,trimNonEmpty,withTreeMetadata};export{BRIEF_LIST_FIELDS2 as BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS2 as DEFAULT_COMPACT_LIST_FIELDS,LIST_COMMAND_DEFAULT_PROJECTIONS,LIST_SORT_FIELDS,LIST_SORT_ORDER_VALUES,_testOnly,applyFilterValueEcho,buildContentFilterEcho,buildGovernanceMissingFilterEcho,listListProjectionFields2 as listListProjectionFields,resolveContentFieldFilters,resolveMissingMetadataFilters,runList};
|
|
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};
|
|
2
2
|
//# sourceMappingURL=list.js.map
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
export type ListProjectionMode = "full" | "compact" | "brief" | "fields";
|
|
3
3
|
/** Stable field order for the compact list projection. */
|
|
4
4
|
export declare const DEFAULT_COMPACT_LIST_FIELDS:readonly ["id","title","status","type","priority","parent","updated_at"];
|
|
5
|
-
/** Stable field order for the
|
|
5
|
+
/** Stable base field order for brief lists; the query appends its effective leading sort field. */
|
|
6
6
|
export declare const BRIEF_LIST_FIELDS:readonly ["id","status","type","title"];
|
|
7
7
|
/** Machine-readable default projection contract for every list command. */
|
|
8
8
|
export declare const LIST_COMMAND_DEFAULT_PROJECTIONS:{
|
|
@@ -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]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="dc76b081-02dc-5b09-ab40-cd57c733b3ad")}catch{}})();import{ITEM_METADATA_KEY_ORDER}from"../../core/shared/item-metadata-contract.js";const DEFAULT_COMPACT_LIST_FIELDS=["id","title","status","type","priority","parent","updated_at"],BRIEF_LIST_FIELDS=["id","status","type","title"],LIST_COMMAND_DEFAULT_PROJECTIONS={list:"brief","list-all":"full","list-draft":"full","list-open":"brief","list-in-progress":"brief","list-blocked":"brief","list-closed":"brief","list-canceled":"full"},TREE_METADATA_FIELDS=["tree_depth","tree_parent","tree_children","tree_title"];function listListProjectionFields(runtimeMetadataKeys=[]){return[...new Set([...ITEM_METADATA_KEY_ORDER,"body",...TREE_METADATA_FIELDS,...runtimeMetadataKeys])].flatMap(field=>[field,`item.${field}`]).sort()}const GET_DEPTH_VALUES=["brief","standard","deep"],GET_ROOT_PROJECTION_FIELDS=["body","linked","claim_state","children","schedule","blockers"],GET_LINKED_PROJECTION_FIELDS=["linked.files","linked.tests","linked.docs"],GET_CLAIM_STATE_PROJECTION_FIELDS=["claim_state.claimed","claim_state.assignee","claim_state.last_claim","claim_state.last_release"],GET_SCHEDULE_PROJECTION_FIELDS=["schedule.deadline","schedule.start_at","schedule.end_at","schedule.location","schedule.reminders","schedule.events"];function listGetProjectionFields(runtimeMetadataKeys=[]){return[...[...new Set([...ITEM_METADATA_KEY_ORDER,...runtimeMetadataKeys,"notes_count","tests_count","collection_counts"])].flatMap(field=>[field,`item.${field}`]),...GET_ROOT_PROJECTION_FIELDS,...GET_LINKED_PROJECTION_FIELDS,...GET_CLAIM_STATE_PROJECTION_FIELDS,...GET_SCHEDULE_PROJECTION_FIELDS].sort()}const DEFAULT_COMPACT_SEARCH_FIELDS=["id","title","status","type","priority","updated_at","score","matched_fields"],SEARCH_HIT_FIELD_KEYS=["score","matched_fields","highlights"],SEARCH_ITEM_FIELD_KEYS=["id","title","description","type","status","priority","tags","created_at","updated_at","deadline","assignee","author","estimated_minutes","acceptance_criteria","dependencies","comments","notes","learnings","reminders","events","files","tests","docs","close_reason","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result","affected_version","fixed_version","component","regression","customer_impact","definition_of_ready","order","rank","goal","objective","value","impact","outcome","why_now","plan"];function listSearchProjectionFields(runtimeMetadataKeys=[]){const runtimeKeys=[...new Set(runtimeMetadataKeys)];return[...SEARCH_HIT_FIELD_KEYS,...SEARCH_ITEM_FIELD_KEYS,...SEARCH_ITEM_FIELD_KEYS.map(field=>`item.${field}`),...runtimeKeys,...runtimeKeys.map(field=>`item.${field}`)].sort()}export{BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS,DEFAULT_COMPACT_SEARCH_FIELDS,GET_DEPTH_VALUES,LIST_COMMAND_DEFAULT_PROJECTIONS,SEARCH_HIT_FIELD_KEYS,SEARCH_ITEM_FIELD_KEYS,listGetProjectionFields,listListProjectionFields,listSearchProjectionFields};
|
|
2
2
|
//# sourceMappingURL=projection-contracts.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="60255cfe-4293-5b4c-babd-278dfe5b6e2c")}catch{}})();import{createQueryFingerprint,encodeQueryCursor,resolveQueryCursorStart}from"./pagination.js";import{createRelationshipKindRegistry}from"./relationships.js";const DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET=1200,RELATIONSHIP_CONTEXT_ROLE_PRIORITY=["prerequisite","dependent","ancestor","descendant","provenance","related"],tokenEncoder=new TextEncoder;function positiveInteger(value,fallback,field){const resolved=value??fallback;if(!Number.isInteger(resolved)||resolved<1)throw new TypeError(`Relationship context ${field} must be positive`);return resolved}function estimateTokens(value){return Math.max(1,Math.ceil(tokenEncoder.encode(JSON.stringify(value)).byteLength/4))}function explainDirectEdge(edge,node,registry){const definition=registry.resolve(edge.kind);if(definition?.ordering){const before=(definition.precedence??"source_before_target")==="source_before_target"?edge.source:edge.target;return node===before?"prerequisite":"dependent"}if(definition?.hierarchy){const parent=definition.hierarchyDirection==="source_parent"?edge.source:edge.target;return node===parent?"ancestor":"descendant"}return edge.kind==="discovered_from"||edge.kind==="incident_from"?"provenance":"related"}function directReasons(rootEdges,root,node,registry){const reasons=rootEdges.filter(edge=>edge.source===root&&edge.target===node||edge.target===root&&edge.source===node).map(edge=>explainDirectEdge(edge,node,registry));return[...new Set(reasons)].sort()}function primaryRole(roles){return RELATIONSHIP_CONTEXT_ROLE_PRIORITY.find(role=>roles.includes(role))}function discoverNodes(graph,root,registry,options){const direction=options.direction??"both",maxDepth=options.maxDepth??3;if(!Number.isInteger(maxDepth)||maxDepth<0)throw new TypeError("Relationship context maxDepth must be non-negative");const seen=new Set([root]),queue=[{id:root,distance:0}],rows=[];let inspectedEdges=0,depthTruncated=!1;for(let index=0;index<queue.length;index+=1){options.signal?.throwIfAborted();const current=queue[index];if(current.distance>=maxDepth&&depthTruncated)continue;const adjacent=graph.neighborEdges(current.id,{direction,kinds:options.kinds,signal:options.signal});if(inspectedEdges+=adjacent.meta.inspectedEdges,current.distance>=maxDepth){adjacent.value.some(row=>!seen.has(row.id))&&(depthTruncated=!0);continue}for(const{id,edge}of adjacent.value){if(seen.has(id))continue;seen.add(id);const row={id,distance:current.distance+1,via:current.id,role:explainDirectEdge(edge,id,registry)};rows.push(row),queue.push(row)}}return rows.sort((left,right)=>left.distance-right.distance||left.id.localeCompare(right.id)),{rows,visitedNodes:queue.length,inspectedEdges,depthTruncated}}function summarizeDirectEdges(graph,root,registry,options){const directEdges={prerequisite:0,dependent:0,ancestor:0,descendant:0,provenance:0,related:0},rows=graph.neighborEdges(root,{direction:options.direction??"both",kinds:options.kinds,signal:options.signal}).value;for(const{id,edge}of rows)directEdges[explainDirectEdge(edge,id,registry)]+=1;return{directEdges,directTotal:rows.length,rootEdges:rows.map(({edge})=>edge)}}function selectContextNodes(params){const nodes=[];let usedTokens=params.initialTokens;for(const candidate of params.candidates){if(nodes.length>=params.nodeLimit)break;const direct=candidate.distance===1?directReasons(params.rootEdges,params.rootId,candidate.id,params.registry):[],node={...params.details.get(candidate.id)??{id:candidate.id},distance:candidate.distance,role:direct.length>0?primaryRole(direct):candidate.role,via:candidate.via,reasons:direct.length>0?direct:[`${candidate.role} via ${candidate.via} (depth ${candidate.distance})`]},cost=estimateTokens(node);if(usedTokens+cost>params.tokenBudget)break;nodes.push(node),usedTokens+=cost}if(params.candidates.length>0&&nodes.length===0)throw new TypeError("Relationship context tokenBudget cannot fit one node");return{nodes,usedTokens}}function selectContextEdges(params){const kinds=params.options.kinds?new Set(params.options.kinds.map(kind=>params.registry.require(kind).kind)):void 0,candidates=params.graph.edges().filter(edge=>{if(!params.included.has(edge.source)||!params.included.has(edge.target))return!1;if(kinds===void 0||kinds.has(edge.kind))return!0;const inverse=params.registry.resolve(edge.kind)?.inverse;return inverse!==void 0&&kinds.has(inverse)}),edges=[];let usedTokens=params.initialTokens;for(const edge of candidates){if(edges.length>=params.edgeLimit)break;const cost=estimateTokens(edge);if(usedTokens+cost>params.tokenBudget)break;edges.push(edge),usedTokens+=cost}return{edges,usedTokens,candidateCount:candidates.length}}function buildRelationshipContext(graph,rootId,details,options={}){if(!graph.nodes().includes(rootId))throw new TypeError(`Relationship node not found: ${rootId}`);const nodeLimit=positiveInteger(options.nodeLimit,20,"nodeLimit"),edgeLimit=positiveInteger(options.edgeLimit,40,"edgeLimit"),tokenBudget=positiveInteger(options.tokenBudget,DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,"tokenBudget"),registry=options.registry??createRelationshipKindRegistry(),byId=new Map(details.map(detail=>[detail.id,detail])),rootDetails=byId.get(rootId)??{id:rootId},{evidence:rootEvidence=[],...root}=rootDetails,evidence=[...rootEvidence],discovery=discoverNodes(graph,rootId,registry,options),{rootEdges,...directSummary}=summarizeDirectEdges(graph,rootId,registry,options),fingerprint=createQueryFingerprint("relationship-context",{rootId,direction:options.direction??"both",kinds:[...options.kinds??[]].sort(),maxDepth:options.maxDepth??3}),pageStart=resolveQueryCursorStart(discovery.rows,options.cursor,fingerprint,({id})=>id,"--cursor"),candidates=discovery.rows.slice(pageStart),initialTokens=estimateTokens(root)+estimateTokens(evidence);if(initialTokens>tokenBudget)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");const nodeSelection=selectContextNodes({candidates,details:byId,rootEdges,rootId,registry,nodeLimit,tokenBudget,initialTokens}),{nodes}=nodeSelection,included=new Set([rootId,...nodes.map(({id})=>id)]),edgeSelection=selectContextEdges({graph,included,options,registry,edgeLimit,tokenBudget,initialTokens:nodeSelection.usedTokens}),{edges,usedTokens}=edgeSelection,consumed=pageStart+nodes.length,hasMoreNodes=consumed<discovery.rows.length,lastNode=nodes.at(-1),omittedEdges=edgeSelection.candidateCount-edges.length,truncated=discovery.depthTruncated||hasMoreNodes||omittedEdges>0,summary={rootId,...root.status===void 0?{}:{rootStatus:root.status},...directSummary,discoveredNodes:discovery.rows.length,returnedNodes:nodes.length,returnedEdges:edges.length,omittedNodes:discovery.rows.length-consumed,omittedEdges,evidenceCount:evidence.length,hasMore:hasMoreNodes};return{root,summary,nodes,edges,evidence,meta:{exact:!0,truncated,completeness:truncated?"truncated":"complete",nodeLimit,edgeLimit,tokenBudget,usedTokens,visitedNodes:discovery.visitedNodes,inspectedEdges:discovery.inspectedEdges,omittedNodes:discovery.rows.length-consumed,omittedEdges,...hasMoreNodes&&lastNode?{nextCursor:encodeQueryCursor(fingerprint,lastNode.id,consumed-1)}:{}}}}export{DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,buildRelationshipContext};
|
|
2
2
|
//# sourceMappingURL=relationship-context.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/** Validate only native create/update clients; MCP retains its declared transport admission. */
|
|
2
|
+
export declare function assertNativeMutationOptions(action:"create" | "update",args:Record<string,unknown>,options:Record<string,unknown>,pmRoot:string | undefined,hoistedKeys:readonly string[]):Promise<void>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d19ff816-7570-5e8a-a4de-ad2ca48f0df0")}catch{}})();import{readRuntimeFieldOptionValue}from"../../core/schema/runtime-field-values.js";import{resolveRuntimeFieldRegistry,runtimeFieldOptionTarget}from"../../core/schema/runtime-schema.js";import{readSettings}from"../../core/store/settings.js";import{resolvePmRoot}from"../../core/store/paths.js";import{PmCliError}from"../../core/shared/errors.js";import{levenshteinDistanceWithinLimit}from"../../core/shared/levenshtein.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS}from"../cli-contracts/commander-mutation-options.js";import{CREATE_FLAG_CONTRACTS,UPDATE_FLAG_CONTRACTS}from"../cli-contracts/flag-contracts.js";import{isMcpMutationTransportInput,isRuntimeRecord}from"../runtime-input.js";function refuseKey(action,key,allowed,misplaced=!1){const suggestion=[...allowed].map(candidate=>({candidate,distance:levenshteinDistanceWithinLimit(key,candidate,3)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0]?.candidate,correction=misplaced?`Put mutation fields under options (options.${key}).`:suggestion?`Did you mean "${suggestion}"?`:"Use the declared command options or the field option for registered item fields.";throw new PmCliError(`Unknown ${action} ${misplaced?"argument":"option"} "${key}". ${correction} No changes were made.`,2,{code:"invalid_argument_value",reason:"unknown_mutation_option",changed:!1,field:key,required:correction,nextSteps:[correction]})}async function assertNativeMutationOptions(action,args,options,pmRoot,hoistedKeys){if(isMcpMutationTransportInput(args))return;const contracts=action==="create"?CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,flagKeys=(action==="create"?CREATE_FLAG_CONTRACTS:UPDATE_FLAG_CONTRACTS).map(({flag})=>flag.slice(2).replace(/-([a-z])/gu,(_match,letter)=>letter.toUpperCase())),allowed=new Set([...contracts.flatMap(contract=>[contract.target,...contract.keys]),...flagKeys]),outputKeys=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];for(const key of["author","message","force","fullChangedFields","idOnly",...outputKeys])allowed.add(key);const topLevel=new Set(["action","options","path","cwd","author","force","noExtensions","no_extensions","fullChangedFields","idOnly",...outputKeys,...hoistedKeys,...action==="update"?["id"]:[]]);for(const key of Object.keys(args))topLevel.has(key)||refuseKey(action,key,allowed,allowed.has(key));const rawOptions=args.options;if(rawOptions!==void 0&&!isRuntimeRecord(rawOptions))throw new PmCliError("Mutation options must be an object. No changes were made.",2,{code:"invalid_argument_value",changed:!1});const unknown=[...new Set([...Object.keys(rawOptions??{}),...Object.keys(options)])].filter(key=>!allowed.has(key));if(unknown.length===0)return;const fields=resolveRuntimeFieldRegistry((await readSettings(resolvePmRoot(process.cwd(),pmRoot))).schema).command_to_fields.get(action)??[];for(const field of fields)allowed.add(runtimeFieldOptionTarget(field));for(const key of unknown)fields.some(field=>readRuntimeFieldOptionValue({[key]:!0},field)===!0)||refuseKey(action,key,allowed)}export{assertNativeMutationOptions};
|
|
2
|
+
//# sourceMappingURL=mutation-admission.js.map
|
|
@@ -23,6 +23,8 @@ export declare function parseRuntimeInteger(value:unknown,label:string):number |
|
|
|
23
23
|
export declare function resolveRuntimeLimit(args:Record<string,unknown>,options:Record<string,unknown>):number | string | undefined;
|
|
24
24
|
/** Fixed SDK-runtime global options derived from one untyped action payload. */
|
|
25
25
|
export declare function actionGlobalOptions(args:Record<string,unknown>):GlobalOptions;
|
|
26
|
+
/** Supported top-level aliases, shared with native mutation admission. */
|
|
27
|
+
export declare const HOISTED_ACTION_OPTION_KEYS:Readonly<Record<string,readonly string[]>>;
|
|
26
28
|
/** Reconcile MCP array/scalar option spellings with CLI flag expectations. */
|
|
27
29
|
export declare function normalizeMcpOptionsArrays(options:Record<string,unknown>,action?:string):Record<string,unknown>;
|
|
28
30
|
/** Merge hoisted top-level action arguments and author aliases into options. */
|