@unbrained/pm-cli 2026.9.30 → 2026.10.2
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 +2 -2
- package/CHANGELOG.md +20 -0
- package/dist/cli/error-guidance.d.ts +5 -0
- package/dist/cli/error-guidance.js +1 -1
- package/dist/cli/main.js +2 -2
- package/dist/cli/register-list-query.d.ts +8 -5
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/register-structured-mutation.d.ts +2 -0
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli/runtime/projection-retry.d.ts +9 -0
- package/dist/cli/runtime/projection-retry.js +2 -0
- package/dist/cli/runtime/selection.d.ts +5 -1
- package/dist/cli/runtime/selection.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +157 -157
- package/dist/cli-bundle/chunks/{chunk-EGAIIWI3.js → chunk-7FUEQOYG.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-7NL3A2BY.js +2 -0
- package/dist/cli-bundle/chunks/chunk-CZLAWXDR.js +8 -0
- package/dist/cli-bundle/chunks/chunk-HY6M34B4.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-O23CQ5T4.js → chunk-MTJMOI4I.js} +14 -14
- package/dist/cli-bundle/chunks/chunk-R4TUD355.js +6 -0
- package/dist/cli-bundle/chunks/chunk-R7ULWMBG.js +238 -0
- package/dist/cli-bundle/chunks/chunk-SV7CZEVV.js +20 -0
- package/dist/cli-bundle/chunks/chunk-TRYXVQ7W.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-BTCE36JS.js → chunk-WP6NRH72.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XRN3JYNN.js → chunk-XOUBIF6Z.js} +38 -38
- package/dist/cli-bundle/chunks/chunk-Z2GYDSAO.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-6YEET7XI.js → chunk-ZI7F3FVE.js} +47 -47
- package/dist/cli-bundle/chunks/{register-list-query-SYNBVMNG.js → register-list-query-R4PHNB7W.js} +6 -6
- package/dist/cli-bundle/chunks/register-mutation-PDDAUDYV.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-7FCJUC4Z.js → register-operations-A5HJT46K.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-YTWW2KL5.js → register-setup-EZ2F25JI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MOUCTR72.js → chunk-3BIYG72P.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-T4PZJQG4.js → chunk-4FFPGNCJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-AKB3JN57.js → chunk-BLCTBSGT.js} +45 -45
- package/dist/cli-bundle/focused-chunks/{chunk-XUCXRZZZ.js → chunk-DBD4W4QP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KZULQIAG.js → chunk-E754JDLY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4AORVUT4.js → chunk-EJN7DY3B.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-OMBDUJWZ.js → chunk-FKK2HI3S.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GBD4EN6S.js +12 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZJ3CLTV4.js → chunk-GMYUNHST.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-IR4UXLRP.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-RIJQQOEZ.js → chunk-UTRSM3ZK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EVMH4SKN.js → chunk-VVWYI2X7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-WCY6HRZO.js +30 -0
- package/dist/cli-bundle/focused-chunks/{chunk-XB5Q2P7Z.js → chunk-XRSCIYHR.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-YC32ZSLS.js +165 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IQBFYQF2.js → chunk-ZIXFMIUL.js} +2 -2
- package/dist/cli-bundle/main.js +22 -22
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +2 -2
- 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 +48 -48
- 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 +7 -7
- package/dist/core/fs/fs-utils.d.ts +11 -0
- package/dist/core/fs/fs-utils.js +2 -2
- package/dist/core/shared/errors.d.ts +9 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/settings.d.ts +15 -5
- package/dist/core/store/settings.js +3 -3
- package/dist/core/telemetry/runtime.js +3 -3
- package/dist/mcp/server.js +1 -1
- package/dist/sdk/agent/closed-domain-contracts.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/item-transaction.d.ts +11 -0
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/merge/install.d.ts +2 -2
- package/dist/sdk/merge/install.js +1 -1
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.d.ts +2 -0
- package/dist/sdk/query/context.js +1 -1
- package/dist/sdk/query/get.d.ts +19 -15
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/query/search-pagination.d.ts +4 -0
- package/dist/sdk/query/search-pagination.js +1 -1
- package/dist/sdk/query/search.js +1 -1
- package/dist/sdk/read-output/options.d.ts +14 -0
- package/dist/sdk/read-output/options.js +2 -0
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.d.ts +4 -0
- package/dist/sdk/read-output-rows.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +2 -2
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/workspace-transaction.d.ts +2 -0
- package/dist/sdk/workspace-transaction.js +2 -2
- package/docs/BOUNDED_CONTEXT_READS.md +10 -7
- package/docs/COMMANDS.md +1 -1
- package/docs/MERGE_SAFETY.md +12 -6
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +27 -0
- package/docs/SDK.md +98 -0
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
- package/marketplace.json +2 -2
- 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 +2 -2
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +2 -2
- package/plugins/pm-codex/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-6XTJLOKW.js +0 -3
- package/dist/cli-bundle/chunks/chunk-A6NDNRCK.js +0 -6
- package/dist/cli-bundle/chunks/chunk-BNAT4EYR.js +0 -20
- package/dist/cli-bundle/chunks/chunk-BX4LEJX4.js +0 -8
- package/dist/cli-bundle/chunks/chunk-FYTXVVZG.js +0 -2
- package/dist/cli-bundle/chunks/chunk-UIAH7UFK.js +0 -238
- package/dist/cli-bundle/chunks/chunk-USTAFHIM.js +0 -2
- package/dist/cli-bundle/chunks/chunk-YM342ELM.js +0 -3
- package/dist/cli-bundle/chunks/register-mutation-4GSUK23D.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-3CAZ7Z4R.js +0 -30
- package/dist/cli-bundle/focused-chunks/chunk-EFD4ATS7.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-IDB6E3ZV.js +0 -165
- package/dist/cli-bundle/focused-chunks/chunk-UPOMLSW7.js +0 -20
|
@@ -276,6 +276,8 @@ interface ContextSummary {
|
|
|
276
276
|
open: number;
|
|
277
277
|
blocked: number;
|
|
278
278
|
};
|
|
279
|
+
/** Optional per-section role/blocker codes for projected rows: i/I in progress, o/O open; uppercase is blocked. */
|
|
280
|
+
focus_row_states?: Record<string, string>;
|
|
279
281
|
active_items: number;
|
|
280
282
|
in_progress: number;
|
|
281
283
|
open: number;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ec0faae4-1fdb-5c7c-bcf1-eb338d73958a")}catch(e2){}})();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{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"];const HIGH_LEVEL_TYPES=new Set(["Epic","Feature"]);const DEFAULT_CONTEXT_LIMIT=10;const CONTEXT_SCALE_THRESHOLD=1e4;const STANDARD_SECTIONS=["hierarchy","activity","progress","recently_created","unparented","workload"];const DEEP_SECTIONS=[...STANDARD_SECTIONS,"blockers","files","staleness","tests"];const LEADING_HYPHEN_DATE=/^(\d{4})-(\d{2})-(\d{2})/;const LEADING_COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;const COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})$/;const 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 void 0;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 void 0;const fields=[];for(const token of raw.split(",")){const normalized=token.trim().toLowerCase();if(normalized.length===0)continue;if(!FOCUS_PROJECTION_FIELDS.has(normalized)){throw new PmCliError(`Context --fields value not projectable: ${normalized} (valid: ${[...FOCUS_PROJECTION_FIELDS].join(", ")})`,EXIT_CODE.USAGE)}if(!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={};const 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)}if(global2.json){return commandFormat==="ndjson"?"ndjson":"json"}return 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)}if(!sections.includes(normalized)){sections.push(normalized)}}return sections}if(depth==="brief")return[];if(depth==="full")return[...CONTEXT_SECTION_VALUES];const pool=depth==="deep"?DEEP_SECTIONS:STANDARD_SECTIONS;return pool.filter(section=>settings.sections[section])}function parseActivityLimit(raw,settings){if(!raw)return settings.activity_limit;const parsed=parseIntegerLimit(raw,"--activity-limit");return parsed??settings.activity_limit}function parseStaleThresholdDays(raw,settings){if(!raw)return settings.stale_threshold_days;const trimmed=raw.trim().toLowerCase();const 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);const blockedStatus=normalizeStatusInput("blocked",statusRegistry);const draftStatus=normalizeStatusInput("draft",statusRegistry);if(normalizedStatus===statusRegistry.in_progress_status)return 0;if(statusRegistry.active_statuses.has(normalizedStatus))return 1;if(blockedStatus&&normalizedStatus===blockedStatus)return 2;if(draftStatus&&normalizedStatus===draftStatus)return 3;if(statusRegistry.blocked_statuses.has(normalizedStatus))return 5;if(statusRegistry.terminal_statuses.has(normalizedStatus))return 7;return 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();const anchor=corpus.find(item=>item.id.trim().toLowerCase()===target);if(!anchor){return{ids:new Set,found:false}}const childrenByParent=buildChildrenByParent(corpus);const descendants=collectDescendants(anchor.id,childrenByParent);const ids=new Set([anchor.id,...descendants.map(item=>item.id)].map(id=>id.trim().toLowerCase()));return{ids,found:true}}function parseContextParent(raw){if(raw===void 0)return void 0;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;const rightValue=right??null;if(leftValue===null&&rightValue===null)return 0;if(leftValue===null)return 1;if(rightValue===null)return-1;return leftValue-rightValue}function compareOptionalDeadline(left,right){const leftValue=left??null;const rightValue=right??null;if(leftValue===null&&rightValue===null)return 0;if(leftValue===null)return 1;if(rightValue===null)return-1;return 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 true}const year=Number.parseInt(match[1],10);const month=Number.parseInt(match[2],10);const 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;const second=secondRaw?`:${secondRaw}`:"";const 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));const 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);const 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;let reminders=0;let scheduled=0;const itemIds=new Set;for(const event of events){itemIds.add(event.item_id);if(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);const activeHighLevelIds=new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)).map(item=>item.id));const nodes=[];for(const parentId of activeHighLevelIds){const parent=itemMap.get(parentId);if(!parent)continue;const allDescendants=collectDescendants(parentId,childrenByParent);const childItems=childrenByParent.get(parentId)??[];let closedCount=0;let openCount=0;let inProgressCount=0;let blockedCount=0;for(const desc of allDescendants){if(isClosedStatus(desc.status,statusRegistry))closedCount++;else if(isInProgressStatus(desc.status,statusRegistry))inProgressCount++;else if(isBlockedStatus(desc.status,statusRegistry))blockedCount++;else if(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);const 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);const bParent=itemMap.get(b.id);return compareCriticalItems(aParent,bParent,statusRegistry)}).slice(0,limit)}function collectDescendants(parentId,childrenByParent){const result=[];const stack=[parentId];const visited=new Set;while(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){const result=await runActivity({compact:true,limit:String(activityLimit)},global2);return result.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));const entries=[];for(const parent of activeHighLevel){const descendants=collectDescendants(parent.id,childrenByParent);const total=descendants.length;if(total===0)continue;let closed=0;let open=0;let inProgress=0;let blocked=0;for(const desc of descendants){if(isClosedStatus(desc.status,statusRegistry))closed++;else if(blockedIds.has(desc.id.trim().toLowerCase()))blocked++;else if(isInProgressStatus(desc.status,statusRegistry))inProgress++;else if(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);const blockedBy=blockers.find(blocker=>!blocker.resolved)?.id??blockers[0]?.id??null;const 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;const 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())/(24*60*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;let itemsWithRecentRuns=0;let passed=0;let failed=0;let skipped=0;const itemsFailing=[];for(const item of activeItems){if((item.tests??[]).length>0){itemsWithTests++}const runs=item.test_runs??[];if(runs.length>0){itemsWithRecentRuns++;let itemHasFailure=false;for(const run of runs){passed+=run.passed??0;failed+=run.failed??0;skipped+=run.skipped??0;if((run.failed??0)>0){itemHasFailure=true}}if(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);const deadlineToken=item.deadline??"-";const parentToken=item.parent?` parent:${item.parent}`:"";const 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}%`:"";const blockedToken=item.blocked===true?` 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];if(Array.isArray(value))return`${field}:${value.join(",")}`;return`${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)":"";const title=event.event_title??event.item_title;return`${base} \u2014 ${title}${recurringSuffix}`}return base}function pushContextFocusSection(lines,title,rows,emptyText,renderFocus){lines.push(`## ${title}`);if(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){return}lines.push("## Blocked fallback");for(const item of result.blocked_fallback){lines.push(`- ${renderFocus(item)}`)}lines.push("")}function pushAgendaSection(lines,result){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})`);if(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){return}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){return}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){return}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){return}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){return}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){return}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:-";const reason=entry.blocked_reason?` reason:"${entry.blocked_reason}"`:"";const 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){return}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){return}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){return}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){if(!result.tests){return}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}`);if(result.tests.items_failing.length>0){lines.push(`- items_failing: [${result.tests.items_failing.join(",")}]`)}lines.push("")}function pushEmptyContextSuggestions(lines,result){const isEmpty=result.summary.active_items===0&&result.summary.blocked===0&&result.agenda.summary.events===0;if(!isEmpty){return}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=[];const focusFields=result.focus_fields;const renderFocus=item=>focusFields?formatProjectedFocusLine(item,focusFields):formatFocusLine(item);lines.push("# pm context");lines.push("");lines.push(`- now: ${result.now}`);lines.push(`- depth: ${result.depth}`);if(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})`);if(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}`);if(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);if(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("")}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);return lines.join("\n")}async function resolveContextRuntime(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);const settings=await readSettings(pmRoot);const contextSettings=settings.context??SETTINGS_DEFAULTS.context;const statusRegistry=resolveRuntimeStatusRegistry(settings.schema);const depth=parseContextDepth(options.depth,contextSettings);const 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:true,limit:void 0,offset:void 0,after:void 0}}async function loadContextCorpus(global2,runtime){const listed=await runList(void 0,buildUnpaginatedContextListOptions(runtime.baseListOptions,{excludeTerminal:false}),global2);const fullCorpus=listed.items;let listedItemMetadata=fullCorpus.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry));let allItems=fullCorpus;const subtreeIds=resolveContextSubtreeIds(runtime.parentScope,fullCorpus);if(subtreeIds){listedItemMetadata=listedItemMetadata.filter(item=>subtreeIds.has(item.id.trim().toLowerCase()));allItems=allItems.filter(item=>subtreeIds.has(item.id.trim().toLowerCase()))}return{listed,listedItemMetadata,allItems,fullCorpus,subtreeIds}}function resolveContextSubtreeIds(parentScope,fullCorpus){if(parentScope===void 0){return void 0}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));const usage=await readContextUsageAffinity({pmRoot,author,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});const featureStore=await readWorkspaceContextSignals(structural,{pmRoot,storeKey:"context",statusRegistry,now,author,usageAffinity:usage.affinity,claimFocus});const ranking=await scoreContextCandidatesWithActiveExtensions("context",featureStore.candidates);const ranked=ranking.ranked.map(entry=>entry.item);const activeStatuses=statusRegistry.active_statuses;const rankedActiveItems=ranked.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry)));const pageStart=useBoundedPage?resolveQueryCursorStart(rankedActiveItems,cursor,cursorFingerprint,item=>item.id):0;const focusPage=useBoundedPage?rankedActiveItems.slice(pageStart,pageStart+limit):rankedActiveItems;const hasMore=useBoundedPage&&focusPage.length>0&&pageStart+focusPage.length<rankedActiveItems.length;const nextCursor=hasMore&&focusPage.length>0?encodeQueryCursor(cursorFingerprint,focusPage[focusPage.length-1].id,pageStart+focusPage.length-1):void 0;const rankedBlockedItems=ranked.filter(item=>blockedIds.has(item.id.trim().toLowerCase()));const packingIds=new Set([...focusPage.map(item=>item.id),...rankedBlockedItems.slice(0,limit).map(item=>item.id)]);const 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)));const packedItems=packing.included.map(entry=>entry.item);const activeItems=packedItems.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry)));const blockedItems=packedItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase()));const childrenByParent=buildChildrenByParent(allItems);const focusChildrenByParent=contextNeedsAllItems(sectionsIncluded)?childrenByParent:void 0;const fullCorpusById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item]));const projectFocusItem=item=>{const focus=toContextFocusItem(item,statusRegistry,focusChildrenByParent);if(!blockedIds.has(item.id.trim().toLowerCase())){return focus}focus.blocked=true;focus.blocker_ids=resolveItemBlockers(item,fullCorpusById,statusRegistry).filter(blocker=>!blocker.resolved).map(blocker=>blocker.id);return focus};const highLevelIds=collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry);const highLevel=activeItems.filter(item=>highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem);const lowLevel=activeItems.filter(item=>!highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem);const 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:true,truncated:true}:{},...nextCursor?{next_cursor:nextCursor}:{}}}}function buildContextCursorFingerprint(options){return createQueryFingerprint("context",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};const agenda=await runCalendar(calendarOptions,global2);const scopedAgenda=subtreeIds===void 0?agenda.events:agenda.events.filter(event=>subtreeIds.has(event.item_id.trim().toLowerCase()));const fullAgendaEvents=filterTerminalCalendarEvents(scopedAgenda,runtime.statusRegistry).slice(0,runtime.limit);const agendaEvents=fullAgendaEvents.map(event=>{if(!listedFocusIds.has(event.item_id)){return event}return{at:event.at,date:event.date,kind:event.kind,item_id:event.item_id,reference_only:true,...event.kind==="reminder"?{reminder_text:event.reminder_text}:{},...event.kind==="event"?{event_title:event.event_title,event_recurring:event.event_recurring}:{}}});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;const childrenByParent=buildChildrenByParent(allItems);const allNonTerminal=allItems.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry));const 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);const activeItems=allItems.filter(item=>statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,statusRegistry)));const 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){if(sections.hierarchy)result.hierarchy=sections.hierarchy;if(sections.activity)result.activity=sections.activity;if(sections.progress)result.progress=sections.progress;if(sections.blockersSection)result.blockers=sections.blockersSection;if(sections.recentlyCreated)result.recently_created=sections.recentlyCreated;if(sections.unparented)result.unparented=sections.unparented;if(sections.filesSection)result.files=sections.filesSection;if(sections.workload)result.workload=sections.workload;if(sections.staleness)result.staleness=sections.staleness;if(sections.tests)result.tests=sections.tests;if(warningDetails!==void 0&&warningDetails.length>0){result.warning_details=warningDetails}}function applyContextFocusProjection(result,focusFields){if(!focusFields){return}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);if(result.recently_created){result.recently_created=projectContextFocusRows(result.recently_created,focusFields)}if(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]));const 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);if(parent&&originalTagSignatures.get(row.id)===originalTagSignatures.get(parent.id)){delete row.tags;row.tags_inherited=parent.id}}}function maybeAttachEmptyContextSuggestions(result,activeItems,blockedItems){if(activeItems.length>0||blockedItems.length>0||result.agenda.events.length>0){return}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));const rows=focusGroups.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)}));const rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(result,"context")){if(!rankedIds.has(id)){rows.push({id,rank:rows.length+1,included:false});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 discovery=await discoverExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:false});const packages=discovery.discovered.map(diagnostic=>({name:diagnostic.name??diagnostic.directory,status:diagnostic.status==="ok"?"ok":"degraded"})).sort((left,right)=>left.name.localeCompare(right.name));const degraded=packages.filter(entry=>entry.status==="degraded").length;if(packages.length===0)return{};return{extension_health:{total:packages.length,ok:packages.length-degraded,degraded,packages:packages.slice(0,20),...packages.length>20?{truncated:true}:{}}}}async function resolveContextSemanticAffinity(pmRoot,author){const identity=detectAgentIdentity();const semanticState=await readSessionState(pmRoot);const attributionKey=identity.instance||semanticAttributionKey(author);return semanticAttributionAffinity(semanticState.semantic_attribution?.[attributionKey])}async function runContext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);const resolvedRuntime=await resolveContextRuntime(options,global2);const corpus=await loadContextCorpus(global2,resolvedRuntime);const scaledLimit=resolveContextLimitAtScale(resolvedRuntime.limit,corpus.fullCorpus.length);const runtime={...resolvedRuntime,limit:scaledLimit,tokenBudget:resolveContextTokenBudget(options.tokenBudget,Math.max(256,scaledLimit*160))};const author=resolveAuthor(void 0,runtime.settings.author_default);const claimFocus=await resolveContextSemanticAffinity(pmRoot,author);const extensionHealthPromise=resolveContextExtensionHealthProjection(options.noExtensionHealth===true,pmRoot,runtime.settings);const blockedIds=collectDependencyBlockedIds(corpus.fullCorpus,runtime.statusRegistry);const focusGroups=await resolveContextFocusGroups(corpus.listedItemMetadata,corpus.allItems,corpus.fullCorpus,blockedIds,runtime.statusRegistry,runtime.sectionsIncluded,runtime.limit,nowIso(),author,options.after,buildContextCursorFingerprint(options),shouldPageContextFocus(options,corpus.fullCorpus.length),pmRoot,runtime.tokenBudget,claimFocus,resolveItemTypeRegistry(runtime.settings,getActiveExtensionRegistrations()));const agendaContext=await buildContextAgenda(global2,runtime,corpus.subtreeIds,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(item=>item.id)));const workspaceMemory=await readWorkspaceMemory(corpus.fullCorpus,{pmRoot,statusRegistry:runtime.statusRegistry,now:agendaContext.agenda.now});const warnings=mergeSortedWarnings(corpus.listed.warnings,agendaContext.agenda.warnings,focusGroups.ranking.warnings,[...focusGroups.featureStore.warnings],workspaceMemory.warnings);const inProgressCount=countContextStatus(focusGroups.activeItems,runtime.statusRegistry.in_progress_status,runtime.statusRegistry);const openCount=focusGroups.activeItems.length-inProgressCount;const sections=await buildOptionalContextSections({runtime,allItems:corpus.allItems,fullCorpus:corpus.fullCorpus,blockedIds,focusGroups,now:agendaContext.agenda.now,global:global2});const summaryExtras=buildContextSummaryExtras(corpus.allItems,runtime.statusRegistry,blockedIds);const 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};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===true);if(options.explainRanking===true){result.ranking=toContextRankingSummary(focusGroups.ranking,focusGroups.featureStore,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(entry=>entry.id)));result.packing=toContextPackingSummary(focusGroups.packing)}applyContextFocusProjection(result,runtime.focusFields);if(warnings.length>0)result.warnings=warnings;maybeAttachEmptyContextSuggestions(result,focusGroups.activeItems,focusGroups.blockedItems);await attachContextUsageFeedback(result,focusGroups,pmRoot,author);return 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="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a37f9e4a-750c-53e0-b8f3-7f92e9538f3d")}catch(e2){}})();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"];const HIGH_LEVEL_TYPES=new Set(["Epic","Feature"]);const DEFAULT_CONTEXT_LIMIT=10;const CONTEXT_SCALE_THRESHOLD=1e4;const STANDARD_SECTIONS=["hierarchy","activity","progress","recently_created","unparented","workload"];const DEEP_SECTIONS=[...STANDARD_SECTIONS,"blockers","files","staleness","tests"];const LEADING_HYPHEN_DATE=/^(\d{4})-(\d{2})-(\d{2})/;const LEADING_COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;const COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})$/;const 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 void 0;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 void 0;const fields=[];for(const token of raw.split(",")){const normalized=token.trim().toLowerCase();if(normalized.length===0)continue;if(!FOCUS_PROJECTION_FIELDS.has(normalized)){throw new PmCliError(`Context --fields value not projectable: ${normalized} (valid: ${[...FOCUS_PROJECTION_FIELDS].join(", ")})`,EXIT_CODE.USAGE)}if(!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={};const 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)}if(global2.json){return commandFormat==="ndjson"?"ndjson":"json"}return 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)}if(!sections.includes(normalized)){sections.push(normalized)}}return sections}if(depth==="brief")return[];if(depth==="full")return[...CONTEXT_SECTION_VALUES];const pool=depth==="deep"?DEEP_SECTIONS:STANDARD_SECTIONS;return pool.filter(section=>settings.sections[section])}function parseActivityLimit(raw,settings){if(!raw)return settings.activity_limit;const parsed=parseIntegerLimit(raw,"--activity-limit");return parsed??settings.activity_limit}function parseStaleThresholdDays(raw,settings){if(!raw)return settings.stale_threshold_days;const trimmed=raw.trim().toLowerCase();const 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);const blockedStatus=normalizeStatusInput("blocked",statusRegistry);const draftStatus=normalizeStatusInput("draft",statusRegistry);if(normalizedStatus===statusRegistry.in_progress_status)return 0;if(statusRegistry.active_statuses.has(normalizedStatus))return 1;if(blockedStatus&&normalizedStatus===blockedStatus)return 2;if(draftStatus&&normalizedStatus===draftStatus)return 3;if(statusRegistry.blocked_statuses.has(normalizedStatus))return 5;if(statusRegistry.terminal_statuses.has(normalizedStatus))return 7;return 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();const anchor=corpus.find(item=>item.id.trim().toLowerCase()===target);if(!anchor){return{ids:new Set,found:false}}const childrenByParent=buildChildrenByParent(corpus);const descendants=collectDescendants(anchor.id,childrenByParent);const ids=new Set([anchor.id,...descendants.map(item=>item.id)].map(id=>id.trim().toLowerCase()));return{ids,found:true}}function parseContextParent(raw){if(raw===void 0)return void 0;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;const rightValue=right??null;if(leftValue===null&&rightValue===null)return 0;if(leftValue===null)return 1;if(rightValue===null)return-1;return leftValue-rightValue}function compareOptionalDeadline(left,right){const leftValue=left??null;const rightValue=right??null;if(leftValue===null&&rightValue===null)return 0;if(leftValue===null)return 1;if(rightValue===null)return-1;return 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 true}const year=Number.parseInt(match[1],10);const month=Number.parseInt(match[2],10);const 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;const second=secondRaw?`:${secondRaw}`:"";const 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));const 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);const 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;let reminders=0;let scheduled=0;const itemIds=new Set;for(const event of events){itemIds.add(event.item_id);if(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);const activeHighLevelIds=new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)).map(item=>item.id));const nodes=[];for(const parentId of activeHighLevelIds){const parent=itemMap.get(parentId);if(!parent)continue;const allDescendants=collectDescendants(parentId,childrenByParent);const childItems=childrenByParent.get(parentId)??[];let closedCount=0;let openCount=0;let inProgressCount=0;let blockedCount=0;for(const desc of allDescendants){if(isClosedStatus(desc.status,statusRegistry))closedCount++;else if(isInProgressStatus(desc.status,statusRegistry))inProgressCount++;else if(isBlockedStatus(desc.status,statusRegistry))blockedCount++;else if(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);const 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);const bParent=itemMap.get(b.id);return compareCriticalItems(aParent,bParent,statusRegistry)}).slice(0,limit)}function collectDescendants(parentId,childrenByParent){const result=[];const stack=[parentId];const visited=new Set;while(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){const result=await runActivity({compact:true,limit:String(activityLimit)},global2);return result.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));const entries=[];for(const parent of activeHighLevel){const descendants=collectDescendants(parent.id,childrenByParent);const total=descendants.length;if(total===0)continue;let closed=0;let open=0;let inProgress=0;let blocked=0;for(const desc of descendants){if(isClosedStatus(desc.status,statusRegistry))closed++;else if(blockedIds.has(desc.id.trim().toLowerCase()))blocked++;else if(isInProgressStatus(desc.status,statusRegistry))inProgress++;else if(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);const blockedBy=blockers.find(blocker=>!blocker.resolved)?.id??blockers[0]?.id??null;const 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;const 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())/(24*60*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;let itemsWithRecentRuns=0;let passed=0;let failed=0;let skipped=0;const itemsFailing=[];for(const item of activeItems){if((item.tests??[]).length>0){itemsWithTests++}const runs=item.test_runs??[];if(runs.length>0){itemsWithRecentRuns++;let itemHasFailure=false;for(const run of runs){passed+=run.passed??0;failed+=run.failed??0;skipped+=run.skipped??0;if((run.failed??0)>0){itemHasFailure=true}}if(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);const deadlineToken=item.deadline??"-";const parentToken=item.parent?` parent:${item.parent}`:"";const 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}%`:"";const blockedToken=item.blocked===true?` 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];if(Array.isArray(value))return`${field}:${value.join(",")}`;return`${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)":"";const title=event.event_title??event.item_title;return`${base} \u2014 ${title}${recurringSuffix}`}return base}function pushContextFocusSection(lines,title,rows,emptyText,renderFocus){lines.push(`## ${title}`);if(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){return}lines.push("## Blocked fallback");for(const item of result.blocked_fallback){lines.push(`- ${renderFocus(item)}`)}lines.push("")}function pushAgendaSection(lines,result){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})`);if(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){return}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){return}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){return}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){return}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){return}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){return}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:-";const reason=entry.blocked_reason?` reason:"${entry.blocked_reason}"`:"";const 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){return}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){return}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){return}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){if(!result.tests){return}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}`);if(result.tests.items_failing.length>0){lines.push(`- items_failing: [${result.tests.items_failing.join(",")}]`)}lines.push("")}function pushEmptyContextSuggestions(lines,result){const isEmpty=result.summary.active_items===0&&result.summary.blocked===0&&result.agenda.summary.events===0;if(!isEmpty){return}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=[];const focusFields=result.focus_fields;const renderFocus=item=>focusFields?formatProjectedFocusLine(item,focusFields):formatFocusLine(item);lines.push("# pm context");lines.push("");lines.push(`- now: ${result.now}`);lines.push(`- depth: ${result.depth}`);if(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})`);if(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}`);if(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);if(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("")}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);return lines.join("\n")}async function resolveContextRuntime(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);const settings=await readSettings(pmRoot);const contextSettings=settings.context??SETTINGS_DEFAULTS.context;const statusRegistry=resolveRuntimeStatusRegistry(settings.schema);const depth=parseContextDepth(options.depth,contextSettings);const 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:true,limit:void 0,offset:void 0,after:void 0}}async function loadContextCorpus(global2,runtime){const listed=await runList(void 0,buildUnpaginatedContextListOptions(runtime.baseListOptions,{excludeTerminal:false}),global2);const fullCorpus=listed.items;let listedItemMetadata=fullCorpus.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry));let allItems=fullCorpus;const subtreeIds=resolveContextSubtreeIds(runtime.parentScope,fullCorpus);if(subtreeIds){listedItemMetadata=listedItemMetadata.filter(item=>subtreeIds.has(item.id.trim().toLowerCase()));allItems=allItems.filter(item=>subtreeIds.has(item.id.trim().toLowerCase()))}return{listed,listedItemMetadata,allItems,fullCorpus,subtreeIds}}function resolveContextSubtreeIds(parentScope,fullCorpus){if(parentScope===void 0){return void 0}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));const usage=await readContextUsageAffinity({pmRoot,author,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});const featureStore=await readWorkspaceContextSignals(structural,{pmRoot,storeKey:"context",statusRegistry,now,author,usageAffinity:usage.affinity,claimFocus});const ranking=await scoreContextCandidatesWithActiveExtensions("context",featureStore.candidates);const ranked=ranking.ranked.map(entry=>entry.item);const activeStatuses=statusRegistry.active_statuses;const rankedActiveItems=ranked.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry)));const pageStart=useBoundedPage?resolveQueryCursorStart(rankedActiveItems,cursor,cursorFingerprint,item=>item.id):0;const focusPage=useBoundedPage?rankedActiveItems.slice(pageStart,pageStart+limit):rankedActiveItems;const hasMore=useBoundedPage&&focusPage.length>0&&pageStart+focusPage.length<rankedActiveItems.length;const nextCursor=hasMore&&focusPage.length>0?encodeQueryCursor(cursorFingerprint,focusPage[focusPage.length-1].id,pageStart+focusPage.length-1):void 0;const rankedBlockedItems=ranked.filter(item=>blockedIds.has(item.id.trim().toLowerCase()));const packingIds=new Set([...focusPage.map(item=>item.id),...rankedBlockedItems.slice(0,limit).map(item=>item.id)]);const 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)));const packedItems=packing.included.map(entry=>entry.item);const activeItems=packedItems.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry)));const blockedItems=packedItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase()));const childrenByParent=buildChildrenByParent(allItems);const focusChildrenByParent=contextNeedsAllItems(sectionsIncluded)?childrenByParent:void 0;const fullCorpusById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item]));const projectFocusItem=item=>{const focus=toContextFocusItem(item,statusRegistry,focusChildrenByParent);if(!blockedIds.has(item.id.trim().toLowerCase())){return focus}focus.blocked=true;focus.blocker_ids=resolveItemBlockers(item,fullCorpusById,statusRegistry).filter(blocker=>!blocker.resolved).map(blocker=>blocker.id);return focus};const highLevelIds=collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry);const highLevel=activeItems.filter(item=>highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem);const lowLevel=activeItems.filter(item=>!highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem);const 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:true,truncated:true}:{},...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};const agenda=await runCalendar(calendarOptions,global2);const scopedAgenda=subtreeIds===void 0?agenda.events:agenda.events.filter(event=>subtreeIds.has(event.item_id.trim().toLowerCase()));const fullAgendaEvents=filterTerminalCalendarEvents(scopedAgenda,runtime.statusRegistry).slice(0,runtime.limit);const agendaEvents=fullAgendaEvents.map(event=>{if(!listedFocusIds.has(event.item_id)){return event}return{at:event.at,date:event.date,kind:event.kind,item_id:event.item_id,reference_only:true,...event.kind==="reminder"?{reminder_text:event.reminder_text}:{},...event.kind==="event"?{event_title:event.event_title,event_recurring:event.event_recurring}:{}}});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;const childrenByParent=buildChildrenByParent(allItems);const allNonTerminal=allItems.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry));const 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);const activeItems=allItems.filter(item=>statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,statusRegistry)));const 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){if(sections.hierarchy)result.hierarchy=sections.hierarchy;if(sections.activity)result.activity=sections.activity;if(sections.progress)result.progress=sections.progress;if(sections.blockersSection)result.blockers=sections.blockersSection;if(sections.recentlyCreated)result.recently_created=sections.recentlyCreated;if(sections.unparented)result.unparented=sections.unparented;if(sections.filesSection)result.files=sections.filesSection;if(sections.workload)result.workload=sections.workload;if(sections.staleness)result.staleness=sections.staleness;if(sections.tests)result.tests=sections.tests;if(warningDetails!==void 0&&warningDetails.length>0){result.warning_details=warningDetails}}function applyContextFocusProjection(result,focusFields){if(!focusFields){return}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);if(result.recently_created){result.recently_created=projectContextFocusRows(result.recently_created,focusFields)}if(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]));const 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);if(parent&&originalTagSignatures.get(row.id)===originalTagSignatures.get(parent.id)){delete row.tags;row.tags_inherited=parent.id}}}function maybeAttachEmptyContextSuggestions(result,activeItems,blockedItems){if(activeItems.length>0||blockedItems.length>0||result.agenda.events.length>0){return}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));const rows=focusGroups.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)}));const rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(result,"context")){if(!rankedIds.has(id)){rows.push({id,rank:rows.length+1,included:false});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 discovery=await discoverExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:false});const packages=discovery.discovered.map(diagnostic=>({name:diagnostic.name??diagnostic.directory,status:diagnostic.status==="ok"?"ok":"degraded"})).sort((left,right)=>left.name.localeCompare(right.name));const degraded=packages.filter(entry=>entry.status==="degraded").length;if(packages.length===0)return{};return{extension_health:{total:packages.length,ok:packages.length-degraded,degraded,packages:packages.slice(0,20),...packages.length>20?{truncated:true}:{}}}}async function resolveContextSemanticAffinity(pmRoot,author){const identity=detectAgentIdentity();const semanticState=await readSessionState(pmRoot);const attributionKey=identity.instance||semanticAttributionKey(author);return semanticAttributionAffinity(semanticState.semantic_attribution?.[attributionKey])}async function runContext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);const resolvedRuntime=await resolveContextRuntime(options,global2);const corpus=await loadContextCorpus(global2,resolvedRuntime);const scaledLimit=resolveContextLimitAtScale(resolvedRuntime.limit,corpus.fullCorpus.length);const runtime={...resolvedRuntime,limit:scaledLimit,tokenBudget:resolveContextTokenBudget(options.tokenBudget,Math.max(256,scaledLimit*160))};const author=resolveAuthor(void 0,runtime.settings.author_default);const claimFocus=await resolveContextSemanticAffinity(pmRoot,author);const extensionHealthPromise=resolveContextExtensionHealthProjection(options.noExtensionHealth===true,pmRoot,runtime.settings);const blockedIds=collectDependencyBlockedIds(corpus.fullCorpus,runtime.statusRegistry);const 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()));const agendaContext=await buildContextAgenda(global2,runtime,corpus.subtreeIds,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(item=>item.id)));const workspaceMemory=await readWorkspaceMemory(corpus.fullCorpus,{pmRoot,statusRegistry:runtime.statusRegistry,now:agendaContext.agenda.now});const warnings=mergeSortedWarnings(corpus.listed.warnings,agendaContext.agenda.warnings,focusGroups.ranking.warnings,[...focusGroups.featureStore.warnings],workspaceMemory.warnings);const inProgressCount=countContextStatus(focusGroups.activeItems,runtime.statusRegistry.in_progress_status,runtime.statusRegistry);const openCount=focusGroups.activeItems.length-inProgressCount;const sections=await buildOptionalContextSections({runtime,allItems:corpus.allItems,fullCorpus:corpus.fullCorpus,blockedIds,focusGroups,now:agendaContext.agenda.now,global:global2});const summaryExtras=buildContextSummaryExtras(corpus.allItems,runtime.statusRegistry,blockedIds);const 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};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===true);if(options.explainRanking===true){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);if(warnings.length>0)result.warnings=warnings;maybeAttachEmptyContextSuggestions(result,focusGroups.activeItems,focusGroups.blockedItems);await attachContextUsageFeedback(result,focusGroups,pmRoot,author);return 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};
|
|
2
2
|
//# sourceMappingURL=context.js.map
|
package/dist/sdk/query/get.d.ts
CHANGED
|
@@ -3,20 +3,24 @@ import { type ChildRollupContext } from "../item-children.js";
|
|
|
3
3
|
import { type ItemScheduleContext } from "../item-schedule.js";
|
|
4
4
|
import type { ItemMetadata, LinkedDoc, LinkedFile, LinkedTest } from "../../types/index.js";
|
|
5
5
|
export { GET_DEPTH_VALUES, listGetProjectionFields, } from "./projection-contracts.js";
|
|
6
|
+
/** Latest claim or release coordinate exposed without its mutation patch. */
|
|
6
7
|
interface ClaimHistoryContext {
|
|
7
8
|
ts: string;
|
|
8
9
|
author: string;
|
|
9
10
|
message: string | null;
|
|
10
11
|
}
|
|
12
|
+
/** Ownership from the selected item snapshot, accompanied by its latest claim and release events. */
|
|
11
13
|
interface ClaimStateContext {
|
|
12
14
|
claimed: boolean;
|
|
13
15
|
assignee: string | null;
|
|
14
16
|
last_claim: ClaimHistoryContext | null;
|
|
15
17
|
last_release: ClaimHistoryContext | null;
|
|
16
18
|
}
|
|
19
|
+
/** Depth or field-selected metadata; identity survives every projection. */
|
|
17
20
|
type GetItemProjection = Partial<ItemMetadata> & {
|
|
18
21
|
/** Canonical item identity retained by every depth and field projection. */
|
|
19
22
|
id: string;
|
|
23
|
+
/** Item document body, included inside metadata for CLI/list parity. */
|
|
20
24
|
body?: string;
|
|
21
25
|
/** Number of notes omitted by a token-bounded projection. */
|
|
22
26
|
notes_count?: number;
|
|
@@ -34,19 +38,19 @@ type GetItemProjection = Partial<ItemMetadata> & {
|
|
|
34
38
|
events: number;
|
|
35
39
|
}>;
|
|
36
40
|
};
|
|
37
|
-
/**
|
|
41
|
+
/** Single-item read with optional derived facets; omission materiality is carried separately from its JSON representation. */
|
|
38
42
|
export interface GetResult {
|
|
39
|
-
/**
|
|
43
|
+
/** Selected metadata and body; requested empty collections are represented explicitly. */
|
|
40
44
|
item: GetItemProjection;
|
|
41
|
-
/**
|
|
45
|
+
/** Requested artifact groups; narrower selectors leave unrequested groups empty. */
|
|
42
46
|
linked?: {
|
|
43
47
|
files: LinkedFile[];
|
|
44
48
|
tests: LinkedTest[];
|
|
45
49
|
docs: LinkedDoc[];
|
|
46
50
|
};
|
|
47
|
-
/**
|
|
51
|
+
/** Ownership evidence for the current or selected historical snapshot. */
|
|
48
52
|
claim_state?: ClaimStateContext;
|
|
49
|
-
/**
|
|
53
|
+
/** Current child rollup for full or explicit child reads and deep container reads; historical hierarchy is not indexed. */
|
|
50
54
|
children?: ChildRollupContext;
|
|
51
55
|
/** Normalized scheduling data for scheduled item types and metadata. */
|
|
52
56
|
schedule?: Partial<ItemScheduleContext>;
|
|
@@ -56,7 +60,7 @@ export interface GetResult {
|
|
|
56
60
|
as_of_version?: number | null;
|
|
57
61
|
/** Timestamp of the last history entry included in a reconstructed read. */
|
|
58
62
|
as_of_timestamp?: string;
|
|
59
|
-
/**
|
|
63
|
+
/** Current descendants selected through registered hierarchy semantics and the optional depth bound. */
|
|
60
64
|
tree?: {
|
|
61
65
|
root_id: string;
|
|
62
66
|
root_title: string | null;
|
|
@@ -65,26 +69,26 @@ export interface GetResult {
|
|
|
65
69
|
items: Record<string, unknown>[];
|
|
66
70
|
};
|
|
67
71
|
}
|
|
68
|
-
/** Decide
|
|
72
|
+
/** Decide which item types receive a child rollup during deep reads. */
|
|
69
73
|
declare function shouldAutoIncludeGetChildren(itemType: string): boolean;
|
|
70
|
-
/**
|
|
74
|
+
/** Select item detail and optional hierarchy or verified historical evidence. Incompatible projections fail before serving the item. */
|
|
71
75
|
export interface GetOptions {
|
|
72
|
-
/**
|
|
76
|
+
/** Detail depth: brief|standard|deep|full. Full includes current children for every type; standard and brief avoid workspace enumeration. */
|
|
73
77
|
depth?: string;
|
|
74
|
-
/**
|
|
78
|
+
/** Comma-separated metadata or facet selectors, including item-prefixed aliases; identity is always retained. */
|
|
75
79
|
fields?: string;
|
|
76
|
-
/**
|
|
80
|
+
/** Complete item and current child rollup for every type, mutually exclusive with fields/depth. Historical reads retain child recovery because past hierarchy is not indexed. */
|
|
77
81
|
full?: boolean;
|
|
78
|
-
/**
|
|
82
|
+
/** Include current descendants; cannot be combined with a historical read. */
|
|
79
83
|
tree?: boolean;
|
|
80
|
-
/**
|
|
84
|
+
/** Non-negative descendant depth limit, valid only when tree is enabled. */
|
|
81
85
|
treeDepth?: string;
|
|
82
86
|
/** One-based history version or ISO timestamp for a mutation-free read. */
|
|
83
87
|
at?: string;
|
|
84
88
|
}
|
|
85
|
-
/**
|
|
89
|
+
/** Read one authoritative item and selected facets. Full current reads compute children for every type; ordinary Task reads avoid corpus enumeration. Historical reads exclude current hierarchy, and failed derived usage recording never invalidates the item read. */
|
|
86
90
|
export declare function runGet(id: string, global: GlobalOptions, options?: GetOptions): Promise<GetResult>;
|
|
87
|
-
/**
|
|
91
|
+
/** Compatibility access to deep-read container classification; explicit full reads override that classification. */
|
|
88
92
|
export declare const _testOnlyGetCommand: {
|
|
89
93
|
shouldAutoIncludeGetChildren: typeof shouldAutoIncludeGetChildren;
|
|
90
94
|
};
|
package/dist/sdk/query/get.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="26bf8487-2515-5885-b6de-56ba6292fb65")}catch(e2){}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,toItemRecord,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,TYPE_TO_FOLDER,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,getHistoryPath,resolvePmRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{renderPmCommand}from"../command-line.js";import{recordContextUsageTouches}from"../context-usage.js";import{buildItemChildrenRollup}from"../item-children.js";import{buildItemSchedule}from"../item-schedule.js";import{getItemAt}from"../history-read.js";import{parseIntegerLimit}from"./parsers.js";import{runList}from"./list.js";import{registerOutputMaterialFieldGroups}from"../output-projection.js";import{GET_DEPTH_VALUES,listGetProjectionFields}from"./projection-contracts.js";import{GET_DEPTH_VALUES as GET_DEPTH_VALUES2,listGetProjectionFields as listGetProjectionFields2}from"./projection-contracts.js";const AUTOMATIC_CHILD_ROLLUP_TYPES=new Set(["epic","feature","milestone","plan"]);const BUILTIN_ITEM_TYPES=new Set(Object.keys(TYPE_TO_FOLDER).map(type=>type.toLowerCase()));function itemCollectionCounts(item){const lengths=Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(key=>[key,item[key]?.length??0]));return lengths}function itemMaterialFieldGroups(item,body){const collectionCounts=itemCollectionCounts(item);return[...body.length>0?["body"]:[],...Object.entries(collectionCounts).flatMap(([name,count])=>count>0?[name]:[]),...collectionCounts.files+collectionCounts.tests+collectionCounts.docs>0?["linked"]:[],"children",...typeof item.assignee==="string"&&item.assignee.trim().length>0?["claim_state"]:[],...buildItemSchedule(item)?["schedule"]:[]]}function shouldAutoIncludeGetChildren(itemType){const normalizedType=itemType.trim().toLowerCase();return normalizedType.length>0&&(AUTOMATIC_CHILD_ROLLUP_TYPES.has(normalizedType)||!BUILTIN_ITEM_TYPES.has(normalizedType))}function toClaimHistoryContext(entry){return{ts:entry.ts,author:entry.author,message:entry.message??null}}function resolveClaimStateContext(assigneeValue,history){const assignee=assigneeValue?.trim();const normalizedAssignee=assignee&&assignee.length>0?assignee:null;const lastClaim=[...history].reverse().find(entry=>entry.op==="claim");const lastRelease=[...history].reverse().find(entry=>entry.op==="release");return{claimed:normalizedAssignee!==null,assignee:normalizedAssignee,last_claim:lastClaim?toClaimHistoryContext(lastClaim):null,last_release:lastRelease?toClaimHistoryContext(lastRelease):null}}function parseGetDepth(raw){if(raw===void 0||raw.trim().length===0){return"standard"}const normalized=raw.trim().toLowerCase();if(normalized==="full"){return"deep"}if(GET_DEPTH_VALUES.includes(normalized)){return normalized}throw new PmCliError("Get --depth must be one of brief|standard|deep|full",EXIT_CODE.USAGE)}function projectItemForDepth(item,depth){const collectionCounts=itemCollectionCounts(item);if(depth==="deep"){return{...item,comments:item.comments??[],notes:item.notes??[],learnings:item.learnings??[],files:item.files??[],tests:item.tests??[],docs:item.docs??[],reminders:item.reminders??[],events:item.events??[],notes_count:collectionCounts.notes,tests_count:collectionCounts.tests,collection_counts:collectionCounts}}const{comments:_comments,notes:_notes,learnings:_learnings,files:_files,tests:_tests,docs:_docs,reminders:_reminders,events:_events,...projected}=item;return{...projected,notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:collectionCounts}}function parseGetFields(raw){if(raw===void 0){return null}const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0){throw new PmCliError("Get --fields requires a comma-separated list of field names",EXIT_CODE.USAGE)}return fields}function normalizeGetField(field){return field.startsWith("item.")?field.slice("item.".length):field}function validateGetFields(fields,runtimeMetadataKeys,id){if(fields===null){return}const allowedValues=listGetProjectionFields(runtimeMetadataKeys);const allowed=new Set(allowedValues);const unknown=fields.filter(field=>{const normalized=normalizeGetField(field);return!allowed.has(field)&&!allowed.has(normalized)});if(unknown.length>0){const suggestedRetryArguments=["get",id,"--fields","id,title,status"];throw new PmCliError(`Unknown get --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const EMPTY_PROJECTED_COLLECTION_FIELDS=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function projectedMetadataValue(source,counts,field){if(Object.hasOwn(counts,field))return counts[field];if(source[field]!==void 0)return source[field];return EMPTY_PROJECTED_COLLECTION_FIELDS.has(field)?[]:void 0}function projectItemForFields(item,fields){const source=toItemRecord(item);const omittedCounts={notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:itemCollectionCounts(item)};const projected={id:item.id};for(const field of fields){const normalized=normalizeGetField(field);if(normalized==="body"||normalized==="linked"||normalized.startsWith("linked.")||normalized==="claim_state"||normalized.startsWith("claim_state.")||normalized==="children"||normalized.startsWith("children.")||normalized==="schedule"||normalized.startsWith("schedule.")){continue}projected[normalized]=projectedMetadataValue(source,omittedCounts,normalized)}return projected}function fieldsInclude(fields,name){return fields?.some(field=>field===name||field===`item.${name}`)??false}function fieldsIncludeRoot(fields,name){return fields.some(field=>{const normalized=normalizeGetField(field);return normalized===name||normalized.startsWith(`${name}.`)})}function resolveGetProjection(options,id){if(options.full&&(options.fields!==void 0||options.depth!==void 0)){throw new PmCliError("Get projection options are mutually exclusive; remove the extra projection flag and retry.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:renderPmCommand(["get",id,"--full"]),suggested_retry_args:["get",id,"--full"]}})}if(options.tree!==true&&options.treeDepth!==void 0){throw new PmCliError("Get --tree-depth requires --tree",EXIT_CODE.USAGE)}if(options.at!==void 0&&options.tree===true){throw new PmCliError("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",EXIT_CODE.USAGE)}return{depth:options.full?"deep":parseGetDepth(options.depth),treeDepth:options.tree===true?parseIntegerLimit(options.treeDepth,"--tree-depth"):void 0,fields:parseGetFields(options.fields),fieldProjection:options.fields!==void 0}}async function loadGetItemContext(id,global2,at){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());if(at!==void 0){const historical=await getItemAt(id,at,{pmRoot:global2.path});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:historical.document.metadata.id,metadata:historical.document.metadata,body:historical.document.body,historical}}const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located){throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeRegistry.type_to_folder)}const loaded=await readLocatedItem(located,{schema:settings.schema});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:located.id,metadata:loaded.document.metadata,body:loaded.document.body}}function validateGetProjectionFields(fields,settings,historical,id){const runtimeMetadataKeys=resolveRuntimeFieldRegistry(settings.schema).definitions.map(field=>field.metadata_key);validateGetFields(fields,runtimeMetadataKeys,id);if(historical&&fieldsIncludeRoot(fields??[],"children")){throw new PmCliError("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",EXIT_CODE.USAGE)}}function shouldIncludeGetField(params){const{fieldProjection,depth,fields,field}=params;if(fieldProjection){if(field==="body"||field==="linked"){return fieldsInclude(fields,field)}return fieldsIncludeRoot(fields,field)}return depth!=="brief"}async function resolveGetClaimState(context,includeClaimState){if(!includeClaimState){return void 0}const historyPath=getHistoryPath(context.pmRoot,context.locatedId);const history=await readHistoryEntries(historyPath,context.locatedId);return resolveClaimStateContext(context.metadata.assignee,context.historical?history.slice(0,context.historical.target.historyIndex+1):history)}function attachGetLinked(result,context,fields,includeLinked){const includeLinkedFiles=includeLinked||fieldsInclude(fields,"linked.files");const includeLinkedTests=includeLinked||fieldsInclude(fields,"linked.tests");const includeLinkedDocs=includeLinked||fieldsInclude(fields,"linked.docs");if(!includeLinked&&!includeLinkedFiles&&!includeLinkedTests&&!includeLinkedDocs){return}result.linked={files:includeLinkedFiles?context.metadata.files??[]:[],tests:includeLinkedTests?context.metadata.tests??[]:[],docs:includeLinkedDocs?context.metadata.docs??[]:[]}}async function buildGetChildrenRollup(context,includeChildren){if(!includeChildren){return void 0}const statusRegistry=resolveRuntimeStatusRegistry(context.settings.schema);const corpus=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,context.typeToFolder,void 0,context.settings.schema);return buildItemChildrenRollup(context.locatedId,corpus,statusRegistry)}function attachGetSchedule(result,context,fields,includeSchedule){if(!includeSchedule){return}const schedule=buildItemSchedule(context.metadata);if(!schedule){return}if(fields===null||fieldsInclude(fields,"schedule")){result.schedule=schedule;return}result.schedule=Object.fromEntries(Object.entries(schedule).filter(([key])=>fields.some(field=>normalizeGetField(field)===`schedule.${key}`)))}async function buildGetTree(context,options,treeDepth,global2){if(options.tree!==true){return void 0}const subtree=await runList(void 0,{parent:context.locatedId,tree:true,treeDepth:treeDepth===void 0?void 0:String(treeDepth),full:true},global2);return{root_id:context.locatedId,root_title:context.metadata.title,depth_limit:treeDepth??null,count:subtree.count,items:subtree.items.map(entry=>toItemRecord(entry))}}async function runGet(id,global2,options={}){const projection=resolveGetProjection(options,id);const context=await loadGetItemContext(id,global2,options.at);validateGetProjectionFields(projection.fields,context.settings,context.historical!==void 0,context.locatedId);const includeBody=shouldIncludeGetField({...projection,field:"body"});const includeLinked=shouldIncludeGetField({...projection,field:"linked"});const includeClaimState=shouldIncludeGetField({...projection,field:"claim_state"});const includeChildren=context.historical===void 0&&(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"children"):projection.depth==="deep"&&shouldAutoIncludeGetChildren(context.metadata.type));const includeSchedule=projection.fieldProjection?fieldsIncludeRoot(projection.fields,"schedule"):projection.depth!=="brief";const claimState=await resolveGetClaimState(context,includeClaimState);const result={item:projection.fieldProjection?projectItemForFields(context.metadata,projection.fields):projectItemForDepth(context.metadata,projection.depth)};if(includeBody){result.item.body=context.body}attachGetLinked(result,context,projection.fields,includeLinked);if(claimState){result.claim_state=claimState}attachGetSchedule(result,context,projection.fields,includeSchedule);const children=await buildGetChildrenRollup(context,includeChildren);if(children!==void 0){result.children=children}const tree=await buildGetTree(context,options,projection.treeDepth,global2);if(tree!==void 0){result.tree=tree}if(context.historical){result.reconstructed=true;result.as_of_version=context.historical.as_of_version;result.as_of_timestamp=context.historical.as_of_timestamp}if(context.historical===void 0){try{await recordContextUsageTouches({pmRoot:context.pmRoot,author:resolveAuthor(void 0,context.settings.author_default),itemIds:[context.locatedId],intent:"get"})}catch{}}registerOutputMaterialFieldGroups(result,itemMaterialFieldGroups(context.metadata,context.body));return result}const _testOnlyGetCommand={shouldAutoIncludeGetChildren};export{GET_DEPTH_VALUES2 as GET_DEPTH_VALUES,_testOnlyGetCommand,listGetProjectionFields2 as listGetProjectionFields,runGet};
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="33c1e75c-e348-5ab1-933f-2f7b6394fe40")}catch(e2){}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,toItemRecord,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,TYPE_TO_FOLDER,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,getHistoryPath,resolvePmRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{renderPmCommand}from"../command-line.js";import{recordContextUsageTouches}from"../context-usage.js";import{buildItemChildrenRollup}from"../item-children.js";import{buildItemSchedule}from"../item-schedule.js";import{getItemAt}from"../history-read.js";import{parseIntegerLimit}from"./parsers.js";import{runList}from"./list.js";import{registerOutputMaterialFieldGroups}from"../output-projection.js";import{GET_DEPTH_VALUES,listGetProjectionFields}from"./projection-contracts.js";import{GET_DEPTH_VALUES as GET_DEPTH_VALUES2,listGetProjectionFields as listGetProjectionFields2}from"./projection-contracts.js";const AUTOMATIC_CHILD_ROLLUP_TYPES=new Set(["epic","feature","milestone","plan"]);const BUILTIN_ITEM_TYPES=new Set(Object.keys(TYPE_TO_FOLDER).map(type=>type.toLowerCase()));function itemCollectionCounts(item){const lengths=Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(key=>[key,item[key]?.length??0]));return lengths}function itemMaterialFieldGroups(item,body,children){const collectionCounts=itemCollectionCounts(item);return[...body.length>0?["body"]:[],...Object.entries(collectionCounts).flatMap(([name,count])=>count>0?[name]:[]),...collectionCounts.files+collectionCounts.tests+collectionCounts.docs>0?["linked"]:[],...children===void 0?["children"]:children.count>0?["children"]:[],...typeof item.assignee==="string"&&item.assignee.trim().length>0?["claim_state"]:[],...buildItemSchedule(item)?["schedule"]:[]]}function shouldAutoIncludeGetChildren(itemType){const normalizedType=itemType.trim().toLowerCase();return normalizedType.length>0&&(AUTOMATIC_CHILD_ROLLUP_TYPES.has(normalizedType)||!BUILTIN_ITEM_TYPES.has(normalizedType))}function toClaimHistoryContext(entry){return{ts:entry.ts,author:entry.author,message:entry.message??null}}function resolveClaimStateContext(assigneeValue,history){const assignee=assigneeValue?.trim();const normalizedAssignee=assignee&&assignee.length>0?assignee:null;const lastClaim=[...history].reverse().find(entry=>entry.op==="claim");const lastRelease=[...history].reverse().find(entry=>entry.op==="release");return{claimed:normalizedAssignee!==null,assignee:normalizedAssignee,last_claim:lastClaim?toClaimHistoryContext(lastClaim):null,last_release:lastRelease?toClaimHistoryContext(lastRelease):null}}function parseGetDepth(raw){if(raw===void 0||raw.trim().length===0){return"standard"}const normalized=raw.trim().toLowerCase();if(normalized==="full"){return"deep"}if(GET_DEPTH_VALUES.includes(normalized)){return normalized}throw new PmCliError("Get --depth must be one of brief|standard|deep|full",EXIT_CODE.USAGE)}function projectItemForDepth(item,depth){const collectionCounts=itemCollectionCounts(item);if(depth==="deep"){return{...item,comments:item.comments??[],notes:item.notes??[],learnings:item.learnings??[],files:item.files??[],tests:item.tests??[],docs:item.docs??[],reminders:item.reminders??[],events:item.events??[],notes_count:collectionCounts.notes,tests_count:collectionCounts.tests,collection_counts:collectionCounts}}const{comments:_comments,notes:_notes,learnings:_learnings,files:_files,tests:_tests,docs:_docs,reminders:_reminders,events:_events,...projected}=item;return{...projected,notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:collectionCounts}}function parseGetFields(raw){if(raw===void 0){return null}const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0){throw new PmCliError("Get --fields requires a comma-separated list of field names",EXIT_CODE.USAGE)}return fields}function normalizeGetField(field){return field.startsWith("item.")?field.slice("item.".length):field}function validateGetFields(fields,runtimeMetadataKeys,id){if(fields===null){return}const allowedValues=listGetProjectionFields(runtimeMetadataKeys);const allowed=new Set(allowedValues);const unknown=fields.filter(field=>{const normalized=normalizeGetField(field);return!allowed.has(field)&&!allowed.has(normalized)});if(unknown.length>0){const suggestedRetryArguments=["get",id,"--fields",fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown get --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const EMPTY_PROJECTED_COLLECTION_FIELDS=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function projectedMetadataValue(source,counts,field){if(Object.hasOwn(counts,field))return counts[field];if(source[field]!==void 0)return source[field];return EMPTY_PROJECTED_COLLECTION_FIELDS.has(field)?[]:void 0}function projectItemForFields(item,fields){const source=toItemRecord(item);const omittedCounts={notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:itemCollectionCounts(item)};const projected={id:item.id};for(const field of fields){const normalized=normalizeGetField(field);if(normalized==="body"||normalized==="linked"||normalized.startsWith("linked.")||normalized==="claim_state"||normalized.startsWith("claim_state.")||normalized==="children"||normalized.startsWith("children.")||normalized==="schedule"||normalized.startsWith("schedule.")){continue}projected[normalized]=projectedMetadataValue(source,omittedCounts,normalized)}return projected}function fieldsInclude(fields,name){return fields?.some(field=>field===name||field===`item.${name}`)??false}function fieldsIncludeRoot(fields,name){return fields.some(field=>{const normalized=normalizeGetField(field);return normalized===name||normalized.startsWith(`${name}.`)})}function resolveGetProjection(options,id){if(options.full&&(options.fields!==void 0||options.depth!==void 0)){throw new PmCliError("Get projection options are mutually exclusive; remove the extra projection flag and retry.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:renderPmCommand(["get",id,"--full"]),suggested_retry_args:["get",id,"--full"]}})}if(options.tree!==true&&options.treeDepth!==void 0){throw new PmCliError("Get --tree-depth requires --tree",EXIT_CODE.USAGE)}if(options.at!==void 0&&options.tree===true){throw new PmCliError("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",EXIT_CODE.USAGE)}return{depth:options.full?"deep":parseGetDepth(options.depth),full:options.full===true||options.depth?.trim().toLowerCase()==="full",treeDepth:options.tree===true?parseIntegerLimit(options.treeDepth,"--tree-depth"):void 0,fields:parseGetFields(options.fields),fieldProjection:options.fields!==void 0}}async function loadGetItemContext(id,global2,at){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());if(at!==void 0){const historical=await getItemAt(id,at,{pmRoot:global2.path});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:historical.document.metadata.id,metadata:historical.document.metadata,body:historical.document.body,historical}}const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located){throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeRegistry.type_to_folder)}const loaded=await readLocatedItem(located,{schema:settings.schema});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:located.id,metadata:loaded.document.metadata,body:loaded.document.body}}function validateGetProjectionFields(fields,settings,historical,id){const runtimeMetadataKeys=resolveRuntimeFieldRegistry(settings.schema).definitions.map(field=>field.metadata_key);validateGetFields(fields,runtimeMetadataKeys,id);if(historical&&fieldsIncludeRoot(fields??[],"children")){throw new PmCliError("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",EXIT_CODE.USAGE)}}function shouldIncludeGetField(params){const{fieldProjection,depth,fields,field}=params;if(fieldProjection){if(field==="body"||field==="linked"){return fieldsInclude(fields,field)}return fieldsIncludeRoot(fields,field)}return depth!=="brief"}async function resolveGetClaimState(context,includeClaimState){if(!includeClaimState){return void 0}const historyPath=getHistoryPath(context.pmRoot,context.locatedId);const history=await readHistoryEntries(historyPath,context.locatedId);return resolveClaimStateContext(context.metadata.assignee,context.historical?history.slice(0,context.historical.target.historyIndex+1):history)}function attachGetLinked(result,context,fields,includeLinked){const includeLinkedFiles=includeLinked||fieldsInclude(fields,"linked.files");const includeLinkedTests=includeLinked||fieldsInclude(fields,"linked.tests");const includeLinkedDocs=includeLinked||fieldsInclude(fields,"linked.docs");if(!includeLinked&&!includeLinkedFiles&&!includeLinkedTests&&!includeLinkedDocs){return}result.linked={files:includeLinkedFiles?context.metadata.files??[]:[],tests:includeLinkedTests?context.metadata.tests??[]:[],docs:includeLinkedDocs?context.metadata.docs??[]:[]}}async function buildGetChildrenRollup(context,includeChildren){if(!includeChildren){return void 0}const statusRegistry=resolveRuntimeStatusRegistry(context.settings.schema);const corpus=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,context.typeToFolder,void 0,context.settings.schema);return buildItemChildrenRollup(context.locatedId,corpus,statusRegistry)}function attachGetSchedule(result,context,fields,includeSchedule){if(!includeSchedule){return}const schedule=buildItemSchedule(context.metadata);if(!schedule){return}if(fields===null||fieldsInclude(fields,"schedule")){result.schedule=schedule;return}result.schedule=Object.fromEntries(Object.entries(schedule).filter(([key])=>fields.some(field=>normalizeGetField(field)===`schedule.${key}`)))}async function buildGetTree(context,options,treeDepth,global2){if(options.tree!==true){return void 0}const subtree=await runList(void 0,{parent:context.locatedId,tree:true,treeDepth:treeDepth===void 0?void 0:String(treeDepth),full:true},global2);return{root_id:context.locatedId,root_title:context.metadata.title,depth_limit:treeDepth??null,count:subtree.count,items:subtree.items.map(entry=>toItemRecord(entry))}}async function runGet(id,global2,options={}){const projection=resolveGetProjection(options,id);const context=await loadGetItemContext(id,global2,options.at);validateGetProjectionFields(projection.fields,context.settings,context.historical!==void 0,context.locatedId);const includeBody=shouldIncludeGetField({...projection,field:"body"});const includeLinked=shouldIncludeGetField({...projection,field:"linked"});const includeClaimState=shouldIncludeGetField({...projection,field:"claim_state"});const includeChildren=context.historical===void 0&&(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"children"):projection.depth==="deep"&&(projection.full||shouldAutoIncludeGetChildren(context.metadata.type)));const includeSchedule=projection.fieldProjection?fieldsIncludeRoot(projection.fields,"schedule"):projection.depth!=="brief";const claimState=await resolveGetClaimState(context,includeClaimState);const result={item:projection.fieldProjection?projectItemForFields(context.metadata,projection.fields):projectItemForDepth(context.metadata,projection.depth)};if(includeBody){result.item.body=context.body}attachGetLinked(result,context,projection.fields,includeLinked);if(claimState){result.claim_state=claimState}attachGetSchedule(result,context,projection.fields,includeSchedule);const children=await buildGetChildrenRollup(context,includeChildren);if(children!==void 0){result.children=children}const tree=await buildGetTree(context,options,projection.treeDepth,global2);if(tree!==void 0){result.tree=tree}if(context.historical){result.reconstructed=true;result.as_of_version=context.historical.as_of_version;result.as_of_timestamp=context.historical.as_of_timestamp}if(context.historical===void 0){try{await recordContextUsageTouches({pmRoot:context.pmRoot,author:resolveAuthor(void 0,context.settings.author_default),itemIds:[context.locatedId],intent:"get"})}catch{}}registerOutputMaterialFieldGroups(result,itemMaterialFieldGroups(context.metadata,context.body,children));return result}const _testOnlyGetCommand={shouldAutoIncludeGetChildren};export{GET_DEPTH_VALUES2 as GET_DEPTH_VALUES,_testOnlyGetCommand,listGetProjectionFields2 as listGetProjectionFields,runGet};
|
|
2
2
|
//# sourceMappingURL=get.js.map
|